Debian Codegraph @

rtuclient_test.go

raw symbols SCIP
1 // Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
2 // This software may be modified and distributed under the terms
3 // of the BSD license. See the LICENSE file for details.
4
5 package modbus
6
7 import (
8 "bytes"
9 "testing"
10 )
11
12 func TestRTUEncoding(t *testing.T) {
13 encoder := rtuPackager{}
14 encoder.SlaveId = 0x01
15
16 pdu := ProtocolDataUnit{}
17 pdu.FunctionCode = 0x03
18 pdu.Data = []byte{0x50, 0x00, 0x00, 0x18}
19
20 adu, err := encoder.Encode(&pdu)
21 if err != nil {
22 t.Fatal(err)
23 }
24 expected := []byte{0x01, 0x03, 0x50, 0x00, 0x00, 0x18, 0x54, 0xC0}
25 if !bytes.Equal(expected, adu) {
26 t.Fatalf("adu: expected %v, actual %v", expected, adu)
27 }
28 }
29
30 func TestRTUDecoding(t *testing.T) {
31 decoder := rtuPackager{}
32 adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
33
34 pdu, err := decoder.Decode(adu)
35 if err != nil {
36 t.Fatal(err)
37 }
38
39 if 16 != pdu.FunctionCode {
40 t.Fatalf("Function code: expected %v, actual %v", 16, pdu.FunctionCode)
41 }
42 expected := []byte{0x8A, 0x00, 0x00, 0x03}
43 if !bytes.Equal(expected, pdu.Data) {
44 t.Fatalf("Data: expected %v, actual %v", expected, pdu.Data)
45 }
46 }
47
48 var responseLengthTests = []struct {
49 adu []byte
50 length int
51 }{
52 {[]byte{4, 1, 0, 0xA, 0, 0xD, 0xDD, 0x98}, 7},
53 {[]byte{4, 2, 0, 0xA, 0, 0xD, 0x99, 0x98}, 7},
54 {[]byte{1, 3, 0, 0, 0, 2, 0xC4, 0xB}, 9},
55 {[]byte{0x11, 5, 0, 0xAC, 0xFF, 0, 0x4E, 0x8B}, 8},
56 {[]byte{0x11, 6, 0, 1, 0, 3, 0x9A, 0x9B}, 8},
57 {[]byte{0x11, 0xF, 0, 0x13, 0, 0xA, 2, 0xCD, 1, 0xBF, 0xB}, 8},
58 {[]byte{0x11, 0x10, 0, 1, 0, 2, 4, 0, 0xA, 1, 2, 0xC6, 0xF0}, 8},
59 }
60
61 func TestCalculateResponseLength(t *testing.T) {
62 for _, input := range responseLengthTests {
63 output := calculateResponseLength(input.adu)
64 if output != input.length {
65 t.Errorf("Response length of %x: expected %v, actual: %v",
66 input.adu, input.length, output)
67 }
68 }
69 }
70
71 func BenchmarkRTUEncoder(b *testing.B) {
72 encoder := rtuPackager{
73 SlaveId: 10,
74 }
75 pdu := ProtocolDataUnit{
76 FunctionCode: 1,
77 Data: []byte{2, 3, 4, 5, 6, 7, 8, 9},
78 }
79 for i := 0; i < b.N; i++ {
80 _, err := encoder.Encode(&pdu)
81 if err != nil {
82 b.Fatal(err)
83 }
84 }
85 }
86
87 func BenchmarkRTUDecoder(b *testing.B) {
88 decoder := rtuPackager{
89 SlaveId: 10,
90 }
91 adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
92 for i := 0; i < b.N; i++ {
93 _, err := decoder.Decode(adu)
94 if err != nil {
95 b.Fatal(err)
96 }
97 }
98 }