forked from goburrow/modbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
494 lines (472 loc) · 14.8 KB
/
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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
// This software may be modified and distributed under the terms
// of the BSD license. See the LICENSE file for details.
package modbus
import (
"encoding/binary"
"fmt"
)
// ClientHandler is the interface that groups the Packager and Transporter methods.
type ClientHandler interface {
Packager
Transporter
}
type client struct {
packager Packager
transporter Transporter
}
// NewClient creates a new modbus client with given backend handler.
func NewClient(handler ClientHandler) Client {
return &client{packager: handler, transporter: handler}
}
// NewClient2 creates a new modbus client with given backend packager and transporter.
func NewClient2(packager Packager, transporter Transporter) Client {
return &client{packager: packager, transporter: transporter}
}
// Request:
// Function code : 1 byte (0x01)
// Starting address : 2 bytes
// Quantity of coils : 2 bytes
// Response:
// Function code : 1 byte (0x01)
// Byte count : 1 byte
// Coil status : N* bytes (=N or N+1)
func (mb *client) ReadCoils(address, quantity uint16) (results []byte, err error) {
if quantity < 1 || quantity > 2000 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 2000)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadCoils,
Data: dataBlock(address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
count := int(response.Data[0])
length := len(response.Data) - 1
if count != length {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", length, count)
return
}
results = response.Data[1:]
return
}
// Request:
// Function code : 1 byte (0x02)
// Starting address : 2 bytes
// Quantity of inputs : 2 bytes
// Response:
// Function code : 1 byte (0x02)
// Byte count : 1 byte
// Input status : N* bytes (=N or N+1)
func (mb *client) ReadDiscreteInputs(address, quantity uint16) (results []byte, err error) {
if quantity < 1 || quantity > 2000 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 2000)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadDiscreteInputs,
Data: dataBlock(address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
count := int(response.Data[0])
length := len(response.Data) - 1
if count != length {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", length, count)
return
}
results = response.Data[1:]
return
}
// Request:
// Function code : 1 byte (0x03)
// Starting address : 2 bytes
// Quantity of registers : 2 bytes
// Response:
// Function code : 1 byte (0x03)
// Byte count : 1 byte
// Register value : Nx2 bytes
func (mb *client) ReadHoldingRegisters(address, quantity uint16) (results []byte, err error) {
if quantity < 1 || quantity > 125 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 125)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadHoldingRegisters,
Data: dataBlock(address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
count := int(response.Data[0])
length := len(response.Data) - 1
if count != length {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", length, count)
return
}
results = response.Data[1:]
return
}
// Request:
// Function code : 1 byte (0x04)
// Starting address : 2 bytes
// Quantity of registers : 2 bytes
// Response:
// Function code : 1 byte (0x04)
// Byte count : 1 byte
// Input registers : N bytes
func (mb *client) ReadInputRegisters(address, quantity uint16) (results []byte, err error) {
if quantity < 1 || quantity > 125 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 125)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadInputRegisters,
Data: dataBlock(address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
count := int(response.Data[0])
length := len(response.Data) - 1
if count != length {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", length, count)
return
}
results = response.Data[1:]
return
}
// Request:
// Function code : 1 byte (0x05)
// Output address : 2 bytes
// Output value : 2 bytes
// Response:
// Function code : 1 byte (0x05)
// Output address : 2 bytes
// Output value : 2 bytes
func (mb *client) WriteSingleCoil(address, value uint16) (results []byte, err error) {
// The requested ON/OFF state can only be 0xFF00 and 0x0000
if value != 0xFF00 && value != 0x0000 {
err = fmt.Errorf("modbus: state '%v' must be either 0xFF00 (ON) or 0x0000 (OFF)", value)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeWriteSingleCoil,
Data: dataBlock(address, value),
}
response, err := mb.send(&request)
if err != nil {
return
}
// Fixed response length
if len(response.Data) != 4 {
err = fmt.Errorf("modbus: response data size '%v' does not match expected '%v'", len(response.Data), 4)
return
}
respValue := binary.BigEndian.Uint16(response.Data)
if address != respValue {
err = fmt.Errorf("modbus: response address '%v' does not match request '%v'", respValue, address)
return
}
results = response.Data[2:]
respValue = binary.BigEndian.Uint16(results)
if value != respValue {
err = fmt.Errorf("modbus: response value '%v' does not match request '%v'", respValue, value)
return
}
return
}
// Request:
// Function code : 1 byte (0x06)
// Register address : 2 bytes
// Register value : 2 bytes
// Response:
// Function code : 1 byte (0x06)
// Register address : 2 bytes
// Register value : 2 bytes
func (mb *client) WriteSingleRegister(address, value uint16) (results []byte, err error) {
request := ProtocolDataUnit{
FunctionCode: FuncCodeWriteSingleRegister,
Data: dataBlock(address, value),
}
response, err := mb.send(&request)
if err != nil {
return
}
// Fixed response length
if len(response.Data) != 4 {
err = fmt.Errorf("modbus: response data size '%v' does not match expected '%v'", len(response.Data), 4)
return
}
respValue := binary.BigEndian.Uint16(response.Data)
if address != respValue {
err = fmt.Errorf("modbus: response address '%v' does not match request '%v'", respValue, address)
return
}
results = response.Data[2:]
respValue = binary.BigEndian.Uint16(results)
if value != respValue {
err = fmt.Errorf("modbus: response value '%v' does not match request '%v'", respValue, value)
return
}
return
}
// Request:
// Function code : 1 byte (0x0F)
// Starting address : 2 bytes
// Quantity of outputs : 2 bytes
// Byte count : 1 byte
// Outputs value : N* bytes
// Response:
// Function code : 1 byte (0x0F)
// Starting address : 2 bytes
// Quantity of outputs : 2 bytes
func (mb *client) WriteMultipleCoils(address, quantity uint16, value []byte) (results []byte, err error) {
if quantity < 1 || quantity > 1968 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 1968)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeWriteMultipleCoils,
Data: dataBlockSuffix(value, address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
// Fixed response length
if len(response.Data) != 4 {
err = fmt.Errorf("modbus: response data size '%v' does not match expected '%v'", len(response.Data), 4)
return
}
respValue := binary.BigEndian.Uint16(response.Data)
if address != respValue {
err = fmt.Errorf("modbus: response address '%v' does not match request '%v'", respValue, address)
return
}
results = response.Data[2:]
respValue = binary.BigEndian.Uint16(results)
if quantity != respValue {
err = fmt.Errorf("modbus: response quantity '%v' does not match request '%v'", respValue, quantity)
return
}
return
}
// Request:
// Function code : 1 byte (0x10)
// Starting address : 2 bytes
// Quantity of outputs : 2 bytes
// Byte count : 1 byte
// Registers value : N* bytes
// Response:
// Function code : 1 byte (0x10)
// Starting address : 2 bytes
// Quantity of registers : 2 bytes
func (mb *client) WriteMultipleRegisters(address, quantity uint16, value []byte) (results []byte, err error) {
if quantity < 1 || quantity > 123 {
err = fmt.Errorf("modbus: quantity '%v' must be between '%v' and '%v',", quantity, 1, 123)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeWriteMultipleRegisters,
Data: dataBlockSuffix(value, address, quantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
// Fixed response length
if len(response.Data) != 4 {
err = fmt.Errorf("modbus: response data size '%v' does not match expected '%v'", len(response.Data), 4)
return
}
respValue := binary.BigEndian.Uint16(response.Data)
if address != respValue {
err = fmt.Errorf("modbus: response address '%v' does not match request '%v'", respValue, address)
return
}
results = response.Data[2:]
respValue = binary.BigEndian.Uint16(results)
if quantity != respValue {
err = fmt.Errorf("modbus: response quantity '%v' does not match request '%v'", respValue, quantity)
return
}
return
}
// Request:
// Function code : 1 byte (0x16)
// Reference address : 2 bytes
// AND-mask : 2 bytes
// OR-mask : 2 bytes
// Response:
// Function code : 1 byte (0x16)
// Reference address : 2 bytes
// AND-mask : 2 bytes
// OR-mask : 2 bytes
func (mb *client) MaskWriteRegister(address, andMask, orMask uint16) (results []byte, err error) {
request := ProtocolDataUnit{
FunctionCode: FuncCodeMaskWriteRegister,
Data: dataBlock(address, andMask, orMask),
}
response, err := mb.send(&request)
if err != nil {
return
}
// Fixed response length
if len(response.Data) != 6 {
err = fmt.Errorf("modbus: response data size '%v' does not match expected '%v'", len(response.Data), 6)
return
}
respValue := binary.BigEndian.Uint16(response.Data)
if address != respValue {
err = fmt.Errorf("modbus: response address '%v' does not match request '%v'", respValue, address)
return
}
respValue = binary.BigEndian.Uint16(response.Data[2:])
if andMask != respValue {
err = fmt.Errorf("modbus: response AND-mask '%v' does not match request '%v'", respValue, andMask)
return
}
respValue = binary.BigEndian.Uint16(response.Data[4:])
if orMask != respValue {
err = fmt.Errorf("modbus: response OR-mask '%v' does not match request '%v'", respValue, orMask)
return
}
results = response.Data[2:]
return
}
// Request:
// Function code : 1 byte (0x17)
// Read starting address : 2 bytes
// Quantity to read : 2 bytes
// Write starting address: 2 bytes
// Quantity to write : 2 bytes
// Write byte count : 1 byte
// Write registers value : N* bytes
// Response:
// Function code : 1 byte (0x17)
// Byte count : 1 byte
// Read registers value : Nx2 bytes
func (mb *client) ReadWriteMultipleRegisters(readAddress, readQuantity, writeAddress, writeQuantity uint16, value []byte) (results []byte, err error) {
if readQuantity < 1 || readQuantity > 125 {
err = fmt.Errorf("modbus: quantity to read '%v' must be between '%v' and '%v',", readQuantity, 1, 125)
return
}
if writeQuantity < 1 || writeQuantity > 121 {
err = fmt.Errorf("modbus: quantity to write '%v' must be between '%v' and '%v',", writeQuantity, 1, 121)
return
}
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadWriteMultipleRegisters,
Data: dataBlockSuffix(value, readAddress, readQuantity, writeAddress, writeQuantity),
}
response, err := mb.send(&request)
if err != nil {
return
}
count := int(response.Data[0])
if count != (len(response.Data) - 1) {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", len(response.Data)-1, count)
return
}
results = response.Data[1:]
return
}
// Request:
// Function code : 1 byte (0x18)
// FIFO pointer address : 2 bytes
// Response:
// Function code : 1 byte (0x18)
// Byte count : 2 bytes
// FIFO count : 2 bytes
// FIFO count : 2 bytes (<=31)
// FIFO value register : Nx2 bytes
func (mb *client) ReadFIFOQueue(address uint16) (results []byte, err error) {
request := ProtocolDataUnit{
FunctionCode: FuncCodeReadFIFOQueue,
Data: dataBlock(address),
}
response, err := mb.send(&request)
if err != nil {
return
}
if len(response.Data) < 4 {
err = fmt.Errorf("modbus: response data size '%v' is less than expected '%v'", len(response.Data), 4)
return
}
count := int(binary.BigEndian.Uint16(response.Data))
if count != (len(response.Data) - 1) {
err = fmt.Errorf("modbus: response data size '%v' does not match count '%v'", len(response.Data)-1, count)
return
}
count = int(binary.BigEndian.Uint16(response.Data[2:]))
if count > 31 {
err = fmt.Errorf("modbus: fifo count '%v' is greater than expected '%v'", count, 31)
return
}
results = response.Data[4:]
return
}
// Helpers
// send sends request and checks possible exception in the response.
func (mb *client) send(request *ProtocolDataUnit) (response *ProtocolDataUnit, err error) {
aduRequest, err := mb.packager.Encode(request)
if err != nil {
return
}
aduResponse, err := mb.transporter.Send(aduRequest)
if err != nil {
return
}
if err = mb.packager.Verify(aduRequest, aduResponse); err != nil {
return
}
response, err = mb.packager.Decode(aduResponse)
if err != nil {
return
}
// Check correct function code returned (exception)
if response.FunctionCode != request.FunctionCode {
err = responseError(response)
return
}
if response.Data == nil || len(response.Data) == 0 {
// Empty response
err = fmt.Errorf("modbus: response data is empty")
return
}
return
}
// dataBlock creates a sequence of uint16 data.
func dataBlock(value ...uint16) []byte {
data := make([]byte, 2*len(value))
for i, v := range value {
binary.BigEndian.PutUint16(data[i*2:], v)
}
return data
}
// dataBlockSuffix creates a sequence of uint16 data and append the suffix plus its length.
func dataBlockSuffix(suffix []byte, value ...uint16) []byte {
length := 2 * len(value)
data := make([]byte, length+1+len(suffix))
for i, v := range value {
binary.BigEndian.PutUint16(data[i*2:], v)
}
data[length] = uint8(len(suffix))
copy(data[length+1:], suffix)
return data
}
func responseError(response *ProtocolDataUnit) error {
mbError := &MbError{FunctionCode: response.FunctionCode}
if response.Data != nil && len(response.Data) > 0 {
mbError.ExceptionCode = response.Data[0]
}
return mbError
}