-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodbus.lua
More file actions
1478 lines (1246 loc) · 46.5 KB
/
modbus.lua
File metadata and controls
1478 lines (1246 loc) · 46.5 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
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--Modbus, supports Modbus RTU, ASCII, TCP, RTU over TCP
--v2.02: Support writeonly object:
-- Add writeonly_input function, when there is active output command,
-- return 0 as reliability, else return 6(NO_OUTPUT)
-- Allow empty readreqs
--Tag config:
--bus:
-- update_interval: milliseconds, default is 10000(10 seconds)
-- offline_interval: milliseconds, default is double of update_interval
-- interval to retry on offline devices
-- command_interval: milliseconds, default is update_interval*2. For
-- commandable object, when value readback doesn't match value outputed,
-- we need to output again. This inteval limit the output frequency.
-- before_idle: milliseconds, bus idle need for sending request, only valid
-- for RS485, default 0 for ASCII, 38.5 bits for RTU
-- debug: boolean, true to print send/recv packet
-- tcp_rtu: rtu over tcp mode, default is false
-- ascii: ASCII mode, default is false
-- init: user initiaize function
-- prototype: init(ctx)
-- global_define: all properties will be propagated to global scope
--device:
-- slave
-- readreqs = {{func_code, start_addr, quantity},
-- {func_code, start_addr, quantity}
-- }
-- func_code only support 1,2,3,4
-- start_addr is starting from 0
-- After data is read from Modbus device, it will append to
-- each elment of readreqs
-- writesinglereg: boolean, when writing one reg, func_code 6 is used
-- writesinglecoil: boolean, when writing one coil, func_code 5 is used
-- endian: 1=1234, 2=2143, 3=3412, 4=4321 (default), only used in
-- default input/output
-- timeout: milliseconds, timeout for response
-- ignore_unmatch: boolean. For a commandable object, when value readback
-- don't match value written, set reliability to unreliable other.
-- init: user initialize function
-- prototype: init(ctx, device)
--point:
-- input: function to map input. If nil, default_input will be used
-- propotype: input(device, point)
-- return value, reliability
-- If value or reliability is not nil, swg.updatepoint will be called
-- output: funcion to generate output, only make sense on BACnet writable
-- object. If nil, default_output will be used
-- propotype: output(device, point, value)
-- value is the value asked to write by BACnet
-- return array of {bits_in_last_byte, address, data}, referring to
-- multiple write request. if nil is returned, no Modbus write
-- will be performed.
-- If bits_in_last_byte == 0, output to holding register, else
-- output to coil.
-- postoutput: function to be called when Modbus write is performed(not nil
-- is returned from output function).
-- propotype: postoutput(device, point, value, output_reqs)
-- return BACnet value actually write to device, it maybe different to
-- the value asked to write by BACnet
-- init: user initialize function
-- prototype: init(ctx, device, point)
-- ignore_unmatch: boolean, point specified property
-- Below parameters are only valid when default input or output function is
-- used, they will stay in point.tag scope, not to be moved to point scope
-- func_code: 1,2 is only valid for binary object.
-- addr: starting from 0
-- datatype: only valid for func_code 3 or 4. enum of
-- "u16"(unsigned 16 bits, default), "u32", "u64", "s16"(signed 16 bits),
-- "s32", "s64", "f32"(32bits float point), "f64"(64 bits float point).
-- For multistate object, only "u16" and "u32" are valid.
-- datatype is meanless for binary object.
-- ms_values: array of integer, only valid to multisate object
-- if ms_values is absense, BACnet present value 1 mapping to Modbus 0
-- if ms_values is present, BACnet present value 1 mapping to ms_values[1]
-- bit: 0~15, default is 0. Only valid for binary on input/holding register
-- or multistate object with "u16" datatype or analog object with
-- "u16" or "s16" datatype
-- bitlen: 1~16. Only valid for multistate object with "u16" datatype or
-- analog object with "u16" or "s16" datatype. if it is nil, the default
-- value is 16 - bit
-- scale, offset: scale=1.0 default, offset=0 default. Only valid for analog
-- object. BACnet value = Modbus value * scale + offset
-- datatype will be parsed to 0="u16","u32","u64", 1="s16","s32", "s64",
-- 2="f32","f64".
-- bitlen will be set as actually bits used by data, for example 64 for "s64"
local crc_tbl = {
0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401,
0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400}
local function crc16(input)
local crc = 0xffff
for i = 1, #input do
local c = string.byte(input, i,i)
crc = (crc >> 8)
~ crc_tbl[((crc ~ c) & 0x0f) + 1]
~ crc_tbl[(((crc ~ c) >> 4) & 0x0f) + 17]
end
return string.char(crc & 0x0ff, (crc >> 8) & 0x0ff)
end
local function append_crc16(packet)
return packet .. crc16(packet)
end
local function verify_crc16(input)
if #input <= 2 then return nil end
local frame = string.sub(input, 1, -3)
if crc16(frame) == string.sub(input, -2) then
return frame
else
return nil
end
end
local function cal_lrc(input)
local lrc = 0
for i = 1, #input do
local c = string.byte(input, i, i)
lrc = lrc + c
end
return (-lrc) & 0x0ff
end
local function encode_ascii(input, lrc)
local pkt = ":"
for i = 1, #input do
local c = string.byte(input, i,i)
pkt = pkt .. string.format("%02X", c)
end
pkt = pkt .. string.format("%02X", lrc)
return pkt .. "\r\n"
end
local function decode_ascii(input)
--return decode packet
local count
input, count = string.gsub(input, "^:+", "")
if count == 0 then return nil end
local cridx = string.find(input, "\r\n")
if cridx == nil then return nil end
input = string.sub(input, 1, cridx - 1)
local lrc = 0
local half = nil
local result = ""
for i = 1, #input do
local c = string.byte(input, i, i)
if c < 0x30 or c > 0x46 then return nil end
if c > 0x39 and c < 0x41 then return nil end
if c >= 0x41 then
c = c - 0x41 + 10
else
c = c - 0x30
end
if half == nil then
half = c << 4
else
c = half + c
lrc = (lrc + c) & 0x0ff
result = result .. string.char(c)
half = nil
end
end
if half ~= nil or lrc ~= 0 or #result == 0 then return nil end
return string.sub(result, 1, #result - 1)
end
local function append_tcpheader(packet, trans_id)
return string.char((trans_id >> 8) & 0x0ff, trans_id & 0x0ff,
0, 0, #packet >> 8, #packet & 0x0ff) .. packet
end
local function decode_tcpheader(packet, trans_id)
--return payload length
if #packet < 6 then return nil end
if (string.byte(packet,1,1) << 8)
+ string.byte(packet,2,2) ~= trans_id then return nil end
if string.byte(packet,3,3) ~= 0 or string.byte(packet,4,4) ~= 0 then
return nil end
local length = (string.byte(packet,5,5) << 8) + string.byte(packet,6,6)
if length < 2 or length > 254 then return nil end
return length
end
local function check_exception(packet, slave, func_code)
if #packet ~= 3 then return nil end
if string.byte(packet,1,1) ~= slave then return nil end
if string.byte(packet,2,2) ~= func_code|0x80 then return nil end
return string.byte(packet,3,3)
end
local function gen_read_req(slave, func_code, start_addr, quantity)
return string.char(slave, func_code, start_addr >> 8, start_addr & 0x0ff, quantity >> 8, quantity & 0x0ff)
end
local function check_read_rsp(packet, slave, func_code, quantity)
--return unit data
if func_code < 3 then
if #packet ~= 3 + (quantity + 7) // 8 then
return nil
end
else
if #packet ~= 3 + quantity * 2 then
return nil
end
end
if string.byte(packet,1,1) ~= slave then return nil end
if string.byte(packet,2,2) ~= func_code then return nil end
if string.byte(packet,3,3) ~= #packet-3 then return nil end
return string.sub(packet, 4)
end
local function gen_write_single_req(slave, func_code, data_addr, data)
return string.char(slave, func_code, data_addr >> 8, data_addr & 0x0ff) .. data
end
local function check_write_single_rsp(packet, slave, func_code, data_addr)
--return error msg
if #packet ~= 6 then return "packet length" end
if string.byte(packet,1,1) ~= slave then return "slave address" end
if string.byte(packet,2,2) ~= func_code then return "function code" end
if string.byte(packet,3,3) ~= (data_addr >> 8)
or string.byte(packet,4,4) ~= (data_addr & 0x0ff) then
return "data address"
end
return nil
end
local function gen_write_multi_req(slave, func_code, start_addr, quantity, data)
return string.char(slave, func_code, start_addr >> 8, start_addr & 0x0ff,
quantity >> 8, quantity & 0x0ff, #data) .. data
end
local function check_write_multi_rsp(packet, slave, func_code, start_addr, quantity)
--return error msg
if #packet ~= 6 then return "packet length" end
if string.byte(packet,1,1) ~= slave then return "slave address" end
if string.byte(packet,2,2) ~= func_code then return "function code" end
if string.byte(packet,3,3) ~= (start_addr >> 8)
or string.byte(packet,4,4) ~= (start_addr & 0x0ff) then
return "data address"
end
if string.byte(packet,5,5) ~= (quantity >> 8)
or string.byte(packet,6,6) ~= (quantity & 0x0ff) then
return "quantity"
end
return nil
end
local exception_msg = {[1] = "1-illegal function",
[2] = "2-illegal data address",
[3] = "3-illegal data value",
[4] = "4-server device failure",
[5] = "5-ackownledge",
[6] = "6-server device busy",
[8] = "8-memory parity error",
[10] = "10-gateway path unavailable",
[11] = "11-gateway target devcie failed to respond" }
local function getExceptionMsg(code)
local err = exception_msg[code]
if err == nil then
string.format("%d", code)
end
return "Exception:" .. err
end
local function getRS485ErrorMsg(result)
if result == -1 then return "bus mess"
elseif result == -2 then return "timeout"
elseif result == -3 then return "byte error"
elseif result == -5 then return "packet overflow"
else return string.format("%d", result) end
end
local function getTCPErrorMsg(result)
if result == -1 then return "connect timeout"
elseif result == -2 then return "read failed"
elseif result == -3 then return "write failed"
elseif result == -4 then return "connect failed"
else return string.format("%d", result) end
end
local function printTxPacket(packet)
local output = {}
local head = "Tx:"
table.insert(output, head)
local char_cnt = #head
for i=1, #packet do
if char_cnt > 120 then
print(table.concat(output, " "))
output = {}
char_cnt = 2
else
char_cnt = char_cnt + 3
end
table.insert(output, string.format("%02x", string.byte(packet,i,i)))
end
print(table.concat(output, " "))
end
local function printRxPacket(packet, err)
local output = {}
local head
if err == nil then
head = "Rx:"
else
head = "Rx(" .. err .. "):"
end
table.insert(output, head)
local char_cnt = #head
for i=1, #packet do
if char_cnt > 120 then
print(table.concat(output, " "))
output = {}
char_cnt = 2
else
char_cnt = char_cnt + 3
end
table.insert(output, string.format("%02x", string.byte(packet,i,i)))
end
print(table.concat(output, " "))
end
local once_callback, tcp_callback
local function send_request(ctx, packet, timeout)
if ctx.type == swg.interface_rs485 then
if ctx.ascii then
packet = encode_ascii(packet, cal_lrc(packet))
swg.sndrcv485(packet, ctx.before_idle, timeout, 516, once_callback)
else
packet = append_crc16(packet)
swg.sndrcv485(packet, ctx.before_idle, timeout, 256, once_callback)
end
elseif ctx.tcp_rtu then
packet = append_crc16(packet)
-- send request and receive all response
-- we assume the response will come in one tcp packet
swg.sndrcvtcp(packet, 2, 257, timeout, once_callback)
else
if not ctx.trans_id then
ctx.trans_id = 0
else
ctx.trans_id = ctx.trans_id + 1
if ctx.trans_id > 65535 then ctx.trans_id = 0 end
end
packet = append_tcpheader(packet, ctx.trans_id)
-- send request and receive response header
swg.sndrcvtcp(packet, 6, 6, timeout, tcp_callback)
ctx.tcp_ts = swg.now()
ctx.tcp_header = nil
end
if ctx.debug then
printTxPacket(packet)
end
end
local post_device_handle
local function send_read_request(ctx)
local device = ctx.devices[ctx.curr_devidx]
local readreq = device.readreqs[ctx.curr_reqidx]
if #readreq == 0 then
swg.timer(0, 0, post_device_handle)
return
end
ctx.curr_comm = {is_read=true, device=device}
local packet = gen_read_req(device.slave,
readreq[1], readreq[2], readreq[3])
send_request(ctx, packet, device.timeout)
end
local function send_write_request(ctx, device, point, output_reqs)
local req = output_reqs[1]
local bits_in_last_byte = req[1]
local addr = req[2]
local data = req[3]
local quantity, func_code
if #data < 1 then error("no data to write") end
if bits_in_last_byte < 0 or bits_in_last_byte > 8 then
error("invalid bits_in_last_byte")
end
if bits_in_last_byte > 0 then
if #data > 247 then
error("too much data to write")
end
quantity = (#data - 1) * 8 + bits_in_last_byte
if quantity == 1 and device.writesinglecoil then
func_code = 5
if (string.byte(data,1,1) & 1) ~= 0 then
data = string.char(0xff, 0)
else
data = string.char(0, 0)
end
else
func_code = 15
end
else
if #data % 2 ~= 0 then
error("data length not round to 2")
end
if #data > 246 then
error("too much data to write")
end
quantity = #data / 2
if quantity == 1 and device.writesinglereg then
func_code = 6
else
func_code = 16
end
end
local packet
if func_code < 15 then
packet = gen_write_single_req(device.slave, func_code, addr, data)
else
packet = gen_write_multi_req(device.slave, func_code, addr, quantity, data)
end
table.remove(output_reqs, 1)
ctx.curr_comm = {is_read=false, device=device, point=point, func_code=func_code,
addr=addr, quantity=quantity, packet=packet, output_reqs=output_reqs}
send_request(ctx, packet, device.timeout)
end
local timer_callback
local max_err_cnt = 3
local function read_next(ctx)
local now = swg.now()
ctx.curr_reqidx = 1
ctx.err_cnt = 0
::continue::
ctx.curr_devidx = ctx.curr_devidx + 1
if ctx.curr_devidx > #ctx.devices then
swg.timer(0, ctx.update_interval - (now - ctx.poll_ts), timer_callback)
return
end
local device = ctx.devices[ctx.curr_devidx]
if device.fail_ts and now - device.fail_ts <= ctx.offline_interval then
goto continue
end
send_read_request(ctx)
end
local function poll_restart(ctx)
ctx.poll_ts = swg.now()
ctx.curr_devidx = 0
read_next(ctx)
end
function timer_callback(ctx)
::continue::
local devidx, pntidx, value = swg.firstwrite()
if devidx == nil then
local now = swg.now()
if now - ctx.poll_ts < ctx.update_interval then
swg.timer(0, ctx.update_interval - (now - ctx.poll_ts), timer_callback)
else
poll_restart(ctx)
end
return
end
local device = ctx.devices[devidx]
local point = device.points[pntidx]
if value == nil then --relinguish
point.last_output = nil
goto continue
end
if device.fail_ts then goto continue end
local last_value
if point.last_output ~= nil then
last_value = point.last_output
else
local reliability
last_value, reliability = swg.pointvalue(devidx, pntidx)
if reliability ~= 0 then
last_value = nil
end
end
if value == last_value then
point.last_output = value
goto continue
end
local output = point.output == nil and default_output or point.output
local output_reqs = output(device, point, value)
if output_reqs == nil or #output_reqs == 0 then --no need to write
goto continue
end
local postoutput = point.postoutput == nil
and default_postoutput or point.postoutput
local output_value = postoutput(device, point, value, output_reqs)
point.last_output = output_value == nil and value or output_value
if point.last_output == last_value then goto continue end
ctx.err_cnt = 0
send_write_request(ctx, device, point, output_reqs)
end
local function scan_commandable(ctx, devidx, start)
--For commandable object, when value readback doesnot match value outputed,
--we need to output again.
--return true if output is ongoing, false if no work to do
local device = ctx.devices[devidx]
local now = swg.now()
while true do
if start then
if device.curr_scanidx == nil then device.curr_scanidx = #device.points end
device.scan_start = device.curr_scanidx
start = false
elseif device.curr_scanidx == device.scan_start then break end
device.curr_scanidx = device.curr_scanidx + 1
if device.curr_scanidx > #device.points then
device.curr_scanidx = 1
end
local point = device.points[device.curr_scanidx]
if not point.commandable then goto continue end
if now - point.output_ts <= ctx.command_interval then goto continue end
local value = swg.getwrite(devidx, device.curr_scanidx)
if value == nil then --relinguish
point.last_output = nil
goto continue
end
local last_value, last_reliability = swg.pointvalue(devidx,
device.curr_scanidx)
if last_reliability ~= 0 then last_value = nil end
if value == last_value then
point.last_output = value
goto continue
end
local output = point.output == nil and default_output or point.output
local output_reqs = output(device, point, value)
if output_reqs == nil or #output_reqs == 0 then goto continue end
local postoutput = point.postoutput == nil
and default_postoutput or point.postoutput
local output_value = postoutput(device, point, value, output_reqs)
point.last_output = output_value == nil and value or output_value
if point.last_output == last_value then goto continue end
ctx.err_cnt = 0
send_write_request(ctx, device, point, output_reqs)
do return true end
::continue::
end
return false --end of scan
end
local function write_callback(ctx, err, data)
if err == nil then
local exception = check_exception(data, ctx.curr_comm.device.slave, ctx.curr_comm.func_code)
if exception ~= nil then
err = getExceptionMsg(exception)
else
if ctx.curr_comm.func_code < 15 then
err = check_write_single_rsp(data, ctx.curr_comm.device.slave,
ctx.curr_comm.func_code, ctx.curr_comm.addr)
else
err = check_write_multi_rsp(data, ctx.curr_comm.device.slave,
ctx.curr_comm.func_code, ctx.curr_comm.addr, ctx.curr_comm.quantity)
end
end
if err ~= nil then
print("Write failed(" .. err .. ") slave "
.. ctx.curr_comm.device.slave .. " func code "
.. ctx.curr_comm.func_code .. " addr "
.. ctx.curr_comm.addr)
err = nil --regards it as success to avoid retry
end
end
if err ~= nil then
if ctx.type ~= swg.interface_rs485 then swg.tcpreset() end
print("Write failed(" .. err .. ") slave "
.. ctx.curr_comm.device.slave .. " func code "
.. ctx.curr_comm.func_code .. " addr "
.. ctx.curr_comm.addr)
ctx.err_cnt = ctx.err_cnt + 1
if ctx.err_cnt < max_err_cnt then
send_request(ctx, ctx.curr_comm.packet, ctx.curr_comm.device.timeout)
return
end
elseif #ctx.curr_comm.output_reqs ~= 0 then --next write req
send_write_request(ctx, ctx.curr_comm.device, ctx.curr_comm.point, ctx.curr_comm.output_reqs)
return
end
ctx.curr_comm.point.output_ts = swg.now()
ctx.curr_comm = nil
if ctx.curr_devidx > #ctx.devices then --write at end of polling
local now = swg.now()
if now - ctx.poll_ts > ctx.update_interval then
poll_restart(ctx)
else
swg.timer(0, ctx.update_interval - (now - ctx.poll_ts), timer_callback)
end
elseif err ~= nil or not scan_commandable(ctx, ctx.curr_devidx, false) then
--turn to next slave when retry failed or scan finished
read_next(ctx)
end
end
function post_device_handle(ctx)
local device = ctx.devices[ctx.curr_devidx]
for pidx, point in ipairs(device.points) do
local input = point.input == nil and default_input or point.input
if not point.commandable then point.last_output = nil end
local value, reliability = input(device, point)
if point.last_output ~= nil and value ~= point.last_output
and reliability == 0 then
local ignore_unmatch
if point.ignore_unmatch ~= nil then
ignore_unmatch = point.ignore_unmatch
else
ignore_unmatch = device.ignore_unmatch
end
if not ignore_unmatch then reliability = 7 end
end
swg.updatepoint(ctx.curr_devidx, pidx, value, reliability)
end
if scan_commandable(ctx, ctx.curr_devidx, true) then
return
end
read_next(ctx)
end
local function read_callback(ctx, err, data)
local device = ctx.devices[ctx.curr_devidx]
local readreq = device.readreqs[ctx.curr_reqidx]
if err == nil then
local exception = check_exception(data, device.slave, readreq[1])
if exception ~= nil then
err = getExceptionMsg(exception)
else
data = check_read_rsp(data, device.slave, readreq[1], readreq[3])
if data == nil then
err = "parse response failed"
end
end
if err ~= nil then
ctx.err_cnt = max_err_cnt
end
end
if err ~= nil then
if ctx.type ~= swg.interface_rs485 then swg.tcpreset() end
print("Read failed(" .. err .. ") on device " .. ctx.curr_devidx
.. " request " .. ctx.curr_reqidx)
ctx.err_cnt = ctx.err_cnt + 1
if device.fail_ts or ctx.err_cnt >= max_err_cnt then
device.fail_ts = swg.now() --flags for offline
swg.onoff(ctx.curr_devidx, false)
read_next(ctx)
else
send_read_request(ctx)
end
return
else
readreq[4] = data
ctx.curr_reqidx = ctx.curr_reqidx + 1
if ctx.curr_reqidx <= #device.readreqs then
ctx.err_cnt = 0
send_read_request(ctx)
return
end
end
swg.onoff(ctx.curr_devidx, true)
device.fail_ts = nil
post_device_handle(ctx)
end
function once_callback(ctx, result, data)
local err
if result < 0 then
if ctx.type == swg.interface_tcp then
err = getTCPErrorMsg(result)
else
err = getRS485ErrorMsg(result)
end
end
if result >= 0 then
if ctx.type == swg.interface_rs485 and ctx.ascii then
data = decode_ascii(data)
else
data = verify_crc16(data)
end
if data == nil then
err = "verify failed"
end
end
if ctx.debug then
printRxPacket(data, err)
end
if ctx.curr_comm.is_read then
read_callback(ctx, err, data)
else
write_callback(ctx, err, data)
end
end
function tcp_callback(ctx, result, data)
local err
if result < 0 then
err = getTCPErrorMsg(result)
end
if ctx.tcp_header == nil and result >= 0 then
local length = decode_tcpheader(data, ctx.trans_id)
if length == nil then
err = "verify failed"
else
ctx.tcp_header = data
local now = swg.now()
-- to receive response body
swg.sndrcvtcp(nil, length, length,
ctx.curr_comm.device.timeout - (now - ctx.tcp_ts),
tcp_callback)
return
end
end
if ctx.debug then
if ctx.tcp_header == nil then
printRxPacket(data, err)
else
printRxPacket(ctx.tcp_header .. data, err)
end
end
if ctx.curr_comm.is_read then
read_callback(ctx, err, data)
else
write_callback(ctx, err, data)
end
end
function setmodbusdata(readreqs, writable, bits_in_last_byte, addr, data)
--the value read from device is stored in readreqs
--when we write to device, we can update stored value
local quantity
if bits_in_last_byte == 0 then --holding register
quantity = #data / 2
else
quantity = (#data - 1) * 8 + bits_in_last_byte
end
for _, req in ipairs(readreqs) do
if addr >= req[2] + req[3] then goto continue end
if req[2] >= addr + quantity then goto continue end
local t = {}
if bits_in_last_byte == 0 then --holding register
if req[1] ~= (writable and 3 or 4) then goto continue end
if addr > req[2] then
table.insert(t, string.sub(req[4], 1, (addr - req[2]) * 2))
table.insert(t, string.sub(data, 1, (req[2] + req[3] - addr) * 2))
else
table.insert(t, string.sub(data, (req[2] - addr) * 2 + 1,
(req[2] + req[3] - addr) * 2))
end
local left = req[2] + req[3] - addr - quantity
if left > 0 then
table.insert(t, string.sub(req[4], left * -2))
end
else --coil
if req[1] ~= (writable and 1 or 2) then goto continue end
local bits = (addr - req[2]) % 8
local startidx = (addr - req[2]) // 8 + 1
if startidx > 1 then
table.insert(t, string.sub(req[4], 1, startidx - 1))
end
local endidx = (addr + quantity - req[2]) // 8
local srcidx = (req[2] - addr) // 8 + 1
local half
if startidx < 1 then
startidx = 1
half = string.byte(data, srcidx, srcidx)
half = half >> (8 - bits) -- save highest bits
srcidx = srcidx + 1
end
if srcidx < 1 then
srcidx = 1
half = string.byte(req[4], startidx, startidx)
half = half & ~(-1 << bits) --save lowest bits
end
if endidx > #req[4] then endidx = #req[4] end
for _ = startidx, endidx do
local byte = string.byte(data, srcidx, srcidx)
table.insert(t, string.char(half + ((byte << bits) & 0x0ff)))
half = byte >> (8 - bits)
srcidx = srcidx + 1
end
if endidx < #req[4] then
local left_bits = (addr + quantity - req[2]) % 8
local byte
if left_bits > bits then
byte = string.byte(data, srcidx, srcidx)
half = half + (byte << bits)
end
half = half & ~(-1 << left_bits)
byte = string.byte(req[4], endidx+1, endidx+1)
byte = byte & (-1 << left_bits) -- use highest bits
table.insert(t, string.char(half + byte))
end
table.insert(t, string.sub(req[4], endidx+2))
end
req[4] = table.concat(t)
::continue::
end
end
function getmodbusdata(readreqs, func_code, addr, quantity)
for reqidx = #readreqs, 1, -1 do
local req = readreqs[reqidx]
if req[1] ~= func_code then goto continue end
if req[2] > addr then goto continue end
if addr + quantity > req[2] + req[3] then goto continue end
if req[4] == nil then return nil end
if func_code >= 3 then --register
return req[4]:sub((addr - req[2]) * 2 + 1, (addr + quantity - req[2]) * 2)
else --coil or discrete
local bits = (addr - req[2]) % 8
local t = {}
local startidx = (addr - req[2]) // 8 + 1
local endidx = (addr + quantity - req[2] + 7) // 8
local half = req[4]:byte(startidx, startidx)
half = half >> bits -- save highest bits
for idx = startidx + 1, endidx do
local byte = req[4]:byte(idx, idx)
table.insert(t, string.char(half + ((byte << (8 - bits)) & 0x0ff)))
half = byte >> bits
end
if quantity > #t * 8 then
table.insert(t, string.char(half))
end
return table.concat(t)
end
::continue::
end
error("no readreqs match")
end
function reorder_registers(value)
local ordered = ""
for i = 1, #value, 2 do
ordered = value:sub(i, i+1) .. ordered
end
return ordered
end
function default_input(device, point)
--return BACnet value, reliability
local value
if point.obj_type == "b" then
value = getmodbusdata(device.readreqs, point.tag.func_code,
point.tag.addr, 1)
if point.tag.func_code >= 3 then
value = string.unpack(((device.endian & 1 ~= 0) and "<I2" or ">I2"),
value)
value = (value & (1 << point.tag.bit)) ~= 0
else
value = (value:byte(1,1) & 1) ~= 0
end
else
value = getmodbusdata(device.readreqs, point.tag.func_code,
point.tag.addr, (point.tag.bitlen + 15) // 16)
if #value > 2 and (device.endian & 2) ~= 0 then
--register order not consistent with byte order, reorder it
value = reorder_registers(value)
end
if point.tag.datatype == 2 then --float
local format = ((device.endian & 1 ~= 0) and "<" or ">") ..
((point.tag.bitlen==32) and "f" or "d")
value = string.unpack(format, value)
if value ~= value then --NaN
return nil, 7 --unreliable other
end
else
local format = ((device.endian & 1 ~= 0) and "<I" or ">I") ..
((point.tag.bitlen + 15) // 16) * 2
value = string.unpack(format, value)
if point.tag.datatype == 0 then --unsigned
if value < 0 then --overflow
value = ((-1 >> 2) + 1) * 4.0 + value