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/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