rts-sim-testing-service/third_party/interlock/beijing11/msg.go

87 lines
2.1 KiB
Go

package beijing11
import (
"encoding/binary"
"fmt"
"hash/crc32"
"joylink.club/bj-rtsts-server/sys_error"
)
type BaseStruct struct {
ID byte
ControlWord byte
Data []byte
}
func (m *BaseStruct) Decode(buf []byte) error {
if buf[0] != FrameHead {
return sys_error.New(logTag + "帧头不正确:" + fmt.Sprintf("%02X", buf[0]))
}
if buf[len(buf)-1] != FrameTail {
return sys_error.New(logTag + "帧尾不正确:" + fmt.Sprintf("%02X", buf[len(buf)-1]))
}
crc := crc32.ChecksumIEEE(buf[1 : len(buf)-5])
if crc != binary.BigEndian.Uint32(buf[len(buf)-5:len(buf)-1]) {
return sys_error.New(logTag + "CRC校验失败")
}
m.ID = buf[1]
m.ControlWord = buf[2]
m.Data = buf[5 : len(buf)-5]
return nil
}
func (m *BaseStruct) Encode() []byte {
var data []byte
data = append(data, FrameHead)
data = append(data, m.ID)
data = append(data, m.ControlWord)
data = binary.BigEndian.AppendUint16(data, uint16(len(m.Data)))
data = append(data, m.Data...)
crc := crc32.ChecksumIEEE(data[1:])
data = binary.BigEndian.AppendUint32(data, crc)
data = append(data, FrameTail)
return data
}
type ReadRegisterReq struct {
RegisterAddr []uint16 //寄存器地址
}
func (r *ReadRegisterReq) Decode(buf []byte) error {
if len(buf)%2 != 0 {
return sys_error.New(logTag + "读寄存器数据字节长度不是2的倍数")
}
for i := 0; i < len(buf); i += 2 {
r.RegisterAddr = append(r.RegisterAddr, binary.BigEndian.Uint16(buf[i:i+2]))
}
return nil
}
type ReadRegisterRes struct {
RegisterData [][]byte //寄存器数据
}
func (r *ReadRegisterRes) Encode() []byte {
var data []byte
for _, datum := range r.RegisterData {
data = append(data, datum...)
}
return data
}
type WriteRegisterReq struct {
RegisterAddr []uint16 //寄存器地址
RegisterData [][]byte //寄存器数据
}
func (w *WriteRegisterReq) Decode(buf []byte) error {
if len(buf)%6 != 0 {
return sys_error.New(logTag + "写寄存器数据字节长度不是6的倍数")
}
for i := 0; i < len(buf); i += 6 {
w.RegisterAddr = append(w.RegisterAddr, binary.BigEndian.Uint16(buf[i:i+2]))
w.RegisterData = append(w.RegisterData, buf[i+2:i+6])
}
return nil
}