package envSensor import ( "encoding/hex" "github.com/valyala/bytebufferpool" ) func (x DataPack) GetEnvGatherCommand() *bytebufferpool.ByteBuffer { buf := bytebufferpool.Get() x.Function = 0x03 decodeAddress, _ := hex.DecodeString(x.Address) buf.Write(decodeAddress) buf.WriteByte(x.Function) buf.Write(x.Start) buf.Write(x.DataLen) x.Crc = calculateCRC16Modbus(buf.Bytes()) buf.Write([]byte{byte(x.Crc & 0xFF), byte(x.Crc >> 8)}) return buf } func calculateCRC16Modbus(data []byte) uint16 { var crc uint16 = 0xFFFF // CRC-16 初始化值 for _, byteVal := range data { crc ^= uint16(byteVal) // 对字节进行异或操作 for i := 0; i < 8; i++ { if crc&0x0001 != 0 { crc >>= 1 crc ^= 0xA001 // 多项式 0xA001 } else { crc >>= 1 } } } return crc }