forked from rellit/resol-vbus-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resol_mysql.py
executable file
·1058 lines (916 loc) · 46.9 KB
/
resol_mysql.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 python
#
# ReSol Datalogger
progname='resol_mysql.py'
# Release 0.1 Start
# Release 0.2 Updated debug
# Release 0.3 Added temperature sensors 11-20
# Release 0.4 Debugged error on septets, added sanity check on date parsing
# Release 0.5 Added strings for Meaning
# Release 0.6 Changed sane & recent times, fixed septett frame > 4 vs >= 4
# Release 2020-03-17 Changed versioning, fixed sleep for negatives
# Release 2020-03-24 Added data for wrong septet lengths
# Release 2020-03-25 Showing dependency on spec.py and config.py
# Release 2020-04-21 Quitting after 10s unsuccessful reads (DL Datalogger rebooting?)
# Release 2020-05-03 Added checking boundaries of variables, added logger.warning messages
# Release 2020-05-04 Rewriting to while loop to exit when insane values (could not escape the for loops), fixed hk2 flow temp to be float, not string
# Updated to independent and dynamic log and sleep interval
# Release 2020-05-11 Fixed checking boundaries of variables
# Release 2020-05-12 Trying to fix message / septett errors in integrate_septett chain
# Release 2020-06-02 Fixing logging name (systemd showing python3 but not progname)
# Release 2020-11-13 Documenting that the resol datagram timestamps are from the DeltaSol MX, not the DL2 Datalogger
version = "2020-11-13"
#
# TODO
# * (nothing)
#
# Author E Zuidema
#
# Although there is an explicit copyright on this sourcecode, anyone may use it freely under a
# "Creative Commons Naamsvermelding-NietCommercieel-GeenAfgeleideWerken 3.0 Nederland" licentie.
# Please check http://creativecommons.org/licenses/by-nc-nd/3.0/nl/ for details
#
# This software is provided as is and comes with absolutely no warranty.
# The author is not responsible or liable (direct or indirect) to anyone for the use or misuse of this software.
# Any person using this software does so entirely at his/her own risk.
# That person bears sole responsibility and liability for any claims or actions, legal or civil, arising from such use.
# If you believe this software is in breach of anyone's copyright you will inform the author immediately so the offending material
# can be removed upon receipt of proof of copyright for that material.
#
# Dependent on Python 3.2+ and Python 3.x packages: PySerial 2.5+
#
import sys
import logging
import serial
import datetime
import time
import csv
import os
import locale
import socket
socket.setdefaulttimeout(30)
import http.client
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
from urllib.error import URLError, HTTPError
MySQL_loaded = True
try:
import mysql.connector
except ImportError:
MySQL_loaded=False
SQLite_loaded = True
try:
import sqlite3
except ImportError:
SQLite_loaded=False
from time import sleep
import time as _time
from datetime import timezone, tzinfo, timedelta, datetime
import argparse
import serial.tools.list_ports
class Resol_LineData:
def __init__(self, id=0, type_id=0, type_desc='', equipment_id='', timestamp='0000-00-00 00:00:00', meterreading=0.0, unit='', valveposition=0):
self.id = id
self.type_id = type_id
self.type_desc = type_desc
self.equipment_id = equipment_id
self.timestamp = timestamp
self.meterreading = meterreading
self.unit = unit
self.valveposition = valveposition
################
#Scherm output #
################
def print_resol_telegram():
print ("---------------------------------------------------------------------------------------")
if use_systemtime == True:
timestamp_qualifier = "System date-time"
else:
timestamp_qualifier = "ReSol date-time"
print ("ReSol telegram received at %s (UTC) / %s (Local) (%s)" % (resol_timestamp_utc, resol_timestamp, timestamp_qualifier))
# resol_temperature 1..9
print ("Temperature Sensor 1: %.1f %s %s" % (resol_temperature_1, resol_unit_temperature_1, resol_meaning_temperature_1 ) )
print ("Temperature Sensor 2: %.1f %s %s" % (resol_temperature_2, resol_unit_temperature_2, resol_meaning_temperature_2 ) )
print ("Temperature Sensor 3: %.1f %s %s" % (resol_temperature_3, resol_unit_temperature_3, resol_meaning_temperature_3 ) )
print ("Temperature Sensor 4: %.1f %s %s" % (resol_temperature_4, resol_unit_temperature_4, resol_meaning_temperature_4 ) )
print ("Temperature Sensor 5: %.1f %s %s" % (resol_temperature_5, resol_unit_temperature_5, resol_meaning_temperature_5 ) )
print ("Temperature Sensor 6: %.1f %s %s" % (resol_temperature_6, resol_unit_temperature_6, resol_meaning_temperature_6 ) )
print ("Temperature Sensor 7: %.1f %s %s" % (resol_temperature_7, resol_unit_temperature_7, resol_meaning_temperature_7 ) )
print ("Temperature Sensor 8: %.1f %s %s" % (resol_temperature_8, resol_unit_temperature_8, resol_meaning_temperature_8 ) )
print ("Temperature Sensor 9: %.1f %s %s" % (resol_temperature_9, resol_unit_temperature_9, resol_meaning_temperature_9 ) )
print ("Temperature Sensor 11: %.1f %s %s" % (resol_temperature_11, resol_unit_temperature_11, resol_meaning_temperature_11 ) )
print ("Temperature Sensor 12: %.1f %s %s" % (resol_temperature_12, resol_unit_temperature_12, resol_meaning_temperature_12 ) )
print ("Temperature Sensor 13: %.1f %s %s" % (resol_temperature_13, resol_unit_temperature_13, resol_meaning_temperature_13 ) )
print ("Temperature Sensor 14: %.1f %s %s" % (resol_temperature_14, resol_unit_temperature_14, resol_meaning_temperature_14 ) )
print ("Temperature Sensor 15: %.1f %s %s" % (resol_temperature_15, resol_unit_temperature_15, resol_meaning_temperature_15 ) )
print ("Temperature Sensor 17: %.1f %s %s" % (resol_temperature_17, resol_unit_temperature_17, resol_meaning_temperature_17 ) )
print ("Temperature Sensor 18: %.1f %s %s" % (resol_temperature_18, resol_unit_temperature_18, resol_meaning_temperature_18 ) )
print ("Temperature Sensor 19: %.1f %s %s" % (resol_temperature_19, resol_unit_temperature_19, resol_meaning_temperature_19 ) )
print ("Temperature Sensor 20: %.1f %s %s" % (resol_temperature_20, resol_unit_temperature_20, resol_meaning_temperature_20 ) )
# resol_pump_speed_11..14
print ("Output A: %3d %s %s" % (resol_output_a, resol_unit_output_a, resol_meaning_output_a) )
print ("Output B: %3d %s %s" % (resol_output_b, resol_unit_output_b, resol_meaning_output_b) )
print ("Output C: %3d %s %s" % (resol_output_c, resol_unit_output_c, resol_meaning_output_c) )
print ("Output D: %3d %s %s" % (resol_output_d, resol_unit_output_d, resol_meaning_output_d) )
# resol_hk1_op_state
print ("HK1 Oper State: %3d %s" % (resol_hk1_op_state, resol_meaning_hk1_op_state) )
# resol_unit_hk1_flow_temp
print ("HK1 Temp: %.1f %s %s" % (resol_hk1_flow_temp, resol_unit_hk1_flow_temp, resol_meaning_hk1_flow_temp ) )
# resol_hk2_op_state
print ("HK2 Oper State: %3d %s" % (resol_hk2_op_state, resol_meaning_hk2_op_state) )
# resol_unit_hk2_flow_temp
print ("HK2 Temp: %.1f %s %s" % (resol_hk2_flow_temp, resol_unit_hk2_flow_temp, resol_meaning_hk2_flow_temp ) )
print ("---------------------------------------------------------------------------------------")
return
################
#DB output #
################
def mysql_resol_telegram():
query = "insert into mx_log values (\'" + \
resol_timestamp_utc + "\',\'" + \
str(resol_temperature_1) + "\',\'" + resol_unit_temperature_1 + "\',\'" + resol_meaning_temperature_1 + "\',\'" + \
str(resol_temperature_2) + "\',\'" + resol_unit_temperature_2 + "\',\'" + resol_meaning_temperature_2 + "\',\'" + \
str(resol_temperature_3) + "\',\'" + resol_unit_temperature_3 + "\',\'" + resol_meaning_temperature_3 + "\',\'" + \
str(resol_temperature_4) + "\',\'" + resol_unit_temperature_4 + "\',\'" + resol_meaning_temperature_4 + "\',\'" + \
str(resol_temperature_5) + "\',\'" + resol_unit_temperature_5 + "\',\'" + resol_meaning_temperature_5 + "\',\'" + \
str(resol_temperature_6) + "\',\'" + resol_unit_temperature_6 + "\',\'" + resol_meaning_temperature_6 + "\',\'" + \
str(resol_temperature_7) + "\',\'" + resol_unit_temperature_7 + "\',\'" + resol_meaning_temperature_7 + "\',\'" + \
str(resol_temperature_8) + "\',\'" + resol_unit_temperature_8 + "\',\'" + resol_meaning_temperature_8 + "\',\'" + \
str(resol_temperature_9) + "\',\'" + resol_unit_temperature_9 + "\',\'" + resol_meaning_temperature_9 + "\',\'" + \
str(resol_temperature_11) + "\',\'" + resol_unit_temperature_11 + "\',\'" + resol_meaning_temperature_11 + "\',\'" + \
str(resol_temperature_12) + "\',\'" + resol_unit_temperature_12 + "\',\'" + resol_meaning_temperature_12 + "\',\'" + \
str(resol_temperature_13) + "\',\'" + resol_unit_temperature_13 + "\',\'" + resol_meaning_temperature_13 + "\',\'" + \
str(resol_temperature_14) + "\',\'" + resol_unit_temperature_14 + "\',\'" + resol_meaning_temperature_14 + "\',\'" + \
str(resol_temperature_15) + "\',\'" + resol_unit_temperature_15 + "\',\'" + resol_meaning_temperature_15 + "\',\'" + \
str(resol_temperature_17) + "\',\'" + resol_unit_temperature_17 + "\',\'" + resol_meaning_temperature_17 + "\',\'" + \
str(resol_temperature_18) + "\',\'" + resol_unit_temperature_18 + "\',\'" + resol_meaning_temperature_18 + "\',\'" + \
str(resol_temperature_19) + "\',\'" + resol_unit_temperature_19 + "\',\'" + resol_meaning_temperature_19 + "\',\'" + \
str(resol_temperature_20) + "\',\'" + resol_unit_temperature_20 + "\',\'" + resol_meaning_temperature_20 + "\',\'" + \
str(resol_output_a) + "\',\'" + resol_unit_output_a + "\',\'" + resol_meaning_output_a + "\',\'" +\
str(resol_output_b) + "\',\'" + resol_unit_output_b + "\',\'" + resol_meaning_output_b + "\',\'" +\
str(resol_output_c) + "\',\'" + resol_unit_output_c + "\',\'" + resol_meaning_output_c + "\',\'" +\
str(resol_output_d) + "\',\'" + resol_unit_output_d + "\',\'" + resol_meaning_output_d + "\',\'" +\
str(resol_hk1_op_state) + "\',\'" + resol_meaning_hk1_op_state + "\',\'" +\
str(resol_hk1_flow_temp) + "\',\'" + resol_unit_hk1_flow_temp + "\',\'" + resol_meaning_hk1_flow_temp + "\',\'" + \
str(resol_hk2_op_state) + "\',\'" + resol_meaning_hk2_op_state + "\',\'" + \
str(resol_hk2_flow_temp) + "\',\'" + resol_unit_hk2_flow_temp + "\',\'" + resol_meaning_hk2_flow_temp + "\');"
logger.debug("Query: %s", query)
try:
db = mysql.connector.connect(user=resol_mysql_user, password=resol_mysql_passwd, host=resol_mysql_host, database=resol_mysql_db)
c = db.cursor()
c.execute(query)
db.commit()
logger.info("Resol telegram logged in database %s / %s with timestamp %s (UTC) / %s (Local)", resol_mysql_host, resol_mysql_db, resol_timestamp_utc, resol_timestamp)
c.close()
db.close()
except:
logger.error("Error opening / writing database %s / %s", resol_mysql_host, resol_mysql_db)
return
##########
### Resol loading and parsing
# Logs in onto the DeltaSol over LAN. Also starts (and maintains) the
# actual stream of data.
def login():
dat = recv()
#Check if device answered
if dat.decode("ascii") != "+HELLO\n":
return False
#Send Password
send("PASS %s\n" % config.vbus_pass)
dat = recv()
return dat.startswith("+OK".encode('ascii'))
def load_data():
# Function in Main loop to Request Data and fill in
logger.debug("LD\t start, sending DATA command")
send("DATA\n")
# EZ: Do we need to do a receive now? Data is dropped!
# dat = recv()
# result is a global dict filled by parse_payload
while len(result) < config.expected_packets:
logger.debug("LD\t len result: %d, less than config: %d", len(result), config.expected_packets)
buf = readstream()
logger.debug("LD\t buf type %s", str(type(buf)))
if not buf: # error reading stream
logger.warning("LD\t End, returning not succesfully read stream")
return False
else:
msgs = splitmsg(buf)
for msg in msgs:
if get_protocolversion(msg) == "PV1":
logger.debug(format_message_pv1(msg))
parse_payload(msg)
elif get_protocolversion(msg) == "PV2":
logger.debug(format_message_pv2(msg))
# Nothing to do
# for msgs
# while existing packets
# Return the amount of tuples produced
logger.debug("LD\t End, returning %d tuples", len(result))
return len(result)
# Receive up to 1024 bytes from stream, non-blocking
def recv():
# logger.debug("RC\t start")
dat = sock.recv(1024)
# logger.debug("RC\t length: %d", len(dat))
# logger.debug("RC\t end")
return dat
# Sends given bytes over the stream. Adds debug
def send(dat):
sock.send(dat.encode('ascii'))
# Read Data until minimum 1 message is received (ending with 0xAA)
def readstream():
logger.debug("RS\t start")
start_secs_since_epoch = time.time()
current_secs_since_epoch = start_secs_since_epoch
data = recv()
# Read until AA or exit if 10 seconds passed without full message
while (data.count(bytearray.fromhex('AA')) < 4) and (current_secs_since_epoch - start_secs_since_epoch < 10):
data += recv()
current_secs_since_epoch = time.time()
logger.debug("RS\t adding data, waiting for 0xAA (%.1f seconds)", current_secs_since_epoch - start_secs_since_epoch)
# logger.debug("RS\t type data: %s", str(type(data)))
logger.debug("RS\t length: %d", len(data))
logger.debug("RS\t data: %s", str(data))
if (current_secs_since_epoch - start_secs_since_epoch >= 60):
logger.warning("RS\t ended unsuccesfully after %.1f seconds" % (current_secs_since_epoch - start_secs_since_epoch))
return False
else:
return data
#Split Messages on Sync Byte
def splitmsg(buf):
return buf.split(bytearray.fromhex('AA'))[1:-1]
# Format 1 byte as String
def format_byte(byte):
# logger.debug("FB\t type byte: %s", str(type(byte)))
if not isinstance(byte, bytes):
raise TypeError('Invalid type: input must be a byte, not %r' % type(byte))
# logger.debug("FB\t str byte: %s", str(byte))
# logger.debug("FB\t byte.hex:" + byte.hex())
# logger.debug("FB\t Returning:" + "0x" + byte.hex())
return '0x' + byte.hex()
# Extract protocol Version from msg
def get_protocolversion(msg):
logger.debug("GPr\t str msg: %s", str(msg)) # message in array of bytes
# logger.debug("GPr\t str msg 4: %s", str(msg[4])) # int
logger.debug("GPr\t str hex msg 4: %s", str(hex(msg[4]))) # in hex
if hex(msg[4]) == '0x10': return "PV1"
if hex(msg[4]) == '0x20': return "PV2"
if hex(msg[4]) == '0x30': return "PV3"
return "UNKNOWN"
# Extract Destination from msg (bytes) to String
def get_destination(msg):
logger.debug("GD\t type msg:" + str(type(msg)))
logger.debug("GD\t type msg[0:1]:" + str(type(msg[0:1])))
logger.debug("GD\t type msg[1:2]:" + str(type(msg[1:2])))
return format_byte(msg[1:2]) + format_byte(msg[0:1])[2:]
#Extract source from msg
def get_source(msg):
return format_byte(msg[3:4]) + format_byte(msg[2:3])[2:]
# Extract command from msg
def get_command(msg):
return format_byte(msg[6:7]) + format_byte(msg[5:6])[2:]
# Get count of frames in msg
def get_frame_count(msg):
return gb(msg, 7, 8)
# Extract payload from msg
def get_payload(msg):
logger.debug("GPa\t type msg:" + str(type(msg)))
payload = b''
for i in range(get_frame_count(msg)):
integrated = integrate_septett(msg[9+(i*6):15+(i*6)])
if integrated:
payload += integrated
else:
logger.debug("GPa\t *** Invalid septett ***")
return False
logger.debug("GPa\t type payload:" + str(type(payload)))
return payload
# parse payload and put result as tuples in result dictionary
def parse_payload(msg):
logger.debug("GP\t parsing payload...")
payload = get_payload(msg)
if payload:
for packet in spec.spec['packet']:
if packet['source'].lower() == get_source(msg).lower() and packet['destination'].lower() == get_destination(msg).lower() and packet['command'].lower() == get_command(msg).lower():
# We have a match for a packet, new tuple
result[get_source_name(msg)] = {}
for field in packet['field']:
# If seconds, do use absolute values (gba) and not two's complement (gb), and factor is an int
if ('unit' in field) and (field['unit'] == " s"):
result[get_source_name(msg)][field['name'][0]] = str(gba(payload, int(field['offset']), int(int(field['offset'])+(int(field['bitSize'])+1) / 8)) * (int(field['factor']) if 'factor' in field else 1)) + field['unit']
else:
result[get_source_name(msg)][field['name'][0]] = str( gb(payload, int(field['offset']), int(int(field['offset'])+(int(field['bitSize'])+1) / 8)) * (float(field['factor']) if 'factor' in field else 1)) + str(field['unit'] if 'unit' in field else '')
else: # no payload
# No new tuple in result, nothing to do
logger.debug("PP\t *** No payload parsed ***")
def format_message_pv1(msg):
logger.debug("FMPV1\ttype msg:" + str(type(msg)))
parsed = "PARSED: \n"
parsed += " ZIEL".ljust(15,'.')+": " + get_destination(msg) + "\n"
parsed += " QUELLE".ljust(15,'.')+": " + get_source(msg) + " " + get_source_name(msg) + "\n"
parsed += " PROTOKOLL".ljust(15,'.')+": " + get_protocolversion(msg) + "\n"
parsed += " BEFEHL".ljust(15,'.')+": " + get_command(msg) + "\n"
parsed += " ANZ_FRAMES".ljust(15,'.')+": " + str(get_frame_count(msg)) + "\n"
parsed += " CHECKSUM".ljust(15,'.')+": " + format_byte(msg[8:9]) + "\n"
for i in range(get_frame_count(msg)):
logger.debug("FM\t i is " + str(i) + " of " + str(get_frame_count(msg)))
integrated = integrate_septett(msg[9+(i*6):15+(i*6)])
if integrated:
logger.debug("FM\t integrated:" + str(integrated))
# for j in range(len(msg)):
# logger.debug("FM\tj is " + str(j) + " str msg[j]:" + str(msg[j]))
# logger.debug("FM\tintegrated septett = msg [" + str(9+(i*6)) + ":" + str(15+(i*6)) + "] :" + str(msg[9+(i*6):15+(i*6)]))
parsed += (" NB"+str(i*4+1)).ljust(15,'.')+": " + format_byte(msg[ 9+(i*6):10+(i*6)]) + " - " + format_byte(integrated[0:1]) + "\n"
parsed += (" NB"+str(i*4+2)).ljust(15,'.')+": " + format_byte(msg[10+(i*6):11+(i*6)]) + " - " + format_byte(integrated[1:2]) + "\n"
parsed += (" NB"+str(i*4+3)).ljust(15,'.')+": " + format_byte(msg[11+(i*6):12+(i*6)]) + " - " + format_byte(integrated[2:3]) + "\n"
parsed += (" NB"+str(i*4+4)).ljust(15,'.')+": " + format_byte(msg[12+(i*6):13+(i*6)]) + " - " + format_byte(integrated[3:4]) + "\n"
parsed += (" SEPTETT"+str(i+1)).ljust(15,'.')+": " + format_byte(msg[13+(i*6):14+(i*6)]) + "\n"
parsed += (" CHECKSUM"+str(i+1)).ljust(15,'.')+": " + format_byte(msg[14+(i*6):15+(i*6)]) + "\n"
else:
logger.debug("FMPV1\t *** Invalid septett")
return "UNABLE TO PARSE: Invalid message"
# Need to fix if get_payload does return False
parsed += " PAYLOAD".ljust(15,'.')+": " + (" ".join(str(b) for b in get_payload(msg)))+"\n"
return parsed
def format_message_pv2(msg):
parsed = "PARSED: \n"
parsed += " ZIEL1".ljust(15,'.')+": " + format_byte(msg[0:1]) + "\n"
parsed += " ZIEL2".ljust(15,'.')+": " + format_byte(msg[1:2]) + "\n"
parsed += " QUELLE1".ljust(15,'.')+": " + format_byte(msg[2:3]) + "\n"
parsed += " QUELLE2".ljust(15,'.')+": " + format_byte(msg[3:4]) + "\n"
parsed += " PROTOKOLL".ljust(15,'.')+": " + format_byte(msg[4:5]) + "\n"
parsed += " BEFEHL1".ljust(15,'.')+": " + format_byte(msg[5:6]) + "\n"
parsed += " BEFEHL2".ljust(15,'.')+": " + format_byte(msg[6:7]) + "\n"
parsed += " ID1".ljust(15,'.')+": " + format_byte(msg[7:8]) + "\n"
parsed += " ID2".ljust(15,'.')+": " + format_byte(msg[8:9]) + "\n"
parsed += " WERT1".ljust(15,'.')+": " + format_byte(msg[9:10]) + "\n"
parsed += " WERT2".ljust(15,'.')+": " + format_byte(msg[10:11]) + "\n"
parsed += " WERT3".ljust(15,'.')+": " + format_byte(msg[11:12]) + "\n"
parsed += " WERT4".ljust(15,'.')+": " + format_byte(msg[12:13]) + "\n"
parsed += " SEPTETT".ljust(15,'.')+": " + format_byte(msg[13:14]) + "\n"
parsed += " CHECKSUM".ljust(15,'.')+": " + format_byte(msg[14:15]) + "\n"
return parsed
def get_compare_length(mask):
i = 1
while i < 6 and mask[i] != '0':
i += 1
return i+1
def get_source_name(msg):
src = format_byte(msg[3:4]) + format_byte(msg[2:3])[2:]
for device in spec.spec['device']:
if src[:get_compare_length(device['mask'])].lower() == device['address'][:get_compare_length(device['mask'])].lower():
return device['name'] if get_compare_length(device['mask']) == 7 else str(device['name']).replace('#',device['address'][get_compare_length(device['mask'])-1:],1)
return ""
def integrate_septett(frame):
# logger.debug("IS\t type frame:" + str(type(frame)))
# logger.debug("IS\t len Frame:" + str(len(frame)))
# logger.debug("IS\t Frame:" + str(frame))
# logger.debug("IS\t Frame(hex):" + frame.hex())
data = b''
if len(frame) > 4:
septet = frame[4]
# logger.debug("IS\t str frame 4 / septet:" + str(septet))
for j in range(4):
if septet & (1 << j):
data += bytes([frame[j] | 0x80])
# logger.debug("IS\t data + frame or 0x80:" + str(bytes([frame[j] | 0x80])))
else:
data += frame[j:j+1]
# logger.debug("IS\t data + frame:" + str(frame[j:j+1]))
# if
# for
else:
logger.info("IS\t **************** ISSUE!!!! LENGTH NOT > 4, returning empty data ******************")
logger.debug("IS\t Frame: %s", str(frame))
return False
# if
# logger.debug("IS\t Returning(str):" + str(data))
# logger.debug("IS\t Returning(hex):" + data.hex())
return data
# Gets the numerical value of a set of bytes (respect Two's complement by value Range)
def gb(data, begin, end): # GetBytes
# logger.debug("GB\t type data:" + str(type(data)))
# logger.debug("GB\t type begin:" + str(type(begin)))
# logger.debug("GB\t type end:" + str(type(end)))
# logger.debug("GB\t begin:" + str(begin) + " end:" + str(end))
# logger.debug("GB\t data:" + " ".join(str(b) for b in data[begin:end]))
# logger.debug("GB\t bytes:" + str(end-begin) + " bits:" + str((end-begin)*8))
wbg = pow(2,(end-begin)*8)-1
# logger.debug("GB\t wbg:" + str(wbg))
s = sum([b << (i * 8) for i, b in enumerate(data[begin:end])])
# logger.debug("GB\t Returning:" + str(s))
if s >= wbg/2:
s = -1 * (wbg - s)
# logger.debug("GB\t Returning:" + str(s))
return s
# Gets the numerical value of a set of bytes (Absolute)
def gba(data, begin, end): # GetBytes
s = sum([b << (i * 8) for i, b in enumerate(data[begin:end])])
# logger.debug("GBA\t Returning:" + str(s))
return s
################################################################################################################################################
#Main program
################################################################################################################################################
print("%s %s" % (progname, version))
comport="TEST"
win_os = (os.name == 'nt')
if win_os:
print("Windows Mode")
else:
print("Non-Windows Mode")
print("Python version %s.%s.%s" % sys.version_info[:3])
print("pySerial version %s" % serial.VERSION)
print("Control-C to abort")
################################################################################################################################################
#Commandline arguments parsing
################################################################################################################################################
parser = argparse.ArgumentParser(prog=progname, description='ReSol Datalogger', epilog="Copyright (c) E. Zuidema")
parser.add_argument("-l", "--log", help="Logging level, can be 'none', 'info', 'warning', 'debug', default='none'", default='none')
parser.add_argument("-f", "--logfile", help="Logging output, can be 'stdout', or filename with path, default='stdout'", default='stdout')
parser.add_argument("-i", "--interval", help="Output frequency in seconds, default=30", default=30, type=int)
parser.add_argument("-o", "--output", help="Output mode(s), can be 'screen', 'mysql', or multiple. Default='screen'", default='screen', nargs='*')
parser.add_argument("-systime", "--systemtime", help="Use system-time instead of ReSol controller-time, default='N'", default='N', choices=['Y', 'N'])
parser.add_argument("-s", "--server", help="MySQL server or socket path, default='localhost'", default='localhost')
parser.add_argument("-d", "--database", help="MySQL database name, default='solar'", default='solar')
parser.add_argument("-u", "--user", help="MySQL user, default='root'", default='root')
parser.add_argument("-p", "--password", help="MySQL user password, default='password'", default='password')
args = parser.parse_args()
# Load stored settings as starting point
try:
import config
except:
sys.exit("Configuration file config.py not found!")
# Handle debugging messages
if (args.logfile == 'stdout'):
if (args.log == 'info'):
# info logging to systemd which already lists timestamp
logging.basicConfig(format='%(name)s - %(levelname)s - %(message)s')
else:
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(message)s')
else:
logging.basicConfig(filename=args.logfile,format='%(asctime)s - %(levelname)s - %(lineno)d - %(message)s')
logger = logging.getLogger(progname)
if (args.log == 'debug'):
logger.setLevel(logging.DEBUG)
if (args.log == 'warning'):
logger.setLevel(logging.WARNING)
if (args.log == 'info'):
logger.setLevel(logging.INFO)
if (args.log == 'error'):
logger.setLevel(logging.ERROR)
logger.info("Started program %s, version %s", progname, version)
use_systemtime = (args.systemtime == "Y")
log_interval = args.interval
output_mode = args.output
#Show startup arguments
logger.info("Loaded config file : config.py")
logger.info("Output mode(s) : %s", output_mode)
logger.info("Log interval : %s seconds", log_interval)
logger.info("Use system time : %s", use_systemtime)
# Load Message specification
try:
import spec
logger.info("Using message spec : spec.py")
except:
sys.exit("Could not load Message Specification")
if ("mysql" in output_mode) and MySQL_loaded:
resol_mysql_host=args.server
resol_mysql_user=args.user
resol_mysql_passwd=args.password
resol_mysql_db=args.database
logger.info("MySQL Server : %s", resol_mysql_host)
logger.info("MySQL User : %s", resol_mysql_user)
logger.debug("MySQL Password: %s", resol_mysql_passwd)
logger.info("MySQL Database: %s", resol_mysql_db)
try:
db = mysql.connector.connect(user=resol_mysql_user, password=resol_mysql_passwd, host=resol_mysql_host, database=resol_mysql_db)
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
results = cursor.fetchone()
db.close()
except MySQLdb.Error:
MySQL_loaded = False
if ("mysql" in output_mode) and not MySQL_loaded:
logger.warning("%s: warning: MySQL or Connector/Python not found. Output mode 'mysql' not allowed. Output mode removed.", progname)
output_mode.remove("mysql")
#################################################################################################################################################
# Open socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(config.address)
except socket.error as msg:
logger.error("MN\t Couldn't connect with the socket-server at %s : %s. Terminating...", config.address, msg)
sys.exit(1)
result = dict()
# First try to sleep half the time as to log
sleep_interval = log_interval / 2
last_resol_secs_since_epoch = 0
last_delay = 0
if (not login()):
logger.error("MN\t Login FAILED, terminating...")
sys.exit(1)
while 1:
#Initialize variables
result.clear()
resol_secs_since_epoch=0
resol_timestamp=""
resol_timestamp_utc=""
resol_temperature_1=0
resol_unit_temperature_1=""
resol_meaning_temperature_1=""
resol_temperature_2=0
resol_unit_temperature_2=""
resol_meaning_temperature_2=""
resol_temperature_3=0
resol_unit_temperature_3=""
resol_meaning_temperature_3=""
resol_temperature_4=0
resol_unit_temperature_4=""
resol_meaning_temperature_4=""
resol_temperature_5=0
resol_unit_temperature_5=""
resol_meaning_temperature_5=""
resol_temperature_6=0
resol_unit_temperature_6=""
resol_meaning_temperature_6=""
resol_temperature_7=0
resol_unit_temperature_7=""
resol_meaning_temperature_7=""
resol_temperature_8=0
resol_unit_temperature_8=""
resol_meaning_temperature_8=""
resol_temperature_9=0
resol_unit_temperature_9=""
resol_meaning_temperature_9=""
resol_temperature_11=0
resol_unit_temperature_11=""
resol_meaning_temperature_11=""
resol_temperature_12=0
resol_unit_temperature_12=""
resol_meaning_temperature_12=""
resol_temperature_13=0
resol_unit_temperature_13=""
resol_meaning_temperature_13=""
resol_temperature_14=0
resol_unit_temperature_14=""
resol_meaning_temperature_14=""
resol_temperature_15=0
resol_unit_temperature_15=""
resol_meaning_temperature_15=""
resol_temperature_17=0
resol_unit_temperature_17=""
resol_meaning_temperature_17=""
resol_temperature_18=0
resol_unit_temperature_18=""
resol_meaning_temperature_18=""
resol_temperature_19=0
resol_unit_temperature_19=""
resol_meaning_temperature_19=""
resol_temperature_20=0
resol_unit_temperature_20=""
resol_meaning_temperature_20=""
resol_pump_speed_11=0
resol_unit_pump_speed_11=""
resol_meaning_pump_speed_11=""
resol_pump_speed_12=0
resol_unit_pump_speed_12=""
resol_meaning_pump_speed_12=""
resol_pump_speed_13=0
resol_unit_pump_speed_13=""
resol_meaning_pump_speed_13=""
resol_pump_speed_14=0
resol_unit_pump_speed_14=""
resol_meaning_pump_speed_14=""
resol_output_a=0
resol_unit_output_a=""
resol_meaning_output_a=""
resol_output_b=0
resol_unit_output_b=""
resol_meaning_output_b=""
resol_output_c=0
resol_unit_output_c=""
resol_meaning_output_c=""
resol_output_d=0
resol_unit_output_d=""
resol_meaning_output_d=""
resol_hk1_op_state=0
resol_meaning_hk1_op_state=""
resol_hk1_flow_temp=""
resol_unit_hk1_flow_temp=""
resol_meaning_hk1_flow_temp=""
resol_hk2_op_state=0
resol_meaning_hk2_op_state=""
resol_hk2_flow_temp=0
resol_unit_hk2_flow_temp=""
resol_meaning_hk2_flow_temp=""
# Call main function to fill data in result dictionary
logger.debug("MN\t load_data - Fill result tuples:")
if (not load_data()):
# Error reading data
logger.error("MN\t ERROR loading data, terminating...")
sys.exit(1)
# Interpret and Print the result tuple sets
logger.debug("MN\t Result: ")
sane = True
log = True
i = 0
while i < len(result) and sane:
k = list(result.keys())[i]
v = list(result.values())[i]
logger.debug(str(k) + ' (k) -> ')
if isinstance(v, dict):
j = 0
while j < len(v.items()) and sane:
k2 = list(v.keys())[j]
v2 = list(v.values())[j]
logger.debug(str(k2) + ' (k2) -> ' + str(v2) + ' (v2)')
if k2[:11] == 'Systemdatum':
# Note that Systemdatum comes from DeltaSol (e.g. MX) system (and not the DL2 Datalogger!)
# So if there is a time issue, check the DeltaSol device, not the logger
# Iterating over 4 elements adding to Systemdatum (92,93,94,95)
logger.debug("MN\t DeltaSol MX Systemdatum found, adding")
resol_secs_since_epoch += int(v2.split()[0])
if k2 == 'Systemdatum95':
# We have seen all elements
logger.debug("MN\t Systemdatum complete, checking limits")
# Correct for 31 year delta by ReSol -> add 31 years ~ 978307200 seconds (from 1987 to 2018)
resol_timestamp_utc = time.strftime("%Y-%m-%d %H:%M:%S" , time.gmtime(resol_secs_since_epoch+978307200))
resol_timestamp = time.strftime("%Y-%m-%d %H:%M:%S" , time.localtime(resol_secs_since_epoch+978307200))
# Sanity check on timestamp
current_secs_since_epoch = time.time()
timestamp_utc = time.strftime("%Y-%m-%d %H:%M:%S" , time.gmtime())
logger.debug("ReSol MX datagram time %d (UTC), current server time %d (UTC)", resol_secs_since_epoch+978307200, current_secs_since_epoch)
logger.info("ReSol MX datagram datetime %s (UTC), current server datetime %s (UTC), delta %.1f seconds", resol_timestamp_utc, timestamp_utc, current_secs_since_epoch - (resol_secs_since_epoch+978307200))
# We only accept data if the time is roughly in line with the server time (sometimes completely off which indicates mis-read data)
if abs(current_secs_since_epoch - (resol_secs_since_epoch + 978307200)) > 2*60:
logger.warning("MN\t DeltaSol MX timestamp off limits, read next")
sane = False
break
elif k2 == 'Temperatur Sensor 1' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 1 found, checking limits")
resol_temperature_1=float(v2.split()[0])
resol_unit_temperature_1=str(v2.split()[1])
resol_meaning_temperature_1="West Collector Temperature"
# West Collector Temperature should be between -30 and +170 degrees
if not -30 < resol_temperature_1 < 170:
logger.warning("MN\t Temp 1 off limits (%0.1f), reading next", resol_temperature_1)
sane = False
break
elif k2 == 'Temperatur Sensor 2' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 2 found, checking limits")
resol_temperature_2=float(v2.split()[0])
resol_unit_temperature_2=str(v2.split()[1])
resol_meaning_temperature_2="Boiler Bottom Temperature"
# Boiler Bottom Temperature should be between +10 and +100 degrees
if not 10 < resol_temperature_2 < 100:
logger.warning("MN\t Temp 2 off limits (%0.1f), reading next", resol_temperature_2)
sane = False
break
elif k2 == 'Temperatur Sensor 3' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 3 found, checking limits")
resol_temperature_3=float(v2.split()[0])
resol_unit_temperature_3=str(v2.split()[1])
resol_meaning_temperature_3="Boiler Middle Temperature"
# Boiler Middle Temperature should be between +10 and +100 degrees
if not 10 < resol_temperature_3 < 100:
logger.warning("MN\t Temp 3 off limits (%0.1f), reading next", resol_temperature_3)
sane = False
break
elif k2 == 'Temperatur Sensor 4' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 4 found, checking limits")
resol_temperature_4=float(v2.split()[0])
resol_unit_temperature_4=str(v2.split()[1])
resol_meaning_temperature_4="Boiler Top Temperature"
# Boiler Top Temperature should be between +10 and +100 degrees
if not 10 < resol_temperature_4 < 100:
logger.warning("MN\t Temp 4 off limits (%0.1f), reading next", resol_temperature_4)
sane = False
break
# Typically bottom is coldest and hottest (like 20 - 50 - 70)
if resol_temperature_2 > resol_temperature_3 or resol_temperature_3 > resol_temperature_4:
logger.warning("MN\t Strange boiler temps: Order %0.1f %0.1f %0.1f (TMB)" % (resol_temperature_4, resol_temperature_3, resol_temperature_2) )
# sane = True
# break
# Typically temperatures should be close (like 20 - 50 - 70)
if abs(resol_temperature_2 - resol_temperature_3) > 30 or abs(resol_temperature_3 - resol_temperature_4) > 20:
logger.warning("MN\t Strange boiler temps: Delta %0.1f %0.1f %0.1f (TMB)" % (resol_temperature_4, resol_temperature_3, resol_temperature_2) )
# Still migth be okay
# sane = True
# break
elif k2 == 'Temperatur Sensor 5' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 5 found, filling in...")
resol_temperature_5=float(v2.split()[0])
resol_unit_temperature_5=str(v2.split()[1])
resol_meaning_temperature_5="(TS5 unused)"
elif k2 == 'Temperatur Sensor 6' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 6 found, checking limits")
resol_temperature_6=float(v2.split()[0])
resol_unit_temperature_6=str(v2.split()[1])
resol_meaning_temperature_6="East Collector Temperature"
# East Collector Temperature should be between -30 and +170 degrees
if not -30 < resol_temperature_6 < 170:
logger.warning("MN\t Temp 6 off limits (%0.1f), reading next", resol_temperature_6)
sane = False
break
elif k2 == 'Temperatur Sensor 7' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 7 found, filling in...")
resol_temperature_7=float(v2.split()[0])
resol_unit_temperature_7=str(v2.split()[1])
resol_meaning_temperature_7="(TS7 unused)"
elif k2 == 'Temperatur Sensor 8' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 8 found, checking limits")
resol_temperature_8=float(v2.split()[0])
resol_unit_temperature_8=str(v2.split()[1])
resol_meaning_temperature_8="Vorlauf HK1"
# Central Heating water Temperature should be between +0 and +75 degrees
if not 0 < resol_temperature_8 < 75:
logger.warning("MN\t Temp 8 off limits (%0.1f), reading next", resol_temperature_8)
sane = False
break
elif k2 == 'Temperatur Sensor 9' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 9 found, checking limits")
resol_temperature_9=float(v2.split()[0])
resol_unit_temperature_9=str(v2.split()[1])
resol_meaning_temperature_9="Outside Temperature"
# Outside Temperature should be between -20 and +50 degrees
if not -20 < resol_temperature_9 < 50:
logger.warning("MN\t Temp 9 off limits (%0.1f), reading next", resol_temperature_9)
sane = False
break
# Sensor 10 is Einstrahlung
elif k2 == 'Temperatur Sensor 11' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 11 found, filling in...")
resol_temperature_11=float(v2.split()[0])
resol_unit_temperature_11=str(v2.split()[1])
resol_meaning_temperature_11="(TS11 wire)"
elif k2 == 'Temperatur Sensor 12' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 12 found, filling in...")
resol_temperature_12=float(v2.split()[0])
resol_unit_temperature_12=str(v2.split()[1])
resol_meaning_temperature_12="(TS12 wire)"
elif k2 == 'Temperatur Sensor 13' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 13 found, filling in...")
resol_temperature_13=float(v2.split()[0])
resol_unit_temperature_13=str(v2.split()[1])
resol_meaning_temperature_13="(TS13 unused)"
elif k2 == 'Temperatur Sensor 14' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 14 found, filling in...")
resol_temperature_14=float(v2.split()[0])
resol_unit_temperature_14=str(v2.split()[1])
resol_meaning_temperature_14="(TS14 unused)"
elif k2 == 'Temperatur Sensor 15' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 15 found, filling in...")
resol_temperature_15=float(v2.split()[0])
resol_unit_temperature_15=str(v2.split()[1])
resol_meaning_temperature_15="(TS15 unused)"
# Sensor 16 is Einstrahlung
elif k2 == 'Temperatur Sensor 17' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 17 found, filling in...")
resol_temperature_17=float(v2.split()[0])
resol_unit_temperature_17=str(v2.split()[1])
resol_meaning_temperature_17="(TS17 unused)"
elif k2 == 'Temperatur Sensor 18' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 18 found, filling in...")
resol_temperature_18=float(v2.split()[0])
resol_unit_temperature_18=str(v2.split()[1])
resol_meaning_temperature_18="(TS18 unused)"
elif k2 == 'Temperatur Sensor 19' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 19 found, filling in...")
resol_temperature_19=float(v2.split()[0])
resol_unit_temperature_19=str(v2.split()[1])
resol_meaning_temperature_19="(TS19 unused)"
elif k2 == 'Temperatur Sensor 20' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Temp 20 found, filling in...")
resol_temperature_20=float(v2.split()[0])
resol_unit_temperature_20=str(v2.split()[1])
resol_meaning_temperature_20="(TS20 unused)"
elif k2 == 'Ausgang A' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Output A found, checking limits")
resol_output_a=int(v2.split()[0])
resol_unit_output_a=str(v2.split()[1])
resol_meaning_output_a="West Collector Pump Speed"
# Pump speed should be between 0 and 100 percent
if not 0 <= resol_output_a <= 100:
logger.warning("MN\t Output A off limits, read next")
sane = False
break
elif k2 == 'Ausgang B' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Output B found, checking limits")
resol_output_b=int(v2.split()[0])
resol_unit_output_b=str(v2.split()[1])
resol_meaning_output_b="East Collector Pump Speed"
# Pump speed should be between 0 and 100 percent
if not 0 <= resol_output_b <= 100:
logger.warning("MN\t Output B off limits, read next")
sane = False
break
elif k2 == 'Ausgang C' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Output C found, filling in...")
resol_output_c=int(v2.split()[0])
resol_unit_output_c=str(v2.split()[1])
resol_meaning_output_c="(OPC unused)"
elif k2 == 'Ausgang D' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Output D found, checking limits")
resol_output_d=int(v2.split()[0])
resol_unit_output_d=str(v2.split()[1])
resol_meaning_output_d="100% - Heating Kettel Power"
# Heating kettel power should be between 0 and 100 percent
if not 0 <= resol_output_d <= 100:
logger.warning("MN\t Output D off limits, read next")
sane = False
break
elif k2 == 'Drehzahl Relais 11' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Pump speed 11 found, filling in...")
resol_pump_speed_11=int(v2.split()[0])
resol_unit_pump_speed_11=str(v2.split()[1])
resol_meaning_pump_speed_11="(PS11 unknown)"
elif k2 == 'Drehzahl Relais 12' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Pump speed 12 found, filling in...")
resol_pump_speed_12=int(v2.split()[0])
resol_unit_pump_speed_12=str(v2.split()[1])
resol_meaning_pump_speed_12="(PS12 unknown)"
elif k2 == 'Drehzahl Relais 13' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Pump speed 13 found, filling in...")
resol_pump_speed_13=int(v2.split()[0])
resol_unit_pump_speed_13=str(v2.split()[1])
resol_meaning_pump_speed_13="(PS13 unknown)"
elif k2 == 'Drehzahl Relais 14' and k == 'DeltaSol MX [Regler]':
logger.debug("MN\t Pump speed 14 found, filling in...")
resol_pump_speed_14=int(v2.split()[0])
resol_unit_pump_speed_14=str(v2.split()[1])
resol_meaning_pump_speed_14="(PS14 unknown)"
elif k2 == 'V' and k == 'DeltaSol MX [Heizkreis 1]':
logger.debug("MN\t HK1 (Central Heating) Temp found, checking limits")
resol_hk1_flow_temp=float(v2.split()[0])
resol_unit_hk1_flow_temp=str(v2.split()[1])
resol_meaning_hk1_flow_temp="Central Heating Temperature"
# Central Heating flow Temperature should be between +0 and +75 degrees
if not 0 < resol_hk1_flow_temp < 75:
logger.warning("MN\t HK1 Flow temp off limits (%0.1f), reading next", resol_hk1_flow_temp)
sane = False
break
elif k2 == 'B' and k == 'DeltaSol MX [Heizkreis 1]':
logger.debug("MN\t HK1 (Central Heating) Oper State found, filling in...")
resol_hk1_op_state=int(v2.split()[0])
resol_meaning_hk1_op_state="Central Heating Operating State"
elif k2 == 'V' and k == 'DeltaSol MX [Heizkreis 2]':
logger.debug("MN\t HK2 (Kettel Flow) Temp found, filling in...")
resol_hk2_flow_temp=float(v2.split()[0])
resol_unit_hk2_flow_temp=str(v2.split()[1])
resol_meaning_hk2_flow_temp="(unused, Kettel Temperature)"
elif k2 == 'B' and k == 'DeltaSol MX [Heizkreis 2]':
logger.debug("MN\t HK2 (Kettel Flow) Oper State found, filling in...")
resol_hk2_op_state=int(v2.split()[0])