This repository has been archived by the owner on Nov 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
2742 lines (2195 loc) · 126 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 sqlvalidator
import datetime
import time
import re
import queue
from dateutil.relativedelta import relativedelta
from typing import Union
import threading
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
import lib.db
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.1.0'
def __init__(self, sh):
"""
Initializes the plugin.
"""
# Call init code of parent class (SmartPlugin)
super().__init__()
# get item and shtime instance
self.shtime = Shtime.get_instance()
self.items = Items.get_instance()
self.plugins = Plugins.get_instance()
# define cache dicts
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
# define variables for database, database connection, working queue and status
self.item_queue = queue.Queue() # Queue containing all to be executed items
self.work_item_queue_thread = None # Working Thread for queue
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.startup_finished = False # Startup of Plugin finished
self.suspended = False # Is plugin activity suspended
self.active_queue_item: str = '-' # String holding item path of currently executed item
# define debug logs
self.parse_debug = False # Enable / Disable debug logging for method 'parse item'
self.execute_debug = False # Enable / Disable debug logging for method 'execute items'
self.sql_debug = False # Enable / Disable debug logging for sql stuff
self.onchange_debug = False # Enable / Disable debug logging for method 'handle_onchange'
self.prepare_debug = False # Enable / Disable debug logging for query preparation
# 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.use_oldest_entry = self.get_parameter_value('use_oldest_entry')
# init cache dicts
self._init_cache_dicts()
# activate debug logger
if self.log_level == 10: # info: 20 debug: 10
self.parse_debug = True
self.execute_debug = True
self.sql_debug = True
self.onchange_debug = True
self.prepare_debug = True
# 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()
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")
# init db
if not self._initialize_db():
return self.deinit()
# check db connection settings
if self.db_driver is not None and 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='5 0 0 * * *', cycle=None, value=None, offset=None, next=None)
# add scheduler to trigger items to be calculated at startup with delay
dt = self.shtime.now() + datetime.timedelta(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
# start the queue consumer thread
self._work_item_queue_thread_startup()
def stop(self):
"""
Stop method for the plugin
"""
self.logger.debug("Stop method called")
self.alive = False
self.scheduler_remove('cyclic')
self._work_item_queue_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_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):
self.logger.debug(f"Attribut '{self.item_attribute_search_str}' has been found for item={item.path()} {i + 1} level above item.")
return _lookup_item
else:
_lookup_item = _lookup_item.return_parent()
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 ALL_ONCHANGE_ATTRIBUTES:
self.logger.debug(f"db_addon item for database item {item.path()} found.")
return True
return False
# handle all items with db_addon_fct
if self.has_iattr(item.conf, 'db_addon_fct'):
if self.parse_debug:
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()
# get attribute value if item should be calculated at plugin startup
db_addon_startup = bool(self.get_iattr_value(item.conf, 'db_addon_startup'))
# get attribute if certain value should be ignored at db query
if self.has_iattr(item.conf, 'database_ignore_value'):
db_addon_ignore_value = self.get_iattr_value(item.conf, 'database_ignore_value')
elif any(x in str(item.id()) for x in self.ignore_0):
db_addon_ignore_value = 0
else:
db_addon_ignore_value = None
# get database item and return if not available
database_item_path = self.get_iattr_value(item.conf, 'db_addon_database_item')
if database_item_path is not None:
database_item = database_item_path
else:
database_item = get_database_item()
if database_item is None:
self.logger.warning(f"No database item found for {item.path()}: Item ignored. Maybe you should check instance of database plugin.")
return
# return if mandatory params for ad_addon_fct not given.
if db_addon_fct in ALL_NEED_PARAMS_ATTRIBUTES and not self.has_iattr(item.conf, 'db_addon_params'):
self.logger.warning(f"Item '{item.path()}' with db_addon_fct={db_addon_fct} ignored, since parameter using 'db_addon_params' not given. Item will be ignored.")
return
# create standard items config
item_config_data_dict = {'db_addon': 'function', 'db_addon_fct': db_addon_fct, 'database_item': database_item, 'ignore_value': db_addon_ignore_value}
if database_item_path is not None:
item_config_data_dict.update({'database_item_path': True})
else:
database_item_path = database_item.path()
if self.parse_debug:
self.logger.debug(f"Item '{item.path()}' added with db_addon_fct={db_addon_fct} and database_item={database_item_path}")
# handle daily items
if db_addon_fct in ALL_DAILY_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'daily'})
# handle weekly items
elif db_addon_fct in ALL_WEEKLY_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'weekly'})
# handle monthly items
elif db_addon_fct in ALL_MONTHLY_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'monthly'})
# handle yearly items
elif db_addon_fct in ALL_YEARLY_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'yearly'})
# handle static items
elif db_addon_fct in ALL_GEN_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'static'})
# handle on-change items
elif db_addon_fct in ALL_ONCHANGE_ATTRIBUTES:
item_config_data_dict.update({'cycle': 'on-change'})
# handle all functions with 'summe' like waermesumme, kaeltesumme, gruenlandtemperatursumme
if 'summe' in db_addon_fct:
db_addon_params = params_to_dict(self.get_iattr_value(item.conf, 'db_addon_params'))
if db_addon_params is None or 'year' not in db_addon_params:
self.logger.info(f"No 'year' for evaluation via 'db_addon_params' of item {item.path()} for function {db_addon_fct} given. Default with 'current year' will be used.")
db_addon_params = {'year': 'current'}
item_config_data_dict.update({'params': db_addon_params})
# handle wachstumsgradtage function
elif db_addon_fct == 'wachstumsgradtage':
DEFAULT_THRESHOLD = 10
db_addon_params = params_to_dict(self.get_iattr_value(item.conf, 'db_addon_params'))
if db_addon_params is None or 'year' not in db_addon_params:
self.logger.info(f"No 'year' for evaluation via 'db_addon_params' of item {item.path()} for function {db_addon_fct} given. Default with 'current year' will be used.")
db_addon_params = {'year': 'current'}
if 'threshold' not in db_addon_params:
self.logger.info(f"No 'threshold' for evaluation via 'db_addon_params' of item {item.path()} for function {db_addon_fct} given. Default with {DEFAULT_THRESHOLD} will be used.")
db_addon_params.update({'threshold': DEFAULT_THRESHOLD})
if not isinstance(db_addon_params['threshold'], int):
threshold = to_int(db_addon_params['threshold'])
db_addon_params['threshold'] = DEFAULT_THRESHOLD if threshold is None else threshold
item_config_data_dict.update({'params': db_addon_params})
# handle tagesmitteltemperatur
elif db_addon_fct == 'tagesmitteltemperatur':
if not self.has_iattr(item.conf, 'db_addon_params'):
self.logger.warning(f"Item '{item.path()}' with db_addon_fct={db_addon_fct} ignored, since parameter using 'db_addon_params' not given. Item will be ignored.")
return
db_addon_params = params_to_dict(self.get_iattr_value(item.conf, 'db_addon_params'))
if db_addon_params is None:
self.logger.warning(f"Error occurred during parsing of item attribute 'db_addon_params' of item {item.path()}. Item will be ignored.")
return
item_config_data_dict.update({'params': db_addon_params})
# handle db_request
elif db_addon_fct == 'db_request':
if not self.has_iattr(item.conf, 'db_addon_params'):
self.logger.warning(f"Item '{item.path()}' with db_addon_fct={db_addon_fct} ignored, since parameter using 'db_addon_params' not given. Item will be ignored")
return
db_addon_params = params_to_dict(self.get_iattr_value(item.conf, 'db_addon_params'))
if db_addon_params is None:
self.logger.warning(f"Error occurred during parsing of item attribute 'db_addon_params' of item {item.path()}. Item will be ignored.")
return
if self.parse_debug:
self.logger.debug(f"parse_item: {db_addon_fct=} for item={item.path()}, {db_addon_params=}")
if not any(param in db_addon_params for param in ('func', 'timeframe')):
self.logger.warning(f"Item '{item.path()}' with {db_addon_fct=} ignored, not all mandatory parameters in {db_addon_params=} given. Item will be ignored.")
return
TIMEFRAMES_2_UPDATECYCLE = {'day': 'daily',
'week': 'weekly',
'month': 'monthly',
'year': 'yearly'}
_timeframe = db_addon_params.get('group', None)
if not _timeframe:
_timeframe = db_addon_params.get('timeframe', None)
update_cycle = TIMEFRAMES_2_UPDATECYCLE.get(_timeframe)
if update_cycle is None:
self.logger.warning(f"Item '{item.path()}' with {db_addon_fct=} ignored. Not able to detect update cycle.")
return
item_config_data_dict.update({'params': db_addon_params, 'cycle': update_cycle})
# debug log item cycle
if self.parse_debug:
self.logger.debug(f"Item '{item.path()}' added to be run {item_config_data_dict['cycle']}.")
# handle item to be run on startup (onchange_items shall not be run at startup, but at first noticed change of item value; therefore remove for list of items to be run at startup)
if (db_addon_startup and db_addon_fct not in ALL_ONCHANGE_ATTRIBUTES) or db_addon_fct in ALL_GEN_ATTRIBUTES:
if self.parse_debug:
self.logger.debug(f"Item '{item.path()}' added to be run on startup")
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.parse_debug:
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.parse_debug:
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():
self.logger.debug(f"reference to update_item for item '{item.path()}' will be set due to on-change")
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():
# self.logger.debug(f"update_item was called with item {item.property.path} with value {item()} from caller {caller}, source {source} and dest {dest}")
if not self.startup_finished:
self.logger.info(f"Handling of 'on-change' is paused for startup. No updated will be processed.")
elif self.suspended:
self.logger.info(f"Plugin is suspended. No updated will be processed.")
else:
self.logger.info(f"+ Updated item '{item.path()}' with value {item()} will be put to queue for processing. {self.item_queue.qsize() + 1} items to do.")
self.item_queue.put((item, item()))
# 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 execute_due_items(self) -> None:
"""
Execute all items, which are due
"""
if self.execute_debug:
self.logger.debug("execute_due_items called")
if not self.suspended:
_todo_items = self._create_due_items()
self.logger.info(f"{len(_todo_items)} items are due and will be calculated.")
[self.item_queue.put(i) for i in _todo_items]
else:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
def execute_startup_items(self) -> None:
"""
Execute all startup_items
"""
if self.execute_debug:
self.logger.debug("execute_startup_items called")
if not self.suspended:
self.logger.info(f"{len(self._startup_items())} items will be calculated at startup.")
[self.item_queue.put(i) for i in self._startup_items()]
self.startup_finished = True
else:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
def execute_static_items(self) -> None:
"""
Execute all static items
"""
if self.execute_debug:
self.logger.debug("execute_static_item called")
if not self.suspended:
self.logger.info(f"{len(self._static_items())} items will be calculated.")
[self.item_queue.put(i) for i in self._static_items()]
else:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
def execute_info_items(self) -> None:
"""
Execute all info items
"""
if self.execute_debug:
self.logger.debug("execute_info_items called")
if not self.suspended:
self.logger.info(f"{len(self._info_items())} items will be calculated.")
[self.item_queue.put(i) for i in self._info_items()]
else:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
def execute_all_items(self) -> None:
"""
Execute all ondemand items
"""
if not self.suspended:
self.logger.info(f"Values for all {len(self._ondemand_items())} items with 'db_addon_fct' attribute, which are not 'on-change', will be calculated!")
[self.item_queue.put(i) for i in self._ondemand_items()]
else:
self.logger.info(f"Plugin is suspended. No items will be calculated.")
def work_item_queue(self) -> None:
"""
Handles item queue were all to be executed items were be placed in.
"""
while self.alive:
try:
queue_entry = self.item_queue.get(True, 10)
self.logger.info(f" Queue Entry: '{queue_entry}' received.")
except queue.Empty:
self.active_queue_item = '-'
pass
else:
if isinstance(queue_entry, tuple):
item, value = queue_entry
self.logger.info(f"# {self.item_queue.qsize() + 1} item(s) to do. || 'on-change' item '{item.path()}' with {value=} will be processed.")
self.active_queue_item = str(item.path())
self.handle_onchange(item, value)
else:
self.logger.info(f"# {self.item_queue.qsize() + 1} item(s) to do. || 'on-demand' item '{queue_entry.path()}' will be processed.")
self.active_queue_item = str(queue_entry.path())
self.handle_ondemand(queue_entry)
def handle_ondemand(self, item: Item) -> None:
"""
Calculate value for requested item, fill cache dicts and set item value.
:param item: Item for which value will be calculated
"""
# set/get parameters
item_config = self.get_item_config(item)
db_addon = item_config['db_addon']
db_addon_fct = item_config['db_addon_fct']
database_item = item_config['database_item']
ignore_value = item_config.get('ignore_value')
result = None
self.logger.debug(f"handle_ondemand: Item={item.path()} with {item_config=}")
# handle info functions
if db_addon == 'info':
# handle info_db_version
if db_addon_fct == 'info_db_version':
result = self._get_db_version()
self.logger.debug(f"handle_ondemand: info_db_version {result=}")
else:
self.logger.warning(f"No handling for attribute {db_addon_fct=} for Item {item.path()} defined.")
# handle general functions
elif db_addon_fct in ALL_GEN_ATTRIBUTES:
# handle oldest_value
if db_addon_fct == 'general_oldest_value':
result = self._get_oldest_value(database_item)
# handle oldest_log
elif db_addon_fct == 'general_oldest_log':
result = self._get_oldest_log(database_item)
else:
self.logger.warning(f"No handling for attribute {db_addon_fct=} for Item {item.path()} defined.")
# handle item starting with 'verbrauch_'
elif db_addon_fct in ALL_VERBRAUCH_ATTRIBUTES:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'verbrauch' detected.")
result = self._handle_verbrauch(database_item, db_addon_fct, ignore_value)
if result and result < 0:
self.logger.warning(f"Result of item {item.path()} with {db_addon_fct=} was negative. Something seems to be wrong.")
# handle item starting with 'zaehlerstand_' of format 'zaehlerstand_timeframe_timedelta' like 'zaehlerstand_woche_minus1'
elif db_addon_fct in ALL_ZAEHLERSTAND_ATTRIBUTES:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'zaehlerstand' detected.")
result = self._handle_zaehlerstand(database_item, db_addon_fct, ignore_value)
# handle item starting with 'minmax_'
elif db_addon_fct in ALL_HISTORIE_ATTRIBUTES:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'minmax' detected.")
result = self._handle_min_max(database_item, db_addon_fct, ignore_value)[0][1]
# handle item starting with 'tagesmitteltemperatur_'
elif db_addon_fct in ALL_TAGESMITTEL_ATTRIBUTES:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'tagesmitteltemperatur' detected.")
result = self._handle_tagesmitteltemperatur(database_item, db_addon_fct, ignore_value)[0][1]
# handle item starting with 'serie_'
elif db_addon_fct in ALL_SERIE_ATTRIBUTES:
if 'minmax' in db_addon_fct:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'serie_minmax' detected.")
result = self._handle_min_max(database_item, db_addon_fct, ignore_value)
elif 'verbrauch' in db_addon_fct:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'serie_verbrauch' detected.")
result = self._handle_verbrauch(database_item, db_addon_fct, ignore_value)
elif 'zaehlerstand' in db_addon_fct:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'serie_zaehlerstand' detected.")
result = self._handle_zaehlerstand(database_item, db_addon_fct, ignore_value)
elif 'tagesmitteltemperatur' in db_addon_fct:
if self.execute_debug:
self.logger.debug(f"handle_ondemand: 'serie_tagesmittelwert' detected.")
result = self._handle_tagesmitteltemperatur(database_item, db_addon_fct, ignore_value)
else:
self.logger.warning(f"No handling for attribute {db_addon_fct=} for Item {item.path()} defined.")
# handle kaeltesumme
elif db_addon_fct == 'kaeltesumme':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected; {db_addon_params=}")
if db_addon_params:
db_addon_params.update({'database_item': item_config['database_item']})
result = self._handle_kaeltesumme(**db_addon_params)
# handle waermesumme
elif db_addon_fct == 'waermesumme':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected; {db_addon_params=}")
if db_addon_params:
db_addon_params.update({'database_item': item_config['database_item']})
result = self._handle_waermesumme(**db_addon_params)
# handle gruenlandtempsumme
elif db_addon_fct == 'gruenlandtempsumme':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected; {db_addon_params=}")
if db_addon_params:
db_addon_params.update({'database_item': item_config['database_item']})
result = self._handle_gruenlandtemperatursumme(**db_addon_params)
# handle wachstumsgradtage
elif db_addon_fct == 'wachstumsgradtage':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected; {db_addon_params}")
if db_addon_params:
db_addon_params.update({'database_item': item_config['database_item']})
result = self._handle_wachstumsgradtage(**db_addon_params)
# handle tagesmitteltemperatur
elif db_addon_fct == 'tagesmitteltemperatur':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected; {db_addon_params=}")
if db_addon_params:
result = self._handle_tagesmitteltemperatur(database_item, db_addon_fct, ignore_value, db_addon_params)
# handle db_request
elif db_addon_fct == 'db_request':
db_addon_params = item_config.get('params')
if self.execute_debug:
self.logger.debug(f"handle_ondemand: {db_addon_fct=} detected with {db_addon_params=}")
if db_addon_params:
db_addon_params.update({'database_item': item_config['database_item']})
if db_addon_params.keys() & {'func', 'item', 'timeframe'}:
result = self._query_item(**db_addon_params)
else:
self.logger.error(f"Attribute 'db_addon_params' not containing needed params for Item {item.id} with {db_addon_fct=}.")
# handle everything else
else:
self.logger.warning(f"handle_ondemand: Function '{db_addon_fct}' for item {item.path()} not defined or found.")
return
# log result
if self.execute_debug:
self.logger.debug(f"handle_ondemand: result is {result} for item '{item.path()}' with '{db_addon_fct=}'")
if result is None:
self.logger.info(f" Result was None; No item value will be set.")
return
# set item value and put data into plugin_item_dict
self.logger.info(f" Item value for '{item.path()}' will be set to {result}")
item_config = self.get_item_config(item)
item_config.update({'value': result})
item(result, self.get_shortname())
def handle_onchange(self, updated_item: Item, value: float) -> None:
"""
Get item and item value for which an update has been detected, fill cache dicts and set item value.
:param updated_item: Item which has been updated
:param value: Value of updated item
"""
if self.onchange_debug:
self.logger.debug(f"handle_onchange called with updated_item={updated_item.path()} and value={value}.")
relevant_item_list = self.get_item_list('database_item', updated_item)
if self.onchange_debug:
self.logger.debug(f"Following items where identified for update: {relevant_item_list}.")
for item in relevant_item_list:
item_config = self.get_item_config(item)
_database_item = item_config['database_item']
_db_addon_fct = item_config['db_addon_fct']
_ignore_value = item_config['ignore_value']
_var = _db_addon_fct.split('_')
# handle minmax on-change items like minmax_heute_max, minmax_heute_min, minmax_woche_max, minmax_woche_min.....
if _db_addon_fct.startswith('minmax') and len(_var) == 3 and _var[2] in ['min', 'max']:
_timeframe = convert_timeframe(_var[1])
_func = _var[2]
_cache_dict = self.current_values[_timeframe]
if not _timeframe:
return
if self.onchange_debug:
self.logger.debug(f"handle_onchange: 'minmax' item {updated_item.path()} with {_func=} detected. Check for update of _cache_dicts and item value.")
_initial_value = False
_new_value = None
# make sure, that database item is in cache dict
if _database_item not in _cache_dict:
_cache_dict[_database_item] = {}
if _cache_dict[_database_item].get(_func) is None:
_query_params = {'func': _func, 'item': _database_item, 'timeframe': _timeframe, 'start': 0, 'end': 0, 'ignore_value': _ignore_value}
_cached_value = self._query_item(**_query_params)[0][1]
_initial_value = True
if self.onchange_debug:
self.logger.debug(f"handle_onchange: Item={updated_item.path()} with _func={_func} and _timeframe={_timeframe} not in cache dict. recent value={_cached_value}.")
else:
_cached_value = _cache_dict[_database_item][_func]
if _cached_value:
# check value for update of cache dict
if _func == 'min' and value < _cached_value:
_new_value = value
if self.onchange_debug:
self.logger.debug(f"handle_onchange: new value={_new_value} lower then current min_value={_cached_value}. _cache_dict will be updated")
elif _func == 'max' and value > _cached_value:
_new_value = value
if self.onchange_debug:
self.logger.debug(f"handle_onchange: new value={_new_value} higher then current max_value={_cached_value}. _cache_dict will be updated")
else:
if self.onchange_debug:
self.logger.debug(f"handle_onchange: new value={_new_value} will not change max/min for period.")
else:
_cached_value = value
if _initial_value and not _new_value:
_new_value = _cached_value
if self.onchange_debug:
self.logger.debug(f"handle_onchange: initial value for item will be set with value {_new_value}")
if _new_value:
_cache_dict[_database_item][_func] = _new_value
self.logger.info(f"Item value for '{item.path()}' with func={_func} will be set to {_new_value}")
item_config = self.get_item_config(item)
item_config.update({'value': _new_value})
item(_new_value, self.get_shortname())
else:
self.logger.info(f"Received value={value} is not influencing min / max value. Therefore item {item.path()} will not be changed.")
# handle verbrauch on-change items ending with heute, woche, monat, jahr
elif _db_addon_fct.startswith('verbrauch') and len(_var) == 2 and _var[1] in ['heute', 'woche', 'monat', 'jahr']:
_timeframe = convert_timeframe(_var[1])
_cache_dict = self.previous_values[_timeframe]
if _timeframe is None:
return
# make sure, that database item is in cache dict
if _database_item not in _cache_dict:
_query_params = {'func': 'max', 'item': _database_item, 'timeframe': _timeframe, 'start': 1, 'end': 1, 'ignore_value': _ignore_value}
_cached_value = self._query_item(**_query_params)[0][1]
_cache_dict[_database_item] = _cached_value
if self.onchange_debug:
self.logger.debug(f"handle_onchange: Item={updated_item.path()} with {_timeframe=} not in cache dict. Value {_cached_value} has been added.")
else:
_cached_value = _cache_dict[_database_item]
# calculate value, set item value, put data into plugin_item_dict
if _cached_value is not None:
_new_value = round(value - _cached_value, 1)
self.logger.info(f"Item value for '{item.path()}' will be set to {_new_value}")
item_config = self.get_item_config(item)
item_config.update({'value': _new_value})
item(_new_value, self.get_shortname())
else:
self.logger.info(f"Value for end of last {_timeframe} not available. No item value will be set.")
def _update_database_items(self):
for item in self._database_item_path_items():
item_config = self.get_item_config(item)
database_item_path = item_config.get('database_item')
database_item = self.items.return_item(database_item_path)
if database_item is None:
self.logger.warning(f"Database-Item for Item with config item path for Database-Item {database_item_path!r} not found. Item '{item.path()}' will be removed from plugin.")
self.remove_item(item)
else:
item_config.update({'database_item': database_item})
@property
def log_level(self):
return self.logger.getEffectiveLevel()
def queue_backlog(self):
return self.item_queue.qsize()
def db_version(self):
return self._get_db_version()
def _startup_items(self) -> list:
return self.get_item_list('startup', True)
def _onchange_items(self) -> list:
return self.get_item_list('cycle', 'on-change')
def _daily_items(self) -> list:
return self.get_item_list('cycle', 'daily')
def _weekly_items(self) -> list:
return self.get_item_list('cycle', 'weekly')
def _monthly_items(self) -> list:
return self.get_item_list('cycle', 'monthly')
def _yearly_items(self) -> list:
return self.get_item_list('cycle', 'yearly')
def _static_items(self) -> list:
return self.get_item_list('cycle', 'static')
def _admin_items(self) -> list:
return self.get_item_list('db_addon', 'admin')
def _info_items(self) -> list:
return self.get_item_list('db_addon', 'info')
def _database_items(self) -> list:
return self.get_item_list('db_addon', 'database')
def _database_item_path_items(self) -> list:
return self.get_item_list('database_item_path', True)
def _ondemand_items(self) -> list:
return self._daily_items() + self._weekly_items() + self._monthly_items() + self._yearly_items() + self._static_items()
##############################
# Public functions / Using item_path
##############################
def gruenlandtemperatursumme(self, item_path: str, year: Union[int, str]) -> Union[int, None]:
"""
Query database for gruenlandtemperatursumme for given year or year
https://de.wikipedia.org/wiki/Gr%C3%BCnlandtemperatursumme
Beim Grünland wird die Wärmesumme nach Ernst und Loeper benutzt, um den Vegetationsbeginn und somit den Termin von Düngungsmaßnahmen zu bestimmen.
Dabei erfolgt die Aufsummierung der Tagesmitteltemperaturen über 0 °C, wobei der Januar mit 0.5 und der Februar mit 0.75 gewichtet wird.
Bei einer Wärmesumme von 200 Grad ist eine Düngung angesagt.
:param item_path: item object or item_id for which the query should be done
:param year: year the gruenlandtemperatursumme should be calculated for
:return: gruenlandtemperatursumme
"""
item = self.items.return_item(item_path)
if item:
return self._handle_gruenlandtemperatursumme(item, year)
def waermesumme(self, item_path: str, year, month: Union[int, str] = None, threshold: int = 0) -> Union[int, None]:
"""
Query database for waermesumme for given year or year/month
https://de.wikipedia.org/wiki/W%C3%A4rmesumme
:param item_path: item object or item_id for which the query should be done
:param year: year the waermesumme should be calculated for
:param month: month the waermesumme should be calculated for
:param threshold: threshold for temperature
:return: waermesumme
"""
item = self.items.return_item(item_path)
if item:
return self._handle_waermesumme(item, year, month, threshold)
def kaeltesumme(self, item_path: str, year, month: Union[int, str] = None) -> Union[int, None]:
"""
Query database for kaeltesumme for given year or year/month
https://de.wikipedia.org/wiki/K%C3%A4ltesumme
:param item_path: item object or item_id for which the query should be done
:param year: year the kaeltesumme should be calculated for
:param month: month the kaeltesumme should be calculated for
:return: kaeltesumme
"""
item = self.items.return_item(item_path)
if item:
return self._handle_kaeltesumme(item, year, month)
def tagesmitteltemperatur(self, item_path: str, timeframe: str = None, count: int = None) -> list:
"""
Query database for tagesmitteltemperatur
https://www.dwd.de/DE/leistungen/klimadatendeutschland/beschreibung_tagesmonatswerte.html
:param item_path: item object or item_id for which the query should be done
:param timeframe: timeincrement for determination
:param count: number of time increments starting from now to the left (into the past)
:return: tagesmitteltemperatur
"""
if not timeframe:
timeframe = 'day'
if not count:
count = 0
item = self.items.return_item(item_path)
if item:
return self._handle_tagesmitteltemperatur(database_item=item, db_addon_fct='tagesmitteltemperatur', params={'timeframe': timeframe, 'count': count})
def wachstumsgradtage(self, item_path: str, year: Union[int, str], threshold: int) -> Union[int, None]:
"""
Query database for wachstumsgradtage
https://de.wikipedia.org/wiki/Wachstumsgradtag
:param item_path: item object or item_id for which the query should be done
:param year: year the wachstumsgradtage should be calculated for
:param threshold: Temperature in °C as threshold: Ein Tage mit einer Tagesdurchschnittstemperatur oberhalb des Schellenwertes gilt als Wachstumsgradtag
:return: wachstumsgradtage
"""
item = self.items.return_item(item_path)
if item:
return self._handle_wachstumsgradtage(item, year, threshold)
def query_item(self, func: str, item_path: str, timeframe: str, start: int = None, end: int = 0, group: str = None, group2: str = None, ignore_value=None) -> list:
item = self.items.return_item(item_path)
if item is None:
return []
return self._query_item(func, item, timeframe, start, end, group, group2, ignore_value)
def fetch_log(self, func: str, item_path: str, timeframe: str, start: int = None, end: int = 0, count: int = None, group: str = None, group2: str = None, ignore_value=None) -> list:
"""
Query database, format response and return it
:param func: function to be used at query
:param item_path: item str or item_id for which the query should be done
:param timeframe: time increment für definition of start, end, count (day, week, month, year)
:param start: start of timeframe (oldest) for query given in x time increments (default = None, meaning complete database)
:param end: end of timeframe (newest) for query given in x time increments (default = 0, meaning today, end of last week, end of last month, end of last year)
:param count: start of timeframe defined by number of time increments starting from end to the left (into the past)
:param group: first grouping parameter (default = None, possible values: day, week, month, year)
:param group2: second grouping parameter (default = None, possible values: day, week, month, year)
:param ignore_value: value of val_num, which will be ignored during query
:return: formatted query response
"""
item = self.items.return_item(item_path)
if count:
start, end = count_to_start(count)
if item and start and end:
return self._query_item(func=func, item=item, timeframe=timeframe, start=start, end=end, group=group, group2=group2, ignore_value=ignore_value)
else:
return []
def fetch_raw(self, query: str, params: dict = None) -> Union[list, None]:
"""
Fetch database with given query string and params
:param query: database query to be executed
:param params: query parameters
:return: result of database query
"""