You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool-biz/nmodbus/serialize/serializer.go

63 lines
2.0 KiB
Go

package serialize
import (
"encoding/binary"
"git.noahlan.cn/noahlan/ntool-biz/nmodbus/util"
)
type Serializer struct {
byteOrder binary.ByteOrder
}
// NewSerializer 新增序列化/反序列化器
func NewSerializer(byteOrder binary.ByteOrder) *Serializer {
tmp := &Serializer{byteOrder: byteOrder}
if tmp.byteOrder == nil {
tmp.byteOrder = binary.BigEndian
}
return tmp
}
// RegisterAddressAndNumber 返回数据帧中的 寄存器起始地址 数量 计算后的结束地址
func (s *Serializer) RegisterAddressAndNumber(data []byte) (register int, numRegs int, endRegister int) {
register = int(s.byteOrder.Uint16(data[0:2]))
numRegs = int(s.byteOrder.Uint16(data[2:4]))
endRegister = register + numRegs
return
}
// RegisterAddressAndValue 获取数据帧中的 寄存器起始地址 数据
func (s *Serializer) RegisterAddressAndValue(data []byte) (register int, value uint16) {
register = int(s.byteOrder.Uint16(data[0:2]))
value = s.byteOrder.Uint16(data[2:4])
return
}
// WriteWithRegisterAndNumber 生成 寄存器起始地址 和 数量
func (s *Serializer) WriteWithRegisterAndNumber(register uint16, number uint16) []byte {
data := make([]byte, 4)
s.byteOrder.PutUint16(data[0:2], register)
s.byteOrder.PutUint16(data[2:4], number)
return data
}
// WriteWithRegisterAndNumberAndValue 写入 寄存器起始地址 数量 数据
func (s *Serializer) WriteWithRegisterAndNumberAndValue(register uint16, number uint16, values []uint16) []byte {
data := make([]byte, 5+len(values)*2)
s.byteOrder.PutUint16(data[0:2], register)
s.byteOrder.PutUint16(data[2:4], number)
data[4] = uint8(len(values) * 2)
copy(data[5:], util.Uint16ToBytes(s.byteOrder, values))
return data
}
// WriteWithRegisterAndNumberAndBytes 写入 寄存器起始地址 数量 数据
func (s *Serializer) WriteWithRegisterAndNumberAndBytes(register uint16, number uint16, bytes []byte) []byte {
data := make([]byte, 5+len(bytes))
s.byteOrder.PutUint16(data[0:2], register)
s.byteOrder.PutUint16(data[2:4], number)
data[4] = byte(len(bytes))
copy(data[5:], bytes)
return data
}