forked from btfak/modbus
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathtcp-client.go
61 lines (51 loc) · 1.79 KB
/
tcp-client.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
package main
import (
"flag"
"fmt"
"github.com/dpapathanasiou/go-modbus"
"log"
)
func main() {
// get device host (url or ip address) and port from the command line
var (
host string
port int
)
const (
defaultHost = "127.0.0.1"
defaultPort = modbusclient.MODBUS_PORT
)
flag.StringVar(&host, "host", defaultHost, "Slave device host (url or ip address)")
flag.IntVar(&port, "port", defaultPort, fmt.Sprintf("Slave device port (the default is %d)", defaultPort))
flag.Parse()
// turn on the debug trace option, to see what is being transmitted
trace := true
conn, cerr := modbusclient.ConnectTCP(host, port)
if cerr != nil {
log.Println(fmt.Sprintf("Connection error: %s", cerr))
} else {
// attempt to read one (0x01) holding registers starting at address 200
readData := make([]byte, 3)
readData[0] = byte(200 >> 8) // (High Byte)
readData[1] = byte(200 & 0xff) // (Low Byte)
readData[2] = 0x01
// make this read request transaction id 1, with a 300 millisecond tcp timeout
readResult, readErr := modbusclient.TCPRead(conn, 300, 1, modbusclient.FUNCTION_READ_HOLDING_REGISTERS, false, 0x00, readData, trace)
if readErr != nil {
log.Println(readErr)
}
log.Println(readResult)
// attempt to write to a single coil at address 300
writeData := make([]byte, 3)
writeData[0] = byte(300 >> 8) // (High Byte)
writeData[1] = byte(300 & 0xff) // (Low Byte)
writeData[2] = 0xff // 0xff turns the coil on; 0x00 turns the coil off
// make this read request transaction id 2, with a 300 millisecond tcp timeout
writeResult, writeErr := modbusclient.TCPWrite(conn, 300, 2, modbusclient.FUNCTION_WRITE_SINGLE_COIL, false, 0x00, writeData, trace)
if writeErr != nil {
log.Println(writeErr)
}
log.Println(writeResult)
modbusclient.DisconnectTCP(conn)
}
}