From 915253f87d4ef04d886bebb50135d75082ae0eee Mon Sep 17 00:00:00 2001 From: zhangqian <zhangqian@123.com> Date: 星期五, 15 九月 2023 13:37:22 +0800 Subject: [PATCH] 换一种方式检查plc连接 --- pkg/plc/plc4x.go | 35 ++++++++++++++++++++++++++++++----- 1 files changed, 30 insertions(+), 5 deletions(-) diff --git a/pkg/plc/plc4x.go b/pkg/plc/plc4x.go index 529c516..06f6c8e 100644 --- a/pkg/plc/plc4x.go +++ b/pkg/plc/plc4x.go @@ -30,7 +30,18 @@ defer cm.mu.Unlock() conn, ok := cm.connections[address] - return conn, ok + if !ok { + return nil, false + } + connOK, err := cm.CheckConnect(conn, time.Second*1) + if err != nil { + logx.Errorf("ping plc err:%v", err.Error()) + return nil, false + } + if connOK { + return conn, ok + } + return nil, false } var connectionManager = newPlcConnectionManager() @@ -41,14 +52,28 @@ 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 { -- Gitblit v1.8.0