-
-
Notifications
You must be signed in to change notification settings - Fork 101
/
terrariumArea.py
1501 lines (1217 loc) · 66.4 KB
/
terrariumArea.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 -*-
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
import copy
import datetime
import time
import statistics
import threading
# http://brettbeauregard.com/blog/2011/04/improving-the-beginners-pid-introduction/
# https://onion.io/2bt-pid-control-python/
# https://github.com/m-lundberg/simple-pid
from simple_pid import PID
from pony import orm
from terrariumAudio import terrariumAudioPlayer
from terrariumDatabase import Sensor, Playlist, Relay, Button, Area
from terrariumUtils import terrariumCache, terrariumUtils, classproperty
class terrariumAreaException(TypeError):
"""There is a problem with loading a hardware sensor."""
class terrariumArea(object):
__TYPES = {
"lights": {"name": _("Lighting"), "sensors": [], "class": lambda: terrariumAreaLights},
"heating": {"name": _("Heating"), "sensors": ["temperature"], "class": lambda: terrariumAreaHeater},
"cooling": {"name": _("Cooling"), "sensors": ["temperature"], "class": lambda: terrariumAreaCooler},
"humidity": {
"name": _("Humidity"),
"sensors": ["humidity", "moisture"],
"class": lambda: terrariumAreaHumidity,
},
"watertank": {"name": _("Water tank"), "sensors": ["distance"], "class": lambda: terrariumAreaWatertank},
"audio": {"name": _("Audio"), "sensors": [], "class": lambda: terrariumAreaAudio},
"co2": {"name": _("CO2"), "sensors": ["co2"], "class": lambda: terrariumAreaCO2},
"conductivity": {
"name": _("Conductivity"),
"sensors": ["conductivity"],
"class": lambda: terrariumAreaConductivity,
},
"fertility": {"name": _("Fertility"), "sensors": ["fertility"], "class": lambda: terrariumAreaFertility},
"moisture": {
"name": _("Moisture"),
"sensors": ["moisture", "humidity"],
"class": lambda: terrariumAreaMoisture,
},
"ph": {"name": _("pH"), "sensors": ["ph"], "class": lambda: terrariumAreaPH},
}
PERIODS = ["low", "high"]
@classproperty
def available_areas(__cls__):
return [
{"type": area_type, "name": area["name"], "sensors": area["sensors"]}
for area_type, area in terrariumArea.__TYPES.items()
]
# Return polymorph area....
def __new__(cls, area_id, enclosure, area_type, name="", mode=None, setup=None):
try:
return super(terrariumArea, cls).__new__(terrariumArea.__TYPES[area_type]["class"]())
except:
raise terrariumAreaException(f"Area of type {area_type} is unknown.")
def __init__(self, area_id, enclosure, area_type, name, mode, setup):
if area_id is None:
area_id = terrariumUtils.generate_uuid()
self.id = area_id
self.type = area_type
self.name = name
self.mode = mode
self.depends_on = []
self.enclosure = enclosure
self.state = {}
self.load_setup(setup)
def __repr__(self):
"""
Show the area in a nice way
Returns:
string: Area with area type
"""
return f'{terrariumArea.__TYPES[self.type]["name"]} named \'{self.name}\''
@property
def _powered(self):
powered = None
for period in self.PERIODS:
if period not in self.state or self.setup.get(period) is None or len(self.setup[period]["relays"]) == 0:
continue
powered = powered or self.state[period]["powered"]
logger.debug(f"Area {self} is powered: {powered}")
return powered
def _time_table(self):
def make_time_table(begin, end, on_period=0, off_period=0):
logger.debug(
f"Make new time table for {self}. Begin: {begin}, End: {end}, On: {on_period}, Off: {off_period}"
)
periods = []
duration = 0
now = datetime.datetime.now()
if not isinstance(begin, datetime.datetime):
begin = now.replace(hour=begin.hour, minute=begin.minute, second=begin.second)
if not isinstance(end, datetime.datetime):
end = now.replace(hour=end.hour, minute=end.minute, second=end.second)
if begin >= end:
logger.debug(f"Begin time is bigger then end time (swap). Add 24 hours to end time (next day) {self}")
end += datetime.timedelta(hours=24)
if begin <= now + datetime.timedelta(hours=24) < end:
# Calculating this at a timestamp before the begin time, can case a power down, while the end time has not passed (previous day on)
begin -= datetime.timedelta(hours=24)
end -= datetime.timedelta(hours=24)
if now < begin - datetime.timedelta(hours=24):
logger.debug(
f"Current time should be running after next day. Period is upcoming. Subtracting 24 hours {self}"
)
begin -= datetime.timedelta(hours=24)
end -= datetime.timedelta(hours=24)
elif now > end:
logger.debug(f"Current time past end. Period is pasted. Use next day by adding 24 hours {self}")
begin += datetime.timedelta(hours=24)
end += datetime.timedelta(hours=24)
if 0 == on_period and 0 == off_period:
logger.debug(f"Area {self} is full period usage")
periods.append((int(begin.timestamp()), int(end.timestamp())))
duration += periods[-1][1] - periods[-1][0]
else:
logger.debug(f"Area {self} has different periods")
while begin < end:
# The 'on' period is to big for the rest of the total timer time. So reduce it to the max left time
if (begin + datetime.timedelta(seconds=on_period)) > end:
on_period = (end - begin).total_seconds()
# Add new entry int he time table
periods.append(
(int(begin.timestamp()), int((begin + datetime.timedelta(seconds=on_period)).timestamp()))
)
duration += periods[-1][1] - periods[-1][0]
# Increase the start time with the on and off duration for the next round
begin += datetime.timedelta(seconds=on_period + off_period)
data = {"periods": periods, "duration": duration}
logger.debug(f"New time table for {self}")
logger.debug(data)
return data
timetable = {}
if "main_lights" == self.mode:
# We copy the timetable from the area with the toggle 'main lights' on. We follow that area its timetable
main_lights = self.enclosure.main_lights
if main_lights is not None:
for period in self.PERIODS:
if period not in self.setup:
continue
self.setup[period]["timetable"] = copy.deepcopy(
main_lights.setup["day" if "low" == period else "night"]["timetable"]
)
self.state[period]["begin"] = main_lights.state["day" if "low" == period else "night"]["begin"]
self.state[period]["end"] = main_lights.state["day" if "low" == period else "night"]["end"]
self.state[period]["duration"] = main_lights.state["day" if "low" == period else "night"][
"duration"
]
return True
if "weather" == self.mode or "weather_inverse" == self.mode:
sunrise = (
self.enclosure.weather.sunrise
if "weather" == self.mode
else self.enclosure.weather.sunset - datetime.timedelta(hours=24)
)
sunset = self.enclosure.weather.sunset if "weather" == self.mode else self.enclosure.weather.sunrise
next_sunrise = (
self.enclosure.weather.next_sunrise
if "weather" == self.mode
else self.enclosure.weather.next_sunset - datetime.timedelta(hours=24)
)
next_sunset = (
self.enclosure.weather.next_sunset if "weather" == self.mode else self.enclosure.weather.next_sunrise
)
max_hours = self.setup["max_day_hours"]
if max_hours != 0 and (sunset - sunrise) > datetime.timedelta(hours=max_hours):
# On period to long, so reduce the on period by shifting the sunrise and sunset times closer to each other
seconds_difference = ((sunset - sunrise) - datetime.timedelta(hours=max_hours)) / 2
sunrise += seconds_difference
sunset -= seconds_difference
if max_hours != 0 and (next_sunset - next_sunrise) > datetime.timedelta(hours=max_hours):
# On period to long, so reduce the on period by shifting the sunrise and sunset times closer to each other
seconds_difference = ((next_sunset - next_sunrise) - datetime.timedelta(hours=max_hours)) / 2
next_sunrise += seconds_difference
next_sunset -= seconds_difference
min_hours = self.setup["min_day_hours"]
if min_hours != 0 and (sunset - sunrise) < datetime.timedelta(hours=min_hours):
# On period to short, so extend the on period by shifting the sunrise and sunset times away from to each other
seconds_difference = (datetime.timedelta(hours=min_hours) - (sunset - sunrise)) / 2
sunrise -= seconds_difference
sunset += seconds_difference
if min_hours != 0 and (next_sunset - next_sunrise) < datetime.timedelta(hours=min_hours):
# On period to short, so extend the on period by shifting the sunrise and sunset times away from to each other
seconds_difference = (datetime.timedelta(hours=min_hours) - (next_sunset - next_sunrise)) / 2
next_sunrise -= seconds_difference
next_sunset += seconds_difference
shift_hours = self.setup["shift_day_hours"]
if shift_hours != 0:
# Shift the times back or forth...
sunrise += datetime.timedelta(hours=shift_hours)
sunset += datetime.timedelta(hours=shift_hours)
next_sunrise += datetime.timedelta(hours=shift_hours)
next_sunset += datetime.timedelta(hours=shift_hours)
# Default day and night schedule:
timetable["day"] = make_time_table(sunrise, sunset)
timetable["night"] = make_time_table(sunset, next_sunrise)
# Pick the next day
if datetime.datetime.now() > sunset:
timetable["day"] = make_time_table(next_sunrise, next_sunset)
# Night is still active till sunrise
if datetime.datetime.now() < sunrise:
timetable["night"] = make_time_table(sunset - datetime.timedelta(hours=24), sunrise)
elif "timer" == self.mode:
for period in self.PERIODS:
if period not in self.setup:
continue
begin = None
try:
begin = datetime.time.fromisoformat(self.setup[period]["begin"])
except Exception as ex:
logger.exception(f'Error loading begin time: {self.setup[period]["begin"]} - {ex}')
end = None
try:
end = datetime.time.fromisoformat(self.setup[period]["end"])
except Exception as ex:
logger.exception(f'Error loading end time: {self.setup[period]["end"]} - {ex}')
if begin is None or end is None:
logger.warning("Error generating timer periods. Either begin or end time is incorrect.")
continue
on_period = max(0.0, self.setup[period]["on_duration"]) * 60.0
off_period = max(0.0, self.setup[period]["off_duration"]) * 60.0
timetable[period] = make_time_table(begin, end, on_period, off_period)
for period in timetable:
if period not in self.setup:
continue
self.setup[period]["timetable"] = copy.deepcopy(timetable[period]["periods"])
self.state[period]["begin"] = self.setup[period]["timetable"][0][0]
self.state[period]["end"] = self.setup[period]["timetable"][-1][1]
self.state[period]["duration"] = timetable[period]["duration"]
return True
def load_setup(self, data):
self.setup = copy.deepcopy(data)
self.setup["day_night_difference"] = (
0.0
if not terrariumUtils.is_float(self.setup.get("day_night_difference"))
else float(self.setup.get("day_night_difference"))
)
if self.state.get("last_update", None) is None:
self.state = {
"is_day": self.setup.get("is_day", None),
"last_update": int(datetime.datetime(1970, 1, 1).timestamp()),
"powered": None,
}
self.depends_on = self.setup.get("depends_on", [])
self.ignore_low_alarm = False
self.ignore_high_alarm = False
try:
self.ignore_low_alarm = bool(self.setup["low"]["ignore_low"])
except Exception:
self.ignore_low_alarm = False
try:
self.ignore_high_alarm = bool(self.setup["high"]["ignore_high"])
except Exception:
self.ignore_high_alarm = False
self.low_deviation = self.setup.get("deviation_low_alarm", 0.0)
self.low_deviation = 0.0 if not terrariumUtils.is_float(self.low_deviation) else float(self.low_deviation)
self.high_deviation = self.setup.get("deviation_high_alarm", 0.0)
self.high_deviation = 0.0 if not terrariumUtils.is_float(self.high_deviation) else float(self.high_deviation)
float_values = ["max_day_hours", "min_day_hours", "shift_day_hours"]
for float_value in float_values:
self.setup[float_value] = self.setup.get(float_value, 0.0)
self.setup[float_value] = (
0.0 if not terrariumUtils.is_float(self.setup[float_value]) else float(self.setup[float_value])
)
for period in self.PERIODS:
# Clean up parts that do not have relays configured)
if period in self.setup and len(self.setup[period]["relays"]) == 0:
del self.setup[period]
continue
# With version 4.6.0 we get also empty string fields back. So we have to make sure that the fields in the list below are all float values
float_values = ["on_duration", "off_duration", "settle_time", "power_on_time", "alarm_threshold"]
for float_value in float_values:
self.setup[period][float_value] = self.setup[period].get(float_value, 0.0)
self.setup[period][float_value] = (
0.0
if not terrariumUtils.is_float(self.setup[period][float_value])
else float(self.setup[period][float_value])
)
self.setup[period]["tweaks"] = {}
if period not in self.state:
self.state[period] = {}
self.state[period]["last_powered_on"] = 0
self.state[period]["powered"] = self.relays_state(period)
self.state[period]["alarm_count"] = 0
if "sensors" != self.mode:
self._time_table()
# Setup variation data
if self.setup.get("variation"):
self._setup_variation_data()
self.state["powered"] = self._powered
def _setup_variation_data(self):
self.state["variation"] = {
"active": len(self.setup["sensors"]) > 0,
"dynamic": False,
"external": False,
"script": False,
"weather": False,
"offset": float(0),
"source": None,
"periods": [],
}
variation_data = copy.deepcopy(self.setup.get("variation", []))
if len(variation_data) == 0:
return
if variation_data[0]["when"] in ["script", "external", "weather"]:
try:
self.state["variation"]["offset"] = float(variation_data[0]["offset"])
except Exception as ex:
# Not a valid float, so use default 0
logger.debug(f'Invalid variation offset value {variation_data[0]["offset"]}: {ex}')
self.state["variation"][variation_data[0]["when"]] = True
if "weather" != variation_data[0]["when"]:
self.state["variation"]["source"] = variation_data[0]["source"]
if "external" == variation_data[0]["when"]:
self.__external_cache = terrariumCache()
variation_data = []
for variation in variation_data:
if "" == variation.get("value", ""):
continue
periods = len(self.state["variation"]["periods"])
if "at" == variation.get("when"):
# Format datetime object to a time object
# TODO: Need to check if this will interfere with utc timestamps from history...
period_timestamp = datetime.datetime.fromtimestamp(int(variation.get("period"))).strftime("%H:%M")
elif "after" == variation.get("when"):
# !! UNTESTED !!
if periods == 0:
# We need main lights on starting time....
self.state["variation"]["dynamic"] = True
else:
# We need the previous period start time and adding the 'after' period duration
period_timestamp = datetime.time.fromisoformat(
self.state["variation"]["periods"][periods - 1]["start"]
)
period_timestamp = datetime.datetime.now().replace(
hour=period_timestamp.hour, minute=period_timestamp.minute
) + datetime.timeldeta(minute=int(variation.get("period")))
period_timestamp = period_timestamp.strftime("%H:%M")
if periods > 0:
# We have at least 1 item so we need to update the previous entry with the new end time and value
self.state["variation"]["periods"][periods - 1]["end"] = period_timestamp
self.state["variation"]["periods"][periods - 1]["end_value"] = str(variation.get("value"))
self.state["variation"]["periods"].append(
{
"start": period_timestamp,
"end": "23:59", # By default, we stop at the end of the day
"start_value": str(variation.get("value")),
"end_value": str(
variation.get("value")
), # This will be overwritten by the next value to get a nice change during the period
}
)
def _is_timer_time(self, period):
if period not in self.setup or "timetable" not in self.setup[period]:
logger.debug(f"Area {self} does not have a timer table")
return False
now = int(datetime.datetime.now().timestamp())
for time_schedule in self.setup[period]["timetable"]:
if now < time_schedule[0]:
logger.debug(f"Area {self} is not time yet. Period has to start first.")
return False
elif time_schedule[0] <= now < time_schedule[1]:
logger.debug(
f"Area {self} is in period, so toggle on: {time_schedule[0]} <= {now} <= {time_schedule[1]}"
)
return True
logger.debug(f"Area {self} does not know if it is time.... Should update new timetable for next day?")
return None
def _update_variation(self):
# !! This variation updates will interfere with the 'day/night difference' setting !!
if ("variation" not in self.state) or (not self.state["variation"]["active"]):
return
# Get the current time in minutes
now = datetime.datetime.now().time()
# Loop over the periods to find the current period
period = None
if self.state["variation"]["script"] or self.state["variation"]["external"]:
value = None
if self.state["variation"]["script"]:
value = (
float(terrariumUtils.get_script_data(self.state["variation"]["source"]))
+ self.state["variation"]["offset"]
)
elif self.state["variation"]["external"]:
# Here we get data from an external source. We cache this data for 10 minutes
cache_key = f"{self.id}_external"
value = self.__external_cache.get_data(cache_key)
if value is None:
start = time.time()
value = (
float(terrariumUtils.get_remote_data(self.state["variation"]["source"]))
+ self.state["variation"]["offset"]
)
if value is not None:
unit = self.enclosure.engine.units[self.state["sensors"]["unit"]]
self.__external_cache.set_data(cache_key, value, 10 * 60)
logger.info(
f"Updated external source variation data with value: {value}{unit} in {time.time() - start:.2f} seconds"
)
else:
logger.error("Could not load data from external source! Please check your settings.")
if value is not None:
period = {
"start": (datetime.datetime.now() - datetime.timedelta(minutes=2)).time(),
"end": (
datetime.datetime.now() + datetime.timedelta(minutes=2)
).time(), # By default, we stop at the end of the day
"start_value": str(value),
"end_value": str(
value
), # This will be overwritten by the next value to get a nice change during the period
}
elif self.state["variation"]["weather"]:
weather_current_source = None
if self.type in ["heating", "cooling"]:
weather_current_source = "temperature"
elif self.type in ["humidity"]:
weather_current_source = "humidity"
if weather_current_source is None:
return
current_timestamp = int((datetime.datetime.now() - datetime.timedelta(hours=24)).timestamp())
for counter, history in enumerate(self.enclosure.engine.weather.history):
if current_timestamp <= history["timestamp"] + time.timezone:
period = {
"start": datetime.datetime.fromtimestamp(
int(self.enclosure.engine.weather.history[counter - 1]["timestamp"] + time.timezone)
),
"end": datetime.datetime.fromtimestamp(int(history["timestamp"] + time.timezone)),
"start_value": str(self.enclosure.engine.weather.history[counter - 1][weather_current_source]),
"end_value": str(history[weather_current_source]),
}
break
else:
for item in self.state["variation"]["periods"]:
if now >= datetime.time.fromisoformat(item["start"]) and now < datetime.time.fromisoformat(item["end"]):
# Fond the right period, so save and stop looping
period = copy.copy(item)
period["start"] = datetime.time.fromisoformat(item["start"])
period["end"] = datetime.time.fromisoformat(item["end"])
break
if period is None:
# No valid period found, so we are done!
return
# Get the current 'wanted' average value based on the alarm min and max values
current_average_value = (self.state["sensors"]["alarm_min"] + self.state["sensors"]["alarm_max"]) / 2.0
# Convert relative sensor values to absolute values based on the current state.
# This is done only once when the period starts. Once converted, we keep the absolute values
# !! UNTESTED !!
if period["start_value"].startswith("+"):
period["start_value"] = current_average_value + int(period["start_value"][1:])
elif period["start_value"].startswith("-"):
period["start_value"] = current_average_value - int(period["start_value"][1:])
if period["end_value"].startswith("+"):
period["end_value"] = current_average_value + int(period["end_value"][1:])
elif period["end_value"].startswith("-"):
period["end_value"] = current_average_value + -int(period["end_value"][1:])
# Start calculation
# Get the total duration of the period in seconds
period_duration = round(
(
datetime.datetime.now().replace(hour=period["end"].hour, minute=period["end"].minute)
- datetime.datetime.now().replace(hour=period["start"].hour, minute=period["start"].minute)
).total_seconds()
)
# Get the total difference that needs to change during the period
period_difference = float(period["end_value"]) - float(period["start_value"])
# How far are we in this period in seconds
period_duration_done = round(
(
datetime.datetime.now().replace(hour=now.hour, minute=now.minute)
- datetime.datetime.now().replace(hour=period["start"].hour, minute=period["start"].minute)
).total_seconds()
)
# Calculate the wanted average based on the start period value and the time elapsed * sensor difference/second
wanted_average_value = float(period["start_value"]) + (
float(period_duration_done) * float(period_difference / period_duration)
)
# Get the difference between the actual current average and the wanted average rounded at .1
sensor_diff = round(wanted_average_value - current_average_value, 1)
if sensor_diff != 0.0:
# Change every sensor its min max alarm values with `sensor_diff` change
with orm.db_session():
for sensor in Sensor.select(lambda s: s.id in self.setup["sensors"]):
sensor.alarm_min += sensor_diff
sensor.alarm_max += sensor_diff
unit = self.enclosure.engine.units[self.state["sensors"]["unit"]]
logger.info(
f"Variation change {sensor.type} sensor '{sensor.name}' for area '{self.name}'. New values min: {sensor.alarm_min:.2f}{unit}, max:{sensor.alarm_max:.2f}{unit}. New average is: {wanted_average_value:.2f}{unit}."
)
# Reload the current sensor values after changing them
self.state["sensors"] = self.current_value(self.setup["sensors"])
def depending_relays_ok(self, part):
depending_relays = self.setup[part].get("depend_on_relays", [])
if len(depending_relays) == 0:
return True
mode = self.setup[part].get("depend_on_relays_mode", None)
if mode is None:
return False
relays_status = []
for relay in depending_relays:
if relay not in self.enclosure.engine.relays:
relays_status.append(False)
else:
relays_status.append(self.enclosure.engine.relays[relay].is_on())
if mode == "all":
return all(relays_status)
elif mode == "one":
return True in relays_status
elif mode == "none":
return not all(relays_status)
return True
@property
def is_day(self):
light_mode = self.setup.get("day_night_source", "")
# Base day time on weather information
if "weather" == light_mode and self.enclosure.weather is not None:
return self.enclosure.weather.is_day
# Else we have to see if we are between the begin and end time of the 'main lights' light area
if (
"lights" == light_mode
and self.enclosure.main_lights is not None
and self.enclosure.main_lights.mode != "disabled"
):
is_day_time = (
self.enclosure.main_lights.state["day"]["begin"]
< int(datetime.datetime.now().timestamp())
< self.enclosure.main_lights.state["day"]["end"]
)
return is_day_time
# Default day period is from 07:00 till 19:00
return 700 < int(time.strftime("%H%M")) < 1900
def update(self, read_only=False):
if self.mode == "disabled":
# Make it readonly, so sensors and relay changes are still shown
read_only = True
start = time.time()
light_state = "on" if self.enclosure.lights_on else "off"
door_state = "closed" if self.enclosure.door_closed else "open"
old_is_day = self.state["is_day"]
self.state["is_day"] = self.is_day
if "variation" in self.state and self.state["variation"]["dynamic"]:
if old_is_day != self.state["is_day"] or int(datetime.datetime.now().strftime("%H%M")) % 400 == 0:
# logger.info('Updating variation data based on day/night change or modulo 400')
self._setup_variation_data()
if "sensors" in self.setup and len(self.setup["sensors"]) > 0:
# Change the sensor limits when changing from day to night and vs.
if old_is_day != self.state["is_day"] and self.setup["day_night_difference"] != 0.0:
difference = self.setup["day_night_difference"] * (-1.0 if self.state["is_day"] else 1.0)
logger.info(
f'Adjusting the sensors based on day/night difference. Changing by {difference} going from {("day" if old_is_day else "night")} to {("day" if self.state["is_day"] else "night")}'
)
with orm.db_session():
for sensor in Sensor.select(lambda s: s.id in self.setup["sensors"]):
sensor.alarm_min += difference
sensor.alarm_max += difference
# If there are sensors in use, calculate the current values
self.state["sensors"] = self.current_value(self.setup["sensors"])
# If there are variations on the alarm values, update them here
if not read_only:
self._update_variation()
# Deviation calculation is done in current_value() function
if self.ignore_low_alarm:
# Use the max alarm value to changing the relays
self.state["sensors"]["alarm_low"] = (
self.state["sensors"]["current"] < self.state["sensors"]["alarm_max"]
)
else:
# Normal state
self.state["sensors"]["alarm_low"] = (
self.state["sensors"]["current"] < self.state["sensors"]["alarm_min"]
)
if self.ignore_high_alarm:
# Use the min alarm value to changing the relays
self.state["sensors"]["alarm_high"] = (
self.state["sensors"]["current"] > self.state["sensors"]["alarm_min"]
)
else:
self.state["sensors"]["alarm_high"] = (
self.state["sensors"]["current"] > self.state["sensors"]["alarm_max"]
)
# If the depending area is in alarm state, we cannot toggle this area and all the relays should be shutdown
depends_on_alarm = False
for area in self.depends_on:
if area in self.enclosure.areas and self.enclosure.areas[area].state.get("sensors"):
depends_on_alarm = depends_on_alarm or self.enclosure.areas[area].state["sensors"]["alarm"]
if depends_on_alarm:
unit_value = self.enclosure.engine.units[self.enclosure.areas[area].state["sensors"]["unit"]]
logger.info(
f'Depending area {self.enclosure.areas[area].name} is in alarm state for area {self}. Current: {self.enclosure.areas[area].state["sensors"]["current"]:.2f}{unit_value}'
)
for period in self.PERIODS:
if period in self.setup and self.relays_state(period):
logger.info(
f"Toggle down the power for period {period} due to depending area {self.enclosure.areas[area].name} alarm state."
)
self.relays_toggle(period, False)
break
for period in self.PERIODS:
if period not in self.setup:
continue
if read_only:
self.state[period]["powered"] = self.relays_state(period)
continue
# Set the lights state. Default True
light_state_ok = True
if "light_status" in self.setup[period] and self.setup[period]["light_status"] not in ["ignore", ""]:
# Change the lights state based on the current state and requested state. False when not equal
light_state_ok = self.setup[period]["light_status"] == light_state
# Set the doors state. Default True
door_state_ok = True
if "door_status" in self.setup[period] and self.setup[period]["door_status"] not in ["ignore", ""]:
# Change the doors state based on the current state and requested state. False when not equal
door_state_ok = self.setup[period]["door_status"] == door_state
# Set depending relays state
depending_relays_ok = self.depending_relays_ok(period)
# First check: Shutdown power when power is on and either the lights or doors are in wrong state. Despite 'mode'
if not self.relays_state(period, False) and not (
light_state_ok and door_state_ok and depending_relays_ok and (not depends_on_alarm)
):
# Power is on, but either the lights or doors are in wrong state. Power down now.
logger.info(
f'Forcing down the {period} power for area {self} because either the lights({"OK" if light_state_ok else "ERROR"}), doors({"OK" if door_state_ok else "ERROR"}) or depending area ({"OK" if not depends_on_alarm else "ERROR"}) are in an invalid state.'
)
self.relays_toggle(period, False)
# And ignore the rest....
continue
if "sensors" != self.mode:
# Weather(inverse) and timer mode
toggle_relay = self._is_timer_time(period)
logger.debug(f"Need to toggle the relays for {self} period {period}? {toggle_relay}")
if toggle_relay is None:
logger.info(f"Refreshing timer table for {self} period: {period}")
self._time_table()
toggle_relay = False
if toggle_relay is True and len(self.setup.get("sensors", [])) > 0:
# We are in timer mode. But when there are sensors configured, they act as a second check
# If there is NOT an alarm with the period name, then skip the toggle action.
if self.state["sensors"][f"alarm_{period}"] is not True:
try:
logger.info(
f'Relays for area {self} at period {period} are not switched because the additional sensors are at value: {self.state["sensors"]["current"]:.2f}{self.enclosure.engine.units[self.state["sensors"]["unit"]]}.'
)
except:
# Some strange happens when data is deleted which should not be deleted #827
pass
continue
else:
if self.state["sensors"]["all_error"]:
logger.warning(
f"All sensors for area {self} at period {period} are in an error state. Relays will not power on! Please check you sensors hardware!"
)
if self.relays_state(period):
logger.warning(
f"Relays for area {self} at period {period} are forced to state off due to non working sensors."
)
self.relays_toggle(period, False)
# And ignore the rest....
continue
# Sensor mode only toggle ON when alarms are triggered (True).
toggle_relay = self.state["sensors"][f"alarm_{period}"]
if toggle_relay is False:
other_alarm = self.state["sensors"][f'alarm_{("low" if period == "high" else "high")}']
toggle_relay = False if other_alarm else None
if toggle_relay is True and not self.relays_state(period):
if not light_state_ok:
logger.info(
f'Relays for {self} period {period} are not switched on because the lights are {light_state} while {self.setup[period]["light_status"]} is requested.'
)
continue
if not door_state_ok:
logger.info(
f'Relays for {self} period {period} are not switched on because the door is {door_state} while {self.setup[period]["door_status"]} is requested.'
)
continue
if not depending_relays_ok:
logger.info(
f"Relays for {self} period {period} are not switched on because the depending relays are not in the correct state."
)
continue
if depends_on_alarm:
logger.info(
f"Relays for {self} period {period} are not switched on because at least one of the depending areas is in an alarm state."
)
continue
time_elapsed = abs(int(datetime.datetime.now().timestamp()) - self.state[period]["last_powered_on"])
# Extra weather check / backup
if self.mode in ["weather", "weather_inverse"] and time_elapsed < (15 * 60):
# Not allowed to toggle for 15 minutes after shutting down based on weather(inverse) mode
# This is a poor fix for wrongly recalculating time tables based on weather data
continue
if time_elapsed <= self.setup[period]["settle_time"]:
logger.info(
f'Relays for {self} period {period} are not switched on because we have to wait for {self.setup[period]["settle_time"]-time_elapsed} more seconds of the total settle time of {self.setup[period]["settle_time"]} seconds.'
)
continue
other_period = list(self.setup.keys())
other_period.remove(period)
if 1 == len(other_period):
other_period = other_period[0]
time_elapsed = abs(
int(datetime.datetime.now().timestamp()) - self.state[other_period]["last_powered_on"]
)
if time_elapsed <= self.setup[other_period]["settle_time"]:
logger.info(
f'Relays for {self} period {period} are not switched on because of the other period {other_period} settle time. We have to wait for {self.setup[other_period]["settle_time"]-time_elapsed} more seconds of the total settle time of {self.setup[other_period]["settle_time"]} seconds.'
)
continue
if self.state[period]["alarm_count"] < self.setup[period]["alarm_threshold"]:
logger.info(
f'The alarm counter ({self.state[period]["alarm_count"]}) for area {self} for alarm {period} is lower than the threshold ({self.setup[period]["alarm_threshold"]}). Skip this round.'
)
self.state[period]["alarm_count"] += 1
continue
self.state[period]["alarm_count"] = 0
self.relays_toggle(period, True)
elif (
toggle_relay is False
and not self.relays_state(period, False)
and not self.state[period].get("timer_on", False)
):
self.relays_toggle(period, False)
self.state[period]["powered"] = self.relays_state(period)
self.state["powered"] = self._powered
self.state["last_update"] = int(datetime.datetime.now().timestamp())
logger.info(
f"Updated area {self} in '{self.mode}' mode at enclosure {self.enclosure.name} in {time.time()-start:.2f} seconds."
)
return self.state
def current_value(self, sensors):
sensor_values = {"current": [], "alarm_max": [], "alarm_min": []}
unit_type = None
all_error = None
with orm.db_session():
for sensor in Sensor.select(lambda s: s.id in sensors):
unit_type = sensor.type
if sensor.value is None:
# Broken sensor, so ignore it
if all_error is None:
all_error = True
continue
sensor_values["current"].append(sensor.value)
sensor_values["alarm_max"].append(sensor.alarm_max)
sensor_values["alarm_min"].append(sensor.alarm_min)
all_error = False
for key in sensor_values:
if len(sensor_values[key]) == 0:
sensor_values[key] = 0
else:
sensor_values[key] = statistics.mean(sensor_values[key])
sensor_values["alarm_min"] += self.low_deviation
sensor_values["alarm_max"] += self.high_deviation
sensor_values["alarm"] = (
not sensor_values["alarm_min"] <= sensor_values["current"] <= sensor_values["alarm_max"]
)
sensor_values["unit"] = unit_type
sensor_values["all_error"] = all_error == True
return sensor_values
def relays_state(self, part, state=True):
old_state = self.state[part].get("powered", None)
relay_states = []
for relay in self.setup[part]["relays"]:
if relay not in self.enclosure.relays:
continue
if state:
relay_states.append(self.enclosure.relays[relay].is_on())
else:
relay_states.append(self.enclosure.relays[relay].is_off())
new_state = all(relay_states)
if (state is False and old_state is True and new_state is True) or (
state is True and old_state is True and new_state is False
):
# Somewhere the power is turned off. Store the time for settle calculation
self.state[part]["last_powered_on"] = int(datetime.datetime.now().timestamp())
return new_state
def relays_toggle(self, part, on):
log_line = f'Toggle the relays for area {self} part {part} to state {("on" if on else "off")}'
power_on_time = self.setup[part].get("power_on_time", 0.0)
if on and power_on_time > 0.0:
log_line += f" and switch back to state off after {power_on_time} seconds"
self.state[part]["timer_on"] = True
threading.Timer(power_on_time, self.relays_toggle, [part, False]).start()
logger.info(f"{log_line}.")
relays = []
with orm.db_session():
relays = orm.select(r.id for r in Relay if r.id in self.setup[part]["relays"] and not r.manual_mode)[:]
for relay in relays:
if relay not in self.enclosure.relays:
continue
relay = self.enclosure.relays[relay]
self._relay_action(part, relay, on)
if not on:
self.state[part]["last_powered_on"] = int(datetime.datetime.now().timestamp())
self.state[part]["timer_on"] = False
self.state[part]["powered"] = on
self.state["powered"] = self._powered
def _relay_action(self, part, relay, action):
if relay.id in self.enclosure.relays:
logger.info(f"Set the relay {relay.name} to {relay.ON if action else relay.OFF}")
self.enclosure.relays[f"{relay.id}"].on(relay.ON if action else relay.OFF)
def stop(self):
logger.info(f"Stopped Area {self}")
class terrariumAreaLights(terrariumArea):
PERIODS = ["day", "night"]
def _relay_action(self, part, relay, action):
if relay.id not in self.enclosure.relays:
return
duration = 0
delay = 0
try:
tweaks = self.setup[part]["tweaks"][f"{relay.id}"]["on" if action else "off"]
duration = tweaks["duration"]