This repository has been archived by the owner on Dec 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
__init__.py
executable file
·2118 lines (1787 loc) · 91.2 KB
/
__init__.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/env python3
# vim: set encoding=utf-8 tabstop=4 softtabstop=4 shiftwidth=4 expandtab
#########################################################################
# Copyright 2020 Michael Wenzel
# Copyright 2020 Sebastian Helms
#########################################################################
# Viessmann-Plugin for SmartHomeNG. https://github.com/smarthomeNG//
#
# This plugin is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This plugin is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this plugin. If not, see <http://www.gnu.org/licenses/>.
#########################################################################
import logging
import sys
import time
import re
import json
import serial
import threading
from datetime import datetime
import dateutil.parser
import cherrypy
if __name__ == '__main__':
# just needed for standalone mode
class SmartPlugin():
pass
class SmartPluginWebIf():
pass
import os
BASE = os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-3])
sys.path.insert(0, BASE)
import commands
else:
from . import commands
from lib.item import Items
from lib.model.smartplugin import SmartPlugin, SmartPluginWebIf, Modules
from bin.smarthome import VERSION
class Viessmann(SmartPlugin):
'''
Main class of the plugin. Provides communication with Viessmann heating systems
via serial / USB-to-serial connections to read values and set operating parameters.
Supported device types must be defined in ./commands.py.
'''
ALLOW_MULTIINSTANCE = False
PLUGIN_VERSION = '1.2.2'
#
# public methods
#
def __init__(self, sh, *args, standalone='', logger=None, **kwargs):
# standalone mode: just setup basic info
if standalone:
self._serialport = standalone
self._timeout = 3
self.logger = logger
self._standalone = True
else:
# Get plugin parameter
self._serialport = self.get_parameter_value('serialport')
self._heating_type = self.get_parameter_value('heating_type')
self._protocol = self.get_parameter_value('protocol')
self._timeout = self.get_parameter_value('timeout')
self._standalone = False
# Set variables
self._error_count = 0
self._params = {} # Item dict
self._init_cmds = [] # List of command codes for read at init
self._cyclic_cmds = {} # Dict of command codes with cylce-times for cyclic readings
self._application_timer = {} # Dict of application timer with command codes and values
self._timer_cmds = [] # List of command codes for timer
self._viess_timer_dict = {}
self._last_values = {}
self._balist_item = None # list of last value per command code
self._lock = threading.Lock()
self._initread = False
self._timerread = False
self._connected = False
self._initialized = False
self._lastbyte = b''
self._lastbytetime = 0
self._cyclic_update_active = False
self._wochentage = {
'MO': ['mo', 'montag', 'monday'],
'TU': ['di', 'dienstag', 'tuesday'],
'WE': ['mi', 'mittwoch', 'wednesday'],
'TH': ['do', 'donnerstag', 'thursday'],
'FR': ['fr', 'freitag', 'friday'],
'SA': ['sa', 'samstag', 'saturday'],
'SU': ['so', 'sonntag', 'sunday']}
# if running standalone, don't initialize command sets
if not sh:
return
# initialize logger if necessary
if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
self.logger = logging.getLogger(__name__)
self._config_loaded = False
if not self._load_configuration():
return None
# Init web interface
self.init_webinterface()
def run(self):
'''
Run method for the plugin
'''
if not self._config_loaded:
if not self._load_configuration():
return
self.alive = True
self._connect()
self._read_initial_values()
self._read_timers()
def stop(self):
'''
Stop method for the plugin
'''
self.alive = False
if self.scheduler_get('cyclic'):
self.scheduler_remove('cyclic')
self._disconnect()
# force reload of configuration on restart
self._config_loaded = False
def parse_item(self, item):
'''
Method for parsing items.
If the item carries any viess_* field, this item is registered to the plugin.
:param item: The item to process.
:type item: object
:return: The item update method to be triggered if the item is changed, or None.
:rtype: object
'''
# Process the update config
if self.has_iattr(item.conf, 'viess_update'):
self.logger.debug(f'Item for requesting update for all items triggered: {item}')
return self.update_item
# Process the timer config and fill timer dict
if self.has_iattr(item.conf, 'viess_timer'):
timer_app = self.get_iattr_value(item.conf, 'viess_timer')
for commandname in self._commandset:
if commandname.startswith(timer_app):
commandconf = self._commandset[commandname]
self.logger.debug(f'Process the timer config, commandname: {commandname}')
# {'addr': '2100', 'len': 8, 'unit': 'CT', 'set': True}
commandcode = (commandconf['addr']).lower()
if timer_app not in self._application_timer:
self._application_timer[timer_app] = {'item': item, 'commandcodes': []}
if commandcode not in self._application_timer[timer_app]['commandcodes']:
self._application_timer[timer_app]['commandcodes'].append(commandcode)
self._application_timer[timer_app]['commandcodes'].sort()
self.logger.info(f'Loaded Application Timer {self._application_timer}')
# self._application_timer: {'Timer_M2': {'item': Item: heizung.heizkreis_m2.schaltzeiten, 'commandcodes': ['3000', '3008', '3010', '3018', '3020', '3028', '3030']}, 'Timer_Warmwasser': {'item': Item: heizung.warmwasser.schaltzeiten, 'commandcodes': ['2100', '2108', '2110', '2118', '2120', '2128', '2130']}}
for subdict in self._application_timer:
for commandcode in self._application_timer[subdict]['commandcodes']:
if commandcode not in self._timer_cmds:
self._timer_cmds.append(commandcode)
self._timer_cmds.sort()
self.logger.debug(f'Loaded Timer commands {self._timer_cmds}')
return self.update_item
# Process the read config
if self.has_iattr(item.conf, 'viess_read'):
commandname = self.get_iattr_value(item.conf, 'viess_read')
if commandname is None or commandname not in self._commandset:
self.logger.error(f'Item {item} contains invalid read command {commandname}!')
return None
# Remember the read config to later update this item if the configured response comes in
self.logger.info(f'Item {item} reads by using command {commandname}')
commandconf = self._commandset[commandname]
commandcode = (commandconf['addr']).lower()
# Fill item dict
self._params[commandcode] = {'item': item, 'commandname': commandname}
self.logger.debug(f'Loaded params {self._params}')
# Allow items to be automatically initiated on startup
if self.has_iattr(item.conf, 'viess_init') and self.get_iattr_value(item.conf, 'viess_init'):
self.logger.info(f'Item {item} is initialized on startup')
if commandcode not in self._init_cmds:
self._init_cmds.append(commandcode)
self.logger.debug(f'CommandCodes should be read at init: {self._init_cmds}')
# Allow items to be cyclically updated
if self.has_iattr(item.conf, 'viess_read_cycle'):
cycle = int(self.get_iattr_value(item.conf, 'viess_read_cycle'))
self.logger.info(f'Item {item} should read cyclic every {cycle} seconds')
nexttime = time.time() + cycle
if commandcode not in self._cyclic_cmds:
self._cyclic_cmds[commandcode] = {'cycle': cycle, 'nexttime': nexttime}
else:
# If another item requested this command already with a longer cycle, use the shorter cycle now
if self._cyclic_cmds[commandcode]['cycle'] > cycle:
self._cyclic_cmds[commandcode]['cycle'] = cycle
self.logger.debug(f'CommandCodes should be read cyclic: {self._cyclic_cmds}')
# Process the write config
if self.has_iattr(item.conf, 'viess_send'):
if self.get_iattr_value(item.conf, 'viess_send'):
commandname = self.get_iattr_value(item.conf, 'viess_read')
else:
commandname = self.get_iattr_value(item.conf, 'viess_send')
if commandname is None or commandname not in self._commandset:
self.logger.error(f'Item {item} contains invalid write command {commandname}!')
return None
else:
self.logger.info(f'Item {item} to be written by using command {commandname}')
return self.update_item
# get operating modes list
if self.has_iattr(item.conf, 'viess_ba_list'):
self._balist_item = item
self.logger.info(f'Item {item} wants list of operating modes')
def parse_logic(self, logic):
pass
def update_item(self, item, caller=None, source=None, dest=None):
'''
Callback method for sending values to the plugin when a registered item has changed
:param item: item to be updated towards the plugin
:param caller: if given it represents the callers name
:param source: if given it represents the source
:param dest: if given it represents the dest
'''
if self.alive and caller != self.get_shortname():
self.logger.info(f'Update item: {item.id()}, item has been changed outside this plugin')
self.logger.debug(f'update_item was called with item {item} from caller {caller}, source {source} and dest {dest}')
if self.has_iattr(item.conf, 'viess_send'):
# Send write command
if self.get_iattr_value(item.conf, 'viess_send'):
commandname = self.get_iattr_value(item.conf, 'viess_read')
else:
commandname = self.get_iattr_value(item.conf, 'viess_send')
value = item()
self.logger.debug(f'Got item value to be written: {value} on command name {commandname}')
if not self._send_command(commandname, value):
# create_write_command() liefert False, wenn das Schreiben fehlgeschlagen ist
# -> dann auch keine weitere Verarbeitung
self.logger.debug(f'Write for {commandname} with value {value} failed, reverting value, canceling followup actions')
item(item.property.last_value, self.get_shortname())
return None
# If a read command should be sent after write
if self.has_iattr(item.conf, 'viess_read') and self.has_iattr(item.conf, 'viess_read_afterwrite'):
readcommandname = self.get_iattr_value(item.conf, 'viess_read')
readafterwrite = self.get_iattr_value(item.conf, 'viess_read_afterwrite')
self.logger.debug(f'Attempting read after write for item {item}, command {readcommandname}, delay {readafterwrite}')
if readcommandname is not None and readafterwrite is not None:
aw = float(readafterwrite)
time.sleep(aw)
self._send_command(readcommandname)
# If commands should be triggered after this write
if self.has_iattr(item.conf, 'viess_trigger'):
trigger = self.get_iattr_value(item.conf, 'viess_trigger')
if trigger is None:
self.logger.error(f'Item {item} contains invalid trigger command list {trigger}!')
else:
tdelay = 5 # default delay
if self.has_iattr(item.conf, 'viess_trigger_afterwrite'):
tdelay = float(self.get_iattr_value(item.conf, 'viess_trigger_afterwrite'))
if type(trigger) != list:
trigger = [trigger]
for triggername in trigger:
triggername = triggername.strip()
if triggername is not None and readafterwrite is not None:
self.logger.debug(f'Triggering command {triggername} after write for item {item}')
time.sleep(tdelay)
self._send_command(triggername)
elif self.has_iattr(item.conf, 'viess_timer'):
timer_app = self.get_iattr_value(item.conf, 'viess_timer')
uzsu_dict = item()
self.logger.debug(f'Got changed UZSU timer: {uzsu_dict} on timer application {timer_app}')
self._uzsu_dict_to_viess_timer(timer_app, uzsu_dict)
elif self.has_iattr(item.conf, 'viess_update'):
if item():
self.logger.debug('Reading of all values/items has been requested')
self.update_all_read_items()
def send_cyclic_cmds(self):
'''
Recall function for shng scheduler. Reads all values configured to be read cyclically.
'''
# check if another cyclic cmd run is still active
if self._cyclic_update_active:
self.logger.warning('Triggered cyclic command read, but previous cyclic run is still active. Check device and cyclic configuration (too much/too short?)')
return
else:
self.logger.info('Triggering cyclic command read')
# set lock
self._cyclic_update_active = True
currenttime = time.time()
read_items = 0
todo = []
for commandcode in list(self._cyclic_cmds.keys()):
entry = self._cyclic_cmds[commandcode]
# Is the command already due?
if entry['nexttime'] <= currenttime:
todo.append(commandcode)
if self._protocol == 'KW':
# see if we got to do anything - maybe no items are due to be read?
if len(todo) > 0:
self._KW_send_multiple_read_commands(todo)
for addr in todo:
self._cyclic_cmds[addr]['nexttime'] = currenttime + self._cyclic_cmds[addr]['cycle']
read_items = len(todo)
else:
for addr in todo:
# as this loop can take considerable time, repeatedly check if shng wants to stop
if not self.alive:
self.logger.info('shng issued stop command, canceling cyclic read.')
return
commandname = self._commandname_by_commandcode(addr)
self.logger.debug(f'Triggering cyclic read command: {commandname}')
self._send_command(commandname, )
entry['nexttime'] = currenttime + entry['cycle']
read_items += 1
self._cyclic_update_active = False
if read_items:
self.logger.debug(f'cyclic command read took {(time.time() - currenttime):.1f} seconds for {read_items} items')
def update_all_read_items(self):
'''
Read all values preset in commands.py as readable
'''
for commandcode in list(self._params.keys()):
commandname = self._commandname_by_commandcode(commandcode)
self.logger.debug(f'Triggering read command: {commandname} for requested value update')
self._send_command(commandname)
def read_addr(self, addr):
'''
Tries to read a data point indepently of item config
:param addr: data point addr (2 byte hex address)
:type addr: str
:return: Value if read is successful, None otherwise
'''
addr = addr.lower()
commandname = self._commandname_by_commandcode(addr)
if commandname is None:
self.logger.debug(f'Address {addr} not defined in commandset, aborting')
return None
self.logger.debug(f'Attempting to read address {addr} for command {commandname}')
(packet, responselen) = self._build_command_packet(commandname)
if packet is None:
return None
response_packet = self._send_command_packet(packet, responselen)
if response_packet is None:
return None
res = self._parse_response(response_packet, commandname)
if res is None:
return None
(value, commandcode) = res
return value
def read_temp_addr(self, addr, length, unit):
'''
Tries to read an arbitrary supplied data point indepently of device config
:param addr: data point addr (2 byte hex address)
:type addr: str
:param len: Length (in byte) expected from address read
:type len: num
:param unit: Unit code from commands.py
:type unit: str
:return: Value if read is successful, None otherwise
'''
# as we have no reference whatever concerning the supplied data, we do a few sanity checks...
addr = addr.lower()
if len(addr) != 4: # addresses are 2 bytes
self.logger.warning(f'temp address: address not 4 digits long: {addr}')
return None
for c in addr: # addresses are hex strings
if c not in '0123456789abcdef':
self.logger.warning(f'temp address: address digit "{c}" is not hex char')
return None
if length < 1 or length > 32: # empiritistical choice
self.logger.warning(f'temp address: len is not > 0 and < 33: {len}')
return None
if unit not in self._unitset: # units need to be predefined
self.logger.warning(f'temp address: unit {unit} not in unitset. Cannot use custom units')
return None
# addr already known?
if addr in self._commandset:
cmd = self._commandname_by_commandcode(addr)
self.logger.info(f'temp address {addr} already known for command {cmd}')
else:
# create temp commandset
cmd = 'temp_cmd'
cmdconf = {'addr': addr, 'len': length, 'unit': unit, 'set': False}
self.logger.debug(f'Adding temporary command config {cmdconf} for command temp_cmd')
self._commandset[cmd] = cmdconf
res = self.read_addr(addr)
if cmd == 'temp_cmd':
del self._commandset['temp_cmd']
return res
def write_addr(self, addr, value):
'''
Tries to write a data point indepently of item config
:param addr: data point addr (2 byte hex address)
:type addr: str
:param value: value to write
:return: Value if read is successful, None otherwise
'''
addr = addr.lower()
commandname = self._commandname_by_commandcode(addr)
if commandname is None:
self.logger.debug(f'Address {addr} not defined in commandset, aborting')
return None
self.logger.debug(f'Attempting to write address {addr} with value {value} for command {commandname}')
(packet, responselen) = self._build_command_packet(commandname, value)
if packet is None:
return None
response_packet = self._send_command_packet(packet, responselen)
if response_packet is None:
return None
return self._parse_response(response_packet, commandname)
#
# initialization methods
#
def _load_configuration(self):
'''
Load configuration sets from commands.py
'''
# Load protocol dependent sets
if self._protocol in commands.controlset and self._protocol in commands.errorset and self._protocol in commands.unitset and self._protocol in commands.returnstatus and self._protocol in commands.setreturnstatus:
self._controlset = commands.controlset[self._protocol]
self.logger.debug(f'Loaded controlset for protocol {self._controlset}')
self._errorset = commands.errorset[self._protocol]
self.logger.debug(f'Loaded errors for protocol {self._errorset}')
self._unitset = commands.unitset[self._protocol]
self.logger.debug(f'Loaded units for protocol {self._unitset}')
self._devicetypes = commands.devicetypes
self.logger.debug(f'Loaded device types for protocol {self._devicetypes}')
self._returnstatus = commands.returnstatus[self._protocol]
self.logger.debug(f'Loaded return status for protocol {self._returnstatus}')
self._setreturnstatus = commands.setreturnstatus[self._protocol]
self.logger.debug(f'Loaded set return status for protocol {self._setreturnstatus}')
else:
self.logger.error(f'Sets for protocol {self._protocol} could not be found or incomplete!')
return False
# Load device dependent sets
if self._heating_type in commands.commandset and self._heating_type in commands.operatingmodes and self._heating_type in commands.systemschemes:
self._commandset = commands.commandset[self._heating_type]
self.logger.debug(f'Loaded commands for heating type {self._commandset}')
self._operatingmodes = commands.operatingmodes[self._heating_type]
self.logger.debug(f'Loaded operating modes for heating type {self._operatingmodes}')
self._systemschemes = commands.systemschemes[self._heating_type]
self.logger.debug(f'Loaded system schemes for heating type {self._systemschemes}')
else:
sets = []
if self._heating_type not in commands.commandset:
sets += 'command'
if self._heating_type not in commands.operatingmodes:
sets += 'operating modes'
if self._heating_type not in commands.systemschemes:
sets += 'system schemes'
self.logger.error(f'Sets {", ".join(sets)} for heating type {self._heating_type} could not be found!')
return False
self.logger.info(f'Loaded configuration for heating type {self._heating_type} with protocol {self._protocol}')
self._config_loaded = True
return True
def _connect(self):
'''
Tries to establish a connection to the serial reading device. To prevent
multiple concurrent connection locking is used.
:return: Returns True if connection was established, False otherwise
:rtype: bool
'''
if not self.alive:
return False
if self._connected and self._serial:
return True
self._lock.acquire()
try:
self.logger.debug(f'Connecting to {self._serialport}..')
self._serial = serial.Serial()
self._serial.baudrate = self._controlset['Baudrate']
self._serial.parity = self._controlset['Parity']
self._serial.bytesize = self._controlset['Bytesize']
self._serial.stopbits = self._controlset['Stopbits']
self._serial.port = self._serialport
# both of the following timeout values are determined by trial and error
if self._protocol == 'KW':
# needed to "capture" the 0x05 sync bytes
self._serial.timeout = 1.0
else:
# not too long to prevent lags in communication.
self._serial.timeout = 0.5
self._serial.open()
self._connected = True
self.logger.info(f'Connected to {self._serialport}')
self._connection_attempts = 0
if not self._standalone and not self.scheduler_get('cyclic'):
self._create_cyclic_scheduler()
return True
except Exception as e:
self.logger.error(f'Could not _connect to {self._serialport}; Error: {e}')
return False
finally:
self._lock.release()
def _disconnect(self):
'''
Disconnect any connected devices.
'''
self._connected = False
self._initialized = False
try:
self._serial.close()
except IOError:
pass
self._serial = None
try:
self._lock.release()
except RuntimeError:
pass
self.logger.info('Disconnected')
def _init_communication(self):
'''
After connecting to the device, setup the communication protocol
:return: Returns True, if communication was established successfully, False otherwise
:rtype: bool
'''
# just try to connect anyway; if connected, this does nothing and no harm, if not, it connects
if not self._connect():
self.logger.error('Init communication not possible as connect failed.')
return False
# initialization only necessary for P300 protocol...
if self._protocol == 'P300':
# init procedure is
# interface: 0x04 (reset)
# device: 0x05 (repeated)
# interface: 0x160000 (sync)
# device: 0x06 (sync ok)
# interface: resume communication, periodically send 0x160000 as keepalive if necessary
self.logger.debug('Init Communication....')
is_initialized = False
initstringsent = False
self.logger.debug(f'send_bytes: Send reset command {self._int2bytes(self._controlset["Reset_Command"], 1)}')
self._send_bytes(self._int2bytes(self._controlset['Reset_Command'], 1))
readbyte = self._read_bytes(1)
self.logger.debug(f'read_bytes: read {readbyte}, last byte is {self._lastbyte}')
for i in range(0, 10):
if initstringsent and self._lastbyte == self._int2bytes(self._controlset['Acknowledge'], 1):
is_initialized = True
self.logger.debug('Device acknowledged initialization')
break
if self._lastbyte == self._int2bytes(self._controlset['Not_initiated'], 1):
self._send_bytes(self._int2bytes(self._controlset['Sync_Command'], 3))
self.logger.debug(f'send_bytes: Send sync command {self._int2bytes(self._controlset["Sync_Command"], 3)}')
initstringsent = True
elif self._lastbyte == self._int2bytes(self._controlset['Init_Error'], 1):
self.logger.error(f'The interface has reported an error (\x15), loop increment {i}')
self._send_bytes(self._int2bytes(self._controlset['Reset_Command'], 1))
self.logger.debug(f'send_bytes: Send reset command {self._int2bytes(self._controlset["Reset_Command"], 1)}')
initstringsent = False
else:
self._send_bytes(self._int2bytes(self._controlset['Reset_Command'], 1))
self.logger.debug(f'send_bytes: Send reset command {self._int2bytes(self._controlset["Reset_Command"], 1)}')
initstringsent = False
readbyte = self._read_bytes(1)
self.logger.debug(f'read_bytes: read {readbyte}, last byte is {self._lastbyte}')
self.logger.debug(f'Communication initialized: {is_initialized}')
self._initialized = is_initialized
else: # at the moment the only other supported protocol is 'KW' which is not stateful
is_initialized = True
self._initialized = is_initialized
return is_initialized
def _create_cyclic_scheduler(self):
'''
Setup the scheduler to handle cyclic read commands and find the proper time for the cycle.
'''
if not self.alive:
return
shortestcycle = -1
# find shortest cycle
for commandname in list(self._cyclic_cmds.keys()):
entry = self._cyclic_cmds[commandname]
if shortestcycle == -1 or entry['cycle'] < shortestcycle:
shortestcycle = entry['cycle']
# Start the worker thread
if shortestcycle != -1:
# Balance unnecessary calls and precision
workercycle = int(shortestcycle / 2)
# just in case it already exists...
if self.scheduler_get('cyclic'):
self.scheduler_remove('cyclic')
self.scheduler_add('cyclic', self.send_cyclic_cmds, cycle=workercycle, prio=5, offset=0)
self.logger.info(f'Added cyclic worker thread ({workercycle} sec cycle). Shortest item update cycle found: {shortestcycle} sec')
def _read_initial_values(self):
'''
Read all values configured to be read at startup / connection
'''
if self._balist_item is not None:
balist = list(self._operatingmodes.values())
self._balist_item(balist, self.get_shortname())
self.logger.info(f'writing list of operating modes ({len(balist)} entries) to item {self._balist_item}')
if self._init_cmds != []:
self.logger.info('Starting initial read commands.')
if self._protocol == 'KW':
self._KW_send_multiple_read_commands(self._init_cmds)
else:
for commandcode in self._init_cmds:
commandname = self._commandname_by_commandcode(commandcode)
self.logger.debug(f'send_init_commands {commandname}')
self._send_command(commandname)
self._initread = True
self.logger.debug(f'self._initread = {self._initread}')
#
# send and receive commands
#
def _read_timers(self):
'''
Read all configured timer values from device and create uzsu timer dict
'''
if self._application_timer is not []:
self.logger.debug('Starting timer read commands.')
for timer_app in self._application_timer:
for commandcode in self._application_timer[timer_app]['commandcodes']:
commandname = self._commandname_by_commandcode(commandcode)
self.logger.debug(f'send_timer_commands {commandname}')
self._send_command(commandname)
self._timerread = True
self.logger.debug(f'Timer Readout done = {self._timerread}')
self._viess_dict_to_uzsu_dict()
def _send_command(self, commandname, value=None):
'''
Create formatted command sequence from command name and send to device
Note: The implementation detail results in "write if value present, read if value is None".
I have not found anything wrong with this; if any use case needs a specific read/write
selection, please tell me.
:param commandname: Command for which to create command sequence as defined in commands.py
:type commandname: str
:param value: Value to write to device, None if command is read command
'''
if value is not None:
self.logger.debug(f'Got a new write job: Command {commandname} with value {value}')
else:
self.logger.debug(f'Got a new read job: Command {commandname}')
# Build packet with value bytes for write commands
(packet, responselen) = self._build_command_packet(commandname, value)
# quit if no packet (error on packet build)
if packet is None:
return False
if value is not None and self._protocol == 'KW':
read_response = False
else:
read_response = True
# hand over built packet to send_command_packet
response_packet = self._send_command_packet(packet, responselen)
# process response
if response_packet is None:
return False
result = self._process_response(response_packet, commandname, read_response)
return result
def _KW_send_multiple_read_commands(self, commandcodes):
'''
Takes list of commandnames, builds all command packets and tries to send them in one go.
This only works for read commands and only with KW protocol.
On error the whole remaining read process is aborted, no retries or continuation is attempted.
:param commandnames: List of commands for which to create command sequence as defined in commands.py
:type commandname: str
'''
if self._protocol != 'KW':
self.logger.error(f'Called _KW_send_multiple_read_commands, but protocol is {self._protocol}. This shouldn\'t happen..')
return
self.logger.debug(f'Got a new bulk read job: Commands {commandcodes}')
bulk = {}
# Build packets with value bytes for write commands
for addr in commandcodes:
commandname = self._commandname_by_commandcode(addr)
(packet, responselen) = self._build_command_packet(commandname, None, True)
if packet:
bulk[addr] = {'packet': packet, 'responselen': responselen, 'command': commandname}
# quit if no packet (error on packet build)
if not bulk:
return
if not self._connected:
self.logger.error('Not connected, trying to reconnect.')
if not self._connect():
self.logger.error('Could not connect to serial device')
return
self._lock.acquire()
try:
self._init_communication()
replies = {}
if not self._KW_get_sync():
return
first_cmd = True
first_packet = bytearray(self._int2bytes(self._controlset['StartByte'], 1))
for addr in bulk.keys():
if first_cmd:
# make sure that the first sent packet has the StartByte (0x01) lead byte set
# this way the first packet actually sent has the start byte, regardless of bulk.keys() order
first_packet.extend(bulk[addr]['packet'])
bulk[addr]['packet'] = first_packet
first_cmd = False
# send query
try:
self._send_bytes(bulk[addr]['packet'])
self.logger.debug(f'Successfully sent packet: {self._bytes2hexstring(bulk[addr]["packet"])}')
except IOError as io:
raise IOError(f'IO Error: {io}')
return
except Exception as e:
raise Exception(f'Exception while sending: {e}')
return
# receive response
replies[addr] = bytearray()
try:
self.logger.debug(f'Trying to receive {bulk[addr]["responselen"]} bytes of the response')
chunk = self._read_bytes(bulk[addr]['responselen'])
self.logger.debug(f'Received {len(chunk)} bytes chunk of response as hexstring {self._bytes2hexstring(chunk)} and as bytes {chunk}')
if len(chunk) != 0:
replies[addr].extend(chunk)
else:
self.logger.error(f'Received 0 bytes chunk from {addr} - this probably is a communication error, possibly a wrong datapoint address?')
return
except IOError as io:
raise IOError(f'IO Error: {io}')
return
except Exception as e:
raise Exception(f'Error receiving response: {e}')
return
# sent all read requests, time to parse the replies
# do this inside the _lock-block so this doesn't interfere with
# possible cyclic read data assignments
for addr in bulk.keys():
if len(replies[addr]) > 0:
self._process_response(replies[addr], bulk[addr]['command'], True)
except IOError as io:
self.logger.error(f'KW_send_multiple_read_commands failed with IO error: {io}')
self.logger.error('Trying to reconnect (disconnecting, connecting')
self._disconnect()
return
except Exception as e:
self.logger.error(f'KW_send_multiple_read_commands failed with error: {e}')
return
finally:
try:
self._lock.release()
except RuntimeError:
pass
def _KW_get_sync(self):
'''
Try to get a sync packet (0x05) from heating system to be able to send commands
:return: True if sync packet received, False otherwise (after retries)
:rtype: bool
'''
if not self._connected or self._protocol != 'KW':
return False # don't even try. We only want to be called by _send_command_packet, which just before executed connect()
retries = 5
# try to reset communication, especially if previous P300 comms is still open
self._send_bytes(self._int2bytes(self._controlset['Reset_Command'], 1))
attempt = 0
while attempt < retries:
self.logger.debug(f'Starting sync loop - attempt {attempt + 1}/{retries}')
self._serial.reset_input_buffer()
chunk = self._read_bytes(1)
# enable for 'raw' debugging
# self.logger.debug(f'sync loop - got {self._bytes2hexstring(chunk)}')
if chunk == self._int2bytes(self._controlset['Not_initiated'], 1, False):
self.logger.debug('Got sync. Commencing command send')
return True
time.sleep(.8)
attempt = attempt + 1
self.logger.error(f'Sync not acquired after {attempt} attempts')
self._disconnect()
return False
def _send_command_packet(self, packet, packetlen_response):
'''
Send command sequence to device
:param packet: Command sequence to send
:type packet: bytearray
:param packetlen_response: number of bytes expected in reply
:type packetlen_response: int
:param read_response: True if command was read command and value is expected, False if only status byte is expected (only needed for KW protocol)
:type read_response: bool
:return: Response packet (bytearray) if no error occured, None otherwise
'''
if not self._connected:
self.logger.error('Not connected, trying to reconnect.')
if not self._connect():
self.logger.error('Could not connect to serial device')
return None
self._lock.acquire()
try:
if not self._initialized or (time.time() - 500) > self._lastbytetime:
if self._protocol == 'P300':
if self._initialized:
self.logger.debug('Communication timed out, trying to reestablish communication.')
else:
self.logger.info('Communication no longer initialized, trying to reestablish.')
self._init_communication()
if self._initialized:
# send query
try:
if self._protocol == 'KW':
# try to get sync, exit if it fails
if not self._KW_get_sync():
return None
self._send_bytes(packet)
self.logger.debug(f'Successfully sent packet: {self._bytes2hexstring(packet)}')
except IOError as io:
raise IOError(f'IO Error: {io}')
return None
except Exception as e:
raise Exception(f'Exception while sending: {e}')
return None
# receive response
response_packet = bytearray()
self.logger.debug(f'Trying to receive {packetlen_response} bytes of the response')
chunk = self._read_bytes(packetlen_response)
if self._protocol == 'P300':
self.logger.debug(f'Received {len(chunk)} bytes chunk of response as hexstring {self._bytes2hexstring(chunk)} and as bytes {chunk}')
if len(chunk) != 0:
if chunk[:1] == self._int2bytes(self._controlset['Error'], 1):
self.logger.error(f'Interface returned error! response was: {chunk}')
elif len(chunk) == 1 and chunk[:1] == self._int2bytes(self._controlset['Not_initiated'], 1):
self.logger.error('Received invalid chunk, connection not initialized. Forcing re-initialize...')
self._initialized = False
elif chunk[:1] != self._int2bytes(self._controlset['Acknowledge'], 1):
self.logger.error(f'Received invalid chunk, not starting with ACK! response was: {chunk}')
self._error_count += 1
if self._error_count >= 5:
self.logger.warning('Encountered 5 invalid chunks in sequence. Maybe communication was lost, re-initializing')
self._initialized = False
else:
response_packet.extend(chunk)
self._error_count = 0
return response_packet
else:
self.logger.error(f'Received 0 bytes chunk - ignoring response_packet! chunk was: {chunk}')
elif self._protocol == 'KW':
self.logger.debug(f'Received {len(chunk)} bytes chunk of response as hexstring {self._bytes2hexstring(chunk)} and as bytes {chunk}')
if len(chunk) != 0:
response_packet.extend(chunk)
return response_packet
else:
self.logger.error('Received 0 bytes chunk - this probably is a communication error, possibly a wrong datapoint address?')
else:
raise Exception('Interface not initialized!')
except IOError as io:
self.logger.error(f'send_command_packet failed with IO error: {io}')
self.logger.error('Trying to reconnect (disconnecting, connecting')
self._disconnect()
except Exception as e:
self.logger.error(f'send_command_packet failed with error: {e}')
finally:
try:
self._lock.release()
except RuntimeError:
pass
# if we didn't return with data earlier, we hit an error. Act accordingly
return None
def _send_bytes(self, packet):
'''