| | |
| | | "github.com/apache/plc4x/plc4go/pkg/api/transports" |
| | | ) |
| | | |
| | | func NewModbusConnection(ipAddr string) (error, plc4go.PlcConnection) { |
| | | func NewModbusConnection(ipAddr string) (plc4go.PlcConnection, error) { |
| | | // 创建驱动管理器 |
| | | driverManager := plc4go.NewPlcDriverManager() |
| | | |
| | |
| | | |
| | | // 判断是否连接成功 |
| | | if err := connectionResult.GetErr(); err != nil { |
| | | return err, nil |
| | | return nil, err |
| | | } |
| | | |
| | | return nil, connectionResult.GetConnection() |
| | | return connectionResult.GetConnection(), nil |
| | | } |
| | | |
| | | func ReadHoldingRegister(connection plc4go.PlcConnection, address int) (error, []byte) { |
| | | func ReadHoldingRegister(connection plc4go.PlcConnection, address int) ([]byte, error) { |
| | | tagAddress := fmt.Sprintf("holding-register:%d:DINT", address) |
| | | |
| | | // 读模式 |
| | | readRequest, err := connection.ReadRequestBuilder().AddTagAddress("tag", tagAddress).Build() |
| | | if err != nil { |
| | | fmt.Printf("Error preparing read-request:%s\n", err.Error()) |
| | | return err, nil |
| | | return nil, err |
| | | } |
| | | |
| | | // 执行 |
| | | readResult := <-readRequest.Execute() |
| | | if err := readResult.GetErr(); err != nil { |
| | | fmt.Printf("Error execting read-request:%s\n", err.Error()) |
| | | return err, nil |
| | | return nil, err |
| | | } |
| | | |
| | | // 判断响应码是否正确 |
| | | if readResult.GetResponse().GetResponseCode("tag") != apiModel.PlcResponseCode_OK { |
| | | fmt.Printf("error an non-ok return code: %s", readResult.GetResponse().GetResponseCode("tag").GetName()) |
| | | return err, nil |
| | | return nil, err |
| | | } |
| | | |
| | | value := readResult.GetResponse().GetValue("tag") |
| | | |
| | | return nil, value.GetRaw() |
| | | return value.GetRaw(), err |
| | | |
| | | } |