package message import ( "bytes" "encoding/binary" "fmt" "strings" ) // CanetFrame USR-CANET200_V1.0.7 设备 以太网-CAN 透传协议帧(12字节) type BtmHeadFrame struct { CanLen byte //CAN帧数据长度[0,8],CanData中有效数据字节数 CanId CanFrameId //CAN帧ID CanData []byte //CAN帧数据,8字节 } func NewBtmHeadFrame(buf []byte) *BtmHeadFrame { cf := &BtmHeadFrame{} cf.Decode(buf) return cf } func (p *BtmHeadFrame) Encode() []byte { buf := make([]byte, 0) //CAN 帧ID frameId := uint32(p.CanId.ID1)<<21 | uint32(p.CanId.ID2)<<13 | uint32(p.CanId.ID3)<<5 | uint32(p.CanId.ID4) buf = binary.BigEndian.AppendUint32(buf, frameId) //CAN 帧数据 if len(p.CanData) != 8 { panic(fmt.Sprintf("len(p.CanData)!=8 datalen:%v", len(p.CanData))) } buf = append(buf, p.CanData...) return buf } func (p *BtmHeadFrame) Decode(buf []byte) { bb := bytes.NewBuffer(buf) var idSource uint32 binary.Read(bb, binary.BigEndian, &idSource) data := make([]byte, bb.Len()) _, err := bb.Read(data) if err != nil { fmt.Println(err) return } b1 := byte((idSource >> 21) & 0xFF) b2 := byte((idSource >> 13) & 0xFF) b3 := byte((idSource >> 5) & 0xFF) b4 := byte(idSource & 0x1F) p.CanId.ID1 = b1 p.CanId.ID2 = b2 p.CanId.ID3 = b3 p.CanId.ID4 = b4 p.CanData = data } func (p *BtmHeadFrame) String() string { sb := strings.Builder{} sb.WriteString(fmt.Sprintf("CanetFrame CanLen = %d, ID1 = 0x%0x, ID2 = 0x%0x, ID3 = 0x%0x, ID4 = 0x%0x", p.CanLen, p.CanId.ID1, p.CanId.ID2, p.CanId.ID3, p.CanId.ID4)) sb.WriteString("CanData = ") for _, d := range p.CanData { sb.WriteString(fmt.Sprintf(" 0x%0x ", d)) } return sb.String() }