-
Notifications
You must be signed in to change notification settings - Fork 27
/
Northcliff_AQI_Monitor_Gen.py
2656 lines (2537 loc) · 147 KB
/
Northcliff_AQI_Monitor_Gen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#Northcliff Environment Monitor
# Requires Home Manager >=8.54 with Enviro Monitor timeout
import paho.mqtt.client as mqtt
import colorsys
import math
import json
import requests
import ST7735
import os
import time
from datetime import datetime, timedelta
from fonts.ttf import RobotoMedium as UserFont
import pytz
from pytz import timezone
from astral.geocoder import database, lookup, add_locations
from astral.sun import sun
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus
try:
# Transitional fix for breaking change in LTR559
from ltr559 import LTR559
ltr559 = LTR559()
except ImportError:
import ltr559
from enviroplus import gas
from bme280 import BME280
from pms5003 import PMS5003, ReadTimeoutError, ChecksumMismatchError
from subprocess import check_output
from PIL import Image, ImageDraw, ImageFont, ImageFilter
try:
from smbus2 import SMBus
except ImportError:
from smbus import SMBus
import logging
monitor_version = "7.2 - Gen"
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logging.info("""Northcliff_Environment_Monitor.py - Pimoroni Enviro+ with noise measurement (and optional SGP30) sensor capture and display.
Supports external sensor capture and Luftdaten, mqtt and Adafruit IO Updates
Disclaimer: The noise measurement is not to be used for accurate sound level measurements.
#Note: you'll need to register with Luftdaten at:
#https://meine.luftdaten.info/ and enter your Raspberry Pi
#serial number that's displayed on the Enviro plus LCD along
#with the other details before the data appears on the
#Luftdaten map.
#""")
print(monitor_version)
bus = SMBus(1)
# Create a BME280 instance
bme280 = BME280(i2c_dev=bus)
# Create an LCD instance
disp = ST7735.ST7735(
port=0,
cs=1,
dc=9,
backlight=12,
rotation=270,
spi_speed_hz=10000000
)
# Initialize display
disp.begin()
def retrieve_config():
try:
with open('<Your config.json file location>', 'r') as f:
parsed_config_parameters = json.loads(f.read())
print('Retrieved Config', parsed_config_parameters)
except IOError:
print('Config Retrieval Failed')
temp_offset = parsed_config_parameters['temp_offset']
altitude = parsed_config_parameters['altitude']
enable_display = parsed_config_parameters['enable_display'] # Enables the display and flags that the
# weather protection cover is used with different temp/hum compensation
enable_adafruit_io = parsed_config_parameters['enable_adafruit_io']
aio_user_name = parsed_config_parameters['aio_user_name']
aio_key = parsed_config_parameters['aio_key']
aio_feed_window = parsed_config_parameters['aio_feed_window']
aio_feed_sequence = parsed_config_parameters['aio_feed_sequence']
aio_household_prefix = parsed_config_parameters['aio_household_prefix']
aio_location_prefix = parsed_config_parameters['aio_location_prefix']
aio_package = parsed_config_parameters['aio_package']
enable_send_data_to_homemanager = parsed_config_parameters['enable_send_data_to_homemanager']
enable_receive_data_from_homemanager = parsed_config_parameters['enable_receive_data_from_homemanager']
enable_indoor_outdoor_functionality = parsed_config_parameters['enable_indoor_outdoor_functionality']
mqtt_broker_name = parsed_config_parameters['mqtt_broker_name']
enable_luftdaten = parsed_config_parameters['enable_luftdaten']
enable_climate_and_gas_logging = parsed_config_parameters['enable_climate_and_gas_logging']
enable_particle_sensor = parsed_config_parameters['enable_particle_sensor']
if 'enable_eco2_tvoc' in parsed_config_parameters:
enable_eco2_tvoc = parsed_config_parameters['enable_eco2_tvoc']
else:
enable_eco2_tvoc = False
if 'gas_daily_r0_calibration_hour' in parsed_config_parameters:
gas_daily_r0_calibration_hour = parsed_config_parameters['gas_daily_r0_calibration_hour']
else:
gas_daily_r0_calibration_hour = 3
if 'reset_gas_sensor_calibration' in parsed_config_parameters:
reset_gas_sensor_calibration = parsed_config_parameters['reset_gas_sensor_calibration']
else:
reset_gas_sensor_calibration = False
if 'mqtt_username' in parsed_config_parameters:
mqtt_username = parsed_config_parameters['mqtt_username']
else:
mqtt_username = None
if 'mqtt_password' in parsed_config_parameters:
mqtt_password = parsed_config_parameters['mqtt_password']
else:
mqtt_password = None
if 'outdoor_source_type' in parsed_config_parameters:
outdoor_source_type = parsed_config_parameters['outdoor_source_type'] # Can be "Enviro", "Luftdaten"
# or "Adafruit IO"
else:
outdoor_source_type = 'Enviro'
if 'outdoor_source_id' in parsed_config_parameters:
outdoor_source_id = parsed_config_parameters['outdoor_source_id'] # Sets Luftdaten or Adafruit IO Sensor IDs
# if using those sensors for outdoor readings, with the format: {"Climate": id, "PM": id} for Luftdaten or
# {"User Name": "<aio_user_name>", "Key": "<aio_key>", "Household Name": "<aio_household_name>"} for Adafruit IO
else:
outdoor_source_id = {}
if 'enable_noise' in parsed_config_parameters: # Enables Noise level sensing
enable_noise = parsed_config_parameters['enable_noise']
else:
enable_noise = False
if 'enable_luftdaten_noise' in parsed_config_parameters: # Enables Noise level uploads to Luftdaten. enable_noise must also be set to true for this to work
enable_luftdaten_noise = parsed_config_parameters['enable_luftdaten_noise']
else:
enable_luftdaten_noise = False
if 'disable_luftdaten_sensor_upload' in parsed_config_parameters: # Luftdaten currently only supports two sensors per node
# When enable_luftdaten_noise is true, this must be set to either 'Climate' to disable climate reading uploads or 'PM' to disable air particle reading uploads
# Set to 'None' when enable_luftdaten_noise is false
disable_luftdaten_sensor_upload = parsed_config_parameters['disable_luftdaten_sensor_upload']
else:
disable_luftdaten_sensor_upload = 'None'
# Correct any Luftdaten Noise misconfigurations
if not enable_noise:
disable_luftdaten_sensor_upload = 'None'
if enable_luftdaten_noise:
print('Noise sensor must be enabled in order to enable Luftdaten Noise. Disabling Luftdaten Noise')
enable_luftdaten_noise = False
else:
if enable_luftdaten_noise and disable_luftdaten_sensor_upload == 'None':
# Comment out next two lines once Luftdaten supports three sensors per node
print('Luftdaten currently only supports two sensors and three have been enabled. Disabling Luftdaten Climate uploads')
disable_luftdaten_sensor_upload = 'Climate'
pass
incoming_temp_hum_mqtt_topic = parsed_config_parameters['incoming_temp_hum_mqtt_topic']
incoming_temp_hum_mqtt_sensor_name = parsed_config_parameters['incoming_temp_hum_mqtt_sensor_name']
incoming_barometer_mqtt_topic = parsed_config_parameters['incoming_barometer_mqtt_topic']
incoming_barometer_sensor_id = parsed_config_parameters['incoming_barometer_sensor_id']
indoor_outdoor_function = parsed_config_parameters['indoor_outdoor_function']
mqtt_client_name = parsed_config_parameters['mqtt_client_name']
outdoor_mqtt_topic = parsed_config_parameters['outdoor_mqtt_topic']
indoor_mqtt_topic = parsed_config_parameters['indoor_mqtt_topic']
city_name = parsed_config_parameters['city_name']
time_zone = parsed_config_parameters['time_zone']
custom_locations = parsed_config_parameters['custom_locations']
return (temp_offset, altitude, enable_display, enable_adafruit_io, aio_user_name, aio_key, aio_feed_window,
aio_feed_sequence, aio_household_prefix, aio_location_prefix, aio_package, enable_send_data_to_homemanager,
enable_receive_data_from_homemanager, enable_indoor_outdoor_functionality,
mqtt_broker_name, mqtt_username, mqtt_password, outdoor_source_type, outdoor_source_id, enable_noise, enable_luftdaten,
enable_luftdaten_noise, disable_luftdaten_sensor_upload, enable_climate_and_gas_logging, enable_particle_sensor,
enable_eco2_tvoc, gas_daily_r0_calibration_hour, reset_gas_sensor_calibration, incoming_temp_hum_mqtt_topic,
incoming_temp_hum_mqtt_sensor_name, incoming_barometer_mqtt_topic, incoming_barometer_sensor_id,
indoor_outdoor_function, mqtt_client_name, outdoor_mqtt_topic, indoor_mqtt_topic, city_name, time_zone,
custom_locations)
# Config Setup
(temp_offset, altitude, enable_display, enable_adafruit_io, aio_user_name, aio_key, aio_feed_window, aio_feed_sequence,
aio_household_prefix, aio_location_prefix, aio_package, enable_send_data_to_homemanager,
enable_receive_data_from_homemanager, enable_indoor_outdoor_functionality, mqtt_broker_name,
mqtt_username, mqtt_password, outdoor_source_type, outdoor_source_id, enable_noise, enable_luftdaten,
enable_luftdaten_noise, disable_luftdaten_sensor_upload, enable_climate_and_gas_logging, enable_particle_sensor, enable_eco2_tvoc,
gas_daily_r0_calibration_hour, reset_gas_sensor_calibration, incoming_temp_hum_mqtt_topic, incoming_temp_hum_mqtt_sensor_name,
incoming_barometer_mqtt_topic, incoming_barometer_sensor_id, indoor_outdoor_function, mqtt_client_name,
outdoor_mqtt_topic, indoor_mqtt_topic, city_name, time_zone, custom_locations) = retrieve_config()
# Add to city database
db = database()
add_locations(custom_locations, db)
if enable_particle_sensor:
# Create a PMS5003 instance
pms5003 = PMS5003()
time.sleep(1)
if enable_noise:
import sounddevice as sd
import numpy as np
from numpy import pi, log10
from scipy.signal import zpk2tf, zpk2sos, freqs, sosfilt
from waveform_analysis.weighting_filters._filter_design import _zpkbilinear
def read_pm_values(luft_values, mqtt_values, own_data, own_disp_values):
if enable_particle_sensor:
try:
pm_values = pms5003.read()
#print('PM Values:', pm_values)
own_data["P2.5"][1] = pm_values.pm_ug_per_m3(2.5)
mqtt_values["P2.5"] = own_data["P2.5"][1]
own_disp_values["P2.5"] = own_disp_values["P2.5"][1:] + [[own_data["P2.5"][1], 1]]
luft_values["P2"] = str(mqtt_values["P2.5"])
own_data["P10"][1] = pm_values.pm_ug_per_m3(10)
mqtt_values["P10"] = own_data["P10"][1]
own_disp_values["P10"] = own_disp_values["P10"][1:] + [[own_data["P10"][1], 1]]
luft_values["P1"] = str(own_data["P10"][1])
own_data["P1"][1] = pm_values.pm_ug_per_m3(1.0)
mqtt_values["P1"] = own_data["P1"][1]
own_disp_values["P1"] = own_disp_values["P1"][1:] + [[own_data["P1"][1], 1]]
except (ReadTimeoutError, ChecksumMismatchError):
logging.info("Failed to read PMS5003")
display_error('Particle Sensor Error')
pms5003.reset()
pm_values = pms5003.read()
own_data["P2.5"][1] = pm_values.pm_ug_per_m3(2.5)
mqtt_values["P2.5"] = own_data["P2.5"][1]
own_disp_values["P2.5"] = own_disp_values["P2.5"][1:] + [[own_data["P2.5"][1], 1]]
luft_values["P2"] = str(mqtt_values["P2.5"])
own_data["P10"][1] = pm_values.pm_ug_per_m3(10)
mqtt_values["P10"] = own_data["P10"][1]
own_disp_values["P10"] = own_disp_values["P10"][1:] + [[own_data["P10"][1], 1]]
luft_values["P1"] = str(own_data["P10"][1])
own_data["P1"][1] = pm_values.pm_ug_per_m3(1.0)
mqtt_values["P1"] = own_data["P1"][1]
own_disp_values["P1"] = own_disp_values["P1"][1:] + [[own_data["P1"][1], 1]]
return(luft_values, mqtt_values, own_data, own_disp_values)
def read_eco2_tvoc_values(mqtt_values, own_data, own_disp_values):
eco2, tvoc = sgp30.command('measure_air_quality')
#print(eco2, tvoc)
own_data["CO2"][1] = eco2
mqtt_values["CO2"] = eco2
own_disp_values["CO2"] = own_disp_values["CO2"][1:] + [[own_data["CO2"][1], 1]]
own_data["VOC"][1] = tvoc
mqtt_values["VOC"] = tvoc
own_disp_values["VOC"] = own_disp_values["VOC"][1:] + [[own_data["VOC"][1], 1]]
return mqtt_values, own_data, own_disp_values
# Read gas and climate values from Home Manager and /or BME280
def read_climate_gas_values(luft_values, mqtt_values, own_data, maxi_temp, mini_temp, own_disp_values, gas_sensors_warm,
gas_calib_temp, gas_calib_hum, gas_calib_bar, altitude, enable_eco2_tvoc):
raw_temp, comp_temp = adjusted_temperature()
raw_hum, comp_hum = adjusted_humidity()
current_time = time.time()
use_external_temp_hum = False
use_external_barometer = False
if enable_receive_data_from_homemanager:
use_external_temp_hum, use_external_barometer = es.check_valid_readings(current_time)
if use_external_temp_hum == False:
print("Internal Temp/Hum Sensor")
luft_values["temperature"] = "{:.2f}".format(comp_temp)
own_data["Temp"][1] = round(comp_temp, 1)
luft_values["humidity"] = "{:.2f}".format(comp_hum)
own_data["Hum"][1] = round(comp_hum, 1)
else: # Use external temp/hum sensor but still capture raw temp and raw hum for gas compensation and logging
print("External Temp/Hum Sensor")
luft_values["temperature"] = es.temperature
own_data["Temp"][1] = float(luft_values["temperature"])
luft_values["humidity"] = es.humidity
own_data["Hum"][1] = float(luft_values["humidity"])
own_data["Dew"][1] = round(calculate_dewpoint(own_data["Temp"][1], own_data["Hum"][1]),1)
own_disp_values["Dew"] = own_disp_values["Dew"][1:] + [[own_data["Dew"][1], 1]]
mqtt_values["Dew"] = own_data["Dew"][1]
own_disp_values["Temp"] = own_disp_values["Temp"][1:] + [[own_data["Temp"][1], 1]]
mqtt_values["Temp"] = own_data["Temp"][1]
own_disp_values["Hum"] = own_disp_values["Hum"][1:] + [[own_data["Hum"][1], 1]]
mqtt_values["Hum"][0] = own_data["Hum"][1]
mqtt_values["Hum"][1] = domoticz_hum_map[describe_humidity(own_data["Hum"][1])]
if enable_eco2_tvoc: # Calculate and send the absolute humidity reading to the SGP30 for humidity compensation
absolute_hum = int(1000 * 216.7 * (raw_hum/100 * 6.112 * math.exp(17.62 * raw_temp / (243.12 + raw_temp)))
/(273.15 + raw_temp))
sgp30.command('set_humidity', [absolute_hum])
else:
absolute_hum = None
# Determine max and min temps
if first_climate_reading_done :
if maxi_temp is None:
maxi_temp = own_data["Temp"][1]
elif own_data["Temp"][1] > maxi_temp:
maxi_temp = own_data["Temp"][1]
else:
pass
if mini_temp is None:
mini_temp = own_data["Temp"][1]
elif own_data["Temp"][1] < mini_temp:
mini_temp = own_data["Temp"][1]
else:
pass
mqtt_values["Min Temp"] = mini_temp
mqtt_values["Max Temp"] = maxi_temp
raw_barometer = bme280.get_pressure()
if use_external_barometer == False:
print("Internal Barometer")
own_data["Bar"][1] = round(raw_barometer * barometer_altitude_comp_factor(altitude, own_data["Temp"][1]), 2)
own_disp_values["Bar"] = own_disp_values["Bar"][1:] + [[own_data["Bar"][1], 1]]
mqtt_values["Bar"][0] = own_data["Bar"][1]
luft_values["pressure"] = "{:.2f}".format(raw_barometer * 100) # Send raw air pressure to Lufdaten,
# since it does its own altitude air pressure compensation
print("Raw Bar:", round(raw_barometer, 2), "Comp Bar:", own_data["Bar"][1])
else:
print("External Barometer")
own_data["Bar"][1] = round(float(es.barometer), 2)
own_disp_values["Bar"] = own_disp_values["Bar"][1:] + [[own_data["Bar"][1], 1]]
mqtt_values["Bar"][0] = own_data["Bar"][1]
# Remove altitude compensation from external barometer because Lufdaten does its own altitude air pressure
# compensation
luft_values["pressure"] = "{:.2f}".format(float(es.barometer) / barometer_altitude_comp_factor (
altitude, own_data["Temp"][1]) * 100)
print("Luft Bar:", luft_values["pressure"], "Comp Bar:", own_data["Bar"][1])
red_in_ppm, oxi_in_ppm, nh3_in_ppm, comp_red_rs, comp_oxi_rs, comp_nh3_rs, raw_red_rs, raw_oxi_rs, raw_nh3_rs =\
read_gas_in_ppm(gas_calib_temp, gas_calib_hum, gas_calib_bar, raw_temp, raw_hum, raw_barometer, gas_sensors_warm)
own_data["Red"][1] = round(red_in_ppm, 2)
own_disp_values["Red"] = own_disp_values["Red"][1:] + [[own_data["Red"][1], 1]]
mqtt_values["Red"] = own_data["Red"][1]
own_data["Oxi"][1] = round(oxi_in_ppm, 2)
own_disp_values["Oxi"] = own_disp_values["Oxi"][1:] + [[own_data["Oxi"][1], 1]]
mqtt_values["Oxi"] = own_data["Oxi"][1]
own_data["NH3"][1] = round(nh3_in_ppm, 2)
own_disp_values["NH3"] = own_disp_values["NH3"][1:] + [[own_data["NH3"][1], 1]]
mqtt_values["NH3"] = own_data["NH3"][1]
mqtt_values["Gas Calibrated"] = gas_sensors_warm
proximity = ltr559.get_proximity()
if proximity < 500:
own_data["Lux"][1] = round(ltr559.get_lux(), 1)
else:
own_data["Lux"][1] = 1
own_disp_values["Lux"] = own_disp_values["Lux"][1:] + [[own_data["Lux"][1], 1]]
mqtt_values["Lux"] = own_data["Lux"][1]
return luft_values, mqtt_values, own_data, maxi_temp, mini_temp, own_disp_values, raw_red_rs, raw_oxi_rs,\
raw_nh3_rs, raw_temp, comp_temp, comp_hum, raw_hum, use_external_temp_hum, use_external_barometer,\
raw_barometer, absolute_hum
def barometer_altitude_comp_factor(alt, temp):
comp_factor = math.pow(1 - (0.0065 * altitude/(temp + 0.0065 * alt + 273.15)), -5.257)
return comp_factor
def read_raw_gas():
gas_data = gas.read_all()
raw_red_rs = round(gas_data.reducing, 0)
raw_oxi_rs = round(gas_data.oxidising, 0)
raw_nh3_rs = round(gas_data.nh3, 0)
return raw_red_rs, raw_oxi_rs, raw_nh3_rs
def read_gas_in_ppm(gas_calib_temp, gas_calib_hum, gas_calib_bar, raw_temp, raw_hum, raw_barometer, gas_sensors_warm):
if gas_sensors_warm:
comp_red_rs, comp_oxi_rs, comp_nh3_rs, raw_red_rs, raw_oxi_rs, raw_nh3_rs = comp_gas(gas_calib_temp,
gas_calib_hum,
gas_calib_bar,
raw_temp,
raw_hum, raw_barometer)
print("Reading Compensated Gas sensors after warmup completed")
else:
raw_red_rs, raw_oxi_rs, raw_nh3_rs = read_raw_gas()
comp_red_rs = raw_red_rs
comp_oxi_rs = raw_oxi_rs
comp_nh3_rs = raw_nh3_rs
print("Reading Raw Gas sensors before warmup completed")
print("Red Rs:", round(comp_red_rs, 0), "Oxi Rs:", round(comp_oxi_rs, 0), "NH3 Rs:", round(comp_nh3_rs, 0))
if comp_red_rs/red_r0 > 0:
red_ratio = comp_red_rs/red_r0
else:
red_ratio = 0.0001
if comp_oxi_rs/oxi_r0 > 0:
oxi_ratio = comp_oxi_rs/oxi_r0
else:
oxi_ratio = 0.0001
if comp_nh3_rs/nh3_r0 > 0:
nh3_ratio = comp_nh3_rs/nh3_r0
else:
nh3_ratio = 0.0001
red_in_ppm = math.pow(10, -1.25 * math.log10(red_ratio) + 0.64)
oxi_in_ppm = math.pow(10, math.log10(oxi_ratio) - 0.8129)
nh3_in_ppm = math.pow(10, -1.8 * math.log10(nh3_ratio) - 0.163)
return red_in_ppm, oxi_in_ppm, nh3_in_ppm, comp_red_rs, comp_oxi_rs, comp_nh3_rs, raw_red_rs, raw_oxi_rs, raw_nh3_rs
def comp_gas(gas_calib_temp, gas_calib_hum, gas_calib_bar, raw_temp, raw_hum, raw_barometer):
gas_data = gas.read_all()
gas_temp_diff = raw_temp - gas_calib_temp
gas_hum_diff = raw_hum - gas_calib_hum
gas_bar_diff = raw_barometer - gas_calib_bar
raw_red_rs = round(gas_data.reducing, 0)
comp_red_rs = round(raw_red_rs - (red_temp_comp_factor * raw_red_rs * gas_temp_diff +
red_hum_comp_factor * raw_red_rs * gas_hum_diff +
red_bar_comp_factor * raw_red_rs * gas_bar_diff), 0)
raw_oxi_rs = round(gas_data.oxidising, 0)
comp_oxi_rs = round(raw_oxi_rs - (oxi_temp_comp_factor * raw_oxi_rs * gas_temp_diff +
oxi_hum_comp_factor * raw_oxi_rs * gas_hum_diff +
oxi_bar_comp_factor * raw_oxi_rs * gas_bar_diff), 0)
raw_nh3_rs = round(gas_data.nh3, 0)
comp_nh3_rs = round(raw_nh3_rs - (nh3_temp_comp_factor * raw_nh3_rs * gas_temp_diff +
nh3_hum_comp_factor * raw_nh3_rs * gas_hum_diff +
nh3_bar_comp_factor * raw_nh3_rs * gas_bar_diff), 0)
print("Gas Compensation. Raw Red Rs:", raw_red_rs, "Comp Red Rs:", comp_red_rs, "Raw Oxi Rs:",
raw_oxi_rs, "Comp Oxi Rs:", comp_oxi_rs,
"Raw NH3 Rs:", raw_nh3_rs, "Comp NH3 Rs:", comp_nh3_rs)
return comp_red_rs, comp_oxi_rs, comp_nh3_rs, raw_red_rs, raw_oxi_rs, raw_nh3_rs
def adjusted_temperature():
raw_temp = bme280.get_temperature()
#comp_temp = comp_temp_slope * raw_temp + comp_temp_intercept
comp_temp = (comp_temp_cub_a * math.pow(raw_temp, 3) + comp_temp_cub_b * math.pow(raw_temp, 2) +
comp_temp_cub_c * raw_temp + comp_temp_cub_d)
return raw_temp, comp_temp
def adjusted_humidity():
raw_hum = bme280.get_humidity()
#comp_hum = comp_hum_slope * raw_hum + comp_hum_intercept
comp_hum = comp_hum_quad_a * math.pow(raw_hum, 2) + comp_hum_quad_b * raw_hum + comp_hum_quad_c
return raw_hum, min(100, comp_hum)
def calculate_dewpoint(dew_temp, dew_hum):
dewpoint = (237.7 * (math.log(dew_hum/100)+17.271*dew_temp/(237.7+dew_temp))/(17.271 - math.log(dew_hum/100) - 17.271*dew_temp/(237.7 + dew_temp)))
return dewpoint
def log_climate_and_gas(run_time, own_data, raw_red_rs, raw_oxi_rs, raw_nh3_rs, raw_temp, comp_temp, comp_hum,
raw_hum, use_external_temp_hum, use_external_barometer, raw_barometer):
# Used to log climate and gas data to create compensation algorithms
raw_temp = round(raw_temp, 2)
raw_hum = round(raw_hum, 2)
comp_temp = round(comp_temp, 2)
comp_hum = round(comp_hum, 2)
raw_barometer = round(raw_barometer, 1)
raw_red_rs = round(raw_red_rs, 0)
raw_oxi_rs = round(raw_oxi_rs, 0)
raw_nh3_rs = round(raw_nh3_rs, 0)
today = datetime.now()
time_stamp = today.strftime('%A %d %B %Y @ %H:%M:%S')
if use_external_temp_hum and use_external_barometer:
environment_log_data = {'Time': time_stamp, 'Run Time': run_time, 'Raw Temperature': raw_temp,
'Output Temp': comp_temp, 'Real Temperature': own_data["Temp"][1],
'Raw Humidity': raw_hum, 'Output Humidity': comp_hum,
'Real Humidity': own_data["Hum"][1], 'Real Bar': own_data["Bar"][1],
'Raw Bar': raw_barometer, 'Oxi': own_data["Oxi"][1], 'Red': own_data["Red"][1],
'NH3': own_data["NH3"][1], 'Raw OxiRS': raw_oxi_rs, 'Raw RedRS': raw_red_rs,
'Raw NH3RS': raw_nh3_rs}
elif use_external_temp_hum and not(use_external_barometer):
environment_log_data = {'Time': time_stamp, 'Run Time': run_time, 'Raw Temperature': raw_temp,
'Output Temp': comp_temp, 'Real Temperature': own_data["Temp"][1],
'Raw Humidity': raw_hum, 'Output Humidity': comp_hum,
'Real Humidity': own_data["Hum"][1], 'Output Bar': own_data["Bar"][1],
'Raw Bar': raw_barometer, 'Oxi': own_data["Oxi"][1], 'Red': own_data["Red"][1],
'NH3': own_data["NH3"][1], 'Raw OxiRS': raw_oxi_rs, 'Raw RedRS': raw_red_rs,
'Raw NH3RS': raw_nh3_rs}
elif not(use_external_temp_hum) and use_external_barometer:
environment_log_data = {'Time': time_stamp, 'Run Time': run_time, 'Raw Temperature': raw_temp,
'Output Temp': comp_temp, 'Raw Humidity': raw_hum, 'Output Humidity': comp_hum,
'Real Bar': own_data["Bar"][1], 'Raw Bar': raw_barometer, 'Oxi': own_data["Oxi"][1],
'Red': own_data["Red"][1], 'NH3': own_data["NH3"][1], 'Raw OxiRS': raw_oxi_rs,
'Raw RedRS': raw_red_rs, 'Raw NH3RS': raw_nh3_rs}
else:
environment_log_data = {'Time': time_stamp, 'Run Time': run_time, 'Raw Temperature': raw_temp,
'Output Temp': comp_temp, 'Raw Humidity': raw_hum, 'Output Humidity': comp_hum,
'Output Bar': own_data["Bar"][1], 'Raw Bar': raw_barometer, 'Oxi': own_data["Oxi"][1],
'Red': own_data["Red"][1], 'NH3': own_data["NH3"][1], 'Raw OxiRS': raw_oxi_rs,
'Raw RedRS': raw_red_rs, 'Raw NH3RS': raw_nh3_rs}
print('Logging Environment Data.', environment_log_data)
with open('<Your Environment Log File Location Here>', 'a') as f:
f.write(',\n' + json.dumps(environment_log_data))
# Calculate Air Quality Level
def max_aqi_level_factor(gas_sensors_warm, air_quality_data, air_quality_data_no_gas, data):
max_aqi_level = 0
max_aqi_factor = 'All'
max_aqi = [max_aqi_factor, max_aqi_level]
if gas_sensors_warm:
aqi_data = air_quality_data
else:
aqi_data = air_quality_data_no_gas
for aqi_factor in aqi_data:
aqi_factor_level = 0
thresholds = data[aqi_factor][2]
for level in range(len(thresholds)):
if data[aqi_factor][1] != None:
if data[aqi_factor][1] > thresholds[level]:
aqi_factor_level = level + 1
if aqi_factor_level > max_aqi[1]:
max_aqi = [aqi_factor, aqi_factor_level]
return max_aqi
# Get Raspberry Pi serial number to use as ID
def get_serial_number():
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line[0:6] == 'Serial':
return line.split(":")[1].strip()
# Check for Wi-Fi connection
def check_wifi():
if check_output(['hostname', '-I']):
return True
else:
return False
# Display Startup Message on LCD when using the SGP30 sensor
def display_startup(message):
text_colour = (255, 255, 255)
back_colour = (85, 15, 15)
error_message = "{}".format(message)
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0))
draw = ImageDraw.Draw(img)
size_x, size_y = draw.textsize(message, mediumfont)
x = (WIDTH - size_x) / 2
y = (HEIGHT / 2) - (size_y / 2)
draw.rectangle((0, 0, 160, 80), back_colour)
draw.text((x, y), error_message, font=mediumfont, fill=text_colour)
disp.display(img)
# Display Error Message on LCD
def display_error(message):
text_colour = (255, 255, 255)
back_colour = (85, 15, 15)
error_message = "System Error\n{}".format(message)
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0))
draw = ImageDraw.Draw(img)
size_x, size_y = draw.textsize(message, mediumfont)
x = (WIDTH - size_x) / 2
y = (HEIGHT / 2) - (size_y / 2)
draw.rectangle((0, 0, 160, 80), back_colour)
draw.text((x, y), error_message, font=mediumfont, fill=text_colour)
disp.display(img)
# Display the Raspberry Pi serial number and Adafruit IO Dashboard URL (if enabled) on a background colour
# based on the air quality level
def disabled_display(gas_sensors_warm, air_quality_data, air_quality_data_no_gas, data, palette, enable_adafruit_io,
aio_user_name, aio_household_prefix):
max_aqi = max_aqi_level_factor(gas_sensors_warm, air_quality_data, air_quality_data_no_gas, data)
back_colour = palette[max_aqi[1]]
text_colour = (0, 0, 0)
id = get_serial_number()
if enable_adafruit_io:
message = "{}\nhttp://io.adafruit.com\n/{}/dashboards\n/{}".format(id, aio_user_name, aio_household_prefix)
else:
message = "{}".format(id)
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0))
draw = ImageDraw.Draw(img)
size_x, size_y = draw.textsize(message, font_smm)
x = (WIDTH - size_x) / 2
y = (HEIGHT / 2) - (size_y / 2)
draw.rectangle((0, 0, 160, 80), back_colour)
draw.text((x, y), message, font=font_smm, fill=text_colour)
disp.display(img)
# Display Raspberry Pi serial and Adafruit IO Dashboard URL (if enabled)
def display_status(enable_adafruit_io, aio_user_name, aio_household_prefix):
wifi_status = "connected" if check_wifi() else "disconnected"
text_colour = (255, 255, 255)
back_colour = (0, 170, 170) if check_wifi() else (85, 15, 15)
id = get_serial_number()
if enable_adafruit_io:
message = "{}\nhttp://io.adafruit.com\n/{}/dashboards\n/{}".format(id, aio_user_name, aio_household_prefix)
else:
message = "Northcliff\nEnviro Monitor\n{}\nwifi: {}".format(id, wifi_status)
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0))
draw = ImageDraw.Draw(img)
size_x, size_y = draw.textsize(message, font_smm)
x = (WIDTH - size_x) / 2
y = (HEIGHT / 2) - (size_y / 2)
draw.rectangle((0, 0, 160, 80), back_colour)
draw.text((x, y), message, font=font_smm, fill=text_colour)
disp.display(img)
def send_data_to_aio(feed_key, data):
aio_json = {"value": data}
resp_error = False
reason = ''
response = ''
try:
response = requests.post(aio_url + '/feeds/' + feed_key + '/data',
headers={'X-AIO-Key': aio_key,
'Content-Type': 'application/json'},
data=json.dumps(aio_json), timeout=5)
status_code = response.status_code
except requests.exceptions.ConnectionError as e:
resp_error = True
reason = 'aio Connection Error'
print('aio Connection Error', e)
except requests.exceptions.Timeout as e:
resp_error = True
reason = 'aio Timeout Error'
print('aio Timeout Error', e)
except requests.exceptions.HTTPError as e:
resp_error = True
reason = 'aio HTTP Error'
print('aio HTTP Error', e)
except requests.exceptions.RequestException as e:
resp_error = True
reason = 'aio Request Error'
print('aio Request Error', e)
else:
if status_code == 429:
resp_error = True
reason = 'Throttling Error'
print('aio Throttling Error')
elif status_code >= 400:
resp_error = True
reason = 'Response Error: ' + str(response.status_code)
print('aio ', reason)
return not resp_error
def send_to_luftdaten(luft_values, id, enable_particle_sensor, enable_noise, luft_noise_values, disable_luftdaten_sensor_upload):
print("Sending Data to Luftdaten")
pm_send_attempt = False
climate_send_attempt = False
noise_send_attempt = False
all_responses_ok = True
resp_1_exception = False
resp_2_exception = False
resp_3_exception = False
if enable_particle_sensor and disable_luftdaten_sensor_upload != 'PM':
pm_values = dict(i for i in luft_values.items() if i[0].startswith("P"))
pm_send_attempt = True
try:
resp_1 = requests.post("https://api.luftdaten.info/v1/push-sensor-data/",
json={
"software_version": "northclff_enviro_monitor " + monitor_version,
"sensordatavalues": [{"value_type": key, "value": val} for
key, val in pm_values.items()]
},
headers={
"X-PIN": "1",
"X-Sensor": id,
"Content-Type": "application/json",
"cache-control": "no-cache"
},
timeout=5
)
except requests.exceptions.ConnectionError as e:
resp_1_exception = True
print('Luftdaten PM Connection Error', e)
except requests.exceptions.Timeout as e:
resp_1_exception = True
print('Luftdaten PM Timeout Error', e)
except requests.exceptions.RequestException as e:
resp_1_exception = True
print('Luftdaten PM Request Error', e)
if disable_luftdaten_sensor_upload != 'Climate':
temp_values = dict(i for i in luft_values.items() if not i[0].startswith("P"))
climate_send_attempt = True
try:
resp_2 = requests.post("https://api.luftdaten.info/v1/push-sensor-data/",
json={
"software_version": "northclff_enviro_monitor " + monitor_version,
"sensordatavalues": [{"value_type": key, "value": val} for
key, val in temp_values.items()]
},
headers={
"X-PIN": "11",
"X-Sensor": id,
"Content-Type": "application/json",
"cache-control": "no-cache"
},
timeout=5
)
except requests.exceptions.ConnectionError as e:
resp_2_exception = True
print('Luftdaten Climate Connection Error', e)
except requests.exceptions.Timeout as e:
resp_2_exception = True
print('Luftdaten Climate Timeout Error', e)
except requests.exceptions.RequestException as e:
resp_2_exception = True
print('Luftdaten Climate Request Error', e)
if enable_noise and enable_luftdaten_noise and luft_noise_values != []:
noise_values = [{"value_type": "noise_LAeq", "value": "{:.2f}".format(sum(luft_noise_values)/len(luft_noise_values))},
{"value_type": "noise_LA_min", "value": "{:.2f}".format(min(luft_noise_values))},
{"value_type": "noise_LA_max", "value": "{:.2f}".format(max(luft_noise_values))}]
print("Sending Luftdaten Noise Data", noise_values)
noise_send_attempt = True
try:
resp_3 = requests.post("https://api.luftdaten.info/v1/push-sensor-data/",
json={
"software_version": "northclff_enviro_monitor " + monitor_version,
"sensordatavalues": noise_values
},
headers={
"X-PIN": "15",
"X-Sensor": id,
"Content-Type": "application/json",
"cache-control": "no-cache"
},
timeout=5
)
except requests.exceptions.ConnectionError as e:
resp_3_exception = True
print('Luftdaten Noise Connection Error', e)
except requests.exceptions.Timeout as e:
resp_3_exception = True
print('Luftdaten Noise Timeout Error', e)
except requests.exceptions.RequestException as e:
resp_3_exception = True
print('Luftdaten Noise Request Error', e)
#print(resp_3)
if not (resp_1_exception or resp_2_exception or resp_3_exception):
if pm_send_attempt:
if not resp_1.ok:
all_responses_ok = False
if climate_send_attempt:
if not resp_2.ok:
all_responses_ok = False
if noise_send_attempt:
if not resp_3.ok:
all_responses_ok = False
else:
all_responses_ok = False
return all_responses_ok
def on_connect(client, userdata, flags, rc):
es.print_update('Northcliff Environment Monitor Connected with result code ' + str(rc))
if enable_receive_data_from_homemanager:
client.subscribe(incoming_temp_hum_mqtt_topic) # Subscribe to the topic for the external temp/hum data
client.subscribe(incoming_barometer_mqtt_topic) # Subscribe to the topic for the external barometer data
if enable_indoor_outdoor_functionality and indoor_outdoor_function == 'Indoor' and outdoor_source_type == "Enviro":
client.subscribe(outdoor_mqtt_topic)
def on_message(client, userdata, msg):
decoded_payload = str(msg.payload.decode("utf-8"))
parsed_json = json.loads(decoded_payload)
# Identify external temp/hum sensor
if msg.topic == incoming_temp_hum_mqtt_topic and parsed_json['name'] == incoming_temp_hum_mqtt_sensor_name:
es.capture_temp_humidity(parsed_json)
# Identify external barometer
if msg.topic == incoming_barometer_mqtt_topic and parsed_json['idx'] == incoming_barometer_sensor_id:
es.capture_barometer(parsed_json['svalue'])
if enable_indoor_outdoor_functionality and indoor_outdoor_function == 'Indoor' and msg.topic == outdoor_mqtt_topic:
capture_outdoor_data(parsed_json)
def capture_outdoor_data(parsed_json):
global captured_outdoor_data
captured_outdoor_data = parsed_json
# Displays graphed data and text on the 0.96" LCD
def display_graphed_data(location, disp_values, variable, data, WIDTH):
# Scale the received disp_values for the variable between 0 and 1
#print ("Display Values", disp_values)
received_disp_values = [disp_values[variable][v][0]*disp_values[variable][v][1]
for v in range(len(disp_values[variable]))]
graph_range = [(v - min(received_disp_values)) / (max(received_disp_values) - min(received_disp_values))
if ((max(received_disp_values) - min(received_disp_values)) != 0)
else 0 for v in received_disp_values]
# Format the variable name and value
if variable == "Oxi":
message = "{} {}: {:.2f} {}".format(location, variable[:4], data[1], data[0])
elif variable == "Bar":
message = "{}: {:.1f} {}".format(variable[:4], data[1], data[0])
elif (variable[:1] == "P" or variable == "Red" or variable == "NH3" or variable == "CO2" or variable == "VOC" or
variable == "Hum" or variable == "Lux"):
message = "{} {}: {:.0f} {}".format(location, variable[:4], round(data[1], 0), data[0])
else:
message = "{} {}: {:.1f} {}".format(location, variable[:4], data[1], data[0])
#logging.info(message)
draw.rectangle((0, 0, WIDTH, HEIGHT), (255, 255, 255))
# Determine the backgound colour for received data, based on level thresholds. Black for data not received.
for i in range(len(disp_values[variable])):
if disp_values[variable][i][1] == 1:
lim = data[2]
rgb = palette[0]
for j in range(len(lim)):
if disp_values[variable][i][0] > lim[j]:
rgb = palette[j+1]
else:
rgb = (0,0,0)
# Draw a 2-pixel wide rectangle of colour based on reading levels relative to level thresholds
draw.rectangle((i*2, top_pos, i*2+2, HEIGHT), rgb)
# Draw a 2 pixel by 2 pixel line graph in black based on the reading levels
line_y = (HEIGHT-2) - ((top_pos + 1) + (graph_range[i] * ((HEIGHT-2) - (top_pos + 1)))) + (top_pos + 1)
draw.rectangle((i*2, line_y, i*2+2, line_y+2), (0, 0, 0))
# Write the text at the top in black
draw.text((0, 0), message, font=font_ml, fill=(0, 0, 0))
disp.display(img)
# Displays the weather forecast on the 0.96" LCD
def display_forecast(valid_barometer_history, forecast, barometer_available_time, barometer, barometer_change):
text_colour = (255, 255, 255)
back_colour = (0, 0, 0)
if valid_barometer_history:
message = "Barometer {:.0f} hPa\n3Hr Change {:.0f} hPa\n{}".format(round(barometer, 0),
round(barometer_change, 0), forecast)
else:
minutes_to_forecast = (barometer_available_time - time.time()) / 60
if minutes_to_forecast >= 2:
message = "WEATHER FORECAST\nReady in {:.0f} minutes".format(minutes_to_forecast)
elif minutes_to_forecast > 0 and minutes_to_forecast < 2:
message = "WEATHER FORECAST\nReady in a minute"
else:
message = "WEATHER FORECAST\nPreparing Summary\nPlease Wait..."
img = Image.new('RGB', (WIDTH, HEIGHT), color=(0, 0, 0))
draw = ImageDraw.Draw(img)
size_x, size_y = draw.textsize(message, mediumfont)
x = (WIDTH - size_x) / 2
y = (HEIGHT / 2) - (size_y / 2)
draw.rectangle((0, 0, 160, 80), back_colour)
draw.text((x, y), message, font=mediumfont, fill=text_colour)
disp.display(img)
# Displays all the air quality text on the 0.96" LCD
def display_all_aq(location, data, data_in_display_all_aq, enable_eco2_tvoc):
draw.rectangle((0, 0, WIDTH, HEIGHT), (0, 0, 0))
column_count = 2
if enable_eco2_tvoc:
font=font_smm
else:
font=font_ml
draw.text((2, 2), location + ' AIR QUALITY', font=font, fill=(255, 255, 255))
row_count = round((len(data_in_display_all_aq) / column_count), 0)
for i in data_in_display_all_aq:
data_value = data[i][1]
unit = data[i][0]
column = int(data[i][3] / row_count)
row = data[i][3] % row_count
x = x_offset + ((WIDTH/column_count) * column)
y = y_offset + ((HEIGHT/(row_count + 1) * (row +1)))
if (i == "CO2" or i == "VOC") and location == "OUT" or data_value == None:
message = "{}: N/A".format(i) # No CO2 or TVOC data comes from an outdoor unit
# and no gas or P1 readings when Luftdaten is the source of outdoor readings
# (used on display of indoor unit when displaying outdoor readings)
elif i == "Oxi" and data_value != None:
message = "{}: {:.2f}".format(i, data_value)
else:
message = "{}: {:.0f}".format(i, round(data_value, 0))
lim = data[i][2]
rgb = palette[0]
if data_value != None:
for j in range(len(lim)):
if data_value > lim[j]:
rgb = palette[j+1]
draw.text((x, y), message, font=font, fill=rgb)
disp.display(img)
def display_noise(location, selected_display_mode, noise_level, noise_max, noise_max_datetime, display_changed, last_page, noise_values, freq_values):
draw.rectangle((0, 0, WIDTH, HEIGHT), noise_back_colour)
if noise_level<=noise_thresholds[0]:
message_colour = (0, 255, 0)
elif noise_thresholds[0]<noise_level<=noise_thresholds[1]:
message_colour=(255, 255, 0)
else:
message_colour = (255, 0, 0)
if selected_display_mode == "Noise Reading":
draw.text((5,0), location + " Noise Level", font=noise_smallfont, fill=message_colour)
draw.text((5, 32), f"{noise_level:.1f} dB(A)", font=noise_largefont, fill=message_colour)
disp.display(img)
elif selected_display_mode == "Noise Level":
if noise_max<=noise_thresholds[0]:
max_graph_colour = (0, 255, 0)
elif noise_thresholds[0]<noise_max<=noise_thresholds[1]:
max_graph_colour = (255, 255, 0)
else:
max_graph_colour = (255, 0, 0)
for i in range(len(noise_values)):
if noise_values[i][1] == 1:
if noise_values[i][0]<=noise_thresholds[0]:
graph_colour = (0, 255, 0)
elif noise_thresholds[0]<noise_max<=noise_thresholds[1]:
graph_colour=(255, 255, 0)
else:
graph_colour = (255, 0, 0)
draw.line((5+i*6, HEIGHT, 5+i*6, HEIGHT - (noise_values[i][0]-35)), fill=graph_colour, width=5)
draw.text((5,0), location + " Noise Level", font=noise_smallfont, fill=message_colour)
if noise_max != 0 and (time.time() - last_page) > 2:
draw.line((0, HEIGHT - (noise_max-35), WIDTH, HEIGHT - (noise_max-35)), fill=max_graph_colour, width=1) #Display Max Line
if noise_max > 85:
text_height = HEIGHT - (noise_max-37)
else:
text_height = HEIGHT - (noise_max-20)
draw.text((0, text_height), f"Max {noise_max:.1f} dB {noise_max_datetime['Time']} {noise_max_datetime['Date']}", font=noise_vsmallfont, fill=max_graph_colour)
disp.display(img)
else:
for i in range(len(freq_values)):
if freq_values[i][3] == 1:
draw.line((15+i*20, HEIGHT, 15+i*20, HEIGHT - (freq_values[i][2]*0.747-45)), fill=(0, 0, 255), width=5)
draw.line((10+i*20, HEIGHT, 10+i*20, HEIGHT - (freq_values[i][1]*0.844-59)), fill=(0, 255, 0), width=5)
draw.line((5+i*20, HEIGHT, 5+i*20, HEIGHT - (freq_values[i][0]*1.14-103)), fill=(255, 0, 0), width=5)
draw.text((0,0), location + " Noise Bands", font=noise_smallfont, fill=message_colour)
disp.display(img)
def display_results(start_current_display, current_display_is_own, display_modes,
indoor_outdoor_display_duration, own_data, data_in_display_all_aq, outdoor_data,
outdoor_reading_captured, own_disp_values, outdoor_disp_values, delay, last_page, mode,
WIDTH, valid_barometer_history, forecast, barometer_available_time, barometer_change,
barometer_trend, icon_forecast, maxi_temp, mini_temp, air_quality_data,
air_quality_data_no_gas, gas_sensors_warm, outdoor_gas_sensors_warm, enable_display,
palette, enable_adafruit_io, aio_user_name, aio_household_prefix, enable_eco2_tvoc,
outdoor_source_type, own_noise_level, own_noise_max, own_noise_max_datetime,
own_noise_values, own_noise_freq_values, outdoor_noise_level, outdoor_noise_max,
outdoor_noise_max_datetime, outdoor_noise_values, outdoor_noise_freq_values):
# Allow for display selection if display is enabled,
# else only display the serial number on a background colour based on max_aqi
if enable_display:
proximity = ltr559.get_proximity()
# If the proximity crosses the threshold, toggle the mode
if proximity > 1500 and time.time() - last_page > delay:
mode += 1
mode %= len(display_modes)
print('Mode', mode)
last_page = time.time()
display_changed = True
else:
display_changed = False
selected_display_mode = display_modes[mode]
if enable_indoor_outdoor_functionality and indoor_outdoor_function == 'Indoor':
if outdoor_reading_captured:
if ((time.time() - start_current_display) > indoor_outdoor_display_duration):
current_display_is_own = not current_display_is_own
start_current_display = time.time()
else:
current_display_is_own = True
if selected_display_mode in own_data:
if current_display_is_own and indoor_outdoor_function == 'Indoor' or selected_display_mode == "Bar":
display_graphed_data('IN', own_disp_values, selected_display_mode, own_data[selected_display_mode],
WIDTH)
elif current_display_is_own and indoor_outdoor_function == 'Outdoor':
display_graphed_data('OUT', own_disp_values, selected_display_mode, own_data[selected_display_mode],
WIDTH)
elif not current_display_is_own and (indoor_outdoor_function == 'Indoor'
and (selected_display_mode == "CO2"
or selected_display_mode == "VOC"
or outdoor_source_type == "Luftdaten"
and (selected_display_mode == "Oxi"
or selected_display_mode == "Red"
or selected_display_mode == "NH3"
or selected_display_mode == "P1"
or selected_display_mode == "Lux")
or outdoor_source_type == "Adafruit IO"
and selected_display_mode == "Lux")):
# No outdoor gas, P1, Lux graphs when outdoor source is Luftdaten.
# No outdoor Lux graphs when the outdoor source is Adafruit IO
# and no outdoor CO2 or TVOC graphs,
# so always display indoor graph
display_graphed_data('IN', own_disp_values, selected_display_mode, own_data[selected_display_mode],
WIDTH)
else:
display_graphed_data('OUT', outdoor_disp_values, selected_display_mode,
outdoor_data[selected_display_mode], WIDTH)
elif selected_display_mode == "Forecast":
display_forecast(valid_barometer_history, forecast, barometer_available_time, own_data["Bar"][1],
barometer_change)
elif selected_display_mode == "Status":
display_status(enable_adafruit_io, aio_user_name, aio_household_prefix)
elif selected_display_mode == "All Air":
# Display everything on one screen
if current_display_is_own and indoor_outdoor_function == 'Indoor':
display_all_aq('IN', own_data, data_in_display_all_aq, enable_eco2_tvoc)
elif current_display_is_own and indoor_outdoor_function == 'Outdoor':
display_all_aq('OUT', own_data, data_in_display_all_aq, enable_eco2_tvoc)
else:
display_all_aq('OUT', outdoor_data, data_in_display_all_aq, enable_eco2_tvoc)
elif selected_display_mode == "Icon Weather":
# Display icon weather/aqi
if current_display_is_own and indoor_outdoor_function == 'Indoor':
display_icon_weather_aqi('IN', own_data, barometer_trend, icon_forecast, maxi_temp, mini_temp,
air_quality_data,
air_quality_data_no_gas, icon_air_quality_levels, gas_sensors_warm, own_noise_level, own_noise_max)
elif current_display_is_own and indoor_outdoor_function == 'Outdoor':
display_icon_weather_aqi('OUT', own_data, barometer_trend, icon_forecast, maxi_temp, mini_temp,
air_quality_data,
air_quality_data_no_gas, icon_air_quality_levels, gas_sensors_warm, own_noise_level, own_noise_max)
else:
display_icon_weather_aqi('OUT', outdoor_data, barometer_trend, icon_forecast, outdoor_maxi_temp,
outdoor_mini_temp,
air_quality_data, air_quality_data_no_gas, icon_air_quality_levels,
outdoor_gas_sensors_warm, outdoor_noise_level, outdoor_noise_max)
elif "Noise" in selected_display_mode:
if selected_display_mode == "Noise Level" and display_changed:
own_noise_max = 0 # Reset Max Noise Reading when first entering "Noise Level Mode"
if current_display_is_own:
display_noise(indoor_outdoor_function, selected_display_mode, own_noise_level, own_noise_max, own_noise_max_datetime, display_changed, last_page, own_noise_values, own_noise_freq_values)
elif not current_display_is_own and indoor_outdoor_function == 'Indoor' and outdoor_noise_level == 0: # Don't display outdoor noise levels on indoor unit when there are no outdoor noise readings
display_noise("Indoor", selected_display_mode, own_noise_level, own_noise_max, own_noise_max_datetime, display_changed, last_page, own_noise_values, own_noise_freq_values)
else:
display_noise("Outdoor", selected_display_mode, outdoor_noise_level, outdoor_noise_max, outdoor_noise_max_datetime, display_changed, last_page, outdoor_noise_values, outdoor_noise_freq_values)
else:
pass
else:
disabled_display(gas_sensors_warm, air_quality_data, air_quality_data_no_gas, own_data, palette,
enable_adafruit_io, aio_user_name, aio_household_prefix)
return last_page, mode, start_current_display, current_display_is_own, own_noise_max
class ExternalSensors(object): # Handles the external temp/hum/bar sensors
def __init__(self):
self.barometer_update_time = 0
self.temp_humidity_update_time = 0
#self.print_update('Instantiated External Sensors')