package protocol import ( "encoding/binary" "errors" "fmt" ) const ( Header0 byte = 0xA5 Header1 byte = 0x5A TypeSetAll byte = 0x01 TypeGetSnapshot byte = 0x02 TypeReserved byte = 0x03 TypeRemoved byte = 0x04 TypeAck byte = 0x06 TypeSnapshot byte = 0x82 SetAllPayloadLen = 32 FrameOverhead = 6 ) var ( ErrHeader = errors.New("bad A5 5A header") ErrLength = errors.New("frame length mismatch") ErrCRC = errors.New("CRC-16/CCITT-FALSE mismatch") ErrPayload = errors.New("invalid SET_ALL payload") ) type SetAll struct { PTC [24]byte Front [4]byte Rear [4]byte } func (s SetAll) Payload() ([]byte, error) { p := make([]byte, SetAllPayloadLen) copy(p[0:24], s.PTC[:]) copy(p[24:28], s.Front[:]) copy(p[28:32], s.Rear[:]) for i, v := range p { if v > 100 { return nil, fmt.Errorf("%w: index %d value %d", ErrPayload, i, v) } } return p, nil } func Encode(frameType byte, payload []byte) []byte { b := make([]byte, 0, FrameOverhead+len(payload)) b = append(b, Header0, Header1, frameType, byte(len(payload))) b = append(b, payload...) c := CRC16(b[2:]) var le [2]byte binary.LittleEndian.PutUint16(le[:], c) return append(b, le[0], le[1]) } func EncodeSetAll(s SetAll) ([]byte, error) { p, err := s.Payload() if err != nil { return nil, err } return Encode(TypeSetAll, p), nil } func EncodeGetSnapshot() []byte { return Encode(TypeGetSnapshot, nil) } type Frame struct { Type byte Payload []byte } func Decode(raw []byte) (Frame, error) { if len(raw) < FrameOverhead || raw[0] != Header0 || raw[1] != Header1 { return Frame{}, ErrHeader } n := int(raw[3]) if len(raw) != FrameOverhead+n { return Frame{}, fmt.Errorf("%w: declared=%d actual=%d", ErrLength, n, len(raw)) } if binary.LittleEndian.Uint16(raw[len(raw)-2:]) != CRC16(raw[2:len(raw)-2]) { return Frame{}, ErrCRC } p := append([]byte(nil), raw[4:4+n]...) return Frame{Type: raw[2], Payload: p}, nil } type Ack struct { OK bool Request byte Status byte Detail byte } func DecodeAck(f Frame) (Ack, error) { if f.Type != TypeAck || len(f.Payload) != 4 { return Ack{}, fmt.Errorf("invalid ACK frame") } return Ack{OK: f.Payload[0] != 0, Request: f.Payload[1], Status: f.Payload[2], Detail: f.Payload[3]}, nil } func CRC16(data []byte) uint16 { crc := uint16(0xFFFF) for _, b := range data { crc ^= uint16(b) << 8 for i := 0; i < 8; i++ { if crc&0x8000 != 0 { crc = (crc << 1) ^ 0x1021 } else { crc <<= 1 } } } return crc }