From 2df84cdc7faf29cc8a2512b627a36a3881276b9f Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期四, 26 十月 2023 16:29:15 +0800 Subject: [PATCH] plc4x读写加入长度 --- pkg/plc/apacheplc4x/modbus.go | 20 +++++++++++++++----- 1 files changed, 15 insertions(+), 5 deletions(-) diff --git a/pkg/plc/apacheplc4x/modbus.go b/pkg/plc/apacheplc4x/modbus.go index b289561..3876010 100644 --- a/pkg/plc/apacheplc4x/modbus.go +++ b/pkg/plc/apacheplc4x/modbus.go @@ -10,6 +10,7 @@ "github.com/apache/plc4x/plc4go/pkg/api/drivers" apiModel "github.com/apache/plc4x/plc4go/pkg/api/model" "github.com/apache/plc4x/plc4go/pkg/api/transports" + "github.com/spf13/cast" "sync/atomic" "time" ) @@ -53,7 +54,7 @@ func readHoldingRegisterSingle(connection plc4go.PlcConnection, address int) ([]byte, error) { tag := fmt.Sprintf("tag:%v", address) - tagAddress := getTagAddress(address) + tagAddress := getTagAddress(address, 1) // 璇绘ā寮� readRequest, err := connection.ReadRequestBuilder().AddTagAddress(tag, tagAddress).Build() @@ -83,7 +84,7 @@ func readHoldingRegisterList(connection plc4go.PlcConnection, address, length int) ([]byte, error) { tag := fmt.Sprintf("tag:%v:%v", address, length) - tagAddress := getTagAddress(address) + tagAddress := getTagAddress(address, length) // 璇绘ā寮� readRequest, err := connection.ReadRequestBuilder().AddTagAddress(tag, tagAddress).Build() @@ -130,12 +131,16 @@ return readHoldingRegisterSingle(connection, address) } -func getTagAddress(address int) string { +func getTagAddress(address int, length int) string { intType := conf.Conf.PLC.ModbusIntType if intType == "" { intType = "DINT" } - return fmt.Sprintf("holding-register:%d:%v", address, intType) + if length == 1 { + return fmt.Sprintf("holding-register:%d:%v", address, intType) + } else { + return fmt.Sprintf("holding-register:%d:%v[%d]", address, intType, length) + } } func WriteHoldingRegister(ipAddr string, address int, value any) (string, error) { @@ -146,7 +151,12 @@ } defer connection.Close() tag := fmt.Sprintf("tag:%v:w", address) - tagAddress := getTagAddress(address) + var tagAddress string + if cast.ToInt32(value) > 2<<16 { + tagAddress = getTagAddress(address, 2) + } else { + tagAddress = getTagAddress(address, 1) + } // 鍐欐ā寮� writeRequest, err := connection.WriteRequestBuilder().AddTagAddress(tag, tagAddress, value).Build() -- Gitblit v1.8.0