-
Notifications
You must be signed in to change notification settings - Fork 5
/
serial_command.go
59 lines (49 loc) · 1.17 KB
/
serial_command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package gocan
import "fmt"
type SerialCommand struct {
Command byte
Data []byte
}
func NewSerialCommand(command byte, data []byte) *SerialCommand {
return &SerialCommand{
Command: command,
Data: data,
}
}
func (sc *SerialCommand) MarshalBinary() ([]byte, error) {
if len(sc.Data) > 255 {
return nil, fmt.Errorf("data size is too big")
}
checksum := sc.Checksum()
buf := make([]byte, 0, 3+len(sc.Data))
buf = append(buf, sc.Command, byte(len(sc.Data)))
buf = append(buf, sc.Data...)
buf = append(buf, checksum)
return buf, nil
}
func (sc *SerialCommand) UnmarshalBinary(data []byte) error {
if len(data) < 3 {
return nil
}
sc.Command = data[0]
commandSize := data[1]
if len(data) != int(commandSize)+3 {
return fmt.Errorf("invalid command size")
}
sc.Data = data[2 : 2+commandSize]
checksum := data[len(data)-1]
if checksum != sc.Checksum() {
return fmt.Errorf("checksum validation failed")
}
return nil
}
func (sc *SerialCommand) Checksum() byte {
var checksum byte
for _, b := range sc.Data {
checksum += b
}
return checksum
}
func (sc *SerialCommand) String() string {
return fmt.Sprintf("command: %02X, data: %02X", sc.Command, sc.Data)
}