From 23a92b7802357da7650c7362fb4dd1b029123aa5 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期一, 18 九月 2023 19:28:05 +0800
Subject: [PATCH] 新库使用短连接

---
 api/v1/plc.go                         |    2 +-
 service/plc.go                        |   10 ++++++++++
 conf/config.go                        |    1 +
 conf/apsClient.json                   |    3 ++-
 pkg/plc/modbusx/connection_manager.go |    7 ++++++-
 5 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/api/v1/plc.go b/api/v1/plc.go
index 8a2baf8..6a6392f 100644
--- a/api/v1/plc.go
+++ b/api/v1/plc.go
@@ -36,7 +36,7 @@
 	resp.TotalNumber = cast.ToInt(totalNumber)
 
 	plcStatus := 1 //鏂紑杩炴帴
-	isConnect := apacheplc4x.IsConnect()
+	isConnect := service.PlcIsConnect()
 	if isConnect {
 		if resp.FinishNumber > 0 { //鐢熶骇
 			plcStatus = 2
diff --git a/conf/apsClient.json b/conf/apsClient.json
index 64f6ab7..d24e60f 100644
--- a/conf/apsClient.json
+++ b/conf/apsClient.json
@@ -33,7 +33,8 @@
     "totalNumberTimeInterval": 0,
     "modbusIntType": "DINT",
     "slaveId": 0,
-    "package": "goburrow"
+    "package": "goburrow",
+    "keepAlive": "false"
   }
 }
 
diff --git a/conf/config.go b/conf/config.go
index 4307f1f..d18e32e 100644
--- a/conf/config.go
+++ b/conf/config.go
@@ -73,6 +73,7 @@
 		ModbusIntType            string
 		SlaveId                  int
 		Package                  string
+		KeepAlive                bool
 	}
 
 	config struct {
diff --git a/pkg/plc/modbusx/connection_manager.go b/pkg/plc/modbusx/connection_manager.go
index 0aef49b..ae0b377 100644
--- a/pkg/plc/modbusx/connection_manager.go
+++ b/pkg/plc/modbusx/connection_manager.go
@@ -12,6 +12,8 @@
 	mu          sync.Mutex
 }
 
+var handler *modbus.TCPClientHandler
+
 func newPlcConnectionManager() *ConnectionManager {
 	return &ConnectionManager{
 		connections: make(map[string]modbus.Client),
@@ -58,10 +60,13 @@
 		return
 	}
 	connectionManager.RemoveConnection(ipAddr)
+	if handler != nil {
+		handler.Close()
+	}
 }
 
 func newGetModbusConnection(ipAddr string) modbus.Client {
-	handler := modbus.NewTCPClientHandler(ipAddr)
+	handler = modbus.NewTCPClientHandler(ipAddr)
 	handler.Timeout = 10 * time.Second
 	handler.SlaveId = byte(conf.Conf.PLC.SlaveId)
 	return modbus.NewClient(handler)
diff --git a/service/plc.go b/service/plc.go
index b86c091..ec7c795 100644
--- a/service/plc.go
+++ b/service/plc.go
@@ -163,3 +163,13 @@
 		return modbusx.Write(ipAddr, uint16(address), cast.ToInt(value))
 	}
 }
+
+func PlcIsConnect() bool {
+	if conf.Conf.PLC.Package == constvar.PlcPackageApache {
+		return apacheplc4x.IsConnect()
+	} else if conf.Conf.PLC.Package == constvar.PlcPackageApacheLongConnection {
+		return false
+	} else {
+		return modbusx.IsConnect()
+	}
+}

--
Gitblit v1.8.0