-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmodbus.go
73 lines (61 loc) · 1.59 KB
/
modbus.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"github.com/TwiN/go-color"
"github.com/simonvetter/modbus"
"time"
)
func setupModbusClient(host string, port int, timeout time.Duration) (*modbus.ModbusClient, error) {
client, err := modbus.NewClient(&modbus.ClientConfiguration{
URL: fmt.Sprintf("tcp://%s:%d", host, port),
Timeout: timeout,
})
if err != nil {
if *verbose {
fmt.Printf(color.Ize(color.Red, "[Verbose] Error creating Modbus client: %s\n"), err)
}
return nil, err
}
err = client.Open()
if err != nil {
if *verbose {
fmt.Printf(color.Ize(color.Red, "[Verbose] Error opening Modbus connection: %s\n"), err)
}
return nil, err
}
if *verbose {
fmt.Printf(color.Ize(color.Green, "[Verbose] Successfully connected to Modbus server at %s:%d\n"), host, port)
}
return client, nil
}
func sendModbusRequest(client *modbus.ModbusClient, step Step) (string, error) {
var response string
if step.InputType == "hex" {
address, err := hexStringToUint16(step.Input)
if err != nil {
return "", err
}
var value uint16
value, err = client.ReadRegister(address, modbus.HOLDING_REGISTER)
if err != nil {
if *verbose {
fmt.Printf(color.Ize(color.Red, "[Verbose] Error reading Modbus register: %s\n"), err)
}
return "", err
}
response = fmt.Sprintf("%v", value)
} else {
}
if *verbose {
fmt.Printf(color.Ize(color.Green, "[Verbose] Modbus response: %s\n"), response)
}
return response, nil
}
func hexStringToUint16(hexStr string) (uint16, error) {
var value uint16
_, err := fmt.Sscanf(hexStr, "%x", &value)
if err != nil {
return 0, err
}
return value, nil
}