-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanconfig.go
43 lines (37 loc) · 1.17 KB
/
canconfig.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
package xsens
import (
"fmt"
)
type CANConfig struct {
Enable bool
BaudRate CANBaudRateID
}
const (
canCfgEnableOffset = 2
canCfgBaudrateOffset = 3
canCfgEnableMask = byte(0b1) // Masks reserved bit in Enable byte
canCfgBaudrateMask = ^byte(1 << 7) // Masks reserved bit in BaudRate byte
)
// MarshalBinary returns the wire representation of the CAN configuration.
func (o *CANConfig) MarshalBinary() ([]byte, error) {
result := make([]byte, 4)
if o.Enable {
result[canCfgEnableOffset] = 1
}
result[canCfgBaudrateOffset] = uint8(o.BaudRate) & canCfgBaudrateMask
return result, nil
}
// MarshalText returns a text representation of the CAN configuration.
func (o *CANConfig) MarshalText() ([]byte, error) {
s := fmt.Sprintf("Enable: %v, BaudRate: %v\n", o.Enable, o.BaudRate)
return []byte(s), nil
}
// UnmarshalBinary sets *o from a wire representation of the CAN configuration.
func (o *CANConfig) UnmarshalBinary(data []byte) error {
if o == nil {
return fmt.Errorf("cannot unmarshal to a nil pointer")
}
o.Enable = (data[canCfgEnableOffset] & canCfgEnableMask) == 1
o.BaudRate = CANBaudRateID(data[canCfgBaudrateOffset] & canCfgBaudrateMask)
return nil
}