This repository has been archived by the owner on Mar 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
tcp_test.go
87 lines (74 loc) · 1.82 KB
/
tcp_test.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package modbus
import (
"reflect"
"testing"
"time"
)
const (
testslaveID1 = 0x01
testslaveID2 = 0x02
)
func Test_TCPClientWithServer(t *testing.T) {
t.Run("", func(t *testing.T) {
mbSrv := NewTCPServer()
mbSrv.AddNodes(NewNodeRegister(testslaveID1,
0, 10, 0, 10,
0, 10, 0, 10),
NewNodeRegister(testslaveID2,
0, 10, 0, 10,
0, 10, 0, 10))
_, err := mbSrv.GetNode(testslaveID2)
if err != nil {
t.Errorf("GetNode(%#v) error = %v, wantErr %v", testslaveID2, err, nil)
return
}
list := mbSrv.GetNodeList()
if list == nil {
t.Errorf("GetNodeList() should not nil")
return
}
mbSrv.DeleteNode(testslaveID2)
_, err = mbSrv.GetNode(testslaveID2)
if err == nil {
t.Errorf("GetNode(%#v) error = %v, wantErr %v", testslaveID2, err, "slaveID not exist")
return
}
go func() {
_ = mbSrv.ListenAndServe("localhost:48091")
}()
time.Sleep(time.Second) // wait for server start
mbPro := NewTCPClientProvider("localhost:48091")
mbCli := NewClient(mbPro)
err = mbCli.Connect()
if err != nil {
t.Errorf("Connect error = %v, wantErr %v", err, nil)
return
}
result, err := mbCli.ReadCoils(testslaveID1, 0, 10)
if err != nil {
t.Errorf("ReadCoils error = %v, wantErr %v", err, nil)
return
}
if !reflect.DeepEqual(result, []byte{0x00, 0x00}) {
t.Errorf("ReadCoils result = %#v, want %#v", result, []byte{0x00, 0x00})
}
if !mbCli.IsConnected() {
t.Errorf("client IsConnected() = %v, want %v", false, true)
return
}
err = mbCli.Close()
if err != nil {
t.Errorf("client Close() error = %v, wantErr %v", err, nil)
return
}
if mbCli.IsConnected() {
t.Errorf("client IsConnected() = %v, want %v", true, false)
return
}
err = mbSrv.Close()
if err != nil {
t.Errorf("server Close() error = %v, wantErr %v", err, nil)
return
}
})
}