From 5220cfff6d68f24875c5ce832bbe4541b9fe6639 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期五, 08 十二月 2023 10:26:38 +0800
Subject: [PATCH] 使用雪花算法生成表id,解决数据同步表相同记录id不一致问题
---
pkg/plc/modbusx/connection_manager.go | 65 +++++++++++++++++++++++++++++---
1 files changed, 59 insertions(+), 6 deletions(-)
diff --git a/pkg/plc/modbusx/connection_manager.go b/pkg/plc/modbusx/connection_manager.go
index 898968f..b8b83ad 100644
--- a/pkg/plc/modbusx/connection_manager.go
+++ b/pkg/plc/modbusx/connection_manager.go
@@ -1,6 +1,8 @@
package modbusx
import (
+ "apsClient/conf"
+ "apsClient/model/common"
"github.com/goburrow/modbus"
"sync"
"time"
@@ -10,6 +12,8 @@
connections map[string]modbus.Client
mu sync.Mutex
}
+
+var handler *modbus.TCPClientHandler
func newPlcConnectionManager() *ConnectionManager {
return &ConnectionManager{
@@ -37,19 +41,68 @@
cm.connections[address] = connection
}
-func (cm *ConnectionManager) CheckConnect(conn modbus.Client, timeout time.Duration) (bool, error) {
- return true, nil
+func (cm *ConnectionManager) RemoveConnection(address string) {
+ cm.mu.Lock()
+ defer cm.mu.Unlock()
+ delete(cm.connections, address)
}
-
func getModbusConnection(ipAddr string) modbus.Client {
if conn, ok := connectionManager.GetConnection(ipAddr); ok {
return conn
}
- conn := newGetModbusConnection(ipAddr)
+ conn := newModbusConnection(ipAddr)
connectionManager.AddConnection(ipAddr, conn)
return conn
}
-func newGetModbusConnection(ipAddr string) modbus.Client {
- return modbus.TCPClient(ipAddr)
+func unsetModbusConnection(ipAddr string) {
+ _, ok := connectionManager.GetConnection(ipAddr)
+ if !ok {
+ return
+ }
+ connectionManager.RemoveConnection(ipAddr)
+ if handler != nil {
+ handler.Close()
+ }
+}
+
+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