/
ModbusRTUConnection.go
451 lines (384 loc) · 11.4 KB
/
ModbusRTUConnection.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
package main
/*
#include <modbus.h>
#include <errno.h>
int getErrno() {
return errno;
}
*/
import "C"
import (
"errors"
"fmt"
"log"
"math"
"regexp"
"runtime"
"strconv"
"time"
"unsafe"
)
const (
str_ModbusRTU = "ModbusRTU"
RTU_CONST_FIELDS_LEN = 4
RTU_01_LEN = 4
RTU_02_LEN = RTU_01_LEN
RTU_03_LEN = RTU_01_LEN
RTU_05_LEN = 4
RTU_06_LEN = RTU_05_LEN
RTU_0F_LEN = 5
RTU_10_LEN = RTU_0F_LEN
)
var parser = regexp.MustCompile(`(\d)([A-Z])(\d)`)
var index = 0
type ioCtlHook interface {
OnStartTransmitting()
OnEndTransmitting()
}
type ModbusRTUConnection struct {
Connection
id int
deviceName string
speed int
serialMode string
attachedDevices [](*ModbusRTUDevice)
hook ioCtlHook
ctx *C.modbus_t
rwCtlChan chan int
}
var ModbusRTUConnections [](*ModbusRTUConnection)
func NewModbusRTUConnection(DeviceName string,
Speed int, SerialMode string, Hook ioCtlHook) (*ModbusRTUConnection, error) {
// is allready opened?
for _, connection := range ModbusRTUConnections {
if connection.Device() == DeviceName {
if connection.serialMode == SerialMode {
return connection, nil
} else {
return nil, errors.New(
fmt.Sprintf("Device '%s' used by connection %d, mode '%s'",
DeviceName, connection.ID(), connection.serialMode))
}
}
}
result := &ModbusRTUConnection{deviceName: DeviceName, speed: Speed,
serialMode: SerialMode, hook: Hook}
if Hook != nil {
result.rwCtlChan = make(chan int)
go func(oneByteTime time.Duration) {
for v := range result.rwCtlChan {
if v < 0 {
break
}
result.hook.OnStartTransmitting()
time.Sleep(oneByteTime * time.Duration(v))
result.hook.OnEndTransmitting()
}
}(time.Duration(math.Ceil(float64(time.Second*(1+8+0+1)) / float64(result.speed))))
}
// try open
match := parser.FindStringSubmatch(result.serialMode)
if len(match) != (1 + 3) {
result.ctx = C.modbus_new_rtu(C.CString(result.deviceName), C.int(result.speed),
C.char('N'), C.int(8), C.int(1))
} else {
databits, _ := strconv.ParseInt(match[1+0], 10, 32)
stopbits, _ := strconv.ParseInt(match[1+2], 10, 32)
result.ctx = C.modbus_new_rtu(C.CString(result.deviceName), C.int(result.speed),
C.char(match[1+1][0]),
C.int(databits),
C.int(stopbits))
}
if result.ctx == nil {
return nil, errors.New(fmt.Sprintf("Unable to create the libmodbus context\n%s",
C.GoString(C.modbus_strerror(C.getErrno()))))
}
runtime.SetFinalizer(result, finaliserModbusRTUConnection)
result.id = index
index++
if len(ModbusRTUConnections) != 0 &&
ModbusRTUConnections[len(ModbusRTUConnections)-1] == nil {
for i := len(ModbusRTUConnections) - 1; i > -1; i-- {
if ModbusRTUConnections[i] != nil {
ModbusRTUConnections[i+1] = result
break
}
}
} else {
ModbusRTUConnections = append(ModbusRTUConnections, result)
}
return result, nil
}
func (this ModbusRTUConnection) ID() int {
return this.id
}
func (this ModbusRTUConnection) Type() string {
return str_Serial
}
func (this ModbusRTUConnection) Device() string {
return this.deviceName
}
func (this ModbusRTUConnection) Options() map[string]interface{} {
return map[string]interface{}{"speed": this.speed, "mode": this.serialMode}
}
func (this ModbusRTUConnection) Protocol() string {
return str_ModbusRTU
}
func (this ModbusRTUConnection) Status() int {
if len(this.attachedDevices) > 0 {
return Connection_used
} else {
return Connection_available
}
}
func (this ModbusRTUConnection) UsedBy() int {
return len(this.attachedDevices)
}
func finaliserModbusRTUConnection(obj *ModbusRTUConnection) {
log.Print("Cleaning libmodbus structure")
C.modbus_close(obj.ctx)
C.modbus_free(obj.ctx)
if obj.hook != nil {
obj.rwCtlChan <- (-1)
}
}
func (this ModbusRTUConnection) Timeout() time.Duration {
var sec, usec C.uint32_t
C.modbus_get_response_timeout(this.ctx, &sec, &usec)
return time.Duration(sec)*time.Second + time.Duration(usec)*time.Microsecond
}
func (this ModbusRTUConnection) SetTimeout(timeout time.Duration) error {
var sec C.uint32_t = C.uint32_t(timeout / time.Second)
var usec C.uint32_t = C.uint32_t((timeout - time.Duration(sec)) / time.Microsecond)
if C.modbus_set_response_timeout(this.ctx, sec, usec) == -1 {
return errors.New("Invalid timeout value")
}
return nil
}
func (this ModbusRTUConnection) SetDebug(flag bool) {
var f C.int = 0
if flag {
f = 1
}
C.modbus_set_debug(this.ctx, f)
}
func (this ModbusRTUConnection) ProcessHook(messageLen int) {
messageLen += RTU_CONST_FIELDS_LEN
this.rwCtlChan <- messageLen
}
func (this ModbusRTUConnection) ReadCoils(slave int8, startAddr int, nb int) ([]bool, error) {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return nil, errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
var space [65535]C.uint8_t
this.ProcessHook(RTU_01_LEN)
if ressived := C.modbus_read_bits(this.ctx, C.int(startAddr), C.int(nb),
&(space[0])); int(ressived) != nb {
if ressived == -1 {
errno := C.getErrno()
if errno == C.EMBMDATA {
return nil, errors.New(C.GoString(C.modbus_strerror(errno)))
}
return nil, errors.New(fmt.Sprintf("Unknown modbus error errno=%d", errno))
} else if ressived == 0 {
return nil, errors.New("No ansver ressived")
}
} else {
result := make([]bool, ressived)
for i := 0; i < int(ressived); i++ {
if space[i] != C.FALSE {
result[i] = true
}
}
return result, nil
}
return nil, nil
}
func (this ModbusRTUConnection) ReadInputBits(slave int8, startAddr int, nb int) ([]bool, error) {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return nil, errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
var space [65535]C.uint8_t
this.ProcessHook(RTU_02_LEN)
if ressived := C.modbus_read_input_bits(this.ctx, C.int(startAddr), C.int(nb),
&(space[0])); int(ressived) != nb {
if ressived == -1 {
errno := C.getErrno()
if errno == C.EMBMDATA {
return nil, errors.New(C.GoString(C.modbus_strerror(errno)))
}
return nil, errors.New(fmt.Sprintf("Unknown modbus error errno=%d", int(errno)))
} else if ressived == 0 {
return nil, errors.New("No ansver ressived")
}
} else {
result := make([]bool, ressived)
for i := 0; i < int(ressived); i++ {
if space[i] != C.FALSE {
result[i] = true
}
}
return result, nil
}
return nil, nil
}
func (this ModbusRTUConnection) ReadHoldings(slave int8, startAddr int, nb int) ([]uint16, error) {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return nil, errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
var space [65535]C.uint16_t
this.ProcessHook(RTU_03_LEN)
if ressived := C.modbus_read_registers(this.ctx, C.int(startAddr),
C.int(nb), &(space[0])); int(ressived) != nb {
if ressived == -1 {
errno := C.getErrno()
if errno == C.EMBMDATA {
return nil, errors.New(C.GoString(C.modbus_strerror(errno)))
}
return nil, errors.New(fmt.Sprintf("Unknown modbus error errno=%d", errno))
} else if ressived == 0 {
return nil, errors.New("No ansver ressived")
}
} else {
result := make([]uint16, ressived)
for i := 0; i < int(ressived); i++ {
result[i] = uint16(space[i])
}
return result, nil
}
return nil, nil
}
func (this ModbusRTUConnection) ReadInputRegisters(slave int8, startAddr int, nb int) ([]uint16, error) {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return nil, errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
var space [65535]C.uint16_t
this.ProcessHook(RTU_03_LEN)
if ressived := C.modbus_read_input_registers(this.ctx, C.int(startAddr),
C.int(nb), &(space[0])); int(ressived) != nb {
if ressived == -1 {
errno := C.getErrno()
if errno == C.EMBMDATA {
return nil, errors.New(C.GoString(C.modbus_strerror(errno)))
}
return nil, errors.New(fmt.Sprintf("Unknown modbus error errno=%d", errno))
} else if ressived == 0 {
return nil, errors.New("No ansver ressived")
}
} else {
result := make([]uint16, ressived)
for i := 0; i < int(ressived); i++ {
result[i] = uint16(space[i])
}
return result, nil
}
return nil, nil
}
func (this ModbusRTUConnection) WriteSingleCoil(slave int8, addr int, value bool) error {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
var v C.int
if value {
v = C.TRUE
}
this.ProcessHook(RTU_05_LEN)
if C.modbus_write_bit(this.ctx, C.int(addr), v) != 1 {
return errors.New(C.GoString(C.modbus_strerror(C.getErrno())))
}
return nil
}
func (this ModbusRTUConnection) WriteHolding(slave int8, addr int, value uint16) error {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
this.ProcessHook(RTU_06_LEN)
if C.modbus_write_register(this.ctx, C.int(addr), C.int(value)) != 1 {
return errors.New(C.GoString(C.modbus_strerror(C.getErrno())))
}
return nil
}
func (this ModbusRTUConnection) WriteCoils(slave int8, startAddr int, values []bool) error {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
vals := make([]C.uint8_t, len(values))
for i, v := range values {
if v {
vals[i] = C.TRUE
}
}
this.ProcessHook(RTU_0F_LEN + int(math.Ceil(float64(len(values))/8.0)))
if C.modbus_write_bits(this.ctx, C.int(startAddr), C.int(len(values)), &vals[0]) < 0 {
return errors.New(C.GoString(C.modbus_strerror(C.getErrno())))
}
return nil
}
func (this ModbusRTUConnection) WriteHoldings(slave int8, startAddr int, values []uint16) error {
if C.modbus_set_slave(this.ctx, C.int(slave)) != 0 {
return errors.New(fmt.Sprintf("Invalid slave id %d", slave))
}
vals := make([]C.uint16_t, len(values))
for i, v := range values {
vals[i] = C.uint16_t(v)
}
this.ProcessHook(RTU_10_LEN + len(values)*int(unsafe.Sizeof(vals[0])))
if C.modbus_write_registers(this.ctx, C.int(startAddr), C.int(len(values)), &vals[0]) < 0 {
return errors.New(C.GoString(C.modbus_strerror(C.getErrno())))
}
return nil
}
func (this ModbusRTUConnection) AttachedDevice(dev AbstarctDevice) error {
if d, ok := dev.(ModbusRTUDevice); ok {
if d.Connection() != &this {
this.attachedDevices = append(this.attachedDevices, &d)
d.BindTo(this)
} else {
return errors.New(fmt.Sprintf("Device allready attached to connection %d", this.ID()))
}
}
return errors.New(fmt.Sprintf("Device requiered incompotable protocol %s", dev.Protocol()))
}
func (this ModbusRTUConnection) RemoveDevice(dev *ModbusRTUDevice) error {
if dev.Connection() != &this {
return errors.New("This device belongs to another connection")
}
var n int
var item *ModbusRTUDevice
var found bool = false
for n, item = range this.attachedDevices {
if item == dev {
found = true
break
}
}
if !found {
return errors.New(fmt.Sprintf("No device ID=%s in devices list of connection %s", dev.ID(),
this.ID()))
}
this.attachedDevices, this.attachedDevices[len(this.attachedDevices)-1] =
append(this.attachedDevices[:n], this.attachedDevices[n+1:]...), nil
return nil
}
func (this ModbusRTUConnection) Close(recursive bool) error {
if recursive {
for _, dev := range this.attachedDevices {
dev.Close(true)
}
return nil
} else {
if this.UsedBy() > 0 {
return errors.New("Connection still used")
}
var n int
var item *ModbusRTUConnection
for n, item = range ModbusRTUConnections {
if item == &this {
break
}
}
ModbusRTUConnections, ModbusRTUConnections[len(ModbusRTUConnections)-1] =
append(ModbusRTUConnections[:n], ModbusRTUConnections[n+1:]...), nil
return nil
}
}