-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
terrariumEngine.py
2019 lines (1657 loc) · 83.6 KB
/
terrariumEngine.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
# -*- coding: utf-8 -*-
from hardware.webcam.rpilive_webcam import terrariumRPILiveWebcam
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
sensorLogger = terrariumLogging.logging.getLogger("terrariumSensor")
relayLogger = terrariumLogging.logging.getLogger("terrariumRelay")
buttonLogger = terrariumLogging.logging.getLogger("terrariumButton")
webcamLogger = terrariumLogging.logging.getLogger("terrariumWebcam")
enclosureLogger = terrariumLogging.logging.getLogger("terrariumEnclosure")
weatherLogger = terrariumLogging.logging.getLogger("terrariumWeather")
import threading
import time
import datetime
import os
import psutil
import subprocess
import re
import pyfiglet
import copy
import statistics
import sdnotify
import gettext
from concurrent import futures
from pathlib import Path
from time import sleep
from packaging.version import Version
from pyfancy.pyfancy import pyfancy
from pony import orm
from terrariumDatabase import init as init_db, db, Setting, Sensor, Relay, Button, Webcam, Enclosure
from terrariumWebserver import terrariumWebserver
from terrariumCalendar import terrariumCalendar
from terrariumUtils import terrariumUtils, terrariumAsync, terrariumCache
from terrariumEnclosure import terrariumEnclosure
from terrariumArea import terrariumArea
from terrariumCloud import TerrariumMerossCloud
from weather import terrariumWeather
from hardware.sensor import terrariumSensor, terrariumSensorLoadingException
from hardware.relay import terrariumRelay, terrariumRelayLoadingException, terrariumRelayUpdateException
from hardware.button import terrariumButton, terrariumButtonLoadingException
from hardware.webcam import terrariumWebcam, terrariumWebcamLoadingException
from terrariumNotification import terrariumNotification
# https://docs.python.org/3/library/gettext.html#deferred-translations
def N_(message):
return message
class terrariumEngine(object):
__ENGINE_LOOP_TIMEOUT = 30.0 # in seconds
__VERSION_UPDATE_CHECK_TIMEOUT = 1 # in days
def __init__(self, version):
self.starttime = time.time()
# Default system units
self.units = {
N_("temperature"): "C",
N_("distance"): "cm",
N_("altitude"): "cm",
N_("pressure"): "hPa",
N_("humidity"): "%",
N_("moisture"): "%",
N_("conductivity"): "mS",
N_("ph"): "pH",
N_("light"): "lux",
N_("uva"): "µW/cm²",
N_("uvb"): "µW/cm²",
N_("uvi"): "",
N_("fertility"): "µS/cm",
N_("co2"): "ppm",
N_("volume"): "L",
# New version... should replace 'volume'
N_("water_volume"): "L",
N_("watertank"): "L",
N_("windspeed"): "kmh",
N_("water_flow"): "L/m",
N_("wattage"): "W",
N_("powerusage"): "kWh",
}
self.__engine = {
"exit": threading.Event(),
"thread": None,
"logtail": None,
"too_late": 0,
"systemd": sdnotify.SystemdNotifier(),
"asyncio": terrariumAsync(),
"cache": terrariumCache(),
}
# Create a salt for encryption. And set it as environment variable
salt = terrariumUtils.get_script_data("grep -i serial /proc/cpuinfo").decode().strip()
salt = salt.split(":")[1].strip()
os.environ["SALT"] = salt
self.meross_cloud = None
self.version = version
self.latest_version = None
self.update_available = False
self.weather = None
# Dirty hack... :(
self.device = Path("/proc/device-tree/model").read_text().rstrip("\x00")
init_db(self.version)
# Send message that startup is ready..... else the startup will wait until done.... can take more then 1 minute
self.__engine["systemd"].notify("READY=1")
self.running = True
# Make the first round of logging visible to the console, as this is the startup
old_log_level = terrariumLogging.logging.getLogger().handlers[0].level
terrariumLogging.logging.getLogger().handlers[0].setLevel(terrariumLogging.logging.INFO)
startup_message = f"Starting up TerrariumPI {self.version} on a {self.device} ..."
logger.info(startup_message)
# Load settings. This will also load the weather data if available
self.load_settings()
# Notification system
self.notification = terrariumNotification(self)
self.notification.engine = self
self.notification.load_services()
self.notification.broadcast(startup_message, startup_message, self.settings["profile_image"])
# Load Web server, as we need it for websocket communication (even when the web server is not yet started)
self.webserver = terrariumWebserver(self)
# Loading calendar
self.calendar = terrariumCalendar()
# Caching total power and water usage
start = time.time()
self.relays = {}
logger.info("Start loading total power and water usage")
self.get_power_usage_water_flow(True)
logger.info(f"Loaded total power and water usage in {time.time()-start:.2f} seconds.")
# Loading the sensors
start = time.time()
logger.info("Loading existing sensors from database.")
self.__load_existing_sensors()
logger.info("Scanning for new sensors ...")
self.scan_new_sensors()
logger.info(f"Loaded {len(self.sensors)} sensors in {time.time()-start:.2f} seconds.")
# Loading relays
start = time.time()
logger.info("Loading existing relays from database.")
self.__load_existing_relays()
logger.info("Scanning for new relays ...")
self.scan_new_relays()
logger.info(f"Loaded {len(self.relays)} relays in {time.time()-start:.2f} seconds.")
# Loading buttons....
start = time.time()
logger.info("Loading existing buttons from database.")
self.__load_existing_buttons()
logger.info(f"Loaded {len(self.buttons)} buttons in {time.time()-start:.2f} seconds.")
# Loading webcams
start = time.time()
logger.info("Loading existing webcams from database.")
self.__load_existing_webcams()
logger.info(f"Loaded {len(self.webcams)} webcams in {time.time()-start:.2f} seconds.")
# Loading enclosures and areas
start = time.time()
logger.info("Loading existing enclosures from database.")
self.__load_existing_enclosures()
logger.info(f"Loaded {len(self.enclosures)} enclosures in {time.time()-start:.2f} seconds.")
self.environment = None
self.motd()
startup_message = f'TerrariumPI {self.version} is up and running at address: http://{self.settings["host"]}:{self.settings["port"]} in {time.time()-self.starttime:.2f} seconds.'
logger.info(startup_message)
self.notification.broadcast(startup_message, startup_message, self.settings["profile_image"])
# Return console logging back to 'normal'
terrariumLogging.logging.getLogger().handlers[0].setLevel(old_log_level)
self.__engine["logtail"] = threading.Thread(target=self.__log_tailing)
self.__engine["thread"] = threading.Thread(target=self.__engine_loop)
self.__engine["logtail"].start()
self.__engine["thread"].start()
# Start the web server. This will be ending by pressing Ctrl-C or sending kill -INT {PID}
self.webserver.start()
# Stop Terrarium engine
if self.running:
self.stop()
def restart(self):
def sigint_process():
# If running with the service, it should restart automatically after 5 sec.
terrariumUtils.get_script_data(f"sleep 1; kill -INT {os.getpid()} &")
threading.Timer(2, sigint_process).start()
logger.warning(f'Restarting TerrariumPI {self.settings["version"]} now!')
return True
def reboot(self):
def sigint_process():
terrariumUtils.get_script_data("sleep 1; sudo reboot &")
threading.Timer(2, sigint_process).start()
logger.warning(f'Rebooting TerrariumPI {self.settings["version"]} now!')
return True
def shutdown(self):
def sigint_process():
terrariumUtils.get_script_data("sleep 1; sudo shutdown &")
threading.Timer(2, sigint_process).start()
logger.warning(f'Shutting down TerrariumPI {self.settings["version"]} now!')
return True
@property
def available_languages(self):
languages = []
for language_file in Path("locales/").glob("**/*.po"):
language = language_file.read_text()
language_code = (
re.search('^"Language: (?P<language>[^<"]+)', language, re.MULTILINE)
.group("language")
.strip()
.replace("\\n", "")
.strip()
)
language_name = (
re.search('^"Language-Team: (?P<language>[^<"]+)', language, re.MULTILINE)
.group("language")
.strip()
.replace("\\n", "")
.strip()
)
if "" == language_name or "none" == language_name:
language_name = language_code
languages.append({"id": language_code, "name": language_name})
return sorted(languages, key=lambda l: l["name"])
@property
def active_language(self):
return self.settings["language"].replace("-", "_")
# -=NEW=-
def load_settings(self):
start = time.time()
logger.debug("Loading settings")
# Store settings first locally, and replace the active settings with the new settings
settings = {}
with orm.db_session():
for setting in Setting.select():
setting = setting.to_dict()
if terrariumUtils.is_float(setting["value"]):
settings[setting["id"]] = float(setting["value"])
elif setting["value"].lower() in ["true", "false", "on", "off", "1", "0"]:
settings[setting["id"]] = terrariumUtils.is_true(setting["value"])
elif setting["id"].lower() in ["power_price", "water_price"]:
settings[setting["id"]] = (
float(setting["value"]) if terrariumUtils.is_float(setting["value"]) else 0.0
)
else:
settings[setting["id"]] = setting["value"]
logger.debug(f"Loaded setting: {setting['id']} with value: {setting['value']}")
settings["exclude_ids"] = [] if "" == settings["exclude_ids"] else settings["exclude_ids"].split(",")
# Force port number to an int.....
settings["port"] = int(settings["port"])
# Set meross login into the current bash environment
# But first check if the credentials have changed.
meross_login = (
os.environ.get("MEROSS_EMAIL", None) != settings["meross_cloud_username"]
or os.environ.get("MEROSS_PASSWORD", None) != settings["meross_cloud_password"]
)
os.environ["MEROSS_EMAIL"] = settings["meross_cloud_username"]
os.environ["MEROSS_PASSWORD"] = settings["meross_cloud_password"]
# Make sure we use PiGPIO daemon for PWM
# Pin factories: https://gpiozero.readthedocs.io/en/latest/api_pins.html
# rgpio should be the coming factory for Raspberry PI 5 https://github.com/gpiozero/gpiozero/pull/1129
os.environ["GPIOZERO_PIN_FACTORY"] = "rgpio" if terrariumUtils.isRaspberryPI5() else "pigpio"
# Add some extra non DB settings
settings["version"] = self.version
# Load device information
settings["device"] = self.device
# Load the languages. Make a copy of the original, so we can reuse this value easier.
settings["languages"] = copy.copy(self.available_languages)
# Custom favicon
favicon = Path("media/favicon.ico")
settings["favicon"] = "/media/favicon.ico" if favicon.exists() else "/favicon.ico"
if settings["profile_image"] == "":
settings["profile_image"] = "public/img/terrariumpi.jpg"
# Set unit values
self.units["temperature"] = (
"C"
if "celsius" == settings["temperature_indicator"]
else ("F" if "fahrenheit" == settings["temperature_indicator"] else "K")
)
self.units["heating"] = self.units["temperature"]
self.units["cooling"] = self.units["temperature"]
self.units["distance"] = "cm" if "cm" == settings["distance_indicator"] else "inch"
self.units["altitude"] = self.units["distance"]
self.units["volume"] = (
"L"
if "l" == settings["water_volume_indicator"]
else ("UKGall" if "ukgall" == settings["water_volume_indicator"] else "USGall")
)
self.units["water_flow"] = self.units["volume"] + "/m"
self.units["watertank"] = self.units["volume"]
if "km/h" == settings["wind_speed_indicator"]:
if "cm" == settings["distance_indicator"]:
self.units["windspeed"] = "km/h"
elif "inch" == settings["distance_indicator"]:
self.units["windspeed"] = "mph"
elif "m/s" == settings["wind_speed_indicator"]:
if "cm" == settings["distance_indicator"]:
self.units["windspeed"] = "m/s"
elif "inch" == settings["distance_indicator"]:
self.units["windspeed"] = "f/s"
elif "m/h" == settings["wind_speed_indicator"]:
self.units["windspeed"] = "mph"
elif "beaufort" == settings["wind_speed_indicator"]:
self.units["windspeed"] = "Bf"
# https://stackoverflow.com/questions/60001991/how-to-convert-windspeed-between-beaufort-scale-and-m-s-and-vice-versa-in-javasc
# Replace active settings with the new settings
self.settings = settings
logger.info(f"Loaded {len(settings)} settings in {time.time()-start:.2f} seconds.")
# Loading active language
try:
gettext.translation("terrariumpi", "locales/", languages=[self.active_language]).install()
logger.info(f"Loaded language '{self.active_language}'.")
except:
logger.warning(f"Translation '{self.active_language}' does not exists! Falling back on English (US).")
gettext.translation("terrariumpi", "locales/", languages=["en_US"]).install()
# Loading git data
gitversion = None
if Path(".gitversion").exists():
gitversion = Path(".gitversion").read_text().strip()
gitversion = None if gitversion == "" else gitversion
if gitversion is None and Path(".git").exists():
gitversion = str(terrariumUtils.get_script_data("git rev-parse HEAD").decode("utf-8")).strip()
self.settings["gitversion"] = gitversion
# Old dark mode conversion #852
if str(self.settings["auto_dark_mode"]).lower() == "true":
self.settings["auto_dark_mode"] = "on"
elif str(self.settings["auto_dark_mode"]).lower() == "false":
self.settings["auto_dark_mode"] = "off"
# Loading weather
if "weather_source" in self.settings:
if "" != self.settings["weather_source"]:
try:
self.weather = terrariumWeather(self.settings["weather_source"], self.units, self.active_language)
except Exception as ex:
weatherLogger.error(f"Failed loading weather data: {ex}")
elif self.weather is not None:
self.weather.address = self.settings["weather_source"]
# Force an update, due to maybe changing speed units or temperature.... lazy fix... :(
self.weather.update()
# Loading Meross cloud
if "" != settings["meross_cloud_username"] and "" != settings["meross_cloud_password"] and meross_login:
logger.info("Loading Meross cloud connection.")
if self.meross_cloud is not None:
logger.info("Stopping existing Meross cloud connection.")
self.meross_cloud.stop()
self.meross_cloud = TerrariumMerossCloud(
settings["meross_cloud_username"],
settings["meross_cloud_password"],
)
# -=NEW=-
def __update_checker(self):
# Set the initial update to 1970 if this is the first update check.
# Else the attribute __last_update_check is known
try:
assert self.__last_update_check
except Exception:
self.__last_update_check = datetime.datetime.fromtimestamp(0)
if datetime.datetime.now() - self.__last_update_check > datetime.timedelta(
days=terrariumEngine.__VERSION_UPDATE_CHECK_TIMEOUT
):
version_data = terrariumUtils.get_remote_data(
"https://api.github.com/repos/theyosh/TerrariumPI/releases/latest", json=True
)
if version_data is None:
logger.warning("Unable to get the latest version information from Github. Will check next round.")
return False
self.latest_version = version_data["tag_name"]
self.update_available = Version(self.version) < Version(self.latest_version)
self.__last_update_check = datetime.datetime.now()
return self.update_available
return False
# -=NEW=-
def add(self, item):
if isinstance(item, terrariumButton):
self.buttons[item.id] = item
elif isinstance(item, terrariumRelay):
self.relays[item.id] = item
elif isinstance(item, terrariumSensor):
self.sensors[item.id] = item
elif isinstance(item, terrariumWebcam):
self.webcams[item.id] = item
elif isinstance(item, terrariumEnclosure):
self.enclosures[item.id] = item
elif isinstance(item, terrariumArea):
self.enclosures[item.enclosure.id].add(item)
return item
def update(self, item, **data):
update_ok = False
if issubclass(item, terrariumButton):
self.buttons[data["id"]].address = data["address"]
self.buttons[data["id"]].name = data["name"]
if "calibration" in data:
self.buttons[data["id"]].calibrate(data["calibration"])
update_ok = True
elif issubclass(item, terrariumRelay):
if data["id"] not in self.relays:
return self.add(item)
self.relays[data["id"]].address = data["address"]
self.relays[data["id"]].name = data["name"]
self.relays[data["id"]].calibrate(data.get("calibration", {}))
update_ok = True
elif issubclass(item, terrariumSensor):
self.sensors[data["id"]].address = data["address"]
self.sensors[data["id"]].name = data["name"]
update_ok = True
elif issubclass(item, terrariumWebcam):
self.webcams[data["id"]].address = data["address"]
self.webcams[data["id"]].name = data["name"]
self.webcams[data["id"]].resolution = (int(data["width"]), int(data["height"]))
self.webcams[data["id"]].rotation = data["rotation"]
self.webcams[data["id"]].awb = data["awb"]
if isinstance(self.webcams[data["id"]], terrariumRPILiveWebcam):
logger.info(f'Stopping webcam {self.webcams[data["id"]].name}')
self.webcams[data["id"]].stop()
sleep(0.2)
self.webcams[data["id"]].load_hardware()
logger.info(f'Started webcam {self.webcams[data["id"]].name} with new configuration.')
update_ok = True
elif issubclass(item, terrariumEnclosure):
update_ok = True
elif issubclass(item, terrariumArea):
self.enclosures[data["enclosure"]].areas[data["id"]].name = data["name"]
self.enclosures[data["enclosure"]].areas[data["id"]].mode = data["mode"]
self.enclosures[data["enclosure"]].areas[data["id"]].load_setup(data["setup"])
update_ok = True
return update_ok
def delete(self, item, item_id, sub_id=None):
delete_ok = False
if issubclass(item, terrariumButton):
if item_id in self.buttons:
self.buttons[item_id].stop()
del self.buttons[item_id]
delete_ok = True
elif issubclass(item, terrariumRelay):
if item_id in self.relays:
self.relays[item_id].stop()
del self.relays[item_id]
delete_ok = True
elif issubclass(item, terrariumSensor):
if item_id in self.sensors:
self.sensors[item_id].stop()
del self.sensors[item_id]
delete_ok = True
elif issubclass(item, terrariumWebcam):
if item_id in self.webcams:
self.webcams[item_id].stop()
del self.webcams[item_id]
delete_ok = True
elif issubclass(item, terrariumArea):
self.enclosures[sub_id].delete(item_id)
delete_ok = True
return delete_ok
# Private/internal functions
# -=NEW=-
def __load_existing_sensors(self):
self.sensors = {}
with orm.db_session():
for sensor in Sensor.select(lambda s: s.id not in self.settings["exclude_ids"]).order_by(Sensor.address):
start = time.time()
if sensor.id not in self.sensors:
sensorLogger.debug(f"Loading {sensor}.")
try:
self.add(terrariumSensor(sensor.id, sensor.hardware, sensor.type, sensor.address, sensor.name))
if "chirp" == sensor.hardware.lower():
# We need some moisture calibration for a Chirp sensor
self.sensors[sensor.id].calibrate(sensor.calibration)
except terrariumSensorLoadingException as ex:
sensorLogger.error(f"Error loading {sensor} with error: {ex}.")
continue
else:
sensorLogger.debug(f"Updated already loaded {self.sensors[sensor.id]}.")
# Update existing sensor with new address
self.sensors[sensor.id].address = sensor.address
# Take a measurement from the sensor
value = self.sensors[sensor.id].update()
if value is None:
logger.warning(
f"{self.sensors[sensor.id]} had problems reading a new value during startup in {time.time()-start:.2f} seconds. Will be updated in the next round."
)
elif not sensor.limit_min <= value <= sensor.limit_max:
sensorLogger.warning(
f"Measurement for sensor {self.sensors[sensor.id]} of {value:.2f}{self.units[sensor.type]} is outside valid range {sensor.limit_min:.2f}{self.units[sensor.type]} to {sensor.limit_max:.2f}{self.units[sensor.type]} during startup in {time.time()-start:.2f} seconds. Will be updated in the next round."
)
else:
# Store the new measurement value in the database
sensor.update(value)
sensorLogger.info(
f"Loaded sensor {self.sensors[sensor.id]} with value {value:.2f}{self.units[sensor.type]} in {time.time()-start:.2f} seconds."
)
# -=NEW=-
def scan_new_sensors(self):
for sensor in terrariumSensor.scan_sensors():
if sensor.id not in self.settings["exclude_ids"] and sensor.id not in self.sensors:
start = time.time()
sensorLogger.debug(f"Found new sensor {sensor}")
action = "Added new"
value = sensor.update()
with orm.db_session():
try:
# First try to see if the Sensor does exist based on ID (means address change)
new_sensor = Sensor[sensor.id]
new_sensor.address = sensor.address
action = "Updated existing"
except orm.core.ObjectNotFound:
# Store new sensor in database
new_sensor = Sensor(
id=sensor.id,
hardware=sensor.HARDWARE,
type=sensor.sensor_type,
name=sensor.name,
address=sensor.address,
)
# Create a new sensor data entry, so we have at least one sensor value
new_sensor.update(value)
# Store the hardware sensor in memory, so we can benefit from the shared cached data for sensors with multiple sensor types
self.add(sensor)
sensorLogger.info(
f"{action} new sensor {sensor} to database with value {value:.2f}{self.units[sensor.type]} in {time.time()-start:.2f} seconds."
)
else:
reason = "excluded" if sensor.id in self.settings["exclude_ids"] else "already loaded"
sensorLogger.debug(f"Ignored sensor {sensor} because it is {reason}.")
def _update_sensors(self):
sensors = []
with orm.db_session():
# Get all loaded sensors ordered by hardware address
sensors = sorted(
Sensor.select(lambda s: s.id in self.sensors.keys() and not s.id in self.settings["exclude_ids"])[:],
key=lambda item: item.address,
)
for sensor in sensors:
with orm.db_session():
current_value = sensor.value
start = time.time()
if "css811" == sensor.hardware.lower():
calibration = {"temperature": [], "humidity": []}
for calibration_sensor in sensor.calibration["ccs811_compensation_sensors"]:
if calibration_sensor in self.sensors:
calibration_sensor = self.sensors[calibration_sensor]
if calibration_sensor.type in calibration:
calibration[calibration_sensor.type].append(calibration_sensor.value)
calibration["temperature"] = (
None if len(calibration["temperature"]) == 0 else statistics.mean(calibration["temperature"])
)
calibration["humidity"] = (
None if len(calibration["humidity"]) == 0 else statistics.mean(calibration["humidity"])
)
self.sensors[sensor.id].calibrate(calibration["temperature"], calibration["humidity"])
new_value = self.sensors[sensor.id].update(self.sensors[sensor.id].erratic > 0)
measurement_time = time.time() - start
if new_value is None:
sensorLogger.warning(
f"Could not take a new measurement from sensor {self.sensors[sensor.id]}. Tried for {measurement_time:.2f} seconds. Skipping this update."
)
continue
# Convert some values like temperature and distance ...
if "temperature" == sensor.type.lower():
if "fahrenheit" == self.settings["temperature_indicator"]:
new_value = terrariumUtils.to_fahrenheit(new_value)
elif "kelvin" == self.settings["temperature_indicator"]:
new_value = terrariumUtils.to_kelvin(new_value)
elif "distance" == sensor.type.lower():
if "inch" == self.settings["distance_indicator"]:
new_value = terrariumUtils.to_inches(new_value)
# We have a valid reading from the hardware sensor. Now increase/decrease with the offset
new_value += sensor.offset
if not sensor.limit_min <= new_value <= sensor.limit_max:
sensorLogger.warning(
f"Measurement for sensor {self.sensors[sensor.id]} of {new_value:.2f}{self.units[sensor.type]} is outside valid range {sensor.limit_min:.2f}{self.units[sensor.type]} to {sensor.limit_max:.2f}{self.units[sensor.type]}. Skipping this update."
)
continue
if current_value is not None and sensor.max_diff != 0 and abs(current_value - new_value) > sensor.max_diff:
self.sensors[sensor.id].erratic += 1
if self.sensors[sensor.id].erratic < 5:
sensorLogger.warning(
f"Sensor {self.sensors[sensor.id]} has an erratic({self.sensors[sensor.id].erratic}) measurement of value {new_value:.2f}{self.units[sensor.type]} compared to old value {current_value:.2f}{self.units[sensor.type]}. The difference of {abs(current_value - new_value):.2f}{self.units[sensor.type]} is more than max allowed difference of {sensor.max_diff:.2f}{self.units[sensor.type]} and will be ignored."
)
new_value = current_value
else:
sensorLogger.warning(
f"After {self.sensors[sensor.id].erratic} erratic measurements the new value {new_value:.2f}{self.units[sensor.type]} is promoted to the current value for sensor {sensor}."
)
self.sensors[sensor.id].erratic = 0
else:
self.sensors[sensor.id].erratic = 0
if new_value is not None:
with orm.db_session():
Sensor[sensor.id].update(new_value)
sensor_data = sensor.to_dict()
db_time = (time.time() - start) - measurement_time
sensor_data["unit"] = self.units[sensor.type]
sensor_data["type"] = sensor.type
self.webserver.websocket_message(
"sensor",
{
field: sensor_data[field]
for field in [
"id",
"value",
"error",
"alarm_min",
"alarm_max",
"limit_min",
"limit_max",
"alarm",
"unit",
"type",
"name",
]
},
)
# Notification message
self.notification.message("sensor_update", sensor_data)
if new_value != current_value:
self.notification.message("sensor_change", sensor_data)
if sensor_data["alarm"]:
self.notification.message("sensor_alarm", sensor_data)
sensorLogger.info(
f"Updated sensor {self.sensors[sensor.id]} with new value {new_value:.2f}{self.units[sensor.type]} in {measurement_time+db_time:.2f} seconds."
)
sensorLogger.debug(
f"Updated sensor {self.sensors[sensor.id]} with new value {new_value:.2f}{self.units[sensor.type]}. M: {measurement_time:.2f} sec, DB:{db_time:.2f} sec."
)
# A small sleep between sensor measurement to get a bit more responsiveness of the system
sleep(0.1)
for sensor_type, avg_data in self.sensor_averages.items():
avg_data["id"] = sensor_type
self.webserver.websocket_message("sensor", avg_data)
return True
@property
def sensor_averages(self):
start = time.time()
data = {}
with orm.db_session():
for sensor in Sensor.select(lambda s: s.exclude_avg == False and not s.id in self.settings["exclude_ids"]):
if sensor.type not in data:
data[sensor.type] = {
"value": 0.0,
"count": 0.0,
"error": 0,
"alarm_min": 0.0,
"alarm_max": 0.0,
"limit_min": 0.0,
"limit_max": 0.0,
}
if sensor.error or sensor.value is None:
data[sensor.type]["error"] += 1
continue
data[sensor.type]["value"] += sensor.value
data[sensor.type]["alarm_min"] += sensor.alarm_min
data[sensor.type]["alarm_max"] += sensor.alarm_max
data[sensor.type]["limit_min"] += sensor.limit_min
data[sensor.type]["limit_max"] += sensor.limit_max
data[sensor.type]["count"] += 1.0
averages = {}
for sensor_type, sensor_data in data.items():
count = sensor_data["count"]
if count == 0:
continue
del sensor_data["count"]
error = sensor_data["error"] > 0
del sensor_data["error"]
averages[sensor_type] = {}
for part, value in sensor_data.items():
averages[sensor_type][part] = value / count
averages[sensor_type]["error"] = error
averages[sensor_type]["alarm"] = (
not averages[sensor_type]["alarm_min"]
<= averages[sensor_type]["value"]
<= averages[sensor_type]["alarm_max"]
)
averages[sensor_type]["unit"] = self.units[sensor_type]
logger.debug(f"Calculated sensor averages in {time.time()-start:.2f} seconds.")
return averages
@property
def sensor_types_loaded(self):
# start = time.time()
data = []
with orm.db_session():
for sensor in Sensor.select(
lambda s: s.id in self.sensors.keys() and not s.id in self.settings["exclude_ids"]
):
if sensor.type not in data:
data.append(sensor.type)
data = [{"id": sensor_type, "value": sensor_type} for sensor_type in data]
return data
def __load_existing_relays(self):
self.relays = {}
with orm.db_session():
# TODO: Fix Meross better!! and r.hardware != 'meross'
for relay in Relay.select(lambda r: r.id not in self.settings["exclude_ids"]).order_by(Relay.address):
start = time.time()
if relay.id not in self.relays:
relayLogger.debug(f"Loading {relay}.")
try:
self.add(
terrariumRelay(
relay.id,
relay.hardware,
relay.address,
relay.name,
relay.calibration,
callback=self.callback_relay,
)
)
# Set the relay back to the old state
last_value = relay.value
# If we do not have a last value, try to get one from the relay
if last_value is None:
# If no state info available, then asume off
last_value = self.relays[relay.id].update() or terrariumRelay.OFF
# Restore the state of the relay
self.relays[relay.id].set_state(last_value, True)
except terrariumRelayLoadingException as ex:
relayLogger.error(f"Error loading relay {relay} with error: {ex}.")
continue
# Take a measurement from the relay
value = self.relays[relay.id].update()
if value is None:
relayLogger.warning(
f"Relay {self.relays[relay.id]} had problems reading a new value during startup in {time.time()-start:.2f} seconds. Will be updated in the next round."
)
else:
# Force a the new measurement value in the database
relay.update(value, True)
relayLogger.info(
f"Loaded relay {self.relays[relay.id]} value {value:.2f} in {time.time()-start:.2f} seconds."
)
def scan_new_relays(self):
for relay in terrariumRelay.scan_relays(callback=self.callback_relay):
if relay.id not in self.settings["exclude_ids"] and relay.id not in self.relays:
relayLogger.debug(f"Found new relay {relay}")
action = "Added new"
value = relay.update()
if value is None:
# Not able to make a readout
continue
with orm.db_session():
try:
# First try to see if the Relay does exist based on ID (means address change)
new_relay = Relay[relay.id]
new_relay.address = relay.address
action = "Updated existing"
except orm.core.ObjectNotFound:
# Store new relay in database
new_relay = Relay(id=relay.id, hardware=relay.HARDWARE, name=relay.name, address=relay.address)
# Create a new relay data entry, so we have at least one relay value
new_relay.update(value)
# Store the hardware relay in memory, so we can benefit from the shared cached data for relays with multiple relay types
self.add(relay)
relayLogger.info(f"{action} relay {relay} to database with current value {value:.2f}.")
else:
relayLogger.debug(
"Ignored relay {} because it is {}.".format(
relay, "excluded" if relay.id in self.settings["exclude_ids"] else "already loaded"
)
)
def _update_relays(self):
# Force an update every 60 minutes. This will make the graphs work better...
force_update = int(time.time()) % (60 * 60) <= terrariumEngine.__ENGINE_LOOP_TIMEOUT
force_totals = False
relays = []
with orm.db_session():
# Get all loaded relays ordered by hardware address
relays = sorted(
Relay.select(lambda r: r.id in self.relays.keys() and not r.id in self.settings["exclude_ids"])[:],
key=lambda item: item.address,
)
for relay in relays:
with orm.db_session():
current_value = relay.value
start = time.time()
try:
new_value = self.relays[relay.id].update()
except terrariumRelayUpdateException:
pass
measurement_time = time.time() - start
if new_value is None:
relayLogger.warning(
f"Could not take a new measurement from relay {self.relays[relay.id]}. Tried for {measurement_time:.2f} seconds. Skipping this update."
)
continue
with orm.db_session():
Relay[relay.id].update(new_value, force_update)
relay_data = relay.to_dict()
db_time = (time.time() - start) - measurement_time
self.webserver.websocket_message("relay", {"id": relay.id, "value": new_value})
relayLogger.info(
f"Updated relay {self.relays[relay.id]} with new value {new_value:.2f} in {measurement_time+db_time:.2f} seconds."
)
relayLogger.debug(
f"Updated relay {self.relays[relay.id]} with new value {new_value:.2f}. M: {measurement_time:.2f} sec, DB:{db_time:.2f} sec."
)
# Notification message
self.notification.message("relay_update", relay_data)
if new_value != current_value:
self.notification.message("relay_change", relay_data)
if not force_totals:
force_totals = new_value == 0
# A small sleep between sensor measurement to get a bit more responsiveness of the system
sleep(0.1)
self.send_websocket_totals(force_totals)
def toggle_relay(self, relay, action="toggle", duration=0):
ok = False
# Convert the action to an int value
if "on" == action:
action = terrariumRelay.ON
elif "off" == action:
action = terrariumRelay.OFF
elif "toggle" == action:
action = terrariumRelay.OFF if relay.value != terrariumRelay.OFF else terrariumRelay.ON
else:
action = int(action)
# Toggle the switch, will return ok = true when succeeded
ok = self.relays[relay.id].set_state(action)
return ok
def callback_relay(self, relay, state):
# First send websocket message before updating database
self.webserver.websocket_message("relay", {"id": relay, "value": state})
# Update database
with orm.db_session():
relay = Relay[relay]
relay.update(state)
relay_data = relay.to_dict()
orm.commit()
# Update enclosure states to reflect the new relay states
if self.__engine["thread"] is not None and self.__engine["thread"].is_alive() and hasattr(self, "enclosures"):
self._update_enclosures(True)
orm.commit()
# Notification message
self.notification.message("relay_toggle", relay_data)
# Forcing new update when relay goes off. New 'on' period can be calculated
self.send_websocket_totals(int(state) == 0)