-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrtu.go
More file actions
168 lines (152 loc) · 4.12 KB
/
Copy pathrtu.go
File metadata and controls
168 lines (152 loc) · 4.12 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package modbus
import (
"encoding/binary"
"fmt"
"io"
"time"
)
const (
rtuMinSize = 4
rtuMaxSize = 256
rtuExceptionSize = 5
)
// RTUPackager implements Packager interface.
type RTUPackager struct {
}
// Encode encodes PDU in a RTU frame:
// Slave Address : 1 byte
// Function : 1 byte
// Data : 0 up to 252 bytes
// CRC : 2 byte
func (rtu *RTUPackager) Encode(slaveID byte, pdu *ProtocolDataUnit) (adu []byte, err error) {
length := len(pdu.Data) + 4
if length > rtuMaxSize {
err = fmt.Errorf("modbus: length of data '%v' must not be bigger than '%v'", length, rtuMaxSize)
return
}
adu = make([]byte, length)
adu[0] = slaveID
adu[1] = pdu.FunctionCode
copy(adu[2:], pdu.Data)
// Append crc
var crc crc
crc.reset().pushBytes(adu[0 : length-2])
checksum := crc.value()
adu[length-1] = byte(checksum >> 8)
adu[length-2] = byte(checksum)
return
}
// Verify verifies response length and slave id.
func (rtu *RTUPackager) Verify(aduRequest []byte, aduResponse []byte) (err error) {
length := len(aduResponse)
// Minimum size (including address, function and CRC)
if length < rtuMinSize {
err = fmt.Errorf("modbus: response length '%v' does not meet minimum '%v'", length, rtuMinSize)
return
}
// Slave address must match
if aduResponse[0] != aduRequest[0] {
err = fmt.Errorf("modbus: response slave id '%v' does not match request '%v'", aduResponse[0], aduRequest[0])
return
}
return
}
// Decode extracts PDU from RTU frame and verify CRC.
func (rtu *RTUPackager) Decode(adu []byte) (pdu *ProtocolDataUnit, err error) {
length := len(adu)
// Calculate checksum
var crc crc
crc.reset().pushBytes(adu[0 : length-2])
checksum := uint16(adu[length-1])<<8 | uint16(adu[length-2])
if checksum != crc.value() {
err = fmt.Errorf("modbus: response crc '%v' does not match expected '%v'", checksum, crc.value())
return
}
// Function code & data
pdu = &ProtocolDataUnit{}
pdu.FunctionCode = adu[1]
pdu.Data = adu[2 : length-2]
return
}
func (rtu *RTUPackager) transceive(transporter Transporter, logger Logger, aduRequest []byte, timeout time.Duration) (aduResponse []byte, err error) {
// make sure port is connected
err = transporter.Connect()
if err != nil {
return
}
// Set write and read timeout
if timeout > 0 {
if err = transporter.SetReadTimeout(timeout); err != nil {
return
}
}
// Send the request
log(logger, "modbus: sending % x\n", aduRequest)
if _, err = transporter.Write(aduRequest); err != nil {
return
}
function := aduRequest[1]
functionFail := aduRequest[1] & 0x80
bytesToRead := calculateResponseLength(aduRequest)
var n int
var n1 int
var data [rtuMaxSize]byte
//We first read the minimum length and then read either the full package
//or the error package, depending on the error status (byte 2 of the response)
n, err = io.ReadAtLeast(transporter, data[:], rtuMinSize)
if err != nil {
return
}
//if the function is correct
if data[1] == function {
//we read the rest of the bytes
if n < bytesToRead {
if bytesToRead > rtuMinSize && bytesToRead <= rtuMaxSize {
if bytesToRead > n {
n1, err = io.ReadFull(transporter, data[n:bytesToRead])
n += n1
}
}
}
} else if data[1] == functionFail {
//for error we need to read 5 bytes
if n < rtuExceptionSize {
n1, err = io.ReadFull(transporter, data[n:rtuExceptionSize])
}
n += n1
}
if err != nil {
return
}
aduResponse = data[:n]
log(logger, "modbus: received % x\n", aduResponse)
return
}
func calculateResponseLength(adu []byte) int {
length := rtuMinSize
switch adu[1] {
case FuncCodeReadDiscreteInputs,
FuncCodeReadCoils:
count := int(binary.BigEndian.Uint16(adu[4:]))
length += 1 + count/8
if count%8 != 0 {
length++
}
case FuncCodeReadInputRegisters,
FuncCodeReadHoldingRegisters,
FuncCodeReadWriteMultipleRegisters:
count := int(binary.BigEndian.Uint16(adu[4:]))
length += 1 + count*2
case FuncCodeWriteSingleCoil,
FuncCodeWriteMultipleCoils,
FuncCodeWriteSingleRegister,
FuncCodeWriteMultipleRegisters:
length += 4
case FuncCodeMaskWriteRegister:
length += 6
case FuncCodeReadFIFOQueue:
// undetermined
default:
}
return length
}