From a699ff979c84d024ca33fb1139224258f278319f Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期五, 20 十月 2023 11:32:23 +0800
Subject: [PATCH] debug
---
pkg/plc/plc4x.go | 32 +++++++++++++++++++++++++++-----
1 files changed, 27 insertions(+), 5 deletions(-)
diff --git a/pkg/plc/plc4x.go b/pkg/plc/plc4x.go
index 529c516..68562a6 100644
--- a/pkg/plc/plc4x.go
+++ b/pkg/plc/plc4x.go
@@ -30,7 +30,14 @@
defer cm.mu.Unlock()
conn, ok := cm.connections[address]
- return conn, ok
+ if !ok {
+ return nil, false
+ }
+ //if ok, _ := cm.CheckConnect(conn, time.Second); !ok {
+ // conn.Close()
+ //}
+
+ return conn, true
}
var connectionManager = newPlcConnectionManager()
@@ -41,17 +48,32 @@
cm.connections[address] = connection
}
+
+func (cm *ConnectionManager) CheckConnect(conn plc4go.PlcConnection, timeout time.Duration) (bool, error) {
+ pingCh := conn.Ping()
+ timer := time.NewTimer(timeout)
+
+ select {
+ case err := <-pingCh:
+ if err == nil {
+ return true, nil
+ }
+ return false, err.GetErr()
+ case <-timer.C:
+ return false, fmt.Errorf("connection timed out after %s", timeout)
+ }
+}
+
func GetModbusConnection(ipAddr string) (plc4go.PlcConnection, error) {
if conn, ok := connectionManager.GetConnection(ipAddr); ok {
- if conn.IsConnected() {
- return conn, nil
- }
+ return conn, nil
}
// 鍒涘缓涓�涓笂涓嬫枃锛屽苟璁剧疆 3 绉掕秴鏃�
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
conn, err := newGetModbusConnection(ctx, ipAddr)
if err != nil {
+ logx.Errorf("new modbus connection err: %v", err.Error())
return nil, err
}
connectionManager.AddConnection(ipAddr, conn)
--
Gitblit v1.8.0