forked from roscoe81/enviro-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Northcliff_AQI_Monitor_Gen.py
1882 lines (1792 loc) · 105 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
monitor_version = "5.22 - Gen"
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
import numpy
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
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+ (and optional SGP30) sensor capture and display, plus external sensor capture and Luftdaten, mqtt and Adafruit IO Updates
#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']
mqtt_username = parsed_config_parameters['mqtt_username']
mqtt_password = parsed_config_parameters['mqtt_password']
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
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, enable_luftdaten, 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,
enable_luftdaten, 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)
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_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]), 1)
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, 1), "Comp Bar:", own_data["Bar"][1])
else:
print("External Barometer")
own_data["Bar"][1] = round(float(es.barometer), 1)
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 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>', '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] > 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):
print("Sending Data to Luftdaten")
if enable_particle_sensor:
pm_values = dict(i for i in luft_values.items() if i[0].startswith("P"))
temp_values = dict(i for i in luft_values.items() if not i[0].startswith("P"))
resp1_exception = False
resp2_exception = False
if enable_particle_sensor:
try:
resp_1 = requests.post("https://api.luftdaten.info/v1/push-sensor-data/",
json={
"software_version": "enviro-plus 0.0.1",
"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:
resp1_exception = True
print('Luftdaten PM Connection Error', e)
except requests.exceptions.Timeout as e:
resp1_exception = True
print('Luftdaten PM Timeout Error', e)
except requests.exceptions.RequestException as e:
resp1_exception = True
print('Luftdaten PM Request Error', e)
try:
resp_2 = requests.post("https://api.luftdaten.info/v1/push-sensor-data/",
json={
"software_version": "enviro-plus 0.0.1",
"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:
resp2_exception = True
print('Luftdaten Climate Connection Error', e)
except requests.exceptions.Timeout as e:
resp2_exception = True
print('Luftdaten Climate Timeout Error', e)
except requests.exceptions.RequestException as e:
resp2_exception = True
print('Luftdaten Climate Request Error', e)
if resp1_exception == False and resp2_exception == False:
if resp_1.ok and resp_2.ok:
return True
else:
return False
else:
return False
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':
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)
if msg.topic == incoming_temp_hum_mqtt_topic and parsed_json['name'] == incoming_temp_hum_mqtt_sensor_name: # Identify external temp/hum sensor
es.capture_temp_humidity(parsed_json)
if msg.topic == incoming_barometer_mqtt_topic and parsed_json['idx'] == incoming_barometer_sensor_id: # Identify external barometer
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
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 == "Oxi":
message = "{}: {:.2f}".format(i, data_value)
elif (i == "CO2" or i == "VOC") and location == "OUT":
message = "{}: N/A".format(i) # No CO2 or TVOC data comes from an outdoor unit (used on display of indoor unit when displaying outdoor readings)
else:
message = "{}: {:.0f}".format(i, round(data_value, 0))
lim = data[i][2]
rgb = palette[0]
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_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, luft_values, mqtt_values, 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):
# 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)
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"): # No outdoor CO2 or TVOC Graph, 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)
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)
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)
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)
last_page = time.time()
return last_page, mode, start_current_display, current_display_is_own
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')
def capture_barometer(self, value):
self.barometer = value[:-2] # Remove forecast data
self.barometer_update_time = time.time()
#self.print_update('External Barometer ' + self.barometer + ' Pa')
def capture_temp_humidity(self, parsed_json):
self.temperature = parsed_json['svalue1']+'0'
#self.print_update('External Temperature ' + self.temperature + ' degrees C')
self.humidity = parsed_json['svalue2']+'.00'
#self.print_update('External Humidity ' + self.humidity + '%')
self.temp_humidity_update_time = time.time()
def check_valid_readings(self, check_time):
if check_time - self.barometer_update_time < 500:
valid_barometer_reading = True
else:
valid_barometer_reading = False
if check_time - self.temp_humidity_update_time < 500:
valid_temp_humidity_reading = True
else:
valid_temp_humidity_reading = False
return valid_temp_humidity_reading, valid_barometer_reading
def print_update(self, message):
today = datetime.now()
print('')
print(message + ' on ' + today.strftime('%A %d %B %Y @ %H:%M:%S'))
def log_barometer(barometer, barometer_history): # Logs 3 hours of barometer readings, taken every 20 minutes
barometer_log_time = time.time()
three_hour_barometer=barometer_history[8] # Capture barometer reading from 3 hours ago
for pointer in range (8, 0, -1): # Move previous temperatures one position in the list to prepare for new temperature to be recorded
barometer_history[pointer] = barometer_history[pointer - 1]
barometer_history[0] = barometer # Log latest reading
if three_hour_barometer!=0:
valid_barometer_history = True
barometer_change = barometer - three_hour_barometer
if barometer_change > -1.1 and barometer_change < 1.1:
barometer_trend = '-'
elif barometer_change <= -1.1 and barometer_change > -4:
barometer_trend = '<'
elif barometer_change <= -4 and barometer_change > -10:
barometer_trend = '<<'
elif barometer_change <= -10:
barometer_trend = '<!'
elif barometer_change >= 1.1 and barometer_change < 6:
barometer_trend = '>'
elif barometer_change >= 6 and barometer_change < 10:
barometer_trend = '>>'
elif barometer_change >= 10:
barometer_trend = '>!'
else:
pass
forecast, icon_forecast, domoticz_forecast, aio_forecast = analyse_barometer(barometer_change, barometer)
else:
valid_barometer_history=False
forecast = 'Insufficient Data'
icon_forecast = 'Wait'
aio_forecast = 'question'
domoticz_forecast = '0'
barometer_change = 0
barometer_trend = ''
#print("Log Barometer")
#print("Result", barometer_history, "Valid Barometer History is", valid_barometer_history, "3 Hour Barometer Change is", round(barometer_change,2), "millibars")
return barometer_history, barometer_change, valid_barometer_history, barometer_log_time, forecast, barometer_trend, icon_forecast, domoticz_forecast, aio_forecast
def analyse_barometer(barometer_change, barometer):
if barometer<1009:
if barometer_change>-1.1 and barometer_change<6:
forecast = 'Clearing and Colder'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'thermometer-quarter'
elif barometer_change>=6 and barometer_change<10:
forecast = 'Strong Wind Warning'
icon_forecast = 'Windy'
domoticz_forecast = '3'
aio_forecast = 'w:wind-beaufort-7'
elif barometer_change>=10:
forecast = 'Gale Warning'
icon_forecast = 'Gale'
domoticz_forecast = '4'
aio_forecast = 'w:wind-beaufort-9'
elif barometer_change<=-1.1 and barometer_change>=-4:
forecast = 'Rain and Wind'
icon_forecast = 'Rain'
domoticz_forecast = '4'
aio_forecast = 'w:rain-wind'
elif barometer_change<-4 and barometer_change>-10:
forecast = 'Storm'
icon_forecast = 'Storm'
domoticz_forecast = '4'
aio_forecast = 'w:thunderstorm'
else:
forecast = 'Storm and Gale'
icon_forecast = 'Gale'
domoticz_forecast = '4'
aio_forecast = 'w:thunderstorm'
elif barometer>=1009 and barometer <=1018:
if barometer_change>-4 and barometer_change<1.1:
forecast = 'No Change'
icon_forecast = 'Stable'
domoticz_forecast = '0'
aio_forecast = 'balance-scale'
elif barometer_change>=1.1 and barometer_change<=6 and barometer<=1015:
forecast = 'No Change'
icon_forecast = 'Stable'
domoticz_forecast = '0'
aio_forecast = 'balance-scale'
elif barometer_change>=1.1 and barometer_change<=6 and barometer>1015:
forecast = 'Poorer Weather'
icon_forecast = 'Poorer'
domoticz_forecast = '3'
aio_forecast = 'w:cloud'
elif barometer_change>=6 and barometer_change<10:
forecast = 'Strong Wind Warning'
icon_forecast = 'Windy'
domoticz_forecast = '3'
aio_forecast = 'w:wind-beaufort-7'
elif barometer_change>=10:
forecast = 'Gale Warning'
icon_forecast = 'Gale'
domoticz_forecast = '4'
aio_forecast = 'w:wind-beaufort-9'
else:
forecast = 'Rain and Wind'
icon_forecast = 'Rain'
domoticz_forecast = '4'
aio_forecast = 'w:rain-wind'
elif barometer>1018 and barometer <=1023:
if barometer_change>0 and barometer_change<1.1:
forecast = 'No Change'
icon_forecast = 'Stable'
domoticz_forecast = '0'
aio_forecast = 'balance-scale'
elif barometer_change>=1.1 and barometer_change<6:
forecast = 'Poorer Weather'
icon_forecast = 'Poorer'
domoticz_forecast = '3'
aio_forecast = 'w:cloud'
elif barometer_change>=6 and barometer_change<10:
forecast = 'Strong Wind Warning'
icon_forecast = 'Windy'
domoticz_forecast = '3'
aio_forecast = 'w:wind-beaufort-7'
elif barometer_change>=10:
forecast = 'Gale Warning'
icon_forecast = 'Gale'
domoticz_forecast = '4'
aio_forecast = 'w:wind-beaufort-9'
elif barometer_change>-1.1 and barometer_change<=0:
forecast = 'Fair Weather with\nSlight Temp Change'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'w:day-sunny'
elif barometer_change<=-1.1 and barometer_change>-4:
forecast = 'No Change but\nRain in 24 Hours'
icon_forecast = 'Stable'
domoticz_forecast = '0'
aio_forecast = 'balance-scale'
else:
forecast = 'Rain, Wind and\n Higher Temp'
icon_forecast = 'Rain'
domoticz_forecast = '4'
aio_forecast = 'w:rain-wind'
else: # barometer>1023
if barometer_change>0 and barometer_change<1.1:
forecast = 'Fair Weather'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'w:day-sunny'
elif barometer_change>-1.1 and barometer_change<=0:
forecast = 'Fair Weather with\nLittle Temp Change'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'w:day-sunny'
elif barometer_change>=1.1 and barometer_change<6:
forecast = 'Poorer Weather'
icon_forecast = 'Poorer'
domoticz_forecast = '3'
aio_forecast = 'w:cloud'
elif barometer_change>=6 and barometer_change<10:
forecast = 'Strong Wind Warning'
icon_forecast = 'Windy'
domoticz_forecast = '3'
aio_forecast = 'w:wind-beaufort-7'
elif barometer_change>=10:
forecast = 'Gale Warning'
icon_forecast = 'Gale'
domoticz_forecast = '4'
aio_forecast = 'w:wind-beaufort-9'
elif barometer_change<=-1.1 and barometer_change>-4:
forecast = 'Fair Weather and\nSlowly Rising Temp'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'w:day-sunny'
else:
forecast = 'Warming Trend'
icon_forecast = 'Fair'
domoticz_forecast = '1'
aio_forecast = 'thermometer-three-quarters'
print('3 hour barometer change is '+str(round(barometer_change,1))+' millibars with a current reading of '+str(round(barometer,1))+' millibars. The weather forecast is '+forecast)
return forecast, icon_forecast, domoticz_forecast, aio_forecast
# Icon Display Methods
def calculate_y_pos(x, centre):
"""Calculates the y-coordinate on a parabolic curve, given x."""
centre = 80
y = 1 / centre * (x - centre) ** 2 + sun_radius
return int(y)
def circle_coordinates(x, y, radius):
"""Calculates the bounds of a circle, given centre and radius."""
x1 = x - radius # Left
x2 = x + radius # Right
y1 = y - radius # Bottom
y2 = y + radius # Top
return (x1, y1, x2, y2)
def map_colour(x, centre, icon_aqi_level, day):
"""Given an x coordinate and a centre point, an aqi hue (in degrees),
and a Boolean for day or night (day is True, night False), calculate a colour
hue representing the 'colour' of that aqi level."""
sat = 1.0
# Dim the brightness as you move from the centre to the edges
val = 0.8 - 0.6 * (abs(centre - x) / (2 * centre))
# Select the hue based on the max aqi level and rescale between 0 and 1
hue = icon_background_hue[icon_aqi_level]/360
# Reverse dimming at night
if not day:
val = 1 - val
#print(day, x, hue, sat, val)
r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, sat, val)]
return (r, g, b)
def x_from_sun_moon_time(progress, period, x_range):
"""Recalculate/rescale an amount of progress through a time period."""
x = int((progress / period) * x_range)
return x
def sun_moon_time(city_name, time_zone):
"""Calculate the progress through the current sun/moon period (i.e day or
night) from the last sunrise or sunset, given a datetime object 't'."""
city = lookup(city_name, db)
# Datetime objects for yesterday, today, tomorrow
utc = pytz.utc
utc_dt = datetime.now(tz=utc)