Created
May 24, 2024 17:22
-
-
Save ahndmal/147a04d17472c854fead9ed774471f83 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (b *Bus) readAndUnpack() ([]byte, error) { | |
n, err := io.ReadAtLeast(b.port, b.buf[:], 2) | |
got := b.buf[:n] | |
if err != nil { | |
return nil, newError("libzzz: cannot read 2-byte preamble [got: % 02X] - error: %w", got, err) | |
} | |
if got[0] != magic_number { | |
return nil, newError("libzzz: bad MAGIC NUMBER in response - message starts with: [% 02X] (expected XX...)", got) | |
} | |
length := int(got[1]) | |
if length < 5 { | |
return nil, newError("libzzz: response too short: len=%d < 5 [% 02X]", length, got) | |
} | |
// Now that we know the total length, we can read the remaining bytes of the response | |
if n < length { | |
n, err = io.ReadAtLeast(b.port, b.buf[n:], length-n) | |
if err != nil { | |
return nil, newError("libzzz: cannot read remaining bytes of a packet [prefix=% 02X][rest=% 02X] - error: %w", | |
got, b.buf[len(got):][:n], err) | |
} | |
got = b.buf[:len(got)+n] | |
} | |
crc := crc(got[:length-2]) | |
if crc != [2]byte{got[length-2], got[length-1]} { | |
return nil, newError("libzzz: bad CRC [% 02X], expected [...% 02X]", got, crc[:]) | |
} | |
payload := append([]byte(nil), got[2:length-2]...) | |
return payload, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment