-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdl485.py
3024 lines (2671 loc) · 168 KB
/
dl485.py
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Class protocol DL485
"""
import json
import os
from pprint import pprint
import re
import signal
import sys
import telepot
# from telepot.loop import MessageLoop
# from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
import time
from tsl2561 import tsl2561_calculate
from bus_dl485 import BusDL485
from log import Log
from bme280 import BME280
# from dl485_mqtt import *
# import paho.mqtt.client as Client
# import paho.mqtt.publish as publish
# from dl485_telegram import message as telegram_message, init_bot, handle
from dl485_telegram import TelBot
def timed_function(f, *args, **kwargs):
"""
Show time of running function
Put decorator @timed_function on function to meter
"""
myname = str(f).split(' ')[1]
def new_func(*args, **kwargs):
t = time.time()
result = f(*args, **kwargs)
delta = time.time() - t
print(' Function {} Time = {:6.5f}ms'.format(myname, delta * 1000))
return result
return new_func
class Bus(BusDL485, Log, BME280):
EEPROM_LANGUAGE = 1 # 1=NEW, 0=old
BROADCAST = 0 # Invia il comando a tutti i nodi.
""" Allow commands """
code = {
0: 'INPUT',
1: 'OUTPUT',
2: 'CR_TRASPORTO_STR',
3: 'CR_RD_PARAM_IO', # Read parametro EEPROM 2 byte ricevuti
4: 'CR_RD_EE', # Comando per leggere la EE
5: 'CR_WR_PARAM_IO', # Write parametro EEPROM 2 byte
6: 'CR_WR_EE', # Comando per scrivere la EE
7: 'CR_RD_IN', # Leggi valore ingresso
8: 'CR_WR_OUT', # Scrivi valore uscita
10: 'CR_INIT_SINGOLO_IO', # Mandare per aggiunare singola configurazione IO oppure REBOOT totale
11: 'CR_REBOOT', # Fa il reboot della scheda
12: 'CR_GET_BOARD_TYPE', # Ritorna il tipo di board
13: 'ERRORE', # Errore generico
14: 'COMUNICA_IO', # Mitt. COmando comunica IO, N. ingresso, valore inresso
15: 'I2C ACK', # Mitt. COmando comunica IO, N. ingresso, valore inresso
16: 'CLEARIO_REBOOT', #cancella area io e fa reboot
18: 'RFID', # comunicazione del pacchetto RDIF
19: 'TIME_LOOP',
'INPUT': 0,
'OUTPUT': 1,
'CR_TRASPORTO_STR': 2,
'CR_RD_PARAM_IO': 3, # Read parametro EEPROM 2 byte ricevuti
'CR_RD_EE': 4, # Comando per leggere la EE
'CR_WR_PARAM_IO': 5, # Write parametro EEPROM 2 byte
'CR_WR_EE': 6, # Comando per scrivere la EE
'CR_RD_IN': 7, # Leggi valore ingresso
'CR_WR_OUT': 8, # Scrivi valore uscita
'CR_INIT_SINGOLO_IO': 10, # Mandare per aggiunare singola configurazione IO oppure REBOOT totale
'CR_REBOOT': 11, # Fa il reboot della scheda
'CR_GET_BOARD_TYPE': 12, # Ritorna il tipo di board
'ERRORE': 13, # Errore generico
'COMUNICA_IO': 14, # Mitt. COmando comunica IO, N. ingresso, valore inresso
'I2C ACK': 15, # Mitt. COmando comunica IO, N. ingresso, valore inresso
'CLEARIO_REBOOT': 16,
'RFID': 18,
'TIME_LOOP': 19, # Comunica il tempo LOOP in uS
}
""" Dict with all errors """
error = { # Dict with ERROR type
1: "Errore 3 zeri",
2: "Errore 3 uni",
3: "Errore CRC",
4: "Ricevuto pacchetto nullo",
5: "Indirizzo mittente fuori range", # da 0 a 24
6: "Manca indirizzo destinatario",
7: "Manca parametri",
8: "Troppi Byte pacchetto",
9: "Manca parametri",
10: "I2C occupata",
11: "Manca Byte residui",
12: "Troppi Byte dati",
13: "Errore comando a zero parametri",
14: "Errore comando a 1 parametro",
15: "Errore comando a 2 parametri",
16: "Errore comando a 3 parametri",
17: "Errore comando a 4 parametri",
18: "Errore comando n parametri non previsto ",
19: "Pacchetto ricevuto troppo lungo",
20: "I2C occupata",
21: "I2C Timeout",
22: "OneWire Occupata",
23: "Indirizzo ricevuto uguale a se stesso",
24: "OneWire Occupata",
25: "Lettura numero ingreso fuori range",
26: "Dimensione pacchetto non conforme",
27: "Accesso EE oltre limite indirizzo",
28: "Scrittura numero uscita fuori range",
29: "Numero parametro fuori range",
30: "Nodo occupato da ordine precedente",
31: "Accesso EE sotto spazio EE IO",
32: "Errore secondo crc",
33: "1W Timeout"
}
""" Types of devices allowed on Config.json """
device_type_dict = {
'AM2320': {'type_io':'i2c', 'direction':'input', 'dtype':'Temp+Hum', 'pullup':0},
'ANALOG_IN': {'type_io':'analog', 'direction':'input', 'dtype':'Switch', 'pullup':0},
'BME280': {'type_io':'i2c', 'direction':'input', 'dtype':'Temp+Hum+Baro', 'pullup':1},
'BME280_CALIB': {'type_io':'i2c', 'direction':'input', 'dtype':'Temp+Hum+Baro', 'pullup':1},
'DIGITAL_IN': {'type_io':'digital', 'direction':'input', 'dtype':'Switch', 'pullup':0},
'DIGITAL_IN_PULLUP': {'type_io':'digital', 'direction':'input', 'dtype':'Switch', 'pullup':1},
'DIGITAL_OUT': {'type_io':'digital', 'direction':'output', 'dtype':'Switch', 'pullup':0},
'DIGITAL_OUT_PWM': {'type_io':'analog', 'direction':'output', 'dtype':'Voltage', 'pullup':0},
'DS18B20': {'type_io':'onewire', 'direction':'input', 'dtype':'Temperature', 'pullup':1},
'PSYCHROMETER': {'type_io':'', 'direction':'input', 'dtype':'Humidity', 'pullup':0},
'RFID_CARD': {'type_io':'', 'direction':'output', 'dtype':'Switch', 'pullup':0},
'RFID_UNIT': {'type_io':'i2c', 'direction':'input', 'dtype':'Text', 'pullup':1},
'RMS_POWER': {'type_io':'discrete', 'direction':'input', 'dtype':'Text', 'pullup':0},
'TEMP_ATMEGA': {'type_io':'temp_atmega', 'direction':'input', 'dtype':'Temperature', 'pullup':0},
'TSL2561': {'type_io':'i2c', 'direction':'input', 'dtype':'Illumination', 'pullup':0},
'VINR1R2': {'type_io':'analog', 'direction':'input', 'dtype':'Voltage', 'pullup':0},
'VINKMKA': {'type_io':'analog', 'direction':'input', 'dtype':'Voltage', 'pullup':0},
'VIN4V': {'type_io':'analog', 'direction':'input', 'dtype':'Voltage', 'pullup':0},
'VIRTUAL': {'type_io':'discrete', 'direction':'output', 'dtype':'Temperature', 'pullup':0},
'RTC': {'type_io':'discrete', 'direction':'output', 'dtype':'', 'pullup':0},
'TIME': {'type_io':'discrete', 'direction':'input', 'dtype':'', 'pullup':0},
}
""" Dict I2C constant """
i2c_const = {
'CONCATENA': 128,
'NON_CONCATENA': 0,
'BYTE_OPZIONI_LETTURA': 64,
'BYTE_OPZIONI_SCRITTURA': 0,
# 'BYTE_OPZIONI_RESET_I2C': ???? ,
'FLAG_PAUSA': 0x20, # definizione per vecchio linguaggio
}
if EEPROM_LANGUAGE == 1: # nuovo linguaggio
i2c_const['FLAG_PAUSA'] = 128
""" Micro GPIO function """
mf = {
'D': 'DIGITAL',
'A': 'ANALOG',
'P': 'PWM',
'SDA': 'I2C_SDA',
'SCL': 'I2C_SCL',
'I': 'INPUT',
'O': 'OUTPUT',
'VCC': 'VCC',
'GND': 'GND',
'X': 'CRYSTAL',
'PR': 'PUSH PROGRAMMER',
'LT': 'LED TX',
'LR': 'LED RX',
'MI': 'MISO',
'MO': 'MOSI',
'SC': 'SCK',
}
""" Types of Boards available. Do not modify!!! """
board_type_available = {
"DL485M": 1,
"DL485B": 2,
"DL485Pold": 3, # scheda tipo 3 vecchia sostituita con 5
"DL485R": 4,
"DL485P": 5,
"DL485D1": 6,
"DL485D3": 7,
"DL485D4": 8,
"1": "DL485M",
"2": "DL485B",
"3": "DL485Pold",
"4": "DL485R",
"5": "DL485P",
"6": "DL485D1",
"7": "DL485D3",
"8": "DL485D4",
}
"""
Function PIN map: I=input, O=output, P=pwm, SDA=sda, VCC=VCC, GND=GND, X=xtal, PROG=prog_button, LED_TX=led TX,
LED_RX=led RX, MO=MOSI, MI=MISO, SC=Serial clock, TX_BUS=BUS, AT=Atemega temp,
"""
mapmicro = { # MAP PIN Atmega328P QFN32PIN
1: {'name': 'PD3', 'fisic_io': 3, 'function': ['I', 'O', 'P']},
2: {'name': 'PD4', 'fisic_io': 4, 'function': ['I', 'O']},
3: {'name': 'PE0', 'fisic_io': 21, 'function': ['I', 'O', 'SDA']},
4: {'name': 'VCC', 'fisic_io': 99, 'function': ['VCC']},
5: {'name': 'GND', 'fisic_io': 99, 'function': ['GND']},
6: {'name': 'PE1', 'fisic_io': 22, 'function': ['I', 'O', 'A']},
7: {'name': 'XTAL1', 'fisic_io': 99, 'function': ['X']},
8: {'name': 'XTAL2', 'fisic_io': 99, 'function': ['X']},
9: {'name': 'PD5', 'fisic_io': 5, 'function': ['PROG']},
10: {'name': 'PD6', 'fisic_io': 6, 'function': ['LED_TX']},
11: {'name': 'PD7', 'fisic_io': 7, 'function': ['LR']},
12: {'name': 'PB0', 'fisic_io': 8, 'function': ['I', 'O']},
13: {'name': 'PB1', 'fisic_io': 9, 'function': ['I', 'O', 'P']},
14: {'name': 'PB2', 'fisic_io': 10, 'function': ['I', 'O', 'P']},
15: {'name': 'PB3', 'fisic_io': 11, 'function': ['I', 'O', 'MO']},
16: {'name': 'PB4', 'fisic_io': 12, 'function': ['I', 'O', 'MI']},
17: {'name': 'PB5', 'fisic_io': 13, 'function': ['I', 'O', 'SC']},
18: {'name': 'AVCC', 'fisic_io': 99, 'function': ['VCC']},
19: {'name': 'ADC6 PE2', 'fisic_io': 23, 'function': []},
20: {'name': 'AREF', 'fisic_io': 99, 'function': []},
21: {'name': 'GND', 'fisic_io': 99, 'function': []},
22: {'name': 'ADC7 PE3', 'fisic_io': 24, 'function': []},
23: {'name': 'PC0', 'fisic_io': 14, 'function': []},
24: {'name': 'PC1', 'fisic_io': 15, 'function': []},
25: {'name': 'PC2', 'fisic_io': 16, 'function': []},
26: {'name': 'PC3', 'fisic_io': 17, 'function': []},
27: {'name': 'PC4', 'fisic_io': 18, 'function': []},
28: {'name': 'PC5', 'fisic_io': 19, 'function': []},
29: {'name': 'RST', 'fisic_io': 99, 'function': []},
30: {'name': 'PD0', 'fisic_io': 0, 'function': []},
31: {'name': 'PD1', 'fisic_io': 1, 'function': ['TX_BUS']},
32: {'name': 'PD2', 'fisic_io': 2, 'function': ['']},
33: {'name': 'BME280', 'fisic_io': 18, 'function': []},
34: {'name': 'BME280', 'fisic_io': 18, 'function': []},
35: {'name': 'DS18B20', 'fisic_io': 3, 'function': []},
37: {'name': 'TEMP_ATMEGA', 'fisic_io': 25, 'function': ['AT']},
38: {'name': 'AM2320', 'fisic_io': 18, 'function': ['AM2320']},
39: {'name': 'BME280_CALIB','fisic_io': 18, 'function': []},
41: {'name': 'VIRT1', 'fisic_io': 40, 'function': ['VIRTUAL1']},
}
common_gpio = { # Definizione GPIO comuni a tutte le board
'VIN': {'pin': 22, 'name': 'VIN'},
'TEMP_ATMEGA': {'pin': 37, 'name': 'TEMP_ATMEGA'},
'SDA': {'pin': 27, 'name': 'SDA'},
'SCL': {'pin': 28, 'name': 'SCL'},
'BME280': {'pin': 27, 'name': 'BME280'},
'BME280_CALIB': {'pin': 27, 'name': 'BME280_CALIB'},
'BME280B': {'pin': 27, 'name': 'BME280'},
'AM2320': {'pin': 27, 'name': 'AM2320'},
'TSL2561': {'pin': 27, 'name': 'TSL2561'},
'PCA9535': {'pin': 27, 'name': 'PCA9535'},
'VIRT1': {'pin': 41, 'name': 'VIRT1'},
'VIRT2': {'pin': 41, 'name': 'VIRT2'},
'VIRT3': {'pin': 41, 'name': 'VIRT3'},
'VIRT4': {'pin': 41, 'name': 'VIRT4'},
'VIRT5': {'pin': 41, 'name': 'VIRT5'},
'VIRT6': {'pin': 41, 'name': 'VIRT6'},
'VIRT7': {'pin': 41, 'name': 'VIRT7'},
'VIRT8': {'pin': 41, 'name': 'VIRT8'},
'VIRT9': {'pin': 41, 'name': 'VIRT9'},
'TIME': {'pin': 41, 'name': 'TIME'},
'RTC': {'pin': 41, 'name': 'RTC'},
'I2C1': {'pin': 27, 'name': 'I2C1'},
'I2C2': {'pin': 27, 'name': 'I2C2'},
'I2C3': {'pin': 27, 'name': 'I2C3'},
'I2C4': {'pin': 27, 'name': 'I2C4'},
'I2C5': {'pin': 27, 'name': 'I2C5'},
'I2C6': {'pin': 27, 'name': 'I2C6'},
'I2C7': {'pin': 27, 'name': 'I2C7'},
'I2C8': {'pin': 27, 'name': 'I2C8'},
'I2C9': {'pin': 27, 'name': 'I2C9'},
}
dl485m_gpio = { # Definizione GPIO DL485M
'PB0': {'pin': 12, 'name': 'IO4'},
'PB1': {'pin': 13, 'name': 'IO5'},
'PB2': {'pin': 14, 'name': 'IO8'},
'PB3': {'pin': 15, 'name': 'IO15'},
'PB4': {'pin': 16, 'name': 'IO13'},
'PB5': {'pin': 17, 'name': 'IO14'},
'PD3': {'pin': 1, 'name': 'IO6'},
'PD4': {'pin': 2, 'name': 'IO7'},
'PC0': {'pin': 23, 'name': 'IO9'},
'PC1': {'pin': 24, 'name': 'IO10'},
'PC2': {'pin': 25, 'name': 'IO11'},
'PC3': {'pin': 26, 'name': 'IO12'},
'PC4': {'pin': 27, 'name': 'IO11'},
'PC5': {'pin': 28, 'name': 'IO12'},
'PE0': {'pin': 3, 'name': 'SDA'},
'PE1': {'pin': 6, 'name': ''},
'PE2': {'pin': 19, 'name': ''},
'DS18B20-1': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-2': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-3': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-4': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-5': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-6': {'pin': 35, 'name': 'DS18B20'},
'DS18B20-7': {'pin': 35, 'name': 'DS18B20'},
}
dl485m_gpio.update(common_gpio)
dl485b_gpio = { # Definizione GPIO DL485B
'IO1': {'pin': 23, 'name': 'IO1'},
'IO2': {'pin': 24, 'name': 'IO2'},
'IO3': {'pin': 25, 'name': 'IO3'},
'IO4': {'pin': 26, 'name': 'IO4'},
'PE2': {'pin': 19, 'name': 'ADC'},
'OUT1': {'pin': 3, 'name': 'RELE1'},
'OUT2': {'pin': 2, 'name': 'RELE2'},
'OUT3': {'pin': 1, 'name': 'RELE3'},
}
dl485b_gpio.update(common_gpio)
dl485r_gpio = { # Definizione GPIO DL485R V.2.2
'IO1': {'pin': 15, 'name': 'IO1', 'function': ['I', 'O', 'A']},
'IO2': {'pin': 16, 'name': 'IO2', 'function': ['I', 'O', 'A']},
'IO3': {'pin': 25, 'name': 'IO3', 'function': ['I', 'O', 'A']},
'IO4': {'pin': 26, 'name': 'IO4', 'function': ['I', 'O', 'A']},
'OUT1': {'pin': 2, 'name': 'RELE1', 'function': ['O']},
'OUT2': {'pin': 1, 'name': 'RELE2', 'function': ['O']},
'VIN': {'pin': 22, 'name': 'VIN', 'function': ['VIN']},
'RMS_POWER_CH1':{'pin': 41, 'name': 'RMS_POWER_CH1'},
'RMS_POWER_CH2':{'pin': 41, 'name': 'RMS_POWER_CH2'},
'RMS_POWER_REAL': {'pin': 41, 'name': 'RMS_POWER_REAL'},
'RMS_POWER_APPARENT': {'pin': 41, 'name': 'RMS_POWER_APPARENT'},
'RMS_POWER_COSFI': {'pin': 41, 'name': 'RMS_POWER_COSFI'},
'RMS_POWER_LOOP': {'pin': 41, 'name': 'RMS_POWER_LOOP'},
}
dl485r_gpio.update(common_gpio)
dl485p_gpio = { # Definizione GPIO DL485P V.2.2
'PB1': {'pin': 13},
'PB2': {'pin': 14},
'PB3': {'pin': 15},
'PB4': {'pin': 16},
'PB5': {'pin': 17},
'PC0': {'pin': 23},
'PC1': {'pin': 24},
'PC2': {'pin': 25},
'PC3': {'pin': 26},
'PD3': {'pin': 1},
'PD5': {'pin': 9},
'PD6': {'pin': 10},
'PE0': {'pin': 3},
'PE1': {'pin': 6},
'PE2': {'pin': 19},
}
dl485p_gpio.update(common_gpio)
dl485d_gpio = { # Definizione GPIO DL485D
'IN1': {'pin': 23, 'name': 'IN1'},
'IN2': {'pin': 24, 'name': 'IN2'},
'IN3': {'pin': 25, 'name': 'IN3'},
'IN4': {'pin': 26, 'name': 'IN4'},
'IN5': {'pin': 27, 'name': 'IN5'},
'IN6': {'pin': 28, 'name': 'IN6'},
'DIM1': {'pin': 14, 'name': 'DIMMER1'},
'DIM2': {'pin': 13, 'name': 'DIMMER2'},
'DIM3': {'pin': 1, 'name': 'DIMMER3'},
'DIM4': {'pin': 15, 'name': 'DIMMER4'},
'DIMG': {'pin': 41, 'name': 'DIMMER GENERALE'},
}
dl485d_gpio.update(common_gpio)
dl485d4_gpio = { # Definizione GPIO DL485D
'IN1': {'pin': 23, 'name': 'IN1'},
'IN2': {'pin': 24, 'name': 'IN2'},
'IN3': {'pin': 25, 'name': 'IN3'},
'IN4': {'pin': 26, 'name': 'IN4'},
'IN5': {'pin': 27, 'name': 'IN5'},
'IN6': {'pin': 28, 'name': 'IN6'},
'DIM1': {'pin': 1, 'name': 'DIMMER1'},
'DIM2': {'pin': 15, 'name': 'DIMMER2'},
'DIM3': {'pin': 14, 'name': 'DIMMER3'},
'DIM4': {'pin': 13, 'name': 'DIMMER4'},
'DIMG': {'pin': 41, 'name': 'DIMMER GENERALE'},
}
dl485d4_gpio.update(common_gpio)
iomap = { # MAP IO of board in base al tipoboard 1,2,3,4,5
1: dl485m_gpio, # DL485B
2: dl485b_gpio, # DL485B
4: dl485r_gpio, # DL485R
5: dl485p_gpio, # DL485P
6: dl485d_gpio, # DL485D1
7: dl485d_gpio, # DL485D3
8: dl485d4_gpio, # DL485D4
}
# Speed Baudate
speed = {
1: 1200,
2: 2400,
3: 4800,
4: 9600,
5: 14400,
6: 19200, # Default
7: 28800,
8: 38400, # Do not use
9: 57600, # Do not use
0: 115200, # Do not use
1200: 1,
2400: 2,
4800: 3,
9600: 4,
14400: 5,
19200: 6,
28800: 7,
38400: 8, # Do not use
57600: 9, # Do not use
115200: 0, # Do not use
}
def __init__(self, config_file_name, logstate=0):
super().__init__(config_file_name, logstate)
self.system = '' # Variabile con il sistema che instanzia la classe (Domoticz, Home Assistence, ....)
self.boardbadcounter_n = 10 # Numero di conteggi prima che la board venga disabilitata
# Contatore SCHEDE che non rispondono. Per evitare che la configurazione si blocchi
self.boardbadcounter = [self.boardbadcounter_n for x in range(64)]
self.BOARD_ADDRESS = 0
self.config = {} # Configuration dict
self.status = {} # Stauts of all IO Board
self.RMS_POWER_DICT = {}
self.mapiotype = {} # Tipi di IO disponibili
self.mapproc = {} # Procedure associate agli ingressi verso le uscite
self.poweroff_voltage_setup = 10 # Time to make shutdown for unvervoltage limit
self.poweroff_voltage_counter = self.poweroff_voltage_setup
self.poweron_linked = 0
self.get_json_config(config_file_name)
# ID assegnato a Raspberry PI per accedere al Bus
self.BOARD_ADDRESS = int(self.config['GENERAL_NET']['board_address'])
self.MAX_BOARD_ADDRESS = int(self.config['GENERAL_NET'].get('max_board_address', 63)) # Max number of boards
self.checkConfigFile()
self.dict_board_io() # Crea il DICT con i valori IO basato sul file di configurazione (solo boards attive)
self.bus_baudrate = int(self.config['GENERAL_NET']['bus_baudrate']) # Legge la velocità del BUS
self.bus_port = self.config['GENERAL_NET']['bus_port'] # Legge la porta del BUS di Raspberry PI
# Flag per sovrascrivere "nome" e "descrizione" degli IO su Domoticz
self.overwrite_text = int(self.config['GENERAL_NET'].get('overwrite_text', 0))
self.TIME_PRINT_LOG = 4 # intervallo di tempo in secondi per la stampa periodica del log a schermo
self.nowtime = self.oldtime = int(time.time())
self.RXtrama = []
self.TXmsg = [] # Lista che contiene le liste da trasmettere sul BUS
self.board_ready = {}
self.BUFF_MSG_TX = {} # dizionario dei messaggi trasmessi indicizzato secondo indirizzo destinatario
self.NLOOPTIMEOUT = 5 # numero di giri del loop dopo i quali si ritrasmettera il messaggio
self.LOOP_WAIT_REINSERIMENTO = 3
self.Connection = False # Setup serial
# Flag per inviare la configurazone dei nodi al boot
self.send_configuration = int(self.config['GENERAL_NET'].get('send_configuration', 1))
# Legge ID assegnato a Raspberry PI per accedere al Bus # Instanza telegram bot
self.telegram_enable = int(self.config['GENERAL_NET'].get('telegram_enable'))
# Legge ID assegnato a Raspberry PI per accedere al Bus # Instanza telegram bot
self.telegram_token = self.config['GENERAL_NET'].get('telegram_token', False)
self.telegram_bot = False # Instance
self.telegram = False # Instance bot
self.chat_id = ''
self.get_board_type = {}
self.crondata = {} # DICT with periodic command
self.cronoldtime = self.cron_sec = self.cron_min = self.cron_hour = self.cron_day = 0
self.getConfiguration() # Set configuration of boardsx e mette la configurazione in coda da inviare
self.cronStartup = False # Flag per invio di cron una sola volta dopo lo startup
self.mqtt_enable = int(self.config['GENERAL_NET']['mqtt_enable'])
if self.mqtt_enable:
try:
self.writelog(f"self.mqtt_enable: {self.mqtt_enable}")
self.mqtt_broker = self.config['GENERAL_NET']['mqtt_broker']
self.mqtt_port = self.config['GENERAL_NET']['mqtt_port']
self.mqtt_topic = self.config['GENERAL_NET']['mqtt_topic']
self.mqtt_username = self.config['GENERAL_NET']['mqtt_broker_username']
self.mqtt_password = self.config['GENERAL_NET']['mqtt_broker_password']
self.mqtt_client_id = self.config['GENERAL_NET']['mqtt_client_id']
self.client = Client.Client(self.mqtt_client_id)
self.client.username_pw_set(self.mqtt_username, self.mqtt_password)
self.client.on_connect = self.on_connect
self.client.connect(self.mqtt_broker)
self.client.on_message = self.on_message
self.client.subscribe(f'{self.mqtt_topic}/#')
self.client.loop_start()
# self.client.loop_forever()
except:
self.writelog("ERROR MQTT CONNECTION. It will be disabled!!!", 'RED')
self.mqtt_enable = 0
if self.telegram_enable:
self.telegram = TelBot(self.telegram_token, self.get_board_type, self.mapiotype, self.status)
self.telegram.init_bot()
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
self.writelog(f"Connected to MQTT Broker {self.mqtt_broker} !")
else:
error = Client.error_string(rc)
self.writelog(f"Failed to connect, return code error:{rc} {error}\n", 'RED')
def on_message(self, client, userdata, message):
bb = message._topic.decode().split("/") # MQTT topic, board_id, logic_io received
# try:
board_id = int(bb[1])
logic_io = int(bb[2])
device_type = self.mapiotype[board_id][logic_io]['device_type']
device_type_name = self.device_type_dict[device_type]['dtype']
value = message.payload.decode()
# print(device_type_name)
# print("----------------MSG:", board_id, logic_io, [value])
if device_type_name in ['Switch']:
msg = self.writeIO(board_id, logic_io, [int(value)])
self.TXmsg.append(msg)
# except:
# print("MQTT ERROR RECEIVED:", message._topic.decode(), message.payload.decode() )
def dict_raise_on_duplicates(self, pairs):
"""
Check if config.json have duplicate keys
"""
error = []
board_list = []
for k, v in pairs:
if k in board_list:
error.append(k)
else:
board_list.append(k)
return error
def recursiveKeyOnDict(self, d, target):
# print("recursiveKeyOnDict")
for key, value in d.items():
yield key
if isinstance(value, dict):
yield from self.recursiveKeyOnDict(value, key)
# elif key == target:
# yield key
@timed_function
def get_json_config(self, config_file_name):
"""
Create self.config from JSON configuration file
"""
# from collections import OrderedDict
config = open(config_file_name, 'r')
config = config.read()
config = re.sub(r'#.*\n', '\n', config)
config = re.sub(r'\\\n', '', config)
config = re.sub(r'//.*\n', '\n', config)
try:
error = json.loads(config, object_pairs_hook=self.dict_raise_on_duplicates)
if error:
self.writelog(f"ERROR board {error} duplicated in config.json !!!", 'RED')
sys.exit()
else:
config = json.loads(config)
self.config = config
except json.decoder.JSONDecodeError as e:
self.writelog(f"Error into config.json file: {e}", 'RED')
sys.exit()
except TypeError as e:
self.writelog("Error into config.json file: {e}", 'RED')
sys.exit()
def checkConfigFile(self):
"""
Check if keys present for each IO are right
To need complete!!!
"""
print("== checkConfigFile == \n")
key_general_net = ['bus_port', 'bus_baudrate', 'max_board_address', 'board_address', 'telegram_token',
'telegram_enable', 'overwrite_text', 'send_configuration',
'mqtt_enable', 'mqtt_port', 'mqtt_broker', 'mqtt_broker_username', 'mqtt_broker_password',
'mqtt_topic', 'mqtt_client_id']
key_general = ['Custom Sensor', 'description', 'device_type', 'dtype', 'dunit', 'enable', 'kadd', 'kmul',
'logic_io', 'name', 'n_refresh_off', 'n_refresh_on', 'time_refresh']
key_plc = ['plc_counter_filter', 'plc_counter_mode', 'plc_counter_timeout', 'plc_delay_off_on', 'plc_delay_on_off',
'plc_function', 'plc_linked_board_id_logic_io',
'plc_mode_timer', 'plc_powermeter_k', 'plc_rfid_card_code', 'plc_timer_n_transitions', 'plc_time_off',
'plc_time_on', 'plc_time_unit']
for c in self.config:
if c == 'TYPEB': # Controlla che non ci sia il dizionario TYPEB di config.json (file configurazione vecchio)
self.writelog("ERROR!!! file config.json is old type.\nPlease delete TYPEB dictionary and change board_type on GENERAL_BOARD with board_type_name: Example: 'board_type_name': 'DL485M'", 'RED')
sys.exit()
for cc in self.config[c]:
if c == "GENERAL_NET":
if cc not in key_general_net: # key scritta male o in modo errato o non esistente
self.writelog(f"ERROR config.json!!!: wrong key {cc} on GENERAL_NET section.", 'RED')
else:
key_general_net.remove(cc)
elif 'BOARD' in c:
if 'offset_temperature' in self.config[c][cc]:
self.writelog(f"ERROR: Change on {c} logic_io:{self.config[c][cc].get('logic_io')} offset_temperature with kadd - kmuk", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'DS18B20':
key_DS18B20 = ['kadd', 'kmul', 'round_temperature']
for ccc in self.config[c][cc]:
if ccc not in key_DS18B20 and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'TEMP_ATMEGA':
key_TEMP_ATEMEGA = ['kadd', 'kmul', 'round_temperature']
for ccc in self.config[c][cc]:
if ccc not in key_TEMP_ATEMEGA and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'ANALOG_IN':
key_ANALOG_IN = ['plc_function', 'round_value', 'va', 'ada', 'vb', 'adb']
for ccc in self.config[c][cc]:
if ccc not in key_ANALOG_IN and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') in ['DIGITAL_IN', 'DIGITAL_IN_PULLUP']:
key_DIGITAL_IN = ['default_startup_filter_value', 'filter', 'inverted', 'default_startup_value']
for ccc in self.config[c][cc]:
if ccc not in key_DIGITAL_IN and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'DIGITAL_OUT':
key_DIGITAL_OUT = ['default_startup_filter_value', 'default_startup_value', 'inverted', 'plc_preset_input', 'plc_params']
for ccc in self.config[c][cc]:
if ccc not in key_DIGITAL_OUT and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'VINKMKA':
key_VINKMKA = ['kadd', 'kmul', 'rvcc', 'rgnd', 'round_value', 'va', 'ada', 'vb', 'adb', 'analog_filter']
for ccc in self.config[c][cc]:
if ccc not in key_VINKMKA and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'VINR1R2':
key_VINR1R2 = ['rgnd', 'rvcc', 'round_value', 'kadd', 'kmul']
for ccc in self.config[c][cc]:
if ccc not in key_VINR1R2 and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'PSYCHROMETER':
key_PSYCHROMETER = ['round_humidity', 'offset_humidity']
for ccc in self.config[c][cc]:
if ccc not in key_PSYCHROMETER and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'DIGITAL_OUT_PWM' and not 'plc_function' in self.config[c][cc].keys():
key_DIGITAL_OUT_PWM = []
for ccc in self.config[c][cc]:
if ccc not in key_DIGITAL_OUT_PWM and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'AM2320':
key_AM2320 = ['address', 'kadd', 'kmul', 'round_temperature']
for ccc in self.config[c][cc]:
if ccc not in key_AM2320 and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'BME280':
key_BME280 = ['address', 'altitude', 'logic_io_calibration', 'offset_humidity', 'offset_pression', 'kadd', 'kmul', 'round_pression', 'round_temperature', 'round_humidity']
for ccc in self.config[c][cc]:
if ccc not in key_BME280 and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'BME280_CALIB':
key_BME280_CALIB = ['address']
for ccc in self.config[c][cc]:
if ccc not in key_BME280_CALIB and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'RFID_CARD':
key_RFID_CARD = []
for ccc in self.config[c][cc]:
if ccc not in key_RFID_CARD and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'RFID_UNIT':
key_RFID_UNIT = ['filter', 'plc_rfid_ack_wait', 'plc_rfid_unit_mode', 'plc_rfid_unit_n_conf_refresh', 'plc_rfid_unit_tpolling_nocard', 'plc_rfid_unit_tpolling_oncard']
for ccc in self.config[c][cc]:
if ccc not in key_RFID_UNIT and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'RMS_POWER':
key_RMS_POWER = []
for ccc in self.config[c][cc]:
if ccc not in key_RMS_POWER and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'TSL2561':
key_TSL2561 = ['address', 'lux_gain', 'lux_integration', 'kadd', 'kmul', 'round_value']
for ccc in self.config[c][cc]:
if ccc not in key_TSL2561 and ccc not in key_general:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
sys.exit()
if self.config[c][cc].get('device_type') == 'VIRTUAL':
key_VIRTUAL = ['plc_counter_min_period_time']
for ccc in self.config[c][cc]:
if ccc not in key_VIRTUAL and ccc not in key_general and ccc not in key_plc:
self.writelog(f"ERROR config.json in board: {c:<6} - logic_io: {self.config[c][cc].get('logic_io'):>1}: wrong key: {ccc:<20} on section {self.config[c][cc].get('device_type'):<10}", 'RED')
# sys.exit()
def dict_board_io(self):
"""
Crea la mappa dove saranno inseriti i valori dei vari di tutti gli IO presenti in self.config
Crea inoltre il DICT self.mapiotype che permette di recuparare dati utili in breve tempo
"""
for b in self.config:
if 'BOARD' in b:
board_id = int(b[5:])
self.status[board_id] = {} # Dict with all IO status
board_enable = 0
for bb in self.config[b]:
if 'GENERAL_BOARD' in bb:
board_enable = self.config[b][bb]['enable'] # Board enable
if board_enable == 0:
self.writelog(f"{b:<8} DISABLED")
else:
self.writelog(f"{b:<8} ENABLED")
self.status[board_id]['boardtypename'] = self.config[b][bb]['board_type_name']
self.status[board_id]['boardenable'] = self.config[b][bb]['enable']
board_type = self.board_type_available[self.config[b][bb]['board_type_name']]
board_overwrite_text = int(self.config[b][bb].get('overwrite_text', 0))
if 'RMS_POWER_CONF' in bb:
self.RMS_POWER_DICT[board_id] = {}
self.RMS_POWER_DICT[board_id] = self.config[b]['RMS_POWER_CONF']
self.status[board_id]['board_type'] = board_type
name = self.config[b]['GENERAL_BOARD']['name'] # Board name
self.status[board_id]['name'] = name
try:
self.status[board_id]['io'] = [0] * len(self.iomap[board_type])
except:
self.writelog(f"BOARD TYPE {board_type} non esistente")
sys.exit()
for bb in self.config[b]:
if 'GENERAL_BOARD' not in bb:
enable = self.config[b][bb].get('enable', 0)
if not enable:
self.writelog(f"{b:<10} IO {self.config[b][bb].get('logic_io', 0):>3} DISABLED")
continue
else:
self.writelog(f"{b:<10} IO {self.config[b][bb].get('logic_io', 0):>3} ENABLED")
logic_io = int(self.config[b][bb].get('logic_io', 0))
if not logic_io:
self.writelog(f"LOGIC_IO non impostato, BoardID={b} {bb}")
sys.exit()
if board_id not in self.mapiotype:
self.mapiotype[board_id] = {}
inverted = int(self.config[b][bb].get('inverted', 0))
# print("-===-", self.config[b][bb])
if 'device_type' in self.config[b][bb]:
device_type = self.config[b][bb]['device_type']
else:
self.writelog(f"DEVICE_TYPE NON DEFINITO IN FILE JSON: board_id: {b} - logic_io: {logic_io} - io_name: {bb}%s")
self.writelog(f"\nVALORI AMMESSI PER device_type su FILE JSON.\nValori validi:\n")
for k in self.device_type_dict.keys():
self.writelog(k)
sys.exit()
try:
pin = self.iomap[board_type][bb]['pin']
except:
self.writelog(f"NOME LABEL '{bb}' NON TROVATO NELLA DEFINIZIONE DELLA '{b}' TIPO: {board_type}")
sys.exit()
pin = 0
if pin > 0:
try:
fisic_io = self.mapmicro[self.iomap[board_type][bb]['pin']]['fisic_io']
except:
fisic_io = 99
else:
fisic_io = 99
direction = self.device_type_dict[device_type].get('direction')
if not direction:
self.writelog(f"ERROR: VALORI AMMESSI: {self.device_type_dict[device_type]}", 'RED')
raise "ERROR: direcrtion NOT DEFINE!!!"
# pprint(self.config[b][bb])
self.mapiotype[board_id][logic_io] = {
'altitude': int(self.config[b][bb].get('altitude', 0)), # OFFSET altitudine
'analog_filter': self.config[b][bb].get('analog_filter', False), # Analog Filter
'board_enable': board_enable, # Abilitazione scheda
'board_overwrite_text': board_overwrite_text,
'board_type': board_type, # Tipo scheda
'plc_rfid_card_code': self.config[b][bb].get('plc_rfid_card_code'),
'default_startup_filter_value': int(self.config[b][bb].get('default_startup_filter_value', 0)), # 0 o 1
'default_startup_value': int(self.config[b][bb].get('default_startup_value', 0)), # Valore di default allo startup
'description': self.config[b][bb].get('description', 'NO description'), # Descrizione IO
'device_address': self.config[b][bb].get('address', []), # Address of I2C / Onewire (serial number for DS18B20)
'device_type': device_type, # Tipo di device collegato al PIN del micro
'dimmer_change_memory': int(self.config[b][bb].get('dimmer_change_memory', 1)),
'dimmer_extension': int(self.config[b][bb].get('dimmer_extension', 0)),
'dimmer_manual_go_off': int(self.config[b][bb].get('dimmer_manual_go_off', 0)),
'dimmer_mode': int(self.config[b][bb].get('dimmer_mode', 0)),
'dimmer_mode_fraction': int(self.config[b][bb].get('dimmer_mode_fraction', 0)),
'dimmer_poweron_state': int(self.config[b][bb].get('dimmer_poweron_state', 0)),
'dimmer_max': int(self.config[b][bb].get('dimmer_max', 255)),
'dimmer_min': int(self.config[b][bb].get('dimmer_min', 1)),
'dimmer_button_time': int(self.config[b][bb].get('dimmer_button_time', 30)),
'dimmer_delay_auto_up': int(self.config[b][bb].get('dimmer_delay_auto_up', 3)),
'dimmer_delay_auto_dw': int(self.config[b][bb].get('dimmer_delay_auto_dw', 3)),
'dimmer_delay_manual': int(self.config[b][bb].get('dimmer_delay_manual', 4)),
'dimmer_fraction_limit': int(self.config[b][bb].get('dimmer_fraction_limit', 200)),
'dimmer_linked': int(self.config[b][bb].get('dimmer_linked', 1)),
'dimmer_step_pwm': int(self.config[b][bb].get('dimmer_step_pwm', 5)),
'dimmer_time_reverse_dir': int(self.config[b][bb].get('dimmer_time_reverse_dir', 200)),
'dimmer_time_reset_dir': int(self.config[b][bb].get('dimmer_time_reset_dir', 200)),
'direction': direction, # Input / Output
'direction_val': 1 if direction == 'output' else 0, # 1=Output, 0=Input (how arduino)
'dtype': self.config[b][bb].get('dtype', self.device_type_dict[device_type].get('dtype', 'Switch')), # Domoticz Device
'enable': enable,
'filter': int(self.config[b][bb].get('filter', 20)), # For digital input (Anti-bounce filter)
'fisic_io': fisic_io, # PIN address od micro
'inverted': inverted, # Logic Invert of IO
'kadd': self.config[b][bb].get('kadd', 0),
'kmul': self.config[b][bb].get('kmul', 1),
'logic_io': logic_io,
'logic_io_calibration': self.config[b][bb].get('logic_io_calibration', 0),
'lux_gain': int(self.config[b][bb].get('lux_gain', 0)),
'lux_integration': int(self.config[b][bb].get('lux_integration', 0)),
'n_refresh_off': int(self.config[b][bb].get('n_refresh_off', 1)),
'n_refresh_on': int(self.config[b][bb].get('n_refresh_on', 1)),
'name': self.config[b][bb].get('name', 'NO Name'),
'offset_pression': int(self.config[b][bb].get('offset_pression', 0)), # OFFSET pression
'offset_humidity': int(self.config[b][bb].get('offset_humidity', 0)), # OFFSET temperature
'only_fronte_off': int(self.config[b][bb].get('only_fronte_off', 0)),
'only_fronte_on': int(self.config[b][bb].get('only_fronte_on', 0)),
'pin_label': bb,
'pin': pin,
'plc_byte_list_io': [],
'plc_counter_filter': self.config[b][bb].get('plc_counter_filter', 0),
'plc_counter_min_period_time': int(self.config[b][bb].get('plc_counter_min_period_time', 0)),
'plc_counter_mode': int(self.config[b][bb].get('plc_counter_mode', 256)), # inizializza con 256 che significa che non è stato inizializzato correttamente
'plc_counter_timeout': int(self.config[b][bb].get('plc_counter_timeout', 0)),
'plc_delay_off_on': int(self.config[b][bb].get('plc_delay_off_on', 0)),
'plc_delay_on_off': int(self.config[b][bb].get('plc_delay_on_off', 0)),
'plc_function': self.config[b][bb].get('plc_function', 'disable'),
'plc_linked_board_id_logic_io': self.config[b][bb].get('plc_linked_board_id_logic_io', []),
'plc_mode_timer': int(self.config[b][bb].get('plc_mode_timer', 0)),
'plc_params': self.config[b][bb].get('plc_params', 0),
'plc_powermeter_k': int(self.config[b][bb].get('plc_powermeter_k', 0)),
'plc_preset_input': int(self.config[b][bb].get('plc_preset_input', 0)),
'plc_rfid_ack_wait': int(self.config[b][bb].get('plc_rfid_ack_wait', 50)),
'plc_rfid_unit_tpolling_nocard': int(self.config[b][bb].get('plc_rfid_unit_tpolling_nocard', 10)),
'plc_rfid_unit_tpolling_oncard': int(self.config[b][bb].get('plc_rfid_unit_tpolling_oncard', 10)),
'plc_rfid_unit_mode': int(self.config[b][bb].get('plc_rfid_unit_mode', 33)),
'plc_rfid_unit_n_conf_refresh': int(self.config[b][bb].get('plc_rfid_unit_n_conf_refresh', 10)),
'plc_time_off': int(self.config[b][bb].get('plc_time_off', 0)),
'plc_time_on': int(self.config[b][bb].get('plc_time_on', 0)),
'plc_time_unit': float(self.config[b][bb].get('plc_time_unit', 1)), # default 1 secondo
'plc_timer_n_transitions': int(self.config[b][bb].get('plc_timer_n_transitions', 0)),
'plc_tmax_on': int(self.config[b][bb].get('plc_tmax_on', 65535)),
'plc_xor_input': 0,
'power_on_timeout': int(self.config[b][bb].get('power_on_timeout', 0)),
'power_on_tmin_off': int(self.config[b][bb].get('power_on_tmin_off', 0)),
'power_on_voltage_off': float(self.config[b][bb].get('power_on_voltage_off', 0)),
'power_on_voltage_on': float(self.config[b][bb].get('power_on_voltage_on', 0)),
'pullup': self.config[b][bb].get('pullup', self.device_type_dict[device_type].get('pullup', 0)),
'rgnd': int(self.config[b][bb].get('rgnd', 100000)),
'rms_power_mode': int(self.config[b][bb].get('rms_power_mode', 0)),
'rms_power_logic_id_ch1': int(self.config[b][bb].get('rms_power_logic_id_ch1', 0)),
'rms_power_logic_id_ch2': int(self.config[b][bb].get('rms_power_logic_id_ch2', 0)),
'rms_power_logic_id_real': int(self.config[b][bb].get('rms_power_logic_id_real', 0)),
'rms_power_logic_id_apparent': int(self.config[b][bb].get('rms_power_logic_id_apparent', 0)),
'rms_power_logic_id_cosfi': self.config[b][bb].get('rms_power_logic_id_cosfi', 0),
'rms_power_logic_id_phase': self.config[b][bb].get('rms_power_logic_id_phase', 0),
'rms_power_filter': int(self.config[b][bb].get('rms_power_filter', 30)),
'rms_power_mul_ch1': int(self.config[b][bb].get('rms_power_mul_ch1', 10)),
'rms_power_mul_ch2': int(self.config[b][bb].get('rms_power_mul_ch2', 10)),
'rms_power_logic_id_offset': int(self.config[b][bb].get('rms_power_logic_id_offset', 0)),
'rms_power_logic_offset_ls': int(self.config[b][bb].get('rms_power_logic_offset_ls', 0)),
'rms_power_logic_offset_ms': int(self.config[b][bb].get('rms_power_logic_offset_ms', 0)),
'rms_power_default_ch2_off': int(self.config[b][bb].get('rms_power_default_ch2_off', 230)),
"rms_power_scale_ch1": int(self.config[b][bb].get('rms_power_scale_ch1', 1)),
"rms_power_scale_ch2": int(self.config[b][bb].get('rms_power_scale_ch2', 1)),
"rms_power_scale": int(self.config[b][bb].get('rms_power_scale', 1)),
'round_value': int(self.config[b][bb].get('round_value', 0)), # sostituisce round
'round_humidity': int(self.config[b][bb].get('round_humidity', 0)),
'round_pression': int(self.config[b][bb].get('round_pression', 0)),
'round_temperature': int(self.config[b][bb].get('round_temperature', 1)),
'rvcc': int(self.config[b][bb].get('rvcc', 1)),
'time_refresh': int(self.config[b][bb].get('time_refresh', 3000)),
'type_io': self.device_type_dict[device_type].get('type_io'),
'dunit': self.config[b][bb].get('dunit'),
'write_ee': self.config[b][bb].get('write_ee', []),
'va': int(self.config[b][bb].get('va', 0)),
'ada': int(self.config[b][bb].get('ada', 0)),
'vb': int(self.config[b][bb].get('vb', 0)),
'adb': int(self.config[b][bb].get('adb', 0)),
}
app = []
plc_xor_input = 0
plc_byte_list_io = []
for x in self.mapiotype[board_id][logic_io]['plc_linked_board_id_logic_io']:
xx = x.split("-")
if xx[0][0] == '!': # sistema la negazione degli ingressi
xx[0] = xx[0][1:]
plc_xor_input = plc_xor_input * 2 + 1
else:
plc_xor_input = plc_xor_input * 2
if "*" in xx[0]:
xx[0] = board_id
plc_byte_list_io.append(int(xx[0]))
plc_byte_list_io.append(int(xx[1]))
app1 = f'{xx[0]}-{xx[1]}'
app.append(app1)
if app1 not in self.mapproc:
self.mapproc[app1] = {}
self.mapproc[app1] = {'board_id': board_id, 'logic_io': logic_io}
self.mapiotype[board_id][logic_io]['plc_linked_board_id_logic_io'] = app
self.mapiotype[board_id][logic_io]['plc_xor_input'] = plc_xor_input
self.mapiotype[board_id][logic_io]['plc_byte_list_io'] = plc_byte_list_io
def make_inverted(self, board_id, logic_io, value):
"""
Invert IO value. To use if not PLC function on board
"""
if board_id not in self.mapiotype or logic_io not in self.mapiotype[board_id]:
return 0
inverted = self.mapiotype[board_id][logic_io]['inverted']
if inverted:
value = 1 - value & 1
self.status[board_id]['io'][logic_io - 1] = value # Valore corrente IO
# print("value2", value)
return value
def calc_crc_DS(self, b, crc):
"""
Calc CRC of DS18xxx
"""
a = 0xff00 | b
while 1:
crc = ((((crc ^ a) & 1) * 280) ^ crc) // 2
a = a // 2
if a <= 255:
return crc
def adc_value(self, VIN, rvcc, rgnd):
"""
Dato il valore della tensione e le resistenze del partitore, ricavo la tensione in ingresso ADC del micro
"""
try:
value = VIN / (rvcc + rgnd) * rgnd * 930.0
return value
except:
self.writelog(f"ERROR def adc_value -> Vin:{VIN} Rvcc:{rvcc} Rgng:{rgnd}", 'RED')
return 0
def byteLSMS2uint(self, byteLS, byteMS):
"""
Dati 2 byte (LS e MS) ritorna 1 WORD senza segno
"""
return byteLS + (byteMS * 256)
def byteLSMS2int(self, byteLS, byteMS):
"""
Dati 2 byte (LS e MS) ritorna 1 WORD con segno
"""
if byteMS > 127:
return -32768 + (byteLS + ((byteMS - 128) * 256))
return self.byteLSMS2uint(byteLS, byteMS)
# return byteLS + (byteMS * 256)