zhangqian
2023-08-25 30eaec8c41e167b0d5527dbcc987fba222f31b93
连接plc5秒超时
3个文件已修改
43 ■■■■■ 已修改文件
datafile/plc_address_key 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
datafile/plc_address_value 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pkg/plc/plc4x.go 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
datafile/plc_address_key
@@ -0,0 +1,3 @@
压强
时间
温度
datafile/plc_address_value
@@ -0,0 +1,3 @@
1000
1001
1002
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)