From cab6eea89a0d82710369604ecb51f1cdb122e433 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期四, 19 十月 2023 17:26:34 +0800
Subject: [PATCH] fix

---
 pkg/plc/modbusx/connection_manager.go |   26 ++++++++++++++++++++++----
 1 files changed, 22 insertions(+), 4 deletions(-)

diff --git a/pkg/plc/modbusx/connection_manager.go b/pkg/plc/modbusx/connection_manager.go
index 898968f..ae0b377 100644
--- a/pkg/plc/modbusx/connection_manager.go
+++ b/pkg/plc/modbusx/connection_manager.go
@@ -1,6 +1,7 @@
 package modbusx
 
 import (
+	"apsClient/conf"
 	"github.com/goburrow/modbus"
 	"sync"
 	"time"
@@ -10,6 +11,8 @@
 	connections map[string]modbus.Client
 	mu          sync.Mutex
 }
+
+var handler *modbus.TCPClientHandler
 
 func newPlcConnectionManager() *ConnectionManager {
 	return &ConnectionManager{
@@ -37,10 +40,11 @@
 	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
@@ -50,6 +54,20 @@
 	return conn
 }
 
+func unsetModbusConnection(ipAddr string) {
+	_, ok := connectionManager.GetConnection(ipAddr)
+	if !ok {
+		return
+	}
+	connectionManager.RemoveConnection(ipAddr)
+	if handler != nil {
+		handler.Close()
+	}
+}
+
 func newGetModbusConnection(ipAddr string) modbus.Client {
-	return modbus.TCPClient(ipAddr)
+	handler = modbus.NewTCPClientHandler(ipAddr)
+	handler.Timeout = 10 * time.Second
+	handler.SlaveId = byte(conf.Conf.PLC.SlaveId)
+	return modbus.NewClient(handler)
 }

--
Gitblit v1.8.0