From 8324f872ef3a4d0c978a9b1d062800c6a1701c12 Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期五, 01 十二月 2023 09:58:17 +0800 Subject: [PATCH] fix --- pkg/plc/modbusx/connection_manager.go | 46 +++++++++++++++++++++++++++++++++++++++++++--- 1 files changed, 43 insertions(+), 3 deletions(-) diff --git a/pkg/plc/modbusx/connection_manager.go b/pkg/plc/modbusx/connection_manager.go index 0aef49b..b8b83ad 100644 --- a/pkg/plc/modbusx/connection_manager.go +++ b/pkg/plc/modbusx/connection_manager.go @@ -2,6 +2,7 @@ import ( "apsClient/conf" + "apsClient/model/common" "github.com/goburrow/modbus" "sync" "time" @@ -11,6 +12,8 @@ connections map[string]modbus.Client mu sync.Mutex } + +var handler *modbus.TCPClientHandler func newPlcConnectionManager() *ConnectionManager { return &ConnectionManager{ @@ -47,7 +50,7 @@ if conn, ok := connectionManager.GetConnection(ipAddr); ok { return conn } - conn := newGetModbusConnection(ipAddr) + conn := newModbusConnection(ipAddr) connectionManager.AddConnection(ipAddr, conn) return conn } @@ -58,11 +61,48 @@ return } connectionManager.RemoveConnection(ipAddr) + if handler != nil { + handler.Close() + } } -func newGetModbusConnection(ipAddr string) modbus.Client { - handler := modbus.NewTCPClientHandler(ipAddr) +func newModbusConnection(ipAddr string) modbus.Client { + handler = modbus.NewTCPClientHandler(ipAddr) handler.Timeout = 10 * time.Second handler.SlaveId = byte(conf.Conf.PLC.SlaveId) return modbus.NewClient(handler) } + +var rtuHandler *modbus.RTUClientHandler + +func getModbusRTUConnection(c *common.RTUConfig) modbus.Client { + if conn, ok := connectionManager.GetConnection(c.SerialName); ok { + return conn + } + conn := newModbusRTUConnection(c) + connectionManager.AddConnection(c.SerialName, conn) + return conn +} + +func unsetModbusRTUConnection(serialName string) { + _, ok := connectionManager.GetConnection(serialName) + if !ok { + return + } + connectionManager.RemoveConnection(serialName) + if handler != nil { + handler.Close() + } +} + +func newModbusRTUConnection(c *common.RTUConfig) modbus.Client { + // Modbus RTU/ASCII + rtuHandler = modbus.NewRTUClientHandler(c.SerialName) + rtuHandler.BaudRate = c.BaudRate + rtuHandler.DataBits = c.DataBit + rtuHandler.Parity = c.Parity.ToString() + rtuHandler.StopBits = c.StopBit + rtuHandler.SlaveId = 1 + rtuHandler.Timeout = 5 * time.Second + return modbus.NewClient(rtuHandler) +} -- Gitblit v1.8.0