forked from theyosh/TerrariumPI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterrariumEnvironment.py
900 lines (707 loc) · 41.9 KB
/
terrariumEnvironment.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
# -*- coding: utf-8 -*-
import terrariumLogging
logger = terrariumLogging.logging.getLogger(__name__)
import thread
import datetime
import time
from threading import Timer
from terrariumUtils import terrariumUtils
from gevent import monkey, sleep
monkey.patch_all()
class terrariumEnvironment():
LOOP_TIMEOUT = 15
def __init__(self, sensors, power_switches, weather, door_status, config):
logger.debug('Init terrariumPI environment')
# Config callback
self.config = config
# Door status callback
self.is_door_open = door_status
self.sensors = sensors
self.power_switches = power_switches
self.weather = weather
self.load_environment()
thread.start_new_thread(self.__engine_loop, ())
def load_environment(self, data = None):
# Load Sensors, with ID as index
starttime = time.time()
reloading = data is not None
logger.info('%s terrariumPI Environment system' % ('Reloading' if reloading else 'Loading',))
data = (self.config() if not reloading else data)
# Cleanup of empty fields.....
config_data = {}
for part in data:
if part not in config_data:
config_data[part] = {}
for field in data[part]:
if not (data[part][field] == '' or data[part][field] is None):
config_data[part][field] = data[part][field]
if len(config_data['light'].keys()) == 0 or not reloading:
self.light = {}
self.light['mode'] = 'disabled' if 'mode' not in config_data['light'] else config_data['light']['mode']
self.light['on'] = '00:00' if 'on' not in config_data['light'] else config_data['light']['on']
self.light['off'] = '00:00' if 'off' not in config_data['light'] else config_data['light']['off']
self.light['on_duration'] = 60.0 if 'on_duration' not in config_data['light'] else float(config_data['light']['on_duration'])
self.light['off_duration'] = 60.0 if 'off_duration' not in config_data['light'] else float(config_data['light']['off_duration'])
self.light['hours_shift'] = 0.0 if 'hours_shift' not in config_data['light'] else float(config_data['light']['hours_shift'])
self.light['min_hours'] = 0.0 if 'min_hours' not in config_data['light'] else float(config_data['light']['min_hours'])
self.light['max_hours'] = 0.0 if 'max_hours' not in config_data['light'] else float(config_data['light']['max_hours'])
self.light['power_switches'] = [] if ('power_switches' not in config_data['light'] or config_data['light']['power_switches'] in ['',None]) else config_data['light']['power_switches']
if not isinstance(self.light['power_switches'], list):
self.light['power_switches'] = self.light['power_switches'].split(',')
self.light['enabled'] = 'disabled' != self.light['mode']
if len(config_data['sprayer'].keys()) == 0 or not reloading:
self.sprayer = {}
self.sprayer['mode'] = 'disabled' if 'mode' not in config_data['sprayer'] else config_data['sprayer']['mode']
self.sprayer['on'] = '00:00' if 'on' not in config_data['sprayer'] else config_data['sprayer']['on']
self.sprayer['off'] = '00:00' if 'off' not in config_data['sprayer'] else config_data['sprayer']['off']
self.sprayer['on_duration'] = 1.0 if 'on_duration' not in config_data['sprayer'] else float(config_data['sprayer']['on_duration'])
self.sprayer['off_duration'] = 59.0 if 'off_duration' not in config_data['sprayer'] else float(config_data['sprayer']['off_duration'])
self.sprayer['night_enabled'] = False if 'night_enabled' not in config_data['sprayer'] else terrariumUtils.is_true(config_data['sprayer']['night_enabled'])
self.sprayer['spray_duration'] = 0.0 if 'spray_duration' not in config_data['sprayer'] else float(config_data['sprayer']['spray_duration'])
self.sprayer['spray_timeout'] = 0.0 if 'spray_timeout' not in config_data['sprayer'] else float(config_data['sprayer']['spray_timeout'])
self.sprayer['power_switches'] = [] if ('power_switches' not in config_data['sprayer'] or config_data['sprayer']['power_switches'] in ['',None]) else config_data['sprayer']['power_switches']
self.sprayer['sensors'] = [] if ('sensors' not in config_data['sprayer'] or config_data['sprayer']['sensors'] in ['',None]) else config_data['sprayer']['sensors']
if not isinstance(self.sprayer['power_switches'], list):
self.sprayer['power_switches'] = self.sprayer['power_switches'].split(',')
if not isinstance(self.sprayer['sensors'], list):
self.sprayer['sensors'] = self.sprayer['sensors'].split(',')
self.sprayer['enabled'] = 'disabled' != self.sprayer['mode']
self.sprayer['lastaction'] = int(time.time())
if len(config_data['watertank'].keys()) == 0 or not reloading:
self.watertank = {}
self.watertank['mode'] = 'disabled' if 'mode' not in config_data['watertank'] else config_data['watertank']['mode']
self.watertank['on'] = '00:00' if 'on' not in config_data['watertank'] else config_data['watertank']['on']
self.watertank['off'] = '00:00' if 'off' not in config_data['watertank'] else config_data['watertank']['off']
self.watertank['on_duration'] = 1.0 if 'on_duration' not in config_data['watertank'] else float(config_data['watertank']['on_duration'])
self.watertank['off_duration'] = 59.0 if 'off_duration' not in config_data['watertank'] else float(config_data['watertank']['off_duration'])
self.watertank['pump_duration'] = 0.0 if 'pump_duration' not in config_data['watertank'] else float(config_data['watertank']['pump_duration'])
self.watertank['volume'] = 1.0 if 'volume' not in config_data['watertank'] else float(config_data['watertank']['volume'])
self.watertank['height'] = 1.0 if 'height' not in config_data['watertank'] else float(config_data['watertank']['height'])
self.watertank['power_switches'] = [] if ('power_switches' not in config_data['watertank'] or config_data['watertank']['power_switches'] in ['',None]) else config_data['watertank']['power_switches']
self.watertank['sensors'] = [] if ('sensors' not in config_data['watertank'] or config_data['watertank']['sensors'] in ['',None]) else config_data['watertank']['sensors']
if not isinstance(self.watertank['power_switches'], list):
self.watertank['power_switches'] = self.watertank['power_switches'].split(',')
if not isinstance(self.watertank['sensors'], list):
self.watertank['sensors'] = self.watertank['sensors'].split(',')
self.watertank['enabled'] = 'disabled' != self.watertank['mode']
self.watertank['lastaction'] = int(time.time())
if len(config_data['heater'].keys()) == 0 or not reloading:
self.heater = {}
self.heater['mode'] = 'disabled' if 'mode' not in config_data['heater'] else config_data['heater']['mode']
self.heater['on'] = '00:00' if 'on' not in config_data['heater'] else config_data['heater']['on']
self.heater['off'] = '00:00' if 'off' not in config_data['heater'] else config_data['heater']['off']
self.heater['on_duration'] = 60.0 if 'on_duration' not in config_data['heater'] else float(config_data['heater']['on_duration'])
self.heater['off_duration'] = 60.0 if 'off_duration' not in config_data['heater'] else float(config_data['heater']['off_duration'])
self.heater['day_enabled'] = False if 'day_enabled' not in config_data['heater'] else terrariumUtils.is_true(config_data['heater']['day_enabled'])
self.heater['power_switches'] = [] if ('power_switches' not in config_data['heater'] or config_data['heater']['power_switches'] in ['',None]) else config_data['heater']['power_switches']
self.heater['sensors'] = [] if ('sensors' not in config_data['heater'] or config_data['heater']['sensors'] in ['',None]) else config_data['heater']['sensors']
if not isinstance(self.heater['power_switches'], list):
self.heater['power_switches'] = self.heater['power_switches'].split(',')
if not isinstance(self.heater['sensors'], list):
self.heater['sensors'] = self.heater['sensors'].split(',')
self.heater['enabled'] = 'disabled' != self.heater['mode']
if len(config_data['cooler'].keys()) == 0 or not reloading:
self.cooler = {}
self.cooler['mode'] = 'disabled' if 'mode' not in config_data['cooler'] else config_data['cooler']['mode']
self.cooler['on'] = '00:00' if 'on' not in config_data['cooler'] else config_data['cooler']['on']
self.cooler['off'] = '00:00' if 'off' not in config_data['cooler'] else config_data['cooler']['off']
self.cooler['on_duration'] = 60.0 if 'on_duration' not in config_data['cooler'] else float(config_data['cooler']['on_duration'])
self.cooler['off_duration'] = 60.0 if 'off_duration' not in config_data['cooler'] else float(config_data['cooler']['off_duration'])
self.cooler['night_enabled'] = False if 'night_enabled' not in config_data['cooler'] else terrariumUtils.is_true(config_data['cooler']['night_enabled'])
self.cooler['power_switches'] = [] if ('power_switches' not in config_data['cooler'] or config_data['cooler']['power_switches'] in ['',None]) else config_data['cooler']['power_switches']
self.cooler['sensors'] = [] if ('sensors' not in config_data['cooler'] or config_data['cooler']['sensors'] in ['',None]) else config_data['cooler']['sensors']
if not isinstance(self.cooler['power_switches'], list):
self.cooler['power_switches'] = self.cooler['power_switches'].split(',')
if not isinstance(self.cooler['sensors'], list):
self.cooler['sensors'] = self.cooler['sensors'].split(',')
self.cooler['enabled'] = 'disabled' != self.cooler['mode']
self.__check_available_power_switches()
self.__check_available_sensors()
self.__update_timing()
logger.info('Done %s terrariumPI Environment %.3f seconds' % ('reloading' if reloading else 'loading',
time.time()-starttime))
def __check_available_power_switches(self):
# Filter out the non existing powerswiches
self.light['power_switches'] = [switchid for switchid in self.light['power_switches'] if switchid in self.power_switches]
self.sprayer['power_switches'] = [switchid for switchid in self.sprayer['power_switches'] if switchid in self.power_switches]
self.heater['power_switches'] = [switchid for switchid in self.heater['power_switches'] if switchid in self.power_switches]
self.cooler['power_switches'] = [switchid for switchid in self.cooler['power_switches'] if switchid in self.power_switches]
self.watertank['power_switches'] = [switchid for switchid in self.watertank['power_switches'] if switchid in self.power_switches]
def __check_available_sensors(self):
# Filter out the non existing sensors
self.sprayer['sensors'] = [sensorid for sensorid in self.sprayer['sensors'] if sensorid in self.sensors]
self.heater['sensors'] = [sensorid for sensorid in self.heater['sensors'] if sensorid in self.sensors]
self.cooler['sensors'] = [sensorid for sensorid in self.cooler['sensors'] if sensorid in self.sensors]
self.watertank['sensors'] = [sensorid for sensorid in self.watertank['sensors'] if sensorid in self.sensors]
def __update_timing(self,part = None):
if part is None or part == 'light':
on_duration = self.light['on_duration']
off_duration = self.light['off_duration']
if self.light['mode'] == 'weather':
on_duration = off_duration = None
# Upate times based on weather
self.light['on'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['rise'])
self.light['off'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['set'])
# Duration check
duration = self.light['off'] - self.light['on']
# Reduce the amount of hours if to much
if self.light['max_hours'] > 0 and duration > datetime.timedelta(hours=self.light['max_hours']):
duration -= datetime.timedelta(hours=self.light['max_hours'])
self.light['on'] += datetime.timedelta(seconds=duration.total_seconds()/2)
self.light['off'] -= datetime.timedelta(seconds=duration.total_seconds()/2)
# Increase the amount of hours if to little
elif self.light['min_hours'] > 0 and duration < datetime.timedelta(hours=self.light['min_hours']):
duration = datetime.timedelta(hours=self.light['min_hours']) - duration
self.light['on'] -= datetime.timedelta(seconds=duration.total_seconds()/2)
self.light['off'] += datetime.timedelta(seconds=duration.total_seconds()/2)
# Shift hours
self.light['on'] += datetime.timedelta(hours=self.light['hours_shift'])
self.light['off'] += datetime.timedelta(hours=self.light['hours_shift'])
self.light['on'] = self.light['on'].strftime('%H:%M')
self.light['off'] = self.light['off'].strftime('%H:%M')
self.light['time_table'] = terrariumUtils.calculate_time_table(self.light['on'],self.light['off'],
on_duration,off_duration)
self.light['duration'] = terrariumUtils.duration(self.light['time_table'])
if part is None or part == 'sprayer':
self.sprayer['time_table'] = terrariumUtils.calculate_time_table(self.sprayer['on'],self.sprayer['off'],
self.sprayer['on_duration'],self.sprayer['off_duration'])
self.sprayer['duration'] = terrariumUtils.duration(self.sprayer['time_table'])
if part is None or part == 'watertank':
self.watertank['time_table'] = terrariumUtils.calculate_time_table(self.watertank['on'],self.watertank['off'],
self.watertank['on_duration'],self.watertank['off_duration'])
self.watertank['duration'] = terrariumUtils.duration(self.watertank['time_table'])
if part is None or part == 'heater':
if self.heater['mode'] == 'weather':
self.heater['on'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['set']).strftime('%H:%M')
self.heater['off'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['rise']).strftime('%H:%M')
self.heater['time_table'] = terrariumUtils.calculate_time_table(self.heater['on'],self.heater['off'],
self.heater['on_duration'],self.heater['off_duration'])
self.heater['duration'] = terrariumUtils.duration(self.heater['time_table'])
if part is None or part == 'cooler':
if self.cooler['mode'] == 'weather':
self.cooler['on'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['rise']).strftime('%H:%M')
self.cooler['off'] = datetime.datetime.fromtimestamp(self.weather.get_data()['sun']['set']).strftime('%H:%M')
self.cooler['time_table'] = terrariumUtils.calculate_time_table(self.cooler['on'],self.cooler['off'],
self.cooler['on_duration'],self.cooler['off_duration'])
self.cooler['duration'] = terrariumUtils.duration(self.cooler['time_table'])
def update_timing(self):
self.__update_timing()
def __update_environment_state(self):
self.sprayer['humidity'] = self.get_average_humidity(self.sprayer['sensors'])
self.heater['temperature'] = self.get_average_temperature(self.heater['sensors'])
self.cooler['temperature'] = self.get_average_temperature(self.cooler['sensors'])
self.watertank['distance'] = self.get_average_distance(self.watertank['sensors'])
def __engine_loop(self):
logger.info('Starting engine')
while True:
logger.debug('Environment starts new checks')
starttime = time.time()
self.__update_environment_state()
# Light checks and actions
if self.light['enabled']:
logger.debug('Environment lighting is enabled in mode %s' % self.light['mode'])
toggle_on = terrariumUtils.is_time(self.light['time_table'])
if toggle_on is None:
self.__update_timing('light')
if toggle_on:
if not self.is_light_on():
logger.info('Environment is turning on the lights based on %s' % self.light['mode'])
self.light_on()
else:
if self.is_light_on():
logger.info('Environment is turning off the lights based on %s' % self.light['mode'])
self.light_off()
#else:
# logger.debug('Make sure that the lights are off when not enabled at all.')
# if self.is_light_on():
# logger.info('Environment is turning off the lights due to disabling it')
# self.light_off()
# Sprayer checks and actions
if self.sprayer['enabled']:
toggle_on = False
extra_logging_message = ''
logger.debug('Environment spraying is enabled.')
logger.debug('Environment spraying is based on: %s' % self.sprayer['mode'])
if 'sensor' == self.sprayer['mode']:
# Only spray when the lights are on. Or when explicit enabled during the nights.
if self.sprayer['night_enabled'] or self.is_light_on():
# Spray based on the average humidity values of the used sensors
toggle_on = self.sprayer['humidity']['current'] < self.sprayer['humidity']['alarm_min']
if toggle_on:
extra_logging_message = 'Sprayer humdity value %f%% is lower then alarm %f%%.' % (self.sprayer['humidity']['current'],
self.sprayer['humidity']['alarm_min'])
else:
# Spray based on time table
toggle_on = terrariumUtils.is_time(self.sprayer['time_table'])
if toggle_on is None:
self.__update_timing('sprayer')
if toggle_on and len(self.sprayer['sensors']) > 0:
# Use the extra added sensors for finetuning the trigger action
toggle_on = self.sprayer['humidity']['current'] < self.sprayer['humidity']['alarm_min']
if toggle_on:
extra_logging_message = 'Sprayer humdity value %f%% is lower then alarm %f%%.' % (self.sprayer['humidity']['current'],
self.sprayer['humidity']['alarm_min'])
if toggle_on:
if self.is_door_open():
logger.warning('Environment could not spray for %f seconds based on %s mode because of an open door.%s' % (self.sprayer['spray_duration'],
self.sprayer['mode'],
extra_logging_message))
else:
if not self.is_sprayer_on():
logger.info('Environment is turning on the sprayer for %f seconds based on %s mode.%s' % (self.sprayer['spray_duration'],
self.sprayer['mode'],
extra_logging_message))
self.sprayer_on()
else:
if self.is_sprayer_on():
logger.info('Environment is turning off the sprayer based on %s mode.' % (self.sprayer['mode'],))
self.sprayer_off()
#else:
# logger.debug('Make sure that the spayer is off when not enabled at all.')
# if self.is_sprayer_on():
# logger.info('Environment is turning off the sprayer due to disabling it')
# self.sprayer_off()
# Watertank checks and actions
if self.watertank['enabled']:
toggle_on = False
extra_logging_message = ''
logger.debug('Environment watertank is enabled.')
logger.debug('Environment watertank is based on: %s' % self.watertank['mode'])
if 'sensor' == self.watertank['mode']:
# Spray based on the average humidity values of the used sensors
toggle_on = self.watertank['height'] - self.watertank['distance']['current'] < self.watertank['distance']['alarm_min']
if toggle_on:
extra_logging_message = 'Water tank level value %f%% is lower then alarm %f%%.' % (self.watertank['height'] - self.watertank['distance']['current'],
self.watertank['distance']['alarm_min'])
else:
# Spray based on time table
toggle_on = terrariumUtils.is_time(self.watertank['time_table'])
if toggle_on is None:
self.__update_timing('watertank')
if toggle_on and len(self.watertank['sensors']) > 0:
# Use the extra added sensors for finetuning the trigger action
toggle_on = self.watertank['height'] - self.watertank['distance']['current'] < self.watertank['distance']['alarm_min']
if toggle_on:
extra_logging_message = 'Water tank level value %f%% is lower then alarm %f%%.' % (self.watertank['height'] - self.watertank['distance']['current'],
self.watertank['distance']['alarm_min'])
if toggle_on:
if not self.is_watertank_on():
logger.info('Environment is turning on the water punt for %f seconds based on %s mode.%s' % (self.watertank['pump_duration'],
self.watertank['mode'],
extra_logging_message))
self.watertank_on()
else:
if self.is_watertank_on():
logger.info('Environment is turning off the water pump based on %s mode.' % (self.watertank['mode'],))
self.watertank_off()
#else:
# logger.debug('Make sure that the water pump is off when not enabled at all.')
# if self.is_watertank_on():
# logger.info('Environment is turning off the water pump due to disabling it')
# self.watertank_off()
# Heater checks and actions
if self.heater['enabled']:
toggle_on = None
extra_logging_message = ''
logger.debug('Environment heater is enabled.')
logger.debug('Environment heater is based on: %s' % self.heater['mode'])
if 'sensor' == self.heater['mode']:
# Only heat when the lights are off. Or when explicit enabled during the day.
if self.heater['day_enabled'] or self.is_light_off():
# Heat based on the average temperature values of the used sensors
if self.heater['temperature']['current'] < self.heater['temperature']['alarm_min']:
toggle_on = True
extra_logging_message = 'Heater temperature value %f%% is lower then alarm %f%%.' % (self.heater['temperature']['current'],
self.heater['temperature']['alarm_min'])
elif self.heater['temperature']['current'] > self.heater['temperature']['alarm_max']:
toggle_on = False
extra_logging_message = 'Heater temperature value %f%% is higher then alarm %f%%.' % (self.heater['temperature']['current'],
self.heater['temperature']['alarm_max'])
else:
# Force off when lights are on!
if self.is_heater_on():
logger.info('Environment is turning off the heater due to lights on based on %s mode.' % (self.heater['mode'],))
toggle_on = False
else:
# Heat based on time table
toggle_on = terrariumUtils.is_time(self.heater['time_table'])
if toggle_on is None:
self.__update_timing('heater')
if toggle_on and len(self.heater['sensors']) > 0:
# Reset toggle based on the extra available sensors
toggle_on = None
# Use the extra added sensors for finetuning the trigger action
if self.heater['temperature']['current'] < self.heater['temperature']['alarm_min']:
toggle_on = True
extra_logging_message = 'Heater temperature value %f%% is lower then alarm %f%%.' % (self.heater['temperature']['current'],
self.heater['temperature']['alarm_min'])
elif self.heater['temperature']['current'] > self.heater['temperature']['alarm_max']:
toggle_on = False
extra_logging_message = 'Heater temperature value %f%% is higher then alarm %f%%.' % (self.heater['temperature']['current'],
self.heater['temperature']['alarm_max'])
if toggle_on is True:
if not self.is_heater_on():
logger.info('Environment is turning on the heater based on %s mode.%s' % (self.heater['mode'],
extra_logging_message))
self.heater_on()
elif toggle_on is False:
if self.is_heater_on():
logger.info('Environment is turning off the heater based on %s mode.%s' % (self.heater['mode'],
extra_logging_message))
self.heater_off()
#else:
# logger.debug('Make sure that the heating is off when not enabled at all.')
# if self.is_heater_on():
# logger.info('Environment is turning off the heater due to disabling it')
# self.heater_off()
# Cooler checks and actions
if self.cooler['enabled']:
toggle_on = None
extra_logging_message = ''
logger.debug('Environment cooler is enabled.')
logger.debug('Environment cooler is based on: %s' % self.cooler['mode'])
if 'sensor' == self.cooler['mode']:
# Only cool when the lights are on. Or when explicit enabled during the night.
if self.cooler['night_enabled'] or self.is_light_on():
# Cooler based on the average temperature values of the used sensors
if self.cooler['temperature']['current'] < self.cooler['temperature']['alarm_min']:
toggle_on = False
extra_logging_message = 'Cooler temperature value %f%% is lower then alarm %f%%.' % (self.cooler['temperature']['current'],
self.cooler['temperature']['alarm_min'])
elif self.cooler['temperature']['current'] > self.cooler['temperature']['alarm_max']:
toggle_on = True
extra_logging_message = 'Cooler temperature value %f%% is higher then alarm %f%%.' % (self.cooler['temperature']['current'],
self.cooler['temperature']['alarm_max'])
else:
# Force off when lights are on!
if self.is_cooler_on():
logger.info('Environment is turning off the cooler due to lights on based on %s mode.' % (self.cooler['mode'],))
toggle_on = False
else:
# Cooler based on time table
toggle_on = terrariumUtils.is_time(self.cooler['time_table'])
if toggle_on is None:
self.__update_timing('cooler')
if toggle_on and len(self.cooler['sensors']) > 0:
# Reset toggle based on the extra available sensors
toggle_on = None
# Use the extra added sensors for finetuning the trigger action
if self.cooler['temperature']['current'] < self.cooler['temperature']['alarm_min']:
toggle_on = False
extra_logging_message = 'Cooler temperature value %f%% is lower then alarm %f%%.' % (self.cooler['temperature']['current'],
self.cooler['temperature']['alarm_min'])
elif self.cooler['temperature']['current'] > self.cooler['temperature']['alarm_max']:
toggle_on = True
extra_logging_message = 'Cooler temperature value %f%% is higher then alarm %f%%.' % (self.cooler['temperature']['current'],
self.cooler['temperature']['alarm_max'])
if toggle_on is True:
if not self.is_cooler_on():
logger.info('Environment is turning on the cooler based on %s mode.%s' % (self.cooler['mode'],
extra_logging_message))
self.cooler_on()
elif toggle_on is False:
if self.is_cooler_on():
logger.info('Environment is turning off the cooler based on %s mode.%s' % (self.cooler['mode'],
extra_logging_message))
self.cooler_off()
#else:
# logger.debug('Make sure that the cooler is off when not enabled at all.')
# if self.is_cooler_on():
# logger.info('Environment is turning off the cooler due to disabling it')
# self.cooler_off()
duration = time.time() - starttime
if duration < terrariumEnvironment.LOOP_TIMEOUT:
logger.info('Update done in %.5f seconds. Waiting for %.5f seconds for next round' % (duration,terrariumEnvironment.LOOP_TIMEOUT - duration))
sleep(terrariumEnvironment.LOOP_TIMEOUT - duration) # TODO: Config setting
else:
logger.warning('Update took to much time. Needed %.5f seconds which is %.5f more then the limit %s' % (duration,duration-terrariumEnvironment.LOOP_TIMEOUT,terrariumEnvironment.LOOP_TIMEOUT))
def __on_off(self,part, state = None):
power_switches = []
if 'light' == part:
power_switches = self.light['power_switches']
elif 'sprayer' == part:
power_switches = self.sprayer['power_switches']
elif 'heater' == part:
power_switches = self.heater['power_switches']
elif 'cooler' == part:
power_switches = self.cooler['power_switches']
elif 'watertank' == part:
power_switches = self.watertank['power_switches']
is_on = len(power_switches) > 0
for switch_id in power_switches:
if switch_id not in self.power_switches:
is_on = False
elif state is None:
is_on = is_on and self.power_switches[switch_id].is_on()
else:
if state:
self.power_switches[switch_id].on()
else:
self.power_switches[switch_id].off()
is_on = state
return is_on
def __switch_on(self,part):
return True == self.__on_off(part,True)
def __switch_off(self,part):
return False == self.__on_off(part,False)
def __is_on(self,part):
return self.__on_off(part) == True
def __is_off(self,part):
return not self.__is_on(part)
def __get_state(self,part,exclude_fields = []):
return_data = {}
state_data = {}
average = {}
state = False
if part == 'light':
state_data = self.light
state = self.is_light_on()
elif part == 'sprayer':
state_data = self.sprayer
average = self.get_average_humidity(self.sprayer['sensors'])
state = self.is_sprayer_on()
elif part == 'watertank':
state_data = self.watertank
average = self.get_average_distance(self.watertank['sensors'])
state = self.is_watertank_on()
# Update to Liters based on the distanes
factor = float(self.watertank['volume']) / float(self.watertank['height'])
average['current'] = (float(self.watertank['height']) - average['current']) * factor
average['alarm_max'] *= factor
average['alarm_min'] *= factor
average['limit_max'] *= factor
average['limit_min'] *= factor
elif part == 'heater':
state_data = self.heater
average = self.get_average_temperature(self.heater['sensors'])
state = self.is_heater_on()
elif part == 'cooler':
state_data = self.cooler
average = self.get_average_temperature(self.cooler['sensors'])
state = self.is_cooler_on()
for key in state_data:
if key not in exclude_fields:
return_data[key] = state_data[key]
return_data.update(average)
# Reset alarm for to high mudity and sprayer, to hot and heater, or to cool and cooling
if part != 'light':
if 'alarm' not in return_data or \
return_data['mode'] == 'disabled' or \
(part in ['sprayer','heater','watertank'] and return_data['current'] >= return_data['alarm_max']) or \
(part == 'cooler' and return_data['current'] <= return_data['alarm_max']):
return_data['alarm'] = False
return_data['state'] = 'on' if state else 'off'
return return_data
# End private functions
# System functions
def set_power_switches(self,data):
self.power_switches = data
self.__check_available_power_switches()
def set_sensors(self,data):
self.sensors = data
self.__check_available_sensors()
def get_config(self):
data = {'light' : self.get_light_config(),
'sprayer' : self.get_sprayer_config() ,
'heater' : self.get_heater_config(),
'cooler' : self.get_cooler_config(),
'watertank' : self.get_watertank_config()}
return data
def get_average_temperature(self,sensors = []):
data = self.get_average(sensors)
if 'temperature' in data:
return data['temperature']
return {'current' : 0.0,
'alarm_min' : 0.0,
'alarm_max' : 0.0,
'limit_min' : 0.0,
'limit_max' : 0.0,
'amount' : 0.0,
'alarm' : False}
def get_average_humidity(self,sensors = []):
data = self.get_average(sensors)
if 'humidity' in data:
return data['humidity']
return {'current' : 0.0,
'alarm_min' : 0.0,
'alarm_max' : 0.0,
'limit_min' : 0.0,
'limit_max' : 0.0,
'amount' : 0.0,
'alarm' : False}
def get_average_distance(self,sensors = []):
data = self.get_average(sensors)
if 'distance' in data:
return data['distance']
return {'current' : 0.0,
'alarm_min' : 0.0,
'alarm_max' : 0.0,
'limit_min' : 0.0,
'limit_max' : 0.0,
'amount' : 0.0,
'alarm' : False}
def get_average(self,sensors_filter = []):
average = {}
# Make a set, in order to get a list of unique sensorids. In other words, set will remove duplicate sensorids
for sensorid in set(self.sprayer['sensors'] + self.heater['sensors'] + self.cooler['sensors'] + self.watertank['sensors']):
if len(sensors_filter) > 0 and sensorid not in sensors_filter:
# If we want to filter, we only count the ones that are giving as parameter
continue
if sensorid not in self.sensors:
part = ''
if sensorid in self.sprayer['sensors']:
part += 'sprayer,'
if sensorid in self.heater['sensors']:
part += 'heater,'
if sensorid in self.cooler['sensors']:
part += 'cooler,'
if sensorid in self.watertank['sensors']:
part += 'watertank,'
part = part[:-1]
logger.error('Error getting average data from sensor with id %s. Sensor is specified in \'%s\' part, but the sensor is not known anymore in confg' % (sensorid,part))
continue
sensor = self.sensors[sensorid]
sensor_type = sensor.get_type()
if sensor_type not in average:
average[sensor_type] = {'current' : 0.0,
'alarm_min' : 0.0,
'alarm_max' : 0.0,
'limit_min' : 0.0,
'limit_max' : 0.0,
'amount' : 0.0,
'alarm' : False}
average[sensor_type]['current'] += sensor.get_current()
average[sensor_type]['alarm_min'] += sensor.get_alarm_min()
average[sensor_type]['alarm_max'] += sensor.get_alarm_max()
average[sensor_type]['limit_min'] += sensor.get_limit_min()
average[sensor_type]['limit_max'] += sensor.get_limit_max()
average[sensor_type]['amount'] += 1
for averagetype in average:
amount = average[averagetype]['amount']
del(average[averagetype]['amount'])
for field in average[averagetype]:
average[averagetype][field] /= amount
average[averagetype]['alarm'] = not (average[averagetype]['alarm_min'] <= average[averagetype]['current'] <= average[averagetype]['alarm_max'])
average[averagetype]['type'] = averagetype
#average[averagetype]['indicator'] = self.__unit_type(averagetype)
return average
# End system functions
# Light functions
def get_light_config(self):
return self.__get_state('light',['time_table','enabled','state','duration'])
def set_light_config(self,data):
self.__set_config('light',data)
def get_light_state(self):
cleanup_fields = []
if 'weather' == self.light['mode']:
cleanup_fields = ['on_duration','off_duration','time_table']
elif 'timer' == self.light['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift']
return self.__get_state('light',cleanup_fields)
def light_on(self):
return self.__switch_on('light')
def light_off(self):
return self.__switch_off('light')
def is_light_on(self):
return self.__is_on('light')
def is_light_off(self):
return self.__is_off('light')
# End light functions
# Sprayer functions
def get_sprayer_config(self):
return self.__get_state('sprayer',['time_table','enabled','state','lastaction','duration'])
def set_sprayer_config(self,data):
self.__set_config('sprayer',data)
def get_sprayer_state(self):
cleanup_fields = []
if 'weather' == self.sprayer['mode']:
cleanup_fields = ['on_duration','off_duration','time_table']
elif 'timer' == self.sprayer['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift']
elif 'sensor' == self.sprayer['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift','time_table']
return self.__get_state('sprayer',cleanup_fields)
def sprayer_on(self):
if int(time.time()) - self.sprayer['lastaction'] > self.sprayer['spray_timeout']:
self.__switch_on('sprayer')
(Timer(self.sprayer['spray_duration'], self.sprayer_off)).start()
self.sprayer['lastaction'] = int(time.time())
def sprayer_off(self):
self.__switch_off('sprayer')
def is_sprayer_on(self):
return self.__is_on('sprayer')
def is_sprayer_off(self):
return self.__is_off('sprayer')
# End sprayer functions
# Watertank functions
def get_watertank_config(self):
return self.__get_state('watertank',['time_table','enabled','state','lastaction','duration'])
def set_watertank_config(self,data):
self.__set_config('watertank',data)
def get_watertank_state(self):
cleanup_fields = []
if 'weather' == self.watertank['mode']:
cleanup_fields = ['on_duration','off_duration','time_table']
elif 'timer' == self.watertank['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift']
elif 'sensor' == self.watertank['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift','time_table']
return self.__get_state('watertank',cleanup_fields)
def watertank_on(self):
# if int(time.time()) - self.watertank['lastaction'] > self.watertank['spray_timeout']:
self.__switch_on('watertank')
(Timer(self.watertank['pump_duration'], self.watertank_off)).start()
self.watertank['lastaction'] = int(time.time())
def watertank_off(self):
self.__switch_off('watertank')
def is_watertank_on(self):
return self.__is_on('watertank')
def is_watertank_off(self):
return self.__is_off('watertank')
# End watertank functions
# Heater functions
def get_heater_config(self):
return self.__get_state('heater',['time_table','enabled','state','duration'])
def set_heater_config(self,data):
self.__set_config('heater',data)
def get_heater_state(self):
cleanup_fields = []
if 'weather' == self.heater['mode']:
cleanup_fields = ['on_duration','off_duration','time_table']
elif 'timer' == self.heater['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift']
elif 'sensor' == self.heater['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift','time_table']
return self.__get_state('heater',cleanup_fields)
def heater_on(self):
self.__switch_on('heater')
def heater_off(self):
self.__switch_off('heater')
def is_heater_on(self):
return self.__is_on('heater')
def is_heater_off(self):
return self.__is_off('heater')
# End heater functions
# Cooler functions
def get_cooler_config(self):
return self.__get_state('cooler',['time_table','enabled','state','duration'])
def set_cooler_config(self,data):
self.__set_config('cooler',data)
def get_cooler_state(self):
cleanup_fields = []
if 'weather' == self.cooler['mode']:
cleanup_fields = ['on_duration','off_duration','time_table']
elif 'timer' == self.cooler['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift']
elif 'sensor' == self.cooler['mode']:
cleanup_fields = ['min_hours','max_hours','hours_shift','time_table']
return self.__get_state('cooler',cleanup_fields)
def cooler_on(self):
self.__switch_on('cooler')
def cooler_off(self):
self.__switch_off('cooler')
def is_cooler_on(self):
return self.__is_on('cooler')
def is_cooler_off(self):
return self.__is_off('cooler')
# End cooler functions