From 30eaec8c41e167b0d5527dbcc987fba222f31b93 Mon Sep 17 00:00:00 2001
From: zhangqian <zhangqian@123.com>
Date: 星期五, 25 八月 2023 20:16:27 +0800
Subject: [PATCH] 连接plc5秒超时
---
pkg/plc/plc4x.go | 37 +++++++++++++++++++++++--------------
datafile/plc_address_value | 3 +++
datafile/plc_address_key | 3 +++
3 files changed, 29 insertions(+), 14 deletions(-)
diff --git a/datafile/plc_address_key b/datafile/plc_address_key
index e69de29..83130ac 100644
--- a/datafile/plc_address_key
+++ b/datafile/plc_address_key
@@ -0,0 +1,3 @@
+鍘嬪己
+鏃堕棿
+娓╁害
\ No newline at end of file
diff --git a/datafile/plc_address_value b/datafile/plc_address_value
index e69de29..3a9e4ec 100644
--- a/datafile/plc_address_value
+++ b/datafile/plc_address_value
@@ -0,0 +1,3 @@
+1000
+1001
+1002
\ No newline at end of file
diff --git a/pkg/plc/plc4x.go b/pkg/plc/plc4x.go
index e269e58..e291148 100644
--- a/pkg/plc/plc4x.go
+++ b/pkg/plc/plc4x.go
@@ -1,10 +1,10 @@
package plc
import (
+ "context"
"errors"
"fmt"
apiModel "github.com/apache/plc4x/plc4go/pkg/api/model"
- "github.com/apache/plc4x/plc4go/spi/options"
"sync"
"time"
@@ -46,13 +46,22 @@
return conn, nil
}
}
+ // 鍒涘缓涓�涓笂涓嬫枃锛屽苟璁剧疆 5 绉掕秴鏃�
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ conn, err := NewGetModbusConnection(ctx, ipAddr)
+ if err != nil {
+ return nil, err
+ }
+ connectionManager.AddConnection(ipAddr, conn)
+ return conn, nil
+}
+func NewGetModbusConnection(ctx context.Context, ipAddr string) (plc4go.PlcConnection, error) {
// 鍒涘缓椹卞姩绠$悊鍣�
- option := options.WithReceiveTimeout(time.Second * 5) //浜旂瓒呮椂
- driverManager := plc4go.NewPlcDriverManager(option)
+ driverManager := plc4go.NewPlcDriverManager()
// 娉ㄥ唽TCP浼犺緭
transports.RegisterTcpTransport(driverManager)
-
// 娉ㄥ唽椹卞姩
//drivers.RegisterKnxDriver(driverManager)
drivers.RegisterModbusTcpDriver(driverManager)
@@ -61,18 +70,18 @@
connectionString := fmt.Sprintf("modbus-tcp://%s", ipAddr)
connectionRequestChanel := driverManager.GetConnection(connectionString)
- // 绛夊緟杩炴帴鍝嶅簲
- connectionResult := <-connectionRequestChanel
-
- // 鍒ゆ柇鏄惁杩炴帴鎴愬姛
- if err := connectionResult.GetErr(); err != nil {
- return nil, err
+ // 绛夊緟杩炴帴鍝嶅簲锛屽悓鏃惰�冭檻涓婁笅鏂囩殑瓒呮椂
+ select {
+ case connectionResult := <-connectionRequestChanel:
+ if err := connectionResult.GetErr(); err != nil {
+ return nil, err
+ }
+ return connectionResult.GetConnection(), nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
}
-
- conn := connectionResult.GetConnection()
- connectionManager.AddConnection(ipAddr, conn)
- return conn, nil
}
+
func ReadHoldingRegisterSingle(connection plc4go.PlcConnection, address int) ([]byte, error) {
tagAddress := fmt.Sprintf("holding-register:%d:UINT", address)
--
Gitblit v1.8.0