-
Notifications
You must be signed in to change notification settings - Fork 0
/
greenhouse.py
1880 lines (1647 loc) · 89.3 KB
/
greenhouse.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""Greenhouse Controller
Reads the configuration from an associated xml file.
Presents a set of webpages to display the temperature.
Controls the temperature of the propagator using a sensor (typically inserted
into the soil).
"""
import csv
import datetime
from email.mime.text import MIMEText
import math
import os
import smtplib
import sys
import threading
import time
import xml.etree.ElementTree as ET
import astral # V1.10.1
from flask import Flask, render_template, request
from influxdb import InfluxDBClient
import RPi.GPIO as GPIO
from w1thermsensor import W1ThermSensor
import am2320
import bh1750
from max31855 import MAX31855, MAX31855Error
# Read CPU temperature
def measure_cpu_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return (temp.replace("temp=","").replace("'C\n",""))
# Debug logging
def debug_log(log_string):
if (debug_logging == "Enabled"):
print(log_string)
debug_file = open(debug_filename, "a")
debug_file.write(log_string + "\n")
debug_file.close()
# Display config
def print_config():
print("Configuration:")
print(" Installation location:")
print(" City = " + city)
print(" Country = " + country)
print(" Time Zone = " + zone)
print(" Lat/Long = " + str(lat) + "/" + str(lon) + ", Elevation = " + str(elev))
print(" Temperature thermocouples:")
for cs_pin, relay_pin, cal, meas, name, status in zip(
propagator_cs_pins,
propagator_relay_pins,
propagator_calibrate,
propagator_measured,
propagator_channel_names,
propagator_enabled):
print(" Propagator: " + name)
print(" > Chip Select = " + str(cs_pin))
print(" > Relay = " + str(relay_pin))
print(" > Calibration = " + str(meas) + "\u00B0C at " + str(cal)
+ "\u00B0C")
print(" > Status = " + status)
for count in temperature_schedule:
print(" From " + str(temperature_schedule[count]["time"]) +
": " + str(temperature_schedule[count]["temp"]) + "\u00B0C")
print(" Air heating:")
print(" > Relay = " + str(air_heating_relay_pin))
print(" > Calibration = " + str(air_measured) + "\u00B0C at " +
str(air_calibrate) + "\u00B0C")
print(" > Status = " + air_enabled)
for count in air_temperature_schedule:
print(" From " + str(air_temperature_schedule[count]["time"]) +
": " + str(air_temperature_schedule[count]["temp"]) + "\u00B0C")
print(" Humidity:")
print(" > Temperature Calibration = " + str(humidity_temp_measured)
+ "\u00B0C at " + str(humidity_temp_calibrate) + "\u00B0C")
print(" > Humidity Calibration = " + str(humidity_humidity_measured)
+ "%RH at " + str(humidity_humidity_calibrate) + "%RH")
print(" Lighting:")
print(" Mode = " + lighting_mode)
if (lighting_mode == "SimulateSunrise"):
print(" Days offset = " + str(lighting_sunrise_offset))
for relay_pin, on_lux, hysteresis, name, status in zip(
lighting_relay_pins,
lighting_on_lux,
lighting_hysteresis,
lighting_channel_names,
lighting_enabled):
print(" Light: " + name)
print(" > Relay = " + str(relay_pin))
print(" > On Lux = " + str(on_lux))
print(" > Hysteresis = " + str (hysteresis))
print(" > Status = " + status)
for count in lighting_schedule:
print(" From " + str(lighting_schedule[count]["time"]) +
": " + str(lighting_schedule[count]["status"]))
print(" Lighting induced temperature offset = " + lighting_temperature_offset)
print(" Logging " + log_status + " at " + str(log_interval)
+ " second interval")
print(" Log CSV = " + log_CSV)
print(" Log Database = " + log_database)
print(" Units = " + units)
print(" Title = " + title)
# Test the hardware
def hardware_test():
test_wait = 4 # Number of seconds between each state change
print("Hardware test.")
print(" > Propagators")
GPIO.setmode(GPIO.BOARD)
for relay_pin in propagator_relay_pins:
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.LOW)
thermocouples = []
for cs_pin in propagator_cs_pins:
thermocouples.append(MAX31855(cs_pin, spi_clock_pin,
spi_data_pin, units,
GPIO.BOARD))
channel = 1
for thermocouple, relay_pin, cal, meas, enabled in zip \
(thermocouples,
propagator_relay_pins,
propagator_calibrate,
propagator_measured,
propagator_enabled):
print(" " + str(channel) + ": " + propagators[channel]["name"])
controller_temp = thermocouple.get_rj()
try:
tc = thermocouple.get() + cal - meas
if (controller_temp == 0) and (thermocouple.get() == 0):
print(" ** Possible interface error - all bits read 0")
except MAX31855Error as e:
tc = "Error: " + e.value
print(" MAX31855 temperature = " + str(controller_temp)
+ "\u00B0C")
print(" Thermocouple temperature = " + str(tc) + "\u00B0C")
print(" Thermocouple calibration = "
+ '{0:+g}'.format(cal - meas)
+ "\u00B0C (included in above temperature)")
GPIO.output(relay_pin, GPIO.HIGH)
print(" Propagator heating relay On")
time.sleep(test_wait)
GPIO.output(relay_pin, GPIO.LOW)
print(" Propagator heating relay Off")
time.sleep(test_wait)
channel = channel + 1
print(" > Air heating")
GPIO.setup(air_heating_relay_pin, GPIO.OUT)
GPIO.output(air_heating_relay_pin, GPIO.LOW)
try:
sensor = W1ThermSensor() # Assumes just one sensor available
sensor_detect = "Detected"
except:
sensor_detect = "Detect Error"
if sensor_detect == "Detected":
try:
air_temperature = sensor.get_temperature() \
+ air_calibrate - air_measured
except:
air_temperature = "Get temperature Error"
print(" Air temperature = " + str(air_temperature)+ "\u00B0C")
print(" Air temperature calibration = "
+ '{0:+g}'.format(air_calibrate - air_measured)
+ "\u00B0C (included in above temperature)")
else:
print(" Failed to detect sensor")
GPIO.output(air_heating_relay_pin, GPIO.HIGH)
print(" Air heating relay On")
time.sleep(test_wait)
GPIO.output(air_heating_relay_pin, GPIO.LOW)
print(" Air heating relay Off")
time.sleep(test_wait)
print(" > Lighting")
for relay_pin in lighting_relay_pins:
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.LOW)
light_sensor = bh1750.BH1750()
channel = 1
try:
current_lux = light_sensor.get_light_mode()
except:
current_lux = "Error"
print(" Current lux = " + str(current_lux))
for relay_pin in lighting_relay_pins:
print(" " + str(channel) + ": " + lighting[channel]["name"])
GPIO.output(relay_pin, GPIO.HIGH)
print(" Lighting relay On")
time.sleep(test_wait)
GPIO.output(relay_pin, GPIO.LOW)
print(" Lighting relay Off")
time.sleep(test_wait)
channel = channel + 1
print(" > Humidity sensor")
airtemp_humidity_sensor = am2320.AM2320()
try:
airtemp_humidity_sensor.get_data()
print(" Air temp: " +
str(airtemp_humidity_sensor.temperature) +
"\u00B0C")
print(" Humidity: " +
str(airtemp_humidity_sensor.humidity) + "%RH")
except am2320.AM2320Error as e:
print(" Humidity sensor error: " + e.value)
if test is not None:
print(" > Unused hardware")
for relay_pin in unused_relay_pins:
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.LOW)
channel = 1
for relay_pin, channel_name in zip(unused_relay_pins,
unused_channel_names):
print(" " + str(channel) + ": " + channel_name)
GPIO.output(relay_pin, GPIO.HIGH)
print(" Unused relay On")
time.sleep(test_wait)
GPIO.output(relay_pin, GPIO.LOW)
print(" Unused relay Off")
time.sleep(test_wait)
channel = channel + 1
print(" > All relays")
for relay_pin in propagator_relay_pins:
GPIO.output(relay_pin, GPIO.HIGH)
GPIO.output(air_heating_relay_pin, GPIO.HIGH)
for relay_pin in lighting_relay_pins:
GPIO.output(relay_pin, GPIO.HIGH)
if test is not None:
for relay_pin in unused_relay_pins:
GPIO.output(relay_pin, GPIO.HIGH)
print(" All relays On")
time.sleep(test_wait)
for relay_pin in propagator_relay_pins:
GPIO.output(relay_pin, GPIO.LOW)
GPIO.output(air_heating_relay_pin, GPIO.LOW)
for relay_pin in lighting_relay_pins:
GPIO.output(relay_pin, GPIO.LOW)
if test is not None:
for relay_pin in unused_relay_pins:
GPIO.output(relay_pin, GPIO.LOW)
print(" All relays Off")
time.sleep(test_wait)
GPIO.cleanup()
# Propagator heater control code: if the temperature is too cold then turn the
# heater on (typically using a relay), else turn it off.
class PropagatorHeaterThread(threading.Thread):
def run(self):
global propagators
global controller_temp
global propagator_set_temperature
MAX_VARIANCE = 0.5 # Maximum permitted change per measurement cycle
MAX_ERROR_STATE = 3 # Maximum consecutive error states before heater
# turned off
GPIO.setmode(GPIO.BOARD)
debug_log("Starting propagator heater thread")
for relay_pin in propagator_relay_pins:
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.LOW)
try:
while 1: # Control the heater forever while powered
thermocouples = []
debug_log("")
debug_log("Measuring propagator temperature... %s" %
(time.ctime(time.time())))
now = datetime.datetime.now().time()
propagator_set_temperature = temperature_schedule[1]["temp"]
# Default to the first timed temperature
for count in temperature_schedule:
if (now >= temperature_schedule[count]["time"]):
propagator_set_temperature = temperature_schedule \
[count]["temp"]
# Keep selecting a new temperature if the time is
# later than the start of the time schedule
channel = 1
for cs_pin in propagator_cs_pins:
thermocouples.append(MAX31855(cs_pin, spi_clock_pin,
spi_data_pin, units,
GPIO.BOARD))
for thermocouple, relay_pin, cal, meas, enabled in zip \
(thermocouples,
propagator_relay_pins,
propagator_calibrate,
propagator_measured,
propagator_enabled):
if (channel == 1):
controller_temp = thermocouple.get_rj()
if (enabled == "Enabled"):
try:
tc = thermocouple.get() + cal - meas
debug_log(str(channel) + ": Raw measured (calibrated) temperature = " + str(tc))
if ((propagators[channel]["lighting_turn_on"] == True) \
and (lighting_temperature_offset \
== "Enabled")):
# The lighting has just come on and
# offset needs calculating
debug_log(str(channel) + ": LO count = " + str(propagators[channel]["light_on_count"]))
if propagators[channel]["light_on_count"] == 0:
if IsFloat(propagators[channel]["no_lights_temp"]):
propagators[channel]["offset_temp"] \
= propagators[channel]["no_lights_temp"] \
- tc
else:
propagators[channel]["offset_temp"] = 0
# Cannot calculate an offset if
# there is no last temp
propagators[channel]["lighting_turn_on"] \
= False
debug_log(str(channel) + ": Temp offset caused by lighting = " \
+ str(propagators[channel]["offset_temp"]))
else:
propagators[channel]["light_on_count"] = propagators[channel]["light_on_count"] - 1
if ((lighting_temperature_offset == "Enabled") \
and (any_lighting == True)):
# The lighting is on and offset needs
# calculating
tc = tc + propagators[channel]["offset_temp"]
debug_log(str(channel) + ": Added offset caused by lighting")
if propagators[channel]["last_temp"] == "None":
# No measurement recorded yet so this is
# the first measurement
debug_log(str(channel) + ": Set temperature to first measurement")
propagators[channel]["temp"] = tc
propagators[channel]["last_temp"] = tc
else:
if abs(tc - propagators[channel]["last_temp"]) \
<= MAX_VARIANCE:
# Change in measurement acceptable
propagators[channel]["temp"] = tc
propagators[channel]["last_temp"] =\
tc
else:
# Allow recorded temperature to
# change by the acceptable variance
# from the last valid temperature
debug_log(str(channel) + ": Max variance exceeded: " \
+ str(tc - propagators[channel]["last_temp"]) \
+ "\u00B0C")
propagators[channel]["temp"] = \
propagators[channel]["last_temp"] \
+ math.copysign(MAX_VARIANCE,\
tc - propagators[channel]["last_temp"])
propagators[channel]["last_temp"] = \
propagators[channel]["temp"]
if IsFloat(propagators[channel]["min_temperature"]):
if (propagators[channel]["temp"]
< propagators[channel]["min_temperature"]):
propagators[channel]["min_temperature"] = \
propagators[channel]["temp"]
else:
# Min temperature is not defined
propagators[channel]["min_temperature"] = \
propagators[channel]["temp"]
if IsFloat(propagators[channel]["max_temperature"]):
if (propagators[channel]["temp"]
> propagators[channel]["max_temperature"]):
propagators[channel]["max_temperature"] = \
propagators[channel]["temp"]
else:
# Max temperature is not defined
propagators[channel]["max_temperature"] = \
propagators[channel]["temp"]
propagators[channel]["error_count"] = 0
propagators[channel]["sensor_error"] = False
propagators[channel]["sensor_alert"] = False
except MAX31855Error as e:
tc = "Error"
propagators[channel]["temp"] = "Error: " \
+ e.value
propagators[channel]["sensor_error"] = True
if (log_status == "On"):
propagators[channel]["log_error_count"] = \
propagators[channel]["log_error_count"]+1
debug_log(str(channel) \
+ ": Log error count = " \
+ str(propagators[channel]["log_error_count"]))
if (propagators[channel]["error_count"] \
< alert_sensor):
propagators[channel]["error_count"] = \
propagators[channel]["error_count"]+1
if ((propagators[channel]["error_count"]
>= alert_sensor)
and
((propagators[channel]["sensor_alert"] == False))):
add_email("Propagator sensor failed "
+ propagators[channel]["name"] + ".")
propagators[channel]["sensor_alert"] = True
debug_log(str(channel) + ": Measured Temperature: " + str(tc)
+ "\u00B0C; Recorded Temperature: "
+ str(propagators[channel]["temp"])
+ "\u00B0C. Set Temperature: "
+ str(propagator_set_temperature)
+ "\u00B0C")
debug_log(str(channel) + ": Min: "
+ str(propagators[channel]["min_temperature"])
+ ", Max: "
+ str(propagators[channel]["max_temperature"]))
if tc == "Error":
if propagators[channel]["error_count"] \
> MAX_ERROR_STATE:
GPIO.output(relay_pin, GPIO.LOW)
# Turn off Relay (fault condition -
# avoid overheating)
if propagators[channel]["heater_state"] \
== "On":
propagators[channel]["relay_activation"] =\
propagators[channel]["relay_activation"] + 1
if propagators[channel]["relay_count"] == 0:
propagators[channel]["consecutive_change"] =\
propagators[channel]["consecutive_change"] + 1
propagators[channel]["relay_count"] = 0
else:
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
propagators[channel]["heater_state"] \
= "Error: Off"
if log_status == "On":
propagators[channel]["log_off"] = \
propagators[channel]["log_off"]+1
debug_log(str(channel) + ": Error: Propagator relay off")
else:
# Maintain heater in current state for
# a short while (assume the temperature
# has not changed much)
debug_log(str(channel) + ": Error: Propagator relay state maintained")
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
if log_status == "On":
if propagators[channel]["heater_state"] \
== "On":
propagators[channel]["log_on"] = \
propagators[channel]["log_on"]+1
else:
propagators[channel]["log_off"] = \
propagators[channel]["log_off"]+1
else:
if propagators[channel]["relay_count"] >= MIN_RELAY_CHANGE:
if propagators[channel]["temp"] \
< propagator_set_temperature:
GPIO.output(relay_pin, GPIO.HIGH)
# Turn on relay
if propagators[channel]["heater_state"] \
!= "On":
propagators[channel]["relay_activation"] =\
propagators[channel]["relay_activation"] + 1
if propagators[channel]["relay_count"] == 0:
propagators[channel]["consecutive_change"] =\
propagators[channel]["consecutive_change"] + 1
propagators[channel]["relay_count"] = 0
else:
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
propagators[channel]["heater_state"] \
= "On"
if (log_status == "On"):
propagators[channel]["log_on"] = \
propagators[channel]["log_on"]+1
debug_log(str(channel) + ": Propagator relay on")
else:
GPIO.output(relay_pin, GPIO.LOW)
# Turn off relay
if propagators[channel]["heater_state"] \
== "On":
propagators[channel]["relay_activation"] =\
propagators[channel]["relay_activation"] + 1
if propagators[channel]["relay_count"] == 0:
propagators[channel]["consecutive_change"] =\
propagators[channel]["consecutive_change"] + 1
propagators[channel]["relay_count"] = 0
else:
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
propagators[channel]["heater_state"] \
= "Off"
if (log_status == "On"):
propagators[channel]["log_off"] = \
propagators[channel]["log_off"]+1
debug_log(str(channel) + ": Propagator relay off")
else:
# Relay state changed recently
debug_log(str(channel) + ": Propagator relay state maintained - recently activated")
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
if (propagators[channel]["temp"]
>= alert_propagator_temp):
if (propagators[channel]["alert_state"] == "None"):
add_email("Greenhouse high propagator temperature alert - "
+ propagators[channel]["name"]
+ ". Temperature = "
+ str(propagators[channel]["temp"])
+ "\u00B0C.")
debug_log(str(channel) + ": High temperature alert e-mail sent")
propagators[channel]["alert_state"] = "Alerted"
if (propagators[channel]["temp"]
< (alert_propagator_temp - alert_hysteresis)):
propagators[channel]["alert_state"] = "None"
else:
# Propagator is disabled
GPIO.output(relay_pin, GPIO.LOW)
# Turn off relay
if propagators[channel]["heater_state"] \
== "On":
propagators[channel]["relay_activation"] =\
propagators[channel]["relay_activation"] + 1
if propagators[channel]["relay_count"] == 0:
propagators[channel]["consecutive_change"] =\
propagators[channel]["consecutive_change"] + 1
propagators[channel]["relay_count"] = 0
else:
propagators[channel]["relay_count"] =\
propagators[channel]["relay_count"] + 1
propagators[channel]["heater_state"] = "Off"
if (log_status == "On"):
propagators[channel]["log_off"] = \
propagators[channel]["log_off"] + 1
debug_log(str(channel) + ": Propagator disabled - Relay off")
channel = channel + 1
for thermocouple in thermocouples:
thermocouple.cleanup()
time.sleep(control_interval)
except KeyboardInterrupt:
GPIO.cleanup()
# Air heater control code: if the temperature is too cold then turn the
# heater on (typically using a relay), else turn it off.
class AirHeaterThread(threading.Thread):
def run(self):
global air_heater_state
global air_log_on
global air_log_off
global air_set_temperature
global heating_air_temp
global air_relay_activation
global air_relay_count
global air_consecutive_change
debug_log("Starting air heating thread")
sensor_detect = "Unknown"
air_temperature_error_count = 0
air_temperature_sensor_error = False
air_temperature_sensor_alert = False
while sensor_detect != "Detected":
try:
sensor = W1ThermSensor() # Assumes just one sensor available
sensor_detect = "Detected"
except:
sensor_detect = "Detect Error"
debug_log("No air heating sensor detected")
air_temperature = "No sensor"
if (air_temperature_error_count < alert_sensor):
air_temperature_error_count = \
air_temperature_error_count + 1
if ((air_temperature_error_count >= alert_sensor) \
and \
(air_temperature_sensor_alert == False)):
add_email("No air heating sensor detected.")
air_temperature_sensor_alert = True
time.sleep(control_interval)
sensor = W1ThermSensor() # Assumes just one sensor available
air_temperature_error_count = 0
air_temperature_sensor_error = False
air_temperature_sensor_alert = False
GPIO.setmode(GPIO.BOARD)
GPIO.setup(air_heating_relay_pin, GPIO.OUT)
GPIO.setup(unused_relay_pins[1], GPIO.OUT) # Temp until relay replaced
GPIO.output(air_heating_relay_pin, GPIO.LOW)
GPIO.output(unused_relay_pins[1], GPIO.LOW) # Temp until relay replaced
try:
while 1: # Control the air heating forever while powered
debug_log("")
debug_log("Measuring air temperature... %s" %
(time.ctime(time.time())))
now = datetime.datetime.now().time()
air_set_temperature = air_temperature_schedule[1]["temp"]
# Default to the first timed temperature
for count in air_temperature_schedule:
if (now >= air_temperature_schedule[count]["time"]):
air_set_temperature = air_temperature_schedule \
[count]["temp"]
# Keep selecting a new temperature if the time is
# later than the start of the time schedule
if (air_enabled == "Enabled"):
try:
air_temperature = sensor.get_temperature() \
+ air_calibrate - air_measured
air_temperature_error_count = 0
air_temperature_sensor_error = False
air_temperature_sensor_alert = False
heating_air_temp = air_temperature
debug_log("Air temperature: " +
"{0:+.1f}".format(air_temperature) +
"\u00B0C")
except:
air_temperature = "Error"
heating_air_temp = "Error"
air_temperature_sensor_error = True
# Improve error handling to see what error the
# sensor returns and add to heating_air_temp
if (air_temperature_error_count < alert_sensor):
air_temperature_error_count = \
air_temperature_error_count + 1
if ((air_temperature_error_count >= alert_sensor) \
and \
(air_temperature_sensor_alert == False)):
add_email("Air heater sensor failed.")
air_temperature_sensor_alert = True
debug_log("Air temperature: " + str(air_temperature))
if air_temperature == "Error":
GPIO.output(air_heating_relay_pin, GPIO.LOW)
GPIO.output(unused_relay_pins[1], GPIO.LOW) # Temp until relay replaced
if air_heater_state == "On":
air_relay_activation = \
air_relay_activation + 1
if air_relay_count == 0:
air_consecutive_change =\
air_consecutive_change + 1
air_relay_count = 0
else:
air_relay_count = air_relay_count + 1
# Turn off relay (fault condition -
# avoid overheating)
air_heater_state = "Off"
if (log_status == "On"):
air_log_off = air_log_off + 1
debug_log("Error: Air heating relay off")
else:
if air_relay_count >= MIN_RELAY_CHANGE:
if air_temperature < air_set_temperature:
# Turn air heater relay on
GPIO.output(air_heating_relay_pin, GPIO.HIGH)
GPIO.output(unused_relay_pins[1], GPIO.HIGH) # Temp until relay replaced
# Turn on relay
if air_heater_state != "On":
air_relay_activation = \
air_relay_activation + 1
if air_relay_count == 0:
air_consecutive_change =\
air_consecutive_change + 1
air_relay_count = 0
else:
air_relay_count = air_relay_count + 1
air_heater_state = "On"
if (log_status == "On"):
air_log_on = air_log_on + 1
debug_log("Air heating relay on")
else:
GPIO.output(air_heating_relay_pin, GPIO.LOW)
GPIO.output(unused_relay_pins[1], GPIO.LOW) # Temp until relay replaced
# Turn off relay
if air_heater_state == "On":
air_relay_activation = \
air_relay_activation + 1
if air_relay_count == 0:
air_consecutive_change =\
air_consecutive_change + 1
air_relay_count = 0
else:
air_relay_count = air_relay_count + 1
air_heater_state = "Off"
if (log_status == "On"):
air_log_off = air_log_off + 1
debug_log("Air heating relay off")
else:
# Relay state changed recently
debug_log(str(channel) + ": Air heater relay state maintained - recently activated")
air_relay_count = air_relay_count + 1
else:
# Air heating disabled
GPIO.output(air_heating_relay_pin, GPIO.LOW)
GPIO.output(unused_relay_pins[1], GPIO.LOW) # Temp until relay replaced
# Turn off relay
if air_heater_state == "On":
air_relay_activation = \
air_relay_activation + 1
if air_relay_count == 0:
air_consecutive_change =\
air_consecutive_change + 1
air_relay_count = 0
else:
air_relay_count = air_relay_count + 1
air_heater_state = "Disabled - Off"
heating_air_temp = "Not measured"
if (log_status == "On"):
air_log_off = air_log_off + 1
debug_log("Air heating disabled - relay off")
time.sleep(control_interval)
except KeyboardInterrupt:
GPIO.cleanup()
# Lighting control code: on a schedule, if the light level is low then turn the
# lighting on (typically using a relay), else turn it off.
def lighting_turn_on():
LIGHT_ON_ASSESSMENT = 5
channel = 1
for child in propagator_sensors:
propagators[channel]["no_lights_temp"] = propagators[channel]["last_temp"]
propagators[channel]["light_on_count"] = LIGHT_ON_ASSESSMENT # No. of measurements before assessment
propagators[channel]["lighting_turn_on"] = True
channel = channel + 1
# Calculate today's simulated sunrise
def lighting_sunrise():
today = datetime.date.today()
future = today + datetime.timedelta(days=lighting_sunrise_offset)
# Lighting simulates an earlier spring, i.e. some days in the future
sunToday = location.sun(local=True, date=today)
debug_log('Sunrise: %s' % str(sunToday['sunrise']))
debug_log('Sunset: %s' % str(sunToday['sunset']))
debug_log('Day Length: %s' % str(sunToday['sunset']-sunToday["sunrise"]))
sunFuture = location.sun(local=True, date=future)
desiredLength = sunFuture["sunset"]-sunFuture["sunrise"]
todayLength = sunToday["sunset"]-sunToday["sunrise"]
simulatedSunrise = sunToday["sunset"] - desiredLength
debug_log('Simulated sunrise: %s' % str(simulatedSunrise))
debug_log('Simulated day Length: %s' % str(sunToday['sunset']-simulatedSunrise))
return (simulatedSunrise.time())
class LightingThread(threading.Thread):
def run(self):
global lighting
global light_level
global any_lighting
GPIO.setmode(GPIO.BOARD)
debug_log("Starting lighting thread")
for relay_pin in lighting_relay_pins:
GPIO.setup(relay_pin, GPIO.OUT)
GPIO.output(relay_pin, GPIO.LOW)
light_sensor = bh1750.BH1750()
sensor_error = False
error_count = 0
sensor_alert = False
if (lighting_mode == "SimulateSunrise"):
lighting_schedule[2]["time"] = lighting_sunrise() # Get initial sunrise simulation
sunrise_calculated = datetime.date.today()
try:
while 1: # Control the lighting forever while powered
debug_log("")
debug_log("Measuring light... %s" %
(time.ctime(time.time())))
channel = 1
lights = "Off" # Assume off initially; will be set to On if
# any lights are on
try:
current_lux = light_sensor.get_light_mode()
light_level = current_lux
error_count = 0
sensor_error = False
sensor_alert = False
except:
debug_log("Light sensor error")
light_level = "Error"
current_lux = 0 # Define illumination as pitch black.
# If the light sensor fails then the lights will be
# turned on for the defined timer duration irrespective
# of actual illumination.
sensor_error = True
if (error_count < alert_sensor):
error_count = error_count + 1
if ((error_count >= alert_sensor)
and (sensor_alert == False)):
add_email("Light sensor failed.")
sensor_alert = True
now = datetime.datetime.now().time()
if (lighting_mode == "SimulateSunrise"):
if (datetime.date.today() > sunrise_calculated):
debug_log("Recalculate sunrise")
lighting_schedule[2]["time"] = lighting_sunrise() # Get initial sunrise simulation
sunrise_calculated = datetime.date.today()
set_status = lighting_schedule[1]["status"]
# Default to the first timed status
for count in lighting_schedule:
if (now >= lighting_schedule[count]["time"]):
set_status = lighting_schedule[count]["status"]
# Keep selecting a new status if the time is
# later than the start of the time schedule
debug_log("Light level: " +
"{0:.1f}".format(current_lux) + " lux")
for relay_pin, on_lux, hysteresis, status, enabled in zip(
lighting_relay_pins,
lighting_on_lux,
lighting_hysteresis,
lighting_status,
lighting_enabled):
if (enabled == "Enabled"):
if (set_status == "On"):
if (current_lux < on_lux):
status = "On"
lights = "On" # Any lights are on
# Turn on relay
GPIO.output(relay_pin, GPIO.HIGH)
if lighting[channel]["light_state"] != "On":
lighting_turn_on()
if lighting[channel]["light_state"] \
!= "On":
lighting[channel]["relay_activation"] =\
lighting[channel]["relay_activation"] + 1
if lighting[channel]["relay_count"] == 0:
lighting[channel]["consecutive_change"] =\
lighting[channel]["consecutive_change"] + 1
lighting[channel]["relay_count"] = 0
else:
lighting[channel]["relay_count"] =\
lighting[channel]["relay_count"] + 1
lighting[channel]["light_state"] = "On"
if (log_status == "On"):
lighting[channel]["log_on"] = \
lighting[channel]["log_on"]+1
debug_log("Light relay on")
elif (current_lux > (on_lux + hysteresis)):
status = "Off"
# Turn off relay
GPIO.output(relay_pin, GPIO.LOW)
if lighting[channel]["light_state"] \
== "On":
lighting[channel]["relay_activation"] =\
lighting[channel]["relay_activation"] + 1
if lighting[channel]["relay_count"] == 0:
lighting[channel]["consecutive_change"] =\
lighting[channel]["consecutive_change"] + 1
lighting[channel]["relay_count"] = 0
else:
lighting[channel]["relay_count"] =\
lighting[channel]["relay_count"] + 1
lighting[channel]["light_state"] = "Off"
if (log_status == "On"):
lighting[channel]["log_off"] = \
lighting[channel]["log_off"]+1
debug_log("Light relay off")
else:
debug_log("Light level within state change hysteresis")
else:
# set_status should be Off (but not checked)
GPIO.output(relay_pin, GPIO.LOW)
if lighting[channel]["light_state"] \
== "On":
lighting[channel]["relay_activation"] =\
lighting[channel]["relay_activation"] + 1
if lighting[channel]["relay_count"] == 0:
lighting[channel]["consecutive_change"] =\
lighting[channel]["consecutive_change"] + 1
lighting[channel]["relay_count"] = 0
else:
lighting[channel]["relay_count"] =\
lighting[channel]["relay_count"] + 1
if (log_status == "On"):
lighting[channel]["log_off"] = \
lighting[channel]["log_off"]+1
lighting[channel]["light_state"] = "Timer Off"
debug_log("Light relay off by time schedule")
else:
# Lighting is disabled
GPIO.output(relay_pin, GPIO.LOW)
if lighting[channel]["light_state"] \
== "On":
lighting[channel]["relay_activation"] =\
lighting[channel]["relay_activation"] + 1
if lighting[channel]["relay_count"] == 0:
lighting[channel]["consecutive_change"] =\
lighting[channel]["consecutive_change"] + 1
lighting[channel]["relay_count"] = 0
else:
lighting[channel]["relay_count"] =\
lighting[channel]["relay_count"] + 1
lighting[channel]["light_state"] = "Disabled - Off"
if (log_status == "On"):
lighting[channel]["log_off"] = \
lighting[channel]["log_off"]+1
debug_log("Light disabled - relay off")
channel = channel + 1
if lights == "On":
any_lighting = True
else:
any_lighting = False
time.sleep(control_interval)
except KeyboardInterrupt:
GPIO.cleanup()
class FakeLightingThread(threading.Thread):
def run(self):
global lighting
global light_level
global any_lighting
debug_log("Starting FAKE lighting thread")
while 1: # Fake forever while powered
time.sleep(10)
print("Pretend lights turn on")
lighting_turn_on()
any_lighting = True
time.sleep(200)
print("Pretend lights turn off")
any_lighting = False
time.sleep(200)
# Humidity code: record the humidity and air temperature
class HumidityThread(threading.Thread):
def run(self):
global air_temp
global humidity_level
GPIO.setmode(GPIO.BOARD)
debug_log("Starting humidity control thread")
airtemp_humidity_sensor = am2320.AM2320()
alert_state = "None"
sensor_error = False
error_count = 0
sensor_alert = False