zhangqian
2023-09-19 583142e22b647955082ea61f8ee6b3641aaa903c
pkg/plc/modbusx/modbus.go
@@ -19,37 +19,24 @@
}
func Write(ipAddr string, address uint16, value int) (err error) {
   address--
   var bytesVal []byte
   if value <= 1<<16 {
      uint16ToBytes(uint16(value))
   } else {
      bytesVal = intToBytes(value)
   }
   bytesVal = intToBytes(value)
   cli := getModbusConnection(ipAddr)
   _, err = cli.WriteMultipleRegisters(address, uint16(len(bytesVal)), bytesVal)
   dealErr(err, ipAddr)
   return err
}
func uint16ToBytes(value uint16) []byte {
   // 创建一个长度为2的字节切片
   bytes := make([]byte, 2)
   // 将 uint16 的值写入字节切片,可以选择使用大端或小端字节序
   bytes[0] = byte(value >> 8) // 获取高8位
   bytes[1] = byte(value)      // 获取低8位
   return bytes
}
func intToBytes(value int) []byte {
   // 创建一个长度为4的字节切片,用于存储 int 值
   bytes := make([]byte, 4)
   // 使用 binary 包将 int 值转换为字节切片
   binary.BigEndian.PutUint32(bytes, uint32(value))
   return bytes
func intToBytes(value int) (data []byte) {
   if value <= 1<<16 {
      data = make([]byte, 2)
      binary.BigEndian.PutUint16(data, uint16(value))
   } else {
      data = make([]byte, 4)
      binary.BigEndian.PutUint32(data, uint32(value))
   }
   return
}
func dealErr(err error, ipAddr string) {