zhangqian
2023-09-19 583142e22b647955082ea61f8ee6b3641aaa903c
写plc fix
1个文件已添加
2个文件已修改
76 ■■■■■ 已修改文件
conf/apsClient.json 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
pkg/plc/modbusx/modbus.go 35 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
test/plc_test.go 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
conf/apsClient.json
@@ -33,7 +33,7 @@
    "totalNumberTimeInterval": 0,
    "modbusIntType": "DINT",
    "slaveId": 0,
    "package": "goburrow",
    "package": "goborrow",
    "keepAlive": "false"
  }
}
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) {
test/plc_test.go
New file
@@ -0,0 +1,39 @@
package test
import (
    "apsClient/service"
    "encoding/binary"
    "log"
    "testing"
)
func TestWriteHoldingRegister(t *testing.T) {
    Init()
    ipPort := "192.168.20.250:502"
    address := 1104
    value := 1104
    err := service.WriteHoldingRegister(ipPort, address, value)
    if err != nil {
        log.Fatal(err)
    }
    var readValue int
    raw, err := service.ReadHoldingRegister(ipPort, address, 1)
    if err != nil {
        log.Fatal(err)
    }
    if len(raw) == 2 {
        readValue = int(binary.BigEndian.Uint16(raw))
    } else if len(raw) == 4 {
        readValue = int(binary.BigEndian.Uint32(raw))
    } else {
        log.Fatal("unknown supported raw value length")
    }
    if readValue != value {
        t.Logf("read value:%v not equal write value:%v", readValue, value)
        t.Fail()
    } else {
        t.Logf("write ok, read value:%v equal write value:%v", readValue, value)
    }
}