-
Notifications
You must be signed in to change notification settings - Fork 103
/
__init__.py
3091 lines (2478 loc) · 138 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 2022- Michael Wenzel [email protected]
#########################################################################
# This file is part of SmartHomeNG.
# https://www.smarthomeNG.de
# https://knx-user-forum.de/forum/supportforen/smarthome-py
#
# This plugin provides additional functionality to mysql database
# connected via database plugin
#
# SmartHomeNG 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.
#
# SmartHomeNG 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 SmartHomeNG. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
import os
import sqlvalidator
import datetime
import time
import re
import queue
import threading
import logging
import pickle
import operator
from dateutil.relativedelta import relativedelta
from typing import Union
from dataclasses import dataclass, InitVar
from collections import deque
from lib.model.smartplugin import SmartPlugin
from lib.item import Items
from lib.item.item import Item
from lib.shtime import Shtime
from lib.plugin import Plugins
from .webif import WebInterface
from .item_attributes import *
from .item_attributes_master import ITEM_ATTRIBUTES
import lib.db
HOUR = 'hour'
DAY = 'day'
WEEK = 'week'
MONTH = 'month'
YEAR = 'year'
class DatabaseAddOn(SmartPlugin):
"""
Main class of the Plugin. Does all plugin specific stuff and provides the update functions for the items
"""
PLUGIN_VERSION = '1.2.7'
def __init__(self, sh):
"""
Initializes the plugin.
"""
# Call init code of parent class (SmartPlugin)
super().__init__()
self.logger.debug(f'Start of {self.get_shortname()} Plugin.')
# get item and shtime instance
self.shtime = Shtime.get_instance()
self.items = Items.get_instance()
self.plugins = Plugins.get_instance()
# define cache dicts
self.pickle_data_validity_time = 600 # seconds after which the data saved in pickle are not valid anymore
self.current_values = {} # Dict to hold min and max value of current day / week / month / year for items
self.previous_values = {} # Dict to hold value of end of last day / week / month / year for items
self.item_cache = {} # Dict to hold item_id, oldest_log_ts and oldest_entry for items
self.value_list_raw_data = {}
# define variables for database, database connection, working queue and status
self.item_queue = queue.Queue() # Queue containing all to be executed items
self.update_item_delay_deque = deque() # Deque for delay working of updated item values
# ToDo: Check if still needed
self.queue_consumer_thread = None # Queue consumer thread
self._db_plugin = None # object if database plugin
self._db = None # object of database
self.connection_data = None # connection data list of database
self.db_driver = None # driver of the used database
self.db_instance = None # instance of the used database
self.item_attribute_search_str = 'database' # attribute, on which an item configured for database can be identified
self.last_connect_time = 0 # mechanism for limiting db connection requests
self.alive = None # Is plugin alive?
self.suspended = False # Is plugin activity suspended
self.active_queue_item: str = '-' # String holding item path of currently executed item
self.onchange_delay_time = 30
# define default mysql settings
self.default_connect_timeout = 60
self.default_net_read_timeout = 60
# define variables from plugin parameters
self.db_configname = self.get_parameter_value('database_plugin_config')
self.startup_run_delay = self.get_parameter_value('startup_run_delay')
self.ignore_0 = self.get_parameter_value('ignore_0')
self.value_filter = self.get_parameter_value('value_filter')
self.optimize_value_filter = self.get_parameter_value('optimize_value_filter')
self.use_oldest_entry = self.get_parameter_value('use_oldest_entry')
self.lock_db_for_query = self.get_parameter_value('lock_db_for_query')
# path and filename for data storage
data_storage_file = 'db_addon_data'
self.data_storage_path = f"{os.getcwd()}/var/plugin_data/{self.get_shortname()}/{data_storage_file}.pkl"
# get debug log options
self.debug_log = DebugLogOptions(self.log_level)
# init cache data
self.init_cache_data()
# init webinterface
self.init_webinterface(WebInterface)
def run(self):
"""
Run method for the plugin
"""
self.logger.debug("Run method called")
# check existence of db-plugin, get parameters, and init connection to db
if not self._check_db_existence():
self.logger.error(f"Check of existence of database plugin incl connection check failed. Plugin not loaded")
return self.deinit()
# create db object
self._db = lib.db.Database("DatabaseAddOn", self.db_driver, self.connection_data)
if not self._db.api_initialized:
self.logger.error("Initialization of database API failed")
return self.deinit()
self.logger.debug("Initialization of database API successful")
# check initialization of db
if not self._initialize_db():
self.logger.error("Connection to database failed")
return self.deinit()
self._db.close()
# check db connection settings
if self.db_driver.lower() == 'pymysql':
self._check_db_connection_setting()
# add scheduler for cyclic trigger item calculation
self.scheduler_add('cyclic', self.execute_due_items, prio=3, cron='10 * * * *', cycle=None, value=None, offset=None, next=None)
# add scheduler to trigger items to be calculated at startup with delay
dt = self.shtime.now() + relativedelta(seconds=(self.startup_run_delay + 3))
self.logger.info(f"Set scheduler for calculating startup-items with delay of {self.startup_run_delay + 3}s to {dt}.")
self.scheduler_add('startup', self.execute_startup_items, next=dt)
# update database_items in item config, where path was given
self._update_database_items()
# set plugin to alive
self.alive = True
# work item queue
self.work_item_queue()
# ToDo: Check if still needed
"""
try:
self._queue_consumer_thread_startup()
except Exception as e:
self.logger.warning(f"During working item queue Exception '{e}' occurred.")
self.logger.debug(e, exc_info=True)
# self.logger.error("Thread for working item queue died. De-init plugin.")
# self.deinit()
self.logger.error("Suspend Plugin and clear Item-Queue.")
self.suspend(True)
"""
def stop(self):
"""
Stop method for the plugin
"""
self.logger.debug("Stop method called")
self.alive = False
self.scheduler_remove('cyclic')
self.scheduler_remove('onchange_delay')
if self._db:
self._db.close()
self.save_cache_data()
# ToDo: Check if still needed
# self._queue_consumer_thread_shutdown()
def parse_item(self, item: Item):
"""
Default plugin parse_item method. Is called when the plugin is initialized.
The plugin can, corresponding to its attribute keywords, decide what to do with the item in the future, like adding it to an internal array for future reference
:param item: The item to process.
:return: If the plugin needs to be informed of an items change you should return a call back function
like the function update_item down below. An example when this is needed is the knx plugin
where parse_item returns the update_item function when the attribute knx_send is found.
This means that when the items value is about to be updated, the call back function is called
with the item, caller, source and dest as arguments and in case of the knx plugin the value
can be sent to the knx with a knx write function within the knx plugin.
"""
def get_query_parameters_from_db_addon_fct() -> Union[dict, None]:
""" derived parameters from given db_addon_fct"""
# get parameter
db_addon_fct_vars = db_addon_fct.split('_')
func = timeframe = timedelta = start = end = group = group2 = data_con_func = log_text = None
required_params = None
if db_addon_fct in HISTORIE_ATTRIBUTES_ONCHANGE:
# handle functions 'minmax onchange' in format 'minmax_timeframe_func' items like 'minmax_heute_max', 'minmax_heute_min', 'minmax_woche_max', 'minmax_woche_min'
timeframe = translate_timeframe(db_addon_fct_vars[1])
func = db_addon_fct_vars[2] if db_addon_fct_vars[2] in ALLOWED_MINMAX_FUNCS else None
start = end = 0
log_text = 'minmax_timeframe_func'
required_params = [func, timeframe, start, end]
elif db_addon_fct in HISTORIE_ATTRIBUTES_LAST:
# handle functions 'minmax_last' in format 'minmax_last_timedelta|timeframe_function' like 'minmax_last_24h_max'
func = db_addon_fct_vars[3]
start, timeframe = split_sting_letters_numbers(db_addon_fct_vars[2])
start = to_int(start)
timeframe = translate_timeframe(timeframe)
end = 0
log_text = 'minmax_last_timedelta|timeframe_function'
required_params = [func, timeframe, start, end]
elif db_addon_fct in HISTORIE_ATTRIBUTES_TIMEFRAME:
# handle functions 'min/max/avg' in format 'minmax_timeframe_timedelta_func' like 'minmax_heute_minus2_max'
func = db_addon_fct_vars[3] # min, max, avg
timeframe = translate_timeframe(db_addon_fct_vars[1]) # day, week, month, year
start = end = to_int(split_sting_letters_numbers(db_addon_fct_vars[2])[1])
log_text = 'minmax_timeframe_timedelta_func'
required_params = [func, timeframe, start, end]
elif db_addon_fct in ZAEHLERSTAND_ATTRIBUTES_TIMEFRAME:
# handle functions 'zaehlerstand' in format 'zaehlerstand_timeframe_timedelta' like 'zaehlerstand_heute_minus1'
func = 'last'
timeframe = translate_timeframe(db_addon_fct_vars[1])
start = end = to_int(split_sting_letters_numbers(db_addon_fct_vars[2])[1])
log_text = 'zaehlerstand_timeframe_timedelta'
required_params = [timeframe, start, end]
elif db_addon_fct in VERBRAUCH_ATTRIBUTES_ONCHANGE:
# handle functions 'verbrauch onchange' items in format 'verbrauch_timeframe' like 'verbrauch_heute', 'verbrauch_woche', 'verbrauch_monat', 'verbrauch_jahr'
timeframe = translate_timeframe(db_addon_fct_vars[1])
start = end = 0
log_text = 'verbrauch_timeframe'
required_params = [timeframe, start, end]
elif db_addon_fct in VERBRAUCH_ATTRIBUTES_TIMEFRAME:
# handle functions 'verbrauch on-demand' in format 'verbrauch_timeframe_timedelta' like 'verbrauch_heute_minus2'
timeframe = translate_timeframe(db_addon_fct_vars[1])
start = end = to_int(split_sting_letters_numbers(db_addon_fct_vars[2])[1])
log_text = 'verbrauch_timeframe_timedelta'
required_params = [timeframe, start, end]
elif db_addon_fct in VERBRAUCH_ATTRIBUTES_LAST:
# handle functions 'verbrauch_last' in format 'verbrauch_last_timedelta|timeframe' like 'verbrauch_last_24h'
start, timeframe = split_sting_letters_numbers(db_addon_fct_vars[2])
start = to_int(start)
timeframe = translate_timeframe(timeframe)
end = 0
log_text = 'verbrauch_last_timedelta|timeframe'
required_params = [timeframe, start, end]
elif db_addon_fct in VERBRAUCH_ATTRIBUTES_ROLLING:
# handle functions 'verbrauch_on-demand' in format 'verbrauch_rolling_window_timeframe_timedelta' like 'verbrauch_rolling_12m_woche_minus1'
func = db_addon_fct_vars[1]
window_inc, window_dur = split_sting_letters_numbers(db_addon_fct_vars[2])
window_inc = to_int(window_inc) # 12
window_dur = translate_timeframe(window_dur) # day, week, month, year
timeframe = translate_timeframe(db_addon_fct_vars[3]) # day, week, month, year
end = to_int(split_sting_letters_numbers(db_addon_fct_vars[4])[1])
if window_dur in ALLOWED_QUERY_TIMEFRAMES and window_inc and timeframe and end:
start = to_int(timeframe_to_timeframe(timeframe, window_dur) * window_inc) + end
log_text = 'verbrauch_rolling_window_timeframe_timedelta'
required_params = [func, timeframe, start, end]
elif db_addon_fct in VERBRAUCH_ATTRIBUTES_JAHRESZEITRAUM:
# handle functions of format 'verbrauch_jahreszeitraum_timedelta' like 'verbrauch_jahreszeitraum_minus1'
timeframe = translate_timeframe(db_addon_fct_vars[1]) # day, week, month, year
timedelta = to_int(split_sting_letters_numbers(db_addon_fct_vars[2])[1])
log_text = 'verbrauch_jahreszeitraum_timedelta'
required_params = [timeframe, timedelta]
elif db_addon_fct in TAGESMITTEL_ATTRIBUTES_ONCHANGE:
# handle functions 'tagesmitteltemperatur onchange' items in format 'tagesmitteltemperatur_timeframe' like 'tagesmitteltemperatur_heute', 'tagesmitteltemperatur_woche', 'tagesmitteltemperatur_monat', 'tagesmitteltemperatur_jahr'
timeframe = translate_timeframe(db_addon_fct_vars[1])
func = 'max'
start = end = 0
log_text = 'tagesmitteltemperatur_timeframe'
required_params = [timeframe, start, end]
elif db_addon_fct in TAGESMITTEL_ATTRIBUTES_TIMEFRAME:
# handle 'tagesmitteltemperatur_timeframe_timedelta' like 'tagesmitteltemperatur_heute_minus1'
func = 'max'
timeframe = translate_timeframe(db_addon_fct_vars[1])
start = end = to_int(split_sting_letters_numbers(db_addon_fct_vars[2])[1])
data_con_func = 'first_hour_avg_day'
log_text = 'tagesmitteltemperatur_timeframe_timedelta'
required_params = [func, timeframe, start, end, data_con_func]
elif db_addon_fct in SERIE_ATTRIBUTES_MINMAX:
# handle functions 'serie_minmax' in format 'serie_minmax_timeframe_func_start|group' like 'serie_minmax_monat_min_15m'
func = db_addon_fct_vars[3]
timeframe = translate_timeframe(db_addon_fct_vars[2])
start, group = split_sting_letters_numbers(db_addon_fct_vars[4])
start = to_int(start)
group = translate_timeframe(group)
end = 0
log_text = 'serie_minmax_timeframe_func_start|group'
required_params = [func, timeframe, start, end, group]
elif db_addon_fct in SERIE_ATTRIBUTES_ZAEHLERSTAND:
# handle functions 'serie_zaehlerstand' in format 'serie_zaehlerstand_timeframe_start|group' like 'serie_zaehlerstand_tag_30d'
timeframe = translate_timeframe(db_addon_fct_vars[2])
start, group = split_sting_letters_numbers(db_addon_fct_vars[3])
start = to_int(start)
group = translate_timeframe(group)
log_text = 'serie_zaehlerstand_timeframe_start|group'
required_params = [timeframe, start, group]
elif db_addon_fct in SERIE_ATTRIBUTES_VERBRAUCH:
# handle all functions of format 'serie_verbrauch_timeframe_start|group' like 'serie_verbrauch_tag_30d'
timeframe = translate_timeframe(db_addon_fct_vars[2])
start, group = split_sting_letters_numbers(db_addon_fct_vars[3])
start = to_int(start)
group = translate_timeframe(group)
log_text = 'serie_verbrauch_timeframe_start|group'
required_params = [timeframe, start, group]
elif db_addon_fct in SERIE_ATTRIBUTES_SUMME:
# handle all summe in format 'serie_xxsumme_timeframe_count|group' like serie_waermesumme_monat_24m
func = 'sum_max'
start, timeframe = split_sting_letters_numbers(db_addon_fct_vars[3])
start = to_int(start)
timeframe = translate_timeframe(timeframe)
end = 0
group = 'day',
group2 = 'month'
log_text = 'serie_xxsumme_timeframe_count|group'
required_params = [func, timeframe, start, end, group, group2]
elif db_addon_fct in SERIE_ATTRIBUTES_MITTEL_D:
# handle 'serie_tagesmittelwert_count|group' like 'serie_tagesmittelwert_0d' => Tagesmittelwert der letzten 0 Tage (also heute)
func = 'max'
timeframe = 'year'
start, group = split_sting_letters_numbers(db_addon_fct_vars[2])
start = to_int(start)
group = translate_timeframe(group)
end = 0
log_text = 'serie_tagesmittelwert_count|group'
required_params = [func, timeframe, start, end, group]
elif db_addon_fct in SERIE_ATTRIBUTES_MITTEL_H:
# handle 'serie_tagesmittelwert_group2_count|group' like 'serie_tagesmittelwert_stunde_0d' => Stundenmittelwerte der letzten 0 Tage (also heute)
func = 'avg1'
timeframe = 'day'
end = 0
group = 'hour'
start, group2 = split_sting_letters_numbers(db_addon_fct_vars[3])
start = to_int(start)
group2 = translate_timeframe(group2)
log_text = 'serie_tagesmittelwert_group2_count|group'
required_params = [func, timeframe, start, end, group, group2]
elif db_addon_fct in SERIE_ATTRIBUTES_MITTEL_H1:
# handle 'serie_tagesmittelwert_stunde_start_end|group' like 'serie_tagesmittelwert_stunde_30_0d' => Stundenmittelwerte von vor 30 Tagen bis vor 0 Tagen (also heute)
data_con_func = 'avg_hour'
start = to_int(db_addon_fct_vars[3])
end, timeframe = split_sting_letters_numbers(db_addon_fct_vars[4])
end = to_int(end)
timeframe = translate_timeframe(timeframe)
log_text = 'serie_tagesmittelwert_stunde_start_end|group'
required_params = [timeframe, data_con_func, start, end]
elif db_addon_fct in SERIE_ATTRIBUTES_MITTEL_D_H:
# handle 'serie_tagesmittelwert_tag_stunde_end|group' like 'serie_tagesmittelwert_tag_stunde_30d' => Tagesmittelwert auf Basis des Mittelwerts pro Stunden für die letzten 30 Tage
data_con_func = 'first_hour_avg_day'
end = 0
start, timeframe = split_sting_letters_numbers(db_addon_fct_vars[4])
start = to_int(start)
timeframe = translate_timeframe(timeframe)
log_text = 'serie_tagesmittelwert_tag_stunde_end|group'
required_params = [timeframe, data_con_func, start, end]
elif db_addon_fct in ALL_GEN_ATTRIBUTES:
log_text = 'all_gen_attributes'
required_params = []
if required_params is None:
self.logger.warning(f"For calculating '{db_addon_fct}' at Item '{item.path()}' no mandatory parameters given.")
return
if required_params and None in required_params:
self.logger.warning(f"For calculating '{db_addon_fct}' at Item '{item.path()}' not all mandatory parameters given. Definitions are: {func=}, {timeframe=}, {timedelta=}, {start=}, {end=}, {group=}, {group2=}, {data_con_func=}")
return
# create dict and reduce dict to keys with value != None
param_dict = {'func': func, 'timeframe': timeframe, 'timedelta': timedelta, 'start': start, 'end': end, 'group': group, 'group2': group2, 'data_con_func': data_con_func}
# return reduced dict w keys with value != None
return {k: v for k, v in param_dict.items() if v is not None}
def get_query_parameters_from_db_addon_params() -> Union[dict, None]:
"""derives parameters from item attribute db_addon_params, if parameter for db_addon_fct are not sufficient
possible_params may be given, if not, default value is used
required_params must be given
"""
db_addon_params = params_to_dict(self.get_iattr_value(item.conf, 'db_addon_params'))
if not db_addon_params:
db_addon_params = self.get_iattr_value(item.conf, 'db_addon_params_dict')
if not db_addon_params:
db_addon_params = {}
new_db_addon_params = {}
possible_params = required_params = []
# create item config for all functions with 'summe' like waermesumme, kaeltesumme, gruenlandtemperatursumme
if db_addon_fct in ('kaeltesumme', 'waermesumme', 'gruenlandtempsumme'):
possible_params = ['year', 'month']
# create item config for wachstumsgradtage attributes
elif db_addon_fct == 'wachstumsgradtage':
possible_params = ['year', 'variant', 'threshold', 'result']
# create item config for kenntage attributes
elif db_addon_fct in ('wuestentage', 'heisse_tage', 'tropennaechte', 'sommertage', 'heiztage', 'vegetationstage', 'frosttage', 'eistage'):
possible_params = ['year', 'month']
# create item config for tagesmitteltemperatur
elif db_addon_fct == 'tagesmitteltemperatur':
possible_params = ['timeframe', 'count']
# create item config for minmax
elif db_addon_fct == 'minmax':
required_params = ['func', 'timeframe', 'start']
# create item config for minmax_last
elif db_addon_fct == 'minmax_last':
required_params = ['func', 'timeframe', 'start', 'end']
# create item config for verbrauch
elif db_addon_fct == 'verbrauch':
required_params = ['timeframe', 'start', 'end']
# create item config for zaehlerstand
elif db_addon_fct == 'zaehlerstand':
required_params = ['timeframe', 'start']
# create item config for db_request and everything else (get_query_parameters_from_db_addon_fct)
else:
required_params = ['func', 'timeframe']
possible_params = ['start', 'end', 'group', 'group2', 'ignore_value_list', 'use_oldest_entry']
if required_params and not any(param in db_addon_params for param in required_params):
self.logger.warning(f"Item '{item.path()}' with {db_addon_fct=} ignored, since not all mandatory parameters in {db_addon_params=} are given. Item will be ignored.")
return
# reduce dict to possible keys + required_params
for key in possible_params + required_params:
value = db_addon_params.get(key)
if value:
new_db_addon_params[key] = value
return new_db_addon_params
def get_database_item_path() -> tuple:
"""
Returns item_path from shNG config which is an item with database attribut valid for current db_addon item
"""
_lookup_item = item
for i in range(3):
if self.has_iattr(_lookup_item.conf, 'db_addon_database_item'):
if self.debug_log.parse:
self.logger.debug(f"Attribut 'db_addon_database_item' for item='{item.path()}' has been found {i} level above item at '{_lookup_item.path()}'.")
_database_item_path = self.get_iattr_value(_lookup_item.conf, 'db_addon_database_item')
if self.debug_log.parse:
self.logger.debug(f"{_database_item_path=}, {_lookup_item.path()}")
return _database_item_path, _lookup_item
else:
_lookup_item = _lookup_item.return_parent()
return None, None
def get_database_item() -> Item:
"""
Returns item from shNG config which is an item with database attribut valid for current db_addon item
"""
_lookup_item = item.return_parent()
for i in range(2):
if self.has_iattr(_lookup_item.conf, self.item_attribute_search_str):
if self.debug_log.parse:
self.logger.debug(f"Attribut '{self.item_attribute_search_str}' for item='{item.path()}' has been found {i + 1} level above item at '{_lookup_item.path()}'.")
return _lookup_item
else:
_lookup_item = _lookup_item.return_parent()
return None, None
def has_db_addon_item() -> bool:
"""Returns item from shNG config which is item with db_addon attribut valid for database item"""
for child in item.return_children():
if check_db_addon_fct(child):
return True
for child_child in child.return_children():
if check_db_addon_fct(child_child):
return True
for child_child_child in child_child.return_children():
if check_db_addon_fct(child_child_child):
return True
return False
def check_db_addon_fct(check_item) -> bool:
"""
Check if item has db_addon_fct and is onchange
"""
if self.has_iattr(check_item.conf, 'db_addon_fct'):
if self.get_iattr_value(check_item.conf, 'db_addon_fct').lower() in ONCHANGE_ATTRIBUTES:
return True
return False
def format_db_addon_ignore_value_list(optimize: bool = self.optimize_value_filter):
""" Check of list of comparison operators is formally valid """
max_values = {'!=': [], '>=': [], '<=': [], '>': [], '<': []}
db_addon_ignore_value_list_formatted = []
for _entry in db_addon_ignore_value_list:
_entry = _entry.strip()
for op in max_values.keys():
if op in _entry:
var = _entry.split(op, 1)
value = var[1].strip()
value = to_int_float(value)
if value is None:
continue
db_addon_ignore_value_list_formatted.append(f"{op} {value}")
max_values[op].append(value)
if self.debug_log.parse:
self.logger.debug(f"Summarized 'ignore_value_list' for item {item.path()}: {db_addon_ignore_value_list_formatted}")
if not db_addon_ignore_value_list_formatted:
return
if not optimize:
return db_addon_ignore_value_list_formatted
if self.debug_log.parse:
self.logger.debug(f"Optimizing 'ignore_value_list' for item {item.path()} active.")
# find low
lower_value_list = max_values['<'] + max_values['<=']
if lower_value_list:
max_lower_value = max(lower_value_list)
lower_op = '<' if max_lower_value in max_values['<'] else '<='
lower_end = (lower_op, max_lower_value)
else:
lower_end = (None, None)
# find high
upper_value_list = max_values['>'] + max_values['>=']
if upper_value_list:
min_upper_value = min(upper_value_list)
upper_op = '>' if min_upper_value in max_values['>'] else '>='
upper_end = (upper_op, min_upper_value)
else:
upper_end = (None, None)
# generate comp_list
db_addon_ignore_value_list_optimized = []
if lower_end[0]:
db_addon_ignore_value_list_optimized.append(f"{lower_end[0]} {lower_end[1]}")
if upper_end[0]:
db_addon_ignore_value_list_optimized.append(f"{upper_end[0]} {upper_end[1]}")
if max_values['!=']:
for v in max_values['!=']:
if (not lower_end[0] or (lower_end[0] and v >= lower_end[1])) or (not upper_end[0] or (upper_end[0] and v <= upper_end[1])):
db_addon_ignore_value_list_optimized.append(f'!= {v}')
if self.debug_log.parse:
self.logger.debug(f"Optimized 'ignore_value_list' for item {item.path()}: {db_addon_ignore_value_list_optimized}")
return db_addon_ignore_value_list_optimized
# handle all items with db_addon_fct
if self.has_iattr(item.conf, 'db_addon_fct'):
if self.debug_log.parse:
self.logger.debug(f"parse item: {item.path()} due to 'db_addon_fct'")
# get db_addon_fct attribute value
db_addon_fct = self.get_iattr_value(item.conf, 'db_addon_fct').lower()
# read item_attribute_dict aus item_attributes_master
item_attribute_dict = ITEM_ATTRIBUTES['db_addon_fct'].get(db_addon_fct)
self.logger.debug(f"{db_addon_fct}: {item_attribute_dict=}")
# get query parameters from db_addon_fct or db_addon_params
if item_attribute_dict['params']:
query_params = get_query_parameters_from_db_addon_params()
else:
query_params = get_query_parameters_from_db_addon_fct()
if query_params is None:
return
# get database item (and attribute value if item should be calculated at plugin startup) and return if not available
database_item, database_item_definition_item = get_database_item_path()
if database_item is None:
database_item = get_database_item()
database_item_definition_item = item
db_addon_startup = self.get_iattr_value(database_item_definition_item.conf, 'db_addon_startup')
db_addon_ignore_value_list = self.get_iattr_value(database_item_definition_item.conf, 'db_addon_ignore_value_list') # ['> 0', '< 35']
db_addon_ignore_value = self.get_iattr_value(database_item_definition_item.conf, 'db_addon_ignore_value') # num
if database_item is None:
self.logger.warning(f"No database item found for item={item.path()}: Item ignored. Maybe you should check instance of database plugin.")
return
else:
if self.debug_log.parse:
self.logger.debug(f"{database_item=}, {db_addon_startup=}, {db_addon_ignore_value_list=}, {db_addon_ignore_value=}")
# create list of comparison operators and check it
if not db_addon_ignore_value_list:
db_addon_ignore_value_list = []
if db_addon_ignore_value:
db_addon_ignore_value_list.append(f"!= {db_addon_ignore_value}")
if any(x in str(item.path()) for x in self.ignore_0):
db_addon_ignore_value_list.append("!= 0")
if self.value_filter:
for entry in list(self.value_filter.keys()):
if entry in str(item.path()):
db_addon_ignore_value_list.extend(self.value_filter[entry])
if db_addon_ignore_value_list:
db_addon_ignore_value_list_final = format_db_addon_ignore_value_list()
if self.debug_log.parse:
self.logger.debug(f"{db_addon_ignore_value_list_final=}")
query_params.update({'ignore_value_list': db_addon_ignore_value_list_final})
# create standard items config
item_config_data_dict = {'db_addon': 'function', 'db_addon_fct': db_addon_fct, 'database_item': database_item, 'query_params': query_params, 'suspended': False}
if isinstance(database_item, str):
item_config_data_dict.update({'database_item_path': True})
else:
database_item = database_item.path()
# do logging
if self.debug_log.parse:
self.logger.debug(f"Item={item.path()} added with db_addon_fct={db_addon_fct} and database_item={database_item}")
# add type (onchange or ondemand) to item dict
item_config_data_dict.update({'on': item_attribute_dict['on']})
# add cycle for item groups
cycle = item_attribute_dict['calc']
if cycle == 'group':
cycle = item_config_data_dict['query_params'].get('group')
if not cycle:
cycle = item_config_data_dict['query_params'].get('timeframe')
cycle = f"{timeframe_to_updatecyle(cycle)}"
elif cycle == 'timeframe':
cycle = item_config_data_dict['query_params'].get('timeframe')
cycle = f"{timeframe_to_updatecyle(cycle)}"
elif cycle == 'None':
cycle = None
item_config_data_dict.update({'cycle': cycle})
# do logging
if self.debug_log.parse:
self.logger.debug(f"Item '{item.path()}' added to be run {item_config_data_dict['cycle']}.")
# create item config for item to be run on startup
if db_addon_startup or item_attribute_dict['cat'] == 'gen':
item_config_data_dict.update({'startup': True})
else:
item_config_data_dict.update({'startup': False})
# add item to plugin item dict
self.add_item(item, config_data_dict=item_config_data_dict)
# handle all items with db_addon_info
elif self.has_iattr(item.conf, 'db_addon_info'):
if self.debug_log.parse:
self.logger.debug(f"parse item={item.path()} due to used item attribute 'db_addon_info'")
self.add_item(item, config_data_dict={'db_addon': 'info', 'db_addon_fct': f"info_{self.get_iattr_value(item.conf, 'db_addon_info').lower()}", 'database_item': None, 'startup': True})
# handle all items with db_addon_admin
elif self.has_iattr(item.conf, 'db_addon_admin'):
if self.debug_log.parse:
self.logger.debug(f"parse item={item.path()} due to used item attribute 'db_addon_admin'")
self.add_item(item, config_data_dict={'db_addon': 'admin', 'db_addon_fct': f"admin_{self.get_iattr_value(item.conf, 'db_addon_admin').lower()}", 'database_item': None})
return self.update_item
# Reference to 'update_item' für alle Items mit Attribut 'database', um die on_change Items zu berechnen
elif self.has_iattr(item.conf, self.item_attribute_search_str) and has_db_addon_item():
if self.debug_log.parse:
self.logger.debug(f"reference to update_item for item={item.path()} will be set due to onchange")
self.add_item(item, config_data_dict={'db_addon': 'database'})
return self.update_item
def update_item(self, item, caller=None, source=None, dest=None):
"""
Handle updated item
This method is called, if the value of an item has been updated by SmartHomeNG.
It should write the changed value out to the device (hardware/interface) that is managed by this plugin.
: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():
# handle database items
if item in self._database_items():
# if not self.startup_finished:
# self.logger.info(f"Handling of 'onchange' is paused for startup. No updated will be processed.")
if self.suspended:
self.logger.info(f"Plugin is suspended. No updated will be processed.")
else:
self.logger.debug(f" Updated Item {item.path()} with value {item()} will be put to queue in approx. {self.onchange_delay_time}s resp. after startup.")
self.update_item_delay_deque.append([item, item(), int(time.time() + self.onchange_delay_time)])
# handle admin items
elif self.has_iattr(item.conf, 'db_addon_admin'):
self.logger.debug(f"update_item was called with item {item.property.path} from caller {caller}, source {source} and dest {dest}")
if self.get_iattr_value(item.conf, 'db_addon_admin') == 'suspend':
self.suspend(item())
elif self.get_iattr_value(item.conf, 'db_addon_admin') == 'recalc_all':
self.execute_all_items()
item(False, self.get_shortname())
elif self.get_iattr_value(item.conf, 'db_addon_admin') == 'clean_cache_values':
self._init_cache_dicts()
item(False, self.get_shortname())
def _save_pickle(self, data) -> None:
"""Saves received data as pickle to given file"""
if data and len(data) > 0:
self.logger.debug(f"Start writing {data=} to '{self.data_storage_path}'")
os.makedirs(os.path.dirname(self.data_storage_path), exist_ok=True)
try:
with open(self.data_storage_path, "wb") as output:
try:
pickle.dump(data, output, pickle.HIGHEST_PROTOCOL)
self.logger.debug(f"Successfully wrote data to '{self.data_storage_path}'")
except Exception as e:
self.logger.debug(f"Unable to write data to '{self.data_storage_path}': {e}")
pass
except OSError as e:
self.logger.debug(f"Unable to write data to '{self.data_storage_path}': {e}")
pass
def _read_pickle(self):
"""read a pickle file to gather data"""
self.logger.debug(f"Start reading data from '{self.data_storage_path}'")
if os.path.exists(self.data_storage_path):
with open(self.data_storage_path, 'rb') as data:
try:
data = pickle.load(data)
self.logger.debug(f"Successfully read data from {self.data_storage_path}")
return data
except Exception as e:
self.logger.debug(f"Unable to read data from {self.data_storage_path}: {e}")
return None
self.logger.debug(f"Unable to read data from {self.data_storage_path}: 'File/Path not existing'")
return None
def init_cache_data(self):
"""init cache dicts by reading pickle"""
def create_items_1(d):
n_d = {}
for item_str in d:
item = self.items.return_item(item_str)
if item:
n_d[item] = d[item_str]
return n_d
def create_items_2(d):
n_d = {}
for timeframe in d:
n_d[timeframe] = {}
for item_str in d[timeframe]:
item = self.items.return_item(item_str)
if item:
n_d[timeframe][item] = d[timeframe][item_str]
return n_d
# init cache dicts
self._init_cache_dicts()
# read pickle and set data
raw_data = self._read_pickle()
if not isinstance(raw_data, dict):
self.logger.info("Unable to extract db_addon data from pickle file. Start with empty cache.")
return
current_values = raw_data.get('current_values')
previous_values = raw_data.get('previous_values')
item_cache = raw_data.get('item_cache')
stop_time = raw_data.get('stop_time')
if not stop_time or (int(time.time()) - stop_time) > self.pickle_data_validity_time:
self.logger.info("Data for db_addon read from pickle are expired. Start with empty cache.")
return
if isinstance(current_values, dict):
self.current_values = create_items_2(current_values)
if isinstance(previous_values, dict):
self.previous_values = create_items_2(previous_values)
if isinstance(item_cache, dict):
self.item_cache = create_items_1(item_cache)
def save_cache_data(self):
"""save all relevant data to survive restart, transform items in item_str"""
def clean_items_1(d):
n_d = {}
for item in d:
n_d[item.path()] = d[item]
return n_d
def clean_items_2(d):
n_d = {}
for timeframe in d:
n_d[timeframe] = {}
for item in d[timeframe]:
n_d[timeframe][item.path()] = d[timeframe][item]
return n_d
self._save_pickle({'current_values': clean_items_2(self.current_values),
'previous_values': clean_items_2(self.previous_values),
'item_cache': clean_items_1(self.item_cache),
'stop_time': int(time.time())})
#########################################
# Item Handling
#########################################
def execute_due_items(self) -> None:
"""Execute all items, which are due"""
self.execute_items()
def execute_startup_items(self) -> None:
"""Execute all startup_items and set scheduler for delaying onchange items"""
# execute item calculation
self.execute_items(option='startup')
# add scheduler for delayed working if onchange items
self.scheduler_add('onchange_delay', self.work_update_item_delay_deque, prio=3, cron=None, cycle=30, value=None, offset=None, next=None)
def execute_items(self, option: str = 'due', item: str = None):
"""Execute all items per option"""
def _create_due_items() -> list:
"""Create list of items which are due and reset cache dicts"""
# set für zu berechnende Items erstellen
_todo_items = set()
_reset_items = set()
# stündlich zu berechnende Items hinzufügen
_todo_items.update(set(self._ondemand_hourly_items()))
# cache dict leeren
self.current_values[HOUR] = {}
self.previous_values[HOUR] = {}
# wenn aktuelle Stunde == 0, werden auch die täglichen Items berechnet
if self.shtime.now().hour == 0:
# item zur Aufgabeliste hinzufügen
_todo_items.update(set(self._ondemand_daily_items()))
# cache dict leeren
self.current_values[DAY] = {}
self.previous_values[DAY] = {}
self.value_list_raw_data = {}
# reset Item-Wert alle onchange
_reset_items.update(set(self._onchange_daily_items()))
# wenn zusätzlich der Wochentag == Montag, werden auch die wöchentlichen Items berechnet
if self.shtime.weekday(self.shtime.today()) == 1:
# item zur Aufgabeliste hinzufügen
_todo_items.update(set(self._ondemand_weekly_items()))
# cache dict leeren
self.current_values[WEEK] = {}
self.previous_values[WEEK] = {}
# reset Item-Wert alle onchange
_reset_items.update(set(self._onchange_weekly_items()))
# wenn zusätzlich der erste Tage eines Monates ist, werden auch die monatlichen Items berechnet
if self.shtime.now().day == 1:
# item zur Aufgabeliste hinzufügen
_todo_items.update(set(self._ondemand_monthly_items()))
# cache dict leeren
self.current_values[MONTH] = {}
self.previous_values[MONTH] = {}
# reset Item-Wert alle onchange
_reset_items.update(set(self._onchange_monthly_items()))
# wenn zusätzlich der erste Monat ist, werden auch die jährlichen Items berechnet
if self.shtime.now().month == 1:
# item zur Aufgabeliste hinzufügen
_todo_items.update(set(self._ondemand_yearly_items()))
# cache dict leeren
self.current_values[YEAR] = {}
self.previous_values[YEAR] = {}
# reset Item-Wert alle onchange
_reset_items.update(set(self._onchange_yearly_items()))
# reset der onchange items
[_item(0, self.get_shortname()) for _item in _reset_items]
return list(_todo_items)
if self.debug_log.execute:
self.logger.debug(f"execute_items called with {option=}")
if self.suspended:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
return
suspended_items = self._suspended_items()
if len(suspended_items) > 0:
self.logger.info(f"{len(suspended_items)} are suspended and will not be calculated.")
todo_items = []
if option == 'startup':
todo_items = self._startup_items()
elif option == 'static':
todo_items = self._static_items()
elif option == 'info':
todo_items = self._info_items()
elif option == 'ondemand':
todo_items = self._ondemand_items()
elif option == 'onchange':
todo_items = self._onchange_items()
elif option == 'all':
todo_items = self._all_items()
elif option == 'due':
todo_items = _create_due_items()
elif option == 'item':
if isinstance(item, str):
item = self.items.return_item(item)
if isinstance(item, Item):
todo_items = [item]
# remove suspended items
if option != 'item':
todo_items = list(set(todo_items) - set(suspended_items))
# put to queue
self.logger.info(f"{len(todo_items)} items will be calculated for {option=}.")
if self.debug_log.execute:
self.logger.debug(f"Items to be calculated: {todo_items=}")
[self.item_queue.put(i) for i in todo_items]
return True
def work_item_queue(self) -> None:
"""Handles item queue were all to be executed items were be placed in."""