-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrscpguimain.py
1319 lines (1095 loc) · 51.5 KB
/
rscpguimain.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
import logging
import math
import os
import traceback
from e3dc._rscp_dto import RSCPDTO
logger = logging.getLogger(__name__)
from socket import setdefaulttimeout
import csv
import re
import random
import base64
import hashlib
import configparser
import time
import json
import requests
import sys
import datetime
import threading
from e3dc._rscp_exceptions import RSCPCommunicationError
from e3dc.rscp_helper import rscp_helper
from e3dc.rscp_tag import RSCPTag
from e3dc.rscp_type import RSCPType
from e3dcwebgui import E3DCWebGui
try:
import paho.mqtt.client as paho
except:
logger.warning('Paho-Libary (paho) nicht gefunden, MQTT wird nicht zur Verfügung stehen')
try:
import influxdb
from influxdb.exceptions import InfluxDBClientError
except:
logger.warning('Influxdb-Libary nicht gefunden, Influx wird nicht zur Verfügung stehen')
try:
import telegram
except Exception as e:
logger.warning('Telegram-Libary (python-telegram-bot) nicht gefunden, Telegram-Benachrichtigungen stehen nicht zur Verfügung')
try:
import thread
except ImportError:
import _thread as thread
class E3DCGui(rscp_helper):
pass
class RSCPGuiMain():
_extsrcavailable = 0
_gui = None
_connected = None
_mbsSettings = {}
debug = False
_AutoExportStarted = False
_args = None
_updateRunning = None
_try_connect = False
_notificationblocker = {}
_mqttclient = None
_exportcache = None
_dcdc_available = []
_pm_available = []
_pvi_available = []
_wb_available = []
_noconfigfile = True
def __init__(self, args):
logger.info('Main initialisiert')
self._args = args
self.clear_values()
self.ConfigFilename = 'rscpe3dc.conf.ini'
self._config = None
self._gui = None
self._cached = {}
setdefaulttimeout(2)
def clear_values(self):
self._data_bat = []
self._data_dcdc = []
self._data_ems = None
self._data_info = None
self._data_pvi = {}
self._data_pm = {}
self._data_wb = []
def tinycode(self, key, text, reverse=False):
"(de)crypt stuff"
rand = random.Random(key).randrange
if reverse:
text = base64.b64decode(text.encode('utf-8')).decode('utf-8', 'ignore')
text = ''.join([chr(ord(elem) ^ rand(256)) for elem in text])
if not reverse:
text = base64.b64encode(text.encode('utf-8')).decode('utf-8', 'ignore')
return text
def StartExport(self):
self._AutoExportStarted = True
self._autoexportthread = threading.Thread(target=self.StartAutoExport, args=())
self._autoexportthread.start()
def StopExport(self):
pass
@property
def config(self):
if self._config is None:
logger.info('Lade Konfigurationsdatei ' + self.ConfigFilename)
self._config = configparser.ConfigParser()
self._noconfigfile = not os.path.isfile(self.ConfigFilename)
self._config.read(self.ConfigFilename)
return self._config
def __setattr__(self, key, value):
if len(key) > 8 and key[0:8] == 'cfgLogin':
name = key[8:]
kat = 'Login'
elif len(key) > 9 and key[0:9] == 'cfgExport':
name = key[9:]
kat = 'Export'
elif len(key) > 15 and key[0:15] == 'cfgNotification':
name = key[15:]
kat = 'Notification'
else:
name = None
kat = None
if name and kat:
if isinstance(value, dict):
self._cached[name + kat] = value
newvalue = []
for k in value.keys():
newvalue.append(k + '|' + value[k])
value = ','.join(newvalue)
if isinstance(value, list):
self._cached[name + kat] = value
value = ','.join(value)
if isinstance(value, int):
value = str(value)
if kat not in self._config:
self._config[kat] = {}
self._config[kat][name] = value
else:
super(RSCPGuiMain, self).__setattr__(key, value)
def __getattr__(self, item):
if len(item) > 8 and item[0:8] == 'cfgLogin':
name = item[8:]
kat = 'Login'
elif len(item) > 9 and item[0:9] == 'cfgExport':
name = item[9:]
kat = 'Export'
elif len(item) > 15 and item[0:15] == 'cfgNotification':
name = item[15:]
kat = 'Notification'
else:
raise AttributeError('Wert ' + item + ' existiert nicht (get)')
if kat in self.config:
if kat == 'Login':
if name in self._config[kat]:
if name == 'password' and self._config[kat][name] != '' and self._config[kat][name][0] == '@':
return self.tinycode('rscpgui', self._config[kat][name][1:], True)
elif name == 'rscppassword' and self._config[kat][name] != '' and self._config[kat][name][0] == '@':
return self.tinycode('rscpgui_rscppass', self._config[kat][name][1:], True)
elif name in ('show_assistant', 'verify_ssl'):
return True if self._config[kat][name].lower() in ('true', '1', 'ja') else False
else:
return self._config[kat][name]
else:
if name == 'websocketaddr':
return 'wss://s10.e3dc.com/ws'
elif name == 'connectiontype':
return 'auto'
elif name in ('show_assistant', 'verify_ssl'):
return True
elif kat == 'Export':
if name in self._config[kat]:
if name in ('csv', 'json', 'mqtt', 'http', 'mqttretain', 'mqttinsecure', 'influx', 'mqttsub'):
return True if self._config[kat][name].lower() in ('true', '1', 'ja') else False
elif name in ('mqttport', 'mqttqos', 'intervall', 'influxport', 'influxtimeout'):
if self._config[kat][name] != '':
return int(self._config[kat][name])
elif name == 'paths':
#if kat + name not in self._cached:
self._cached[kat + name] = self._config[kat][name].split(',')
return self._cached[kat + name]
elif name == 'mqttpassword' and self._config[kat][name] != '' and self._config[kat][name][0] == '@':
return self.tinycode('rscpgui_mqttpass', self._config[kat][name][1:], True)
elif name == 'pathnames':
items = self._config[kat][name].split(',')
ret = {}
for item in items:
if item:
tmp = item.split('|')
if len(tmp) == 2:
ret[tmp[0]] = tmp[1]
self._cached[kat + name] = ret
return self._cached[kat + name]
else:
return self._config[kat][name]
elif kat == 'Notification':
if name in self._config[kat]:
if name == 'telegramtoken' and self._config[kat][name] != '' and self._config[kat][name][0] == '@':
return self.tinycode('telegramtoken', self._config[kat][name][1:], True)
elif name in ('telegram'):
return True if self._config[kat][name].lower() in ('true', '1', 'ja') else False
else:
return self._config[kat][name]
return None
@property
def connected(self):
return self._connected
@property
def connectiontype(self):
if isinstance(self._gui, E3DCGui):
return 'direkt'
elif isinstance(self._gui, E3DCWebGui):
return 'web'
else:
return None
@property
def gui(self):
if self._try_connect:
while self._try_connect:
time.sleep(0.1)
if self.connected:
return self._gui
self._try_connect = True
def test_connection(testgui):
requests = []
requests.append(RSCPTag.INFO_REQ_SERIAL_NUMBER)
requests.append(RSCPTag.INFO_REQ_IP_ADDRESS)
return testgui.get_data(requests, True)
if self.cfgLoginusername and self.cfgLoginpassword and self.cfgLoginconnectiontype == 'auto':
logger.info("Ermittle beste Verbindungsart (Verbindungsart auto)")
seriennummer = self.cfgLoginseriennummer
address = self.cfgLoginaddress
testgui = None
testgui_web = None
if self.cfgLoginusername and self.cfgLoginpassword and not seriennummer:
if self.cfgLoginusername and self.cfgLoginpassword and address and self.cfgLoginrscppassword:
try:
testgui = E3DCGui(self.cfgLoginusername, self.cfgLoginpassword, address,
self.cfgLoginrscppassword)
seriennummer = repr(test_connection(testgui)['INFO_SERIAL_NUMBER'])
except:
pass
if not seriennummer:
ret = self.getSerialnoFromWeb(self.cfgLoginusername, self.cfgLoginpassword)
if len(ret) == 1:
seriennummer = self.getSNFromNumbers(ret[0]['serialno'])
if self.cfgLoginusername and self.cfgLoginpassword and self.cfgLoginrscppassword and seriennummer and not address and self.cfgLoginwebsocketaddr:
logger.debug('Versuche IP-Adresse zu ermitteln')
try:
testgui = E3DCWebGui(self.cfgLoginusername, self.cfgLoginpassword, seriennummer)
ip = repr(test_connection(testgui)['INFO_IP_ADDRESS'])
if ip:
address = ip
logger.debug('IP-Adresse konnte ermittelt werden: ' + ip)
testgui_web = testgui
else:
raise Exception('IP-Adresse konnte nicht ermittelt werden, kein Inahlt')
except:
testgui = None
logger.exception('Bei der Ermittlung der IP-Adresse ist ein Fehler aufgetreten')
if self.cfgLoginusername and self.cfgLoginpassword and address and self.cfgLoginrscppassword:
logger.info('Teste direkte Verbindungsart')
if not isinstance(testgui, E3DCGui):
testgui = E3DCGui(self.cfgLoginusername, self.cfgLoginpassword, address, self.cfgLoginrscppassword)
try:
result = test_connection(testgui)
if not seriennummer:
seriennummer = repr(result['INFO_SERIAL_NUMBER'])
logger.info('Verwende Direkte Verbindung / Verbindung mit System ' + repr(
result['INFO_SERIAL_NUMBER']) + ' / ' + repr(result['INFO_IP_ADDRESS']))
self.serialnumber = result['INFO_SERIAL_NUMBER']
except ConnectionResetError as e:
logger.warning(
"Direkte Verbindung fehlgeschlagen (Socket) error({0}): {1}".format(e.errno, e.strerror))
testgui = None
except RSCPCommunicationError as e:
logger.warning("Direkte Verbindung fehlgeschlagen (RSCP)")
testgui = None
except:
logger.exception('Fehler beim Aufbau der direkten Verbindung')
testgui = None
if self.cfgLoginusername and self.cfgLoginpassword and seriennummer and self.cfgLoginwebsocketaddr and not testgui:
if testgui_web:
logger.info('Verwende Web Verbindung')
testgui = testgui_web
else:
logger.info('Teste Web Verbindungsart')
testgui = E3DCWebGui(self.cfgLoginusername, self.cfgLoginpassword, seriennummer)
try:
result = test_connection(testgui)
if not address:
address = repr(result['INFO_IP_ADDRESS'])
logger.info('Verwende Web Verbindung / Verbindung mit System ' + repr(
result['INFO_SERIAL_NUMBER']) + ' / ' + repr(result['INFO_IP_ADDRESS']))
self.serialnumber = result['INFO_SERIAL_NUMBER']
except:
logger.exception('Fehler beim Aufbau der Web Verbindung')
testgui = None
if not testgui:
logger.error('Es konnte keine Verbindungsart ermittelt werden')
else:
if self.cfgLoginseriennummer != seriennummer:
self.cfgLoginseriennummer = seriennummer
self.txtConfigSeriennummer.SetValue(seriennummer)
if self.cfgLoginaddress != address:
self.cfgLoginaddress = address
self.txtIP.SetValue(address)
self._gui = testgui
elif self.cfgLoginusername and self.cfgLoginpassword and self.cfgLoginaddress and self.cfgLoginrscppassword and self.cfgLoginconnectiontype == 'direkt':
testgui = E3DCGui(self.cfgLoginusername, self.cfgLoginpassword, self.cfgLoginaddress,
self.cfgLoginrscppassword)
try:
result = test_connection(testgui)
self._gui = testgui
logger.info('Verwende Direkte Verbindung')
except:
self._gui = None
elif self.cfgLoginusername and self.cfgLoginpassword and self.cfgLoginseriennummer and self.cfgLoginwebsocketaddr and self.cfgLoginconnectiontype == 'web':
testgui = E3DCWebGui(self.cfgLoginusername, self.cfgLoginpassword, self.cfgLoginseriennummer)
try:
result = test_connection(testgui)
self._gui = testgui
logger.info('Verwende Websocket')
except:
self._gui = None
else:
self._gui = None
if not self._gui:
logger.info('Kein Verbindungstyp kann verwendet werden, es fehlen Verbindungsdaten')
self._try_connect = False
return self._gui
def getSNFromNumbers(self, sn):
if sn[0:2] in ('70', '75'):
return 'P10-' + sn
elif sn[0:2] == '60':
return 'Q10-' + sn
elif sn[0:2] in ('85', '81', '82'):
return 'H20-' + sn
else:
return 'S10-' + sn
def getModelFromSerial(self, sn):
sn = sn[4:]
if sn[0:1] == '4' or sn[0:2] == '72':
return "S10E"
if sn[0:2] == '74':
return "S10E Compact"
if sn[0:1] == '5':
return "S10 Mini"
if sn[0:1] == '6':
return "Quattroporte"
if sn[0:2] == '70':
return "S10E Pro"
if sn[0:2] == '75':
return "S10E Pro Compact"
if sn[0:1] == '8':
return "S10X"
return "Unknown"
def getSerialnoFromWeb(self, username, password):
logger.debug('Ermittle Seriennummer über Webzugriff')
userlevel = None
try:
r = requests.post('https://s10.e3dc.com/s10/phpcmd/cmd.php', data={'DO': 'LOGIN',
'USERNAME': username,
'PASSWD': hashlib.md5(password.encode()).hexdigest(),
'DENV': 'E3DC'})
r.raise_for_status()
r_json = r.json()
if r_json['ERRNO'] != 0:
raise Exception('Abfrage Fehlerhaft #1, Fehlernummer ' + str(r_json['ERRNO']))
userlevel = int(r_json['CONTENT']['USERLEVEL'])
cookies = r.cookies
if userlevel in (1, 128):
r = requests.post('https://s10.e3dc.com/s10/phpcmd/cmd.php', data={'DO': 'GETCONTENT',
'MODID': 'IDOVERVIEWCOMMONTABLE',
'ARG0': 'undefined',
'TOS': -7200,
'DENV': 'E3DC'}, cookies=cookies)
r.raise_for_status()
r_json = r.json()
if r_json['ERRNO'] != 0:
raise Exception('Abfrage fehlerhaft #2, Fehlernummer ' + str(r_json['ERRNO']))
content = r_json['CONTENT']
html = None
for lst in content:
if 'HTML' in lst:
html = lst['HTML']
break
if not html:
raise Exception('Abfrage Fehlerhaft #3, Daten nicht gefunden')
regex = r"s10list = '(\[\{.*\}\])';"
try:
match = re.search(regex, html, re.MULTILINE).group(1)
obj = json.loads(match)
return obj
except:
raise Exception('Abfrage Fehlerhaft #4, Regex nicht erfolgreich')
except:
logger.exception('Fehler beim Abruf der Seriennummer, Zugangsdaten fehlerhaft?')
return []
def updateData(self):
if not self._updateRunning:
self._updateRunning = True
try:
if self.gui:
logger.info('Aktualisiere Daten')
self.clear_values()
try:
self.fill_info()
except:
logger.exception('Fehler beim Abruf der INFO-Daten')
try:
self.fill_bat()
except:
logger.exception('Fehler beim Abruf der BAT-Daten')
try:
self.fill_dcdc()
except:
logger.exception('Fehler beim Abruf der DCDC-Daten')
try:
self.fill_pvi()
except:
logger.exception('Fehler beim Abruf der PVI-Daten')
try:
self.fill_ems()
self.fill_mbs()
except:
logger.exception('Fehler beim Abruf der EMS-Daten')
try:
self.fill_pm()
except:
logger.exception('Fehler beim Abruf der PM-Daten')
try:
self.fill_wb()
except:
logger.exception('Fehler beim Abruf der WB-Daten')
try:
self.fill_mbs()
except:
logger.exception('Fehler beim Abruf der Modbus-Daten')
else:
logger.warning('Konfiguration unvollständig, Verbindung nicht möglich')
except:
logger.exception('Fehler beim Aktualisieren der Daten')
self._updateRunning = False
def sammle_data(self, anon = True):
logger.info('Sammle Daten')
self.updateData()
anonymize = ['DCDC_SERIAL_NUMBER', 'INFO_MAC_ADDRESS', 'BAT_DCB_SERIALNO', 'BAT_DCB_SERIALCODE', 'INFO_SERIAL_NUMBER',
'INFO_A35_SERIAL_NUMBER', 'PVI_SERIAL_NUMBER', 'INFO_PRODUCTION_DATE']
remove = ['INFO_IP_ADDRESS']
data = {}
if self._data_bat:
data['BAT_DATA'] = []
for d in self._data_bat:
data['BAT_DATA'].append(d.asDict())
if self._data_dcdc:
data['DCDC_DATA'] = []
for d in self._data_dcdc:
data['DCDC_DATA'].append(d.asDict())
if self._data_ems:
data['EMS_DATA'] = self._data_ems.asDict()
if self._data_info:
data['INFO_DATA'] = self._data_info.asDict()
if self._data_pvi:
data['PVI_DATA'] = {}
for k in self._data_pvi:
d = self._data_pvi[k]
data['PVI_DATA'][k] = d.asDict()
if self._data_pm:
data['PM_DATA'] = {}
for k in self._data_pm:
d = self._data_pm[k]
data['PM_DATA'][k] = d.asDict()
if self._data_wb:
data['WB_DATA'] = []
for d in self._data_wb:
data['WB_DATA'].append(d.asDict())
if anon:
logger.info('Anonymisiere Daten')
data = self.anonymize_data(data, anonymize, remove)
logger.info('Daten wurden anonymisiert')
logger.info('Datensammlung beendet')
return data
def anonymize_data(self, data, anonymize, remove):
if isinstance(data, dict):
toremove = []
for i in data.keys():
if isinstance(data[i], dict) or isinstance(data[i], list):
data[i] = self.anonymize_data(data[i], anonymize, remove)
elif i in anonymize:
if isinstance(data[i], int) or isinstance(data[i], float):
data[i] = str(data[i])
if len(data[i]) >= 6:
tmp = 'X' * (len(data[i])-6)
data[i] = data[i][:6] + tmp
else:
data[i] = 'X' * len(data[i])
elif i in remove:
toremove.append(i)
for r in toremove:
del data[r]
elif isinstance(data, list):
nl = []
for i in data:
nl += [self.anonymize_data(i, anonymize, remove)]
data = nl
return data
def setMaxChargePower(self, value):
temp = [RSCPDTO(tag=RSCPTag.EMS_MAX_CHARGE_POWER, rscp_type=RSCPType.Uint32, data=int(value))]
r = [RSCPDTO(tag=RSCPTag.EMS_REQ_SET_POWER_SETTINGS, rscp_type=RSCPType.Container, data=temp)]
res = self.gui.get_data(r, True)
logger.info('Wert über setMaxChargePower auf ' + str(value) + ' geändert')
def setMaxDischargePower(self, value):
temp = [RSCPDTO(tag=RSCPTag.EMS_MAX_DISCHARGE_POWER, rscp_type=RSCPType.Uint32, data=int(value))]
r = [RSCPDTO(tag=RSCPTag.EMS_REQ_SET_POWER_SETTINGS, rscp_type=RSCPType.Container, data=temp)]
res = self.gui.get_data(r, True)
logger.info('Wert über setMaxDischargePower auf ' + str(value) + ' geändert') \
def setDischargeStartPower(self, value):
temp = [RSCPDTO(tag=RSCPTag.EMS_DISCHARGE_START_POWER, rscp_type=RSCPType.Uint32, data=int(value))]
r = [RSCPDTO(tag=RSCPTag.EMS_REQ_SET_POWER_SETTINGS, rscp_type=RSCPType.Container, data=temp)]
res = self.gui.get_data(r, True)
logger.info('Wert über setDischageStartPower auf ' + str(value) + ' geändert') \
@property
def mqttclient(self):
#TODO: Weitere Möglichkeiten ergänzen
sublist = {
'E3DC/EMS_DATA/EMS_GET_POWER_SETTINGS/EMS_MAX_CHARGE_POWER': self.setMaxChargePower,
'E3DC/EMS_DATA/EMS_GET_POWER_SETTINGS/EMS_MAX_DISCHARGE_POWER': self.setMaxDischargePower,
'E3DC/EMS_DATA/EMS_GET_POWER_SETTINGS/EMS_DISCHARGE_START_POWER': self.setDischargeStartPower
}
def on_message(client, userdata, message):
topic = message.topic[1:]
if topic[-4:] == '/SET':
topic = topic[:-4]
if topic in self.cfgExportpathnames.values():
path = list(self.cfgExportpathnames.keys())[list(self.cfgExportpathnames.values()).index(topic)]
if path in sublist.keys():
callback = sublist[path]
value = str(message.payload.decode("utf-8"))
try:
test = int(self._exportcache[topic])
if test != value:
callback(value)
else:
logger.debug(topic + ' Wert hat sich nicht geändert ' + str(value) + ' <-> ' + str(test))
except:
logger.exception('Fehler bei ' + topic + ' (' + value + ')')
def on_connect(client, userdata, flags, rc):
logger.debug('MQTT-Client connected')
if sub:
for path in sublist.keys():
if path in self.cfgExportpathnames.keys():
topic = '/' + self.cfgExportpathnames[path] + '/SET'
logger.debug('MQTT Subscribe: ' + topic)
self._mqttclient.subscribe(topic)
def on_disconnect(client, userdata, rc):
logger.debug('MQTT-Client disconnect')
if self._mqttclient is not None:
if self._mqttclient.is_connected():
return self._mqttclient
self._mqttclient = None
if self.cfgExportmqtt if 'paho' in sys.modules.keys() else False:
broker = self.cfgExportmqttbroker
port = self.cfgExportmqttport
sub = self.cfgExportmqttsub
username = self.cfgExportmqttusername
password = self.cfgExportmqttpassword
zertifikat = self.cfgExportmqttzertifikat
insecure = self.cfgExportmqttinsecure
logger.info('Verbinde mit MQTT-Broker ' + broker + ':' + str(port))
self._mqttclient = paho.Client("RSCPGui")
if username and password:
self._mqttclient.username_pw_set(username, password)
if insecure and zertifikat:
if os.path.isfile(zertifikat):
self._mqttclient.tls_set(ca_certs=zertifikat)
self._mqttclient.tls_insecure_set(insecure)
self._mqttclient.enable_logger(logger)
self._mqttclient.on_message=on_message
self._mqttclient.on_disconnect=on_disconnect
self._mqttclient.on_connect=on_connect
self._mqttclient.connect(broker, port)
self._mqttclient.loop_start()
return self._mqttclient
def StartAutoExport(self):
def influx_connect(influxhost, influxport, influxtimeout, influxdatenbank):
logger.debug('Verbinde mit Influxdb ' + influxhost + ':' + str(influxport) + '/' + influxdatenbank)
influxclient = influxdb.InfluxDBClient(host=influxhost, port=influxport, timeout=influxtimeout)
influxclient.switch_database(influxdatenbank)
return influxclient
try:
logger.info('Starte automatischen Export')
if len(self.cfgExportpaths) > 0:
logger.debug('Es sind ' + str(len(self.cfgExportpaths)) + ' Datenfelder zum Export vorgesehen')
else:
logger.debug('Es wurden keine Exporfelder definiert!')
csvwriter = None
csvfile = None
csvactive = self.cfgExportcsv
csvfilename = self.cfgExportcsvfile
jsonactive = self.cfgExportjson
jsonfilename = self.cfgExportjsonfile
mqttqos = self.cfgExportmqttqos
mqttretain = self.cfgExportmqttretain
httpactive = self.cfgExporthttp
httpurl = self.cfgExporthttpurl
influxactive = self.cfgExportinflux if 'influxdb' in sys.modules.keys() else False
influxhost = self.cfgExportinfluxhost
influxport = self.cfgExportinfluxport
influxdatenbank = self.cfgExportinfluxdatenbank
influxtimeout = self.cfgExportinfluxtimeout
influxname = self.cfgExportinfluxname
influxclient = influx_connect(influxhost, influxport, influxtimeout, influxdatenbank) if influxactive else None
intervall = self.cfgExportintervall
notificationactive = False
if 'telegram' in sys.modules.keys():
if self.cfgNotificationtelegram is True:
if not self.cfgNotificationtelegramtoken or not self.cfgNotificationtelegramempfaenger:
logger.warning('Benachrichtigung an Telegram nicht möglich, Token oder Empfänger sind nicht gefüllt')
else:
self.notificationblocker = {}
notificationactive = True
if csvactive:
csvfile = open(csvfilename, 'a', newline='')
fields: list = self.cfgExportpaths.copy()
for key,val in enumerate(fields):
if val in self.cfgExportpathnames:
fields[key] = self.cfgExportpathnames[val]
fields.insert(0,'datetime')
fields.insert(0,'ts')
csvwriter = csv.DictWriter(csvfile, fieldnames = fields)
csvwriter.writeheader()
while self._AutoExportStarted:
laststart = time.time()
logger.debug('Exportiere Daten (autoexport)')
try:
values, value_path = self.getUploadDataFromPath()
values['ts'] = time.time()
values['datetime'] = datetime.datetime.now().isoformat()
self._exportcache = values
if csvactive:
threading.Thread(target=self.exportCSV, args=(csvfilename, csvwriter, csvfile, values)).start()
if jsonactive:
threading.Thread(target=self.exportJson, args=(jsonfilename, values)).start()
if self.mqttclient is not None:
threading.Thread(target=self.exportMQTT, args=(mqttqos, mqttretain, values)).start()
if httpactive:
threading.Thread(target=self.exportHTTP, args=(httpurl, values)).start()
if influxactive:
threading.Thread(target=self.exportInflux, args=(influxclient, influxname,values)).start()
if notificationactive:
self.notify(value_path)
#threading.Thread(target=self.notify, args={values}).start()
except:
logger.exception('Fehler beim Abruf der Exportdaten')
diff = time.time() - laststart
if diff < intervall:
wait = intervall - diff
logger.debug('Warte ' + str(wait) + 's')
waits = int(math.floor(wait))
time.sleep(wait-waits)
for i in range(0,waits):
if self._AutoExportStarted:
time.sleep(1)
else:
break
if self._mqttclient is not None:
self._mqttclient.loop_stop()
self._mqttclient.disconnect()
if csvactive:
csvfile.close()
except:
logger.exception('Fehler beim automatischen Export')
self._AutoExportStarted = False
def exportCSV(self, csvfilename, csvwriter, csvfile, values):
logger.info('Exportiere in CSV-Datei ' + csvfilename)
try:
csvwriter.writerow(values)
csvfile.flush()
logger.debug('Export in CSV-Datei erfolgreich')
except:
logger.exception('Fehler beim Export in CSV-Datei')
def exportHTTP(self, httpurl, values):
try:
logger.info('Exportiere an Http-Url ' + httpurl)
r = requests.post(httpurl, json=values)
r.raise_for_status()
logger.debug('Export an URL erfolgreich ' + str(r.status_code))
logger.debug('Response: ' + r.text)
except:
logger.exception('Fehler beim Export in Http')
def exportMQTT(self, mqttqos, mqttretain, values):
try:
logger.info('Exportiere nach MQTT')
for key in values.keys():
if key not in ('ts', 'datetime'):
topic = '/' + key
res, mid = self.mqttclient.publish(topic, values[key], mqttqos, mqttretain)
if res != 0:
self.mqttclient.disconnect()
logger.debug('Export an MQTT abgeschlossen')
except:
logger.exception('Fehler beim Export nach MQTT')
def exportJson(self, jsonfilename, values):
try:
logger.info('Exportiere in JSON-Datei ' + jsonfilename)
with open(jsonfilename, 'w') as jsonfile:
json.dump(values, jsonfile)
logger.debug('Export an JSON-Datei erfolgreich')
except:
logger.exception('Fehler beim Export in JSON-Datei')
def exportInflux(self, influxclient, influxname, fields):
try:
logger.info('Exportiere an Influxdb')
values = {}
for key in fields.keys():
if key not in ('ts', 'datetime'):
values[key] = fields[key]
if len(values) > 0:
write_points = [{'measurement': influxname, 'fields': values}]
influxclient.write_points(write_points)
logger.debug('Export an Influxdb erfolgreich')
else:
logger.warning('Keine Daten zur Übergabe an Influxdb zur Verfügung')
except:
logger.exception('Fehler beim Export an Influxdb')
def notify(self, values):
# path|datatype|expression|notificationservice|text|waittime(seconds)
#[Notification / Rules]
#1 = E3DC / EMS_DATA / EMS_POWER_GRID | int | {value} < -2000 | telegram | Einspeiseleistung > 2000
#W({value}) | 3600
def execute_rule(value, datatype, expression, text):
try:
if datatype in ('int', 'integer', 'smallint', 'uint', 'int16', 'int32', 'int64'):
value = int(value)
elif datatype in ('float', 'numeric', 'double'):
value = float(value)
elif datatype in ('str','string',''):
value = str(value)
except:
logger.exception('Datenkonvertierung in notify fehlgeschlagen: ' + str(value) + ' Datentyp: ' + datatype)
expression = expression.format(value=str(value))
logger.debug('Validiere Daten ' + expression )
try:
if eval(expression):
text = text.format(value=str(value))
return text
except:
logger.exception('Fehler beim Ausführen der Expression: ' + expression)
return ''
def send_telegram(text):
logger.debug('Sende Nachricht über Telegram: ' + text)
try:
bot = telegram.Bot(token=self.cfgNotificationtelegramtoken)
bot.send_message(chat_id=self.cfgNotificationtelegramempfaenger, text=text)
except:
logger.exception('Fehler beim versand einer Telegram-Benachrichtigung')
logger.debug('Sende Benachrichtigungen')
rules = self._config['Notification/Rules']
for rule in rules:
path,datatype,expression,service,text,waittime = rules[rule].split('|')
waittime = float(waittime)
telegramactive = service == 'telegram'
block = False
if waittime > 0:
if rule in self._notificationblocker:
if time.time() - self._notificationblocker[rule] < waittime:
logger.debug('Benachrichtigung nicht verschickt, Wartezeit nicht abgelaufen ' + str(time.time() - self._notificationblocker[rule]) + 'ts < ' + str(waittime))
block = True
if not block:
if path in values:
if values[path] is not None:
logger.debug('Regel (' + rule + ') für Path ' + path + ' gefunden mit Value: ' + str(values[path]))
if waittime == -1:
if rule not in self._notificationblocker:
pass
elif self._notificationblocker[rule] != values[path]:
text = execute_rule(values[path], datatype, expression, text)
if text != '':
if telegramactive:
send_telegram(text)
else:
logger.debug('Keine Benachrichtigung für ' + path + ' verschickt, Wert hat sich nicht geändert ' + str(values[path]))
self._notificationblocker[rule] = values[path]
else:
text = execute_rule(values[path], datatype, expression, text)
if text != '':
self._notificationblocker[rule] = time.time()
if telegramactive:
send_telegram(text)
else:
logger.warning('Wert für Pfad ' + path + ' konnte nicht ermittelt werden, überspringe Benachrichtigung')
def getUploadDataFromPath(self):
def getDataFromPath(teile, data):
if data is not None:
if isinstance(data, dict):
if teile[0] in data.keys():
if len(teile) == 1:
return data[teile[0]]
else:
return getDataFromPath(teile[1:], data[teile[0]])
elif isinstance(data, list):
if data[int(teile[0])] is not None:
if len(teile) == 1:
return data[int(teile[0])]
else:
return getDataFromPath(teile[1:], data[int(teile[0])])
else:
logger.warning('Element not Found ' + '/'.join(teile))
ems_data = None
bat_data = {}
info_data = None
dcdc_data = {}
pm_data = {}
pvi_data = {}
wb_data = {}
values = {}
value_path = {}
for path in self.cfgExportpaths:
logger.debug('Ermittle Pfad aus ' + path)
teile = path.split('/')
if teile[0] == 'E3DC':
newvalue = None
if teile[1] == 'EMS_DATA':
try:
if not ems_data:
ems_data = self._fill_ems().asDict()
newvalue = getDataFromPath(teile[2:], ems_data)
except:
logger.exception('Fehler beim Abruf von EMS')
elif teile[1] == 'BAT_DATA':
try:
index = int(teile[2])
if index not in bat_data.keys():
bat_data[index] = self.gui.get_data(self.gui.getBatDcbData(bat_index=index), True).asDict()
newvalue = getDataFromPath(teile[3:], bat_data[index])
except:
logger.exception('Fehler beim Abruf von BAT')
elif teile[1] == 'INFO_DATA':
try:
if not info_data:
info_data = self._fill_info().asDict()
newvalue = getDataFromPath(teile[2:], info_data)
except:
logger.exception('Fehler beim Abruf von INFO')
elif teile[1] == 'DCDC_DATA':
try:
index = int(teile[2])