-
Notifications
You must be signed in to change notification settings - Fork 0
/
powered_air_quality.ino
1519 lines (1327 loc) · 53.3 KB
/
powered_air_quality.ino
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
/*
Project: Powered Air Quality
Description: Sample and log indoor air quality via AC powered device
See README.md for target information
*/
// hardware and internet configuration parameters
#include "config.h"
// private credentials for network, MQTT
#include "secrets.h"
#ifndef HARDWARE_SIMULATE
// sensor support
// instanstiate pm hardware object
// #include "Adafruit_PM25AQI.h"
// Adafruit_PM25AQI pmSensor = Adafruit_PM25AQI();
#include <SensirionI2CSen5x.h>
SensirionI2CSen5x pmSensor;
// instanstiate SCD4X hardware object
#include <SensirionI2CScd4x.h>
SensirionI2CScd4x co2Sensor;
// WiFi support
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include <HTTPClient.h>
WiFiClient client; // used by OWM and MQTT
#endif
#include <SPI.h>
// Note: the ESP32 has 2 SPI ports, to have ESP32-2432S028R work with the TFT and Touch on different SPI ports each needs to be defined and passed to the library
SPIClass hspi = SPIClass(HSPI);
SPIClass vspi = SPIClass(VSPI);
// screen support
// 3.2″ 320x240 color TFT w/resistive touch screen, ILI9341 driver
#include "Adafruit_ILI9341.h"
Adafruit_ILI9341 display = Adafruit_ILI9341(&hspi, TFT_DC, TFT_CS, TFT_RST);
// works without SPIClass call, slower
// Adafruit_ILI9341 display = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST, TFT_MISO);
#include <XPT2046_Touchscreen.h>
XPT2046_Touchscreen ts(XPT2046_CS,XPT2046_IRQ);
#include <Fonts/FreeSans9pt7b.h>
#include <Fonts/FreeSans12pt7b.h>
#include <Fonts/FreeSans18pt7b.h>
#include <Fonts/FreeSans24pt7b.h>
#include "Fonts/meteocons20pt7b.h"
#include "Fonts/meteocons16pt7b.h"
#include "Fonts/meteocons12pt7b.h"
// Library needed to access Open Weather Map
#include "ArduinoJson.h" // Needed by OWM retrieval routines
// UI glyphs
#include "glyphs.h"
#if defined(MQTT) || defined(INFLUX) || defined(HASSIO_MQTT)
// NTP setup using Esperiff library
#include <time.h>
#endif
// button support
// #include <ezButton.h>
// ezButton buttonOne(buttonD1Pin);
// external function dependencies
#ifdef DWEET
extern void post_dweet(float pm25, float minaqi, float maxaqi, float aqi, float temperatureF, float vocIndex, float humidity, int rssi);
#endif
#ifdef THINGSPEAK
extern void post_thingspeak(float pm25, float minaqi, float maxaqi, float aqi);
#endif
#ifdef INFLUX
extern bool post_influx(float pm25, float temperatureF, float vocIndex, float humidity, uint16_t co2, uint8_t rssi);
#endif
#ifdef MQTT
// MQTT interface depends on the underlying network client object, which is defined and
// managed here (so needs to be defined here).
#include <Adafruit_MQTT.h>
#include <Adafruit_MQTT_Client.h>
Adafruit_MQTT_Client aq_mqtt(&client, MQTT_BROKER, MQTT_PORT, DEVICE_ID, MQTT_USER, MQTT_PASS);
extern bool mqttDeviceWiFiUpdate(uint8_t rssi);
extern bool mqttSensorTemperatureFUpdate(float temperatureF);
extern bool mqttSensorHumidityUpdate(float humidity);
extern bool mqttSensorCO2Update(uint16_t co2);
extern bool mqttSensorPM25Update(float pm25);
extern bool mqttSensorVOCIndexUpdate(float vocIndex);
#ifdef HASSIO_MQTT
extern void hassio_mqtt_publish(float pm25, float temperatureF, float vocIndex, float humidity, uint16_t co2);
#endif
#endif
// global variables
// environment sensor data
typedef struct envData
{
// SCD40 data
float ambientTemperatureF; // range -10C to 60C
float ambientHumidity; // RH [%], range 0 to 100
uint16_t ambientCO2; // ppm, range 400 to 2000
// Common data to PMSA003I and SEN5x
float pm25; // PM2.5 [µg/m³], (SEN54 -> range 0 to 1000, NAN if unknown)
float pm1; // PM1.0 [µg/m³], (SEN54 -> range 0 to 1000, NAN if unknown)
float pm10; // PM10.0 [µg/m³], (SEN54 -> range 0 to 1000, NAN if unknown)
// SEN5x specific data
float pm4; // PM4.0 [µg/m³], range 0 to 1000, NAN if unknown
float vocIndex; // Sensiron VOC Index, range 0 to 500, NAN in unknown
float noxIndex; // NAN for SEN54, also NAN for first 10-11 seconds on SEN55
// PMSA003I specific data
// uint16_t pm10_env; // Environmental PM1.0
// uint16_t pm25_env; // Environmental PM2.5
// uint16_t pm100_env; // Environmental PM10.0
// uint16_t particles_03um; //< 0.3um Particle Count
// unit16_t particles_05um; //< 0.5um Particle Count
// unit16_t particles_10um; //< 1.0um Particle Count
// unit16_t particles_25um; //< 2.5um Particle Count
// unit16_t particles_50um; //< 5.0um Particle Count
// unit16_t particles_100um; //< 10.0um Particle Count
} envData;
envData sensorData;
float temperatureFTotal = 0; // running total of temperature over report interval
float humidityTotal = 0; // running total of humidity over report interval
uint16_t co2Total = 0; // running total of C02 over report interval
float vocTotal = 0; // running total of VOC over report interval
float pm25Total = 0; // running total of humidity over report interval
// IMPROVEMENT: avg values can be local to loop() vs. global?
float avgtemperatureF = 0; // average temperature over report interval
float avgHumidity = 0; // average humidity over report interval
uint16_t avgCO2 = 0; // average CO2 over report interval
float avgVOC = 0; // average VOC over report interval
float avgPM25 = 0; // average PM2.5 over report interval
uint8_t numSamples = 0; // Number of overall sensor readings over reporting interval
uint32_t timeLastSample = 0; // timestamp (in ms) for last captured sample
uint32_t timeLastReport = 0; // timestamp (in ms) for last report to network endpoints
// used by thingspeak and dweet
float MinPm25 = 1999; /* Observed minimum PM2.5 */
float MaxPm25 = -99; /* Observed maximum PM2.5 */
// hardware status data
typedef struct hdweData
{
// float batteryPercent;
// float batteryVoltage;
// float batteryTemperatureF;
uint8_t rssi; // WiFi RSSI value
} hdweData;
hdweData hardwareData;
// OpenWeatherMap Current data
typedef struct {
// float lon; // "lon": 8.54
// float lat; // "lat": 47.37
// uint16_t weatherId; // "id": 521
// String main; // "main": "Rain"
// String description; // "description": "shower rain"
String icon; // "icon": "09d"
float tempF; // "temp": 90.56, in F (API request for imperial units)
// uint16_t pressure; // "pressure": 1013, in hPa
uint16_t humidity; // "humidity": 87, in RH%
// float tempMin; // "temp_min": 89.15
// float tempMax; // "temp_max": 92.15
// uint16_t visibility; // visibility: 10000, in meters
// float windSpeed; // "wind": {"speed": 1.5}, in meters/s
// float windDeg; // "wind": {deg: 226.505}
// uint8_t clouds; // "clouds": {"all": 90}, in %
// time_t observationTime; // "dt": 1527015000, in UTC
// String country; // "country": "CH"
// time_t sunrise; // "sunrise": 1526960448, in UTC
// time_t sunset; // "sunset": 1527015901, in UTC
String cityName; // "name": "Zurich"
// time_t timezone; // shift in seconds from UTC
} OpenWeatherMapCurrentData;
OpenWeatherMapCurrentData owmCurrentData; // global variable for OWM current data
// OpenWeatherMap Air Quality data
typedef struct {
// float lon; // "lon": 8.54
// float lat; // "lat": 47.37
uint16_t aqi; // "aqi": 2
// float co; // "co": 453.95, in μg/m3
// float no; // "no": 0.47, in μg/m3
// float no2; // "no2": 52.09, in μg/m3
// float o3; // "o3": 17.17, in μg/m3
// float so2; // "so2": 7.51, in μg/m3
float pm25; // "pm2.5": 8.04, in μg/m3
// float pm10; // "pm10": 9.96, in μg/m3
// float nh3; // "nh3": 0.86, in μg/m3
} OpenWeatherMapAirQuality;
OpenWeatherMapAirQuality owmAirQuality; // global variable for OWM current data
bool screenWasTouched = false;
// set first screen to display
uint8_t screenCurrent = 0;
void setup()
{
// handle Serial first so debugMessage() works
#ifdef DEBUG
Serial.begin(115200);
// wait for serial port connection
while (!Serial);
// Display key configuration parameters
debugMessage(String("Starting Powered Air Quality with ") + sensorSampleInterval + " second sample interval",1);
#if defined(MQTT) || defined(INFLUX) || defined(HASSIO_MQTT)
debugMessage(String("Report interval is ") + sensorReportInterval + " minutes",1);
#endif
debugMessage(String("Internet reconnect delay is ") + networkConnectAttemptInterval + " seconds",2);
#endif
// generate random numbers for every boot cycle
randomSeed(analogRead(0));
// initialize screen first to display hardware error messages
pinMode(TFT_BACKLIGHT, OUTPUT);
digitalWrite(TFT_BACKLIGHT, HIGH);
display.begin();
display.setRotation(screenRotation);
display.setTextWrap(false);
display.fillScreen(ILI9341_BLACK);
screenAlert("Initializing");
// Initialize PM25 sensor
if (!sensorPMInit()) {
debugMessage("SEN5X initialization failure", 1);
screenAlert("No SEN5X");
}
// Initialize SCD4X
if (!sensorCO2Init()) {
debugMessage("SCD4X initialization failure",1);
screenAlert("No SCD4X");
// This error often occurs right after a firmware flash and reset.
// Hardware deep sleep typically resolves it, so quickly cycle the hardware
powerDisable(hardwareRebootInterval);
}
// Setup the VSPI to use custom pins for the touchscreen
vspi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS);
ts.begin(vspi);
// buttonOne.setDebounceTime(buttonDebounceDelay);
// start WiFi (for OWM)
if (!networkConnect())
hardwareData.rssi = 0; // 0 = no WiFi
// start tracking timers
timeLastSample = -(sensorSampleInterval*1000); // forces immediate sample in loop()
timeLastReport = millis();
}
void loop()
{
// update current timer value
uint32_t timeCurrent = millis();
// is it time to read the sensor?
if((timeCurrent - timeLastSample) >= (sensorSampleInterval * 1000)) // converting sensorSampleInterval into milliseconds
{
if (!sensorPMRead())
{
// TODO: what else to do here, see OWM Reads...
}
if (!sensorCO2Read())
{
// TODO: what else to do here
}
// Get local weather and air quality info from Open Weather Map
if (!OWMCurrentWeatherRead()) {
owmCurrentData.tempF = 10000;
}
if (!OWMAirPollutionRead()) {
owmAirQuality.aqi = 10000;
}
// add to the running totals
numSamples++;
temperatureFTotal += sensorData.ambientTemperatureF;
humidityTotal += sensorData.ambientHumidity;
co2Total += sensorData.ambientCO2;
vocTotal += sensorData.vocIndex;
pm25Total += sensorData.pm25;
debugMessage(String("Sample #") + numSamples + ", running totals: ",2);
debugMessage(String("temperatureF total: ") + temperatureFTotal,2);
debugMessage(String("Humidity total: ") + humidityTotal,2);
debugMessage(String("CO2 total: ") + co2Total,2);
debugMessage(String("VOC total: ") + vocTotal,2);
debugMessage(String("PM25 total: ") + pm25Total,2);
screenSaver();
// Save last sample time
timeLastSample = millis();
}
// user input = change screens
boolean istouched = ts.touched();
if (istouched)
{
((screenCurrent + 1) >= screenCount) ? screenCurrent = 0 : screenCurrent ++;
debugMessage(String("touchscreen pressed, switch to screen ") + screenCurrent,1);
screenUpdate(true);
}
// buttonOne.loop();
// if (buttonOne.isReleased())
// {
// ((screenCurrent + 1) >= screenCount) ? screenCurrent = 0 : screenCurrent ++;
// debugMessage(String("button 1 press, switch to screen ") + screenCurrent,1);
// screenUpdate(true);
// }
// do we have network endpoints to report to?
#if defined(MQTT) || defined(INFLUX) || defined(HASSIO_MQTT)
// is it time to report to the network endpoints?
if ((timeCurrent - timeLastReport) >= (sensorReportInterval * 60 * 1000)) // converting sensorReportInterval into milliseconds
{
// do we have samples to report?
if (numSamples != 0)
{
// average the sample totals
avgtemperatureF = temperatureFTotal / numSamples;
avgHumidity = humidityTotal / numSamples;
avgCO2 = co2Total / numSamples;
avgVOC = vocTotal / numSamples;
avgPM25 = pm25Total / numSamples;
if (avgPM25 > MaxPm25) MaxPm25 = avgPM25;
if (avgPM25 < MinPm25) MinPm25 = avgPM25;
debugMessage("----- Reporting -----",1);
debugMessage(String("Reporting averages (") + sensorReportInterval + " minute): ",1);
debugMessage(String("Temp: ") + avgtemperatureF + " F",1);
debugMessage(String("Humidity: ") + avgHumidity + "%",1);
debugMessage(String("CO2: ") + avgCO2 + " ppm",1);
debugMessage(String("VOC: ") + avgVOC,1);
debugMessage(String("PM2.5: ") + avgPM25 + " = AQI " + pm25toAQI(avgPM25),1);
if (networkConnect())
{
/* Post both the current readings and historical max/min readings to the internet */
#ifdef DWEET
post_dweet(avgPM25, pm25toAQI(MinPm25), pm25toAQI(MaxPm25), pm25toAQI(avgPM25), avgtemperatureF, avgVOC, avgHumidity, rssi);
#endif
// Also post the AQI sensor data to ThingSpeak
#ifdef THINGSPEAK
post_thingspeak(avgPM25, pm25toAQI(MinPm25), pm25toAQI(MaxPm25), pm25toAQI(avgPM25));
#endif
#ifdef INFLUX
if (!post_influx(avgPM25, avgtemperatureF, avgVOC, avgHumidity, avgCO2 , hardwareData.rssi))
debugMessage("Did not write to influxDB",1);
#endif
#ifdef MQTT
if (!mqttDeviceWiFiUpdate(hardwareData.rssi))
debugMessage("Did not write device data to MQTT broker",1);
if ((!mqttSensorTemperatureFUpdate(avgtemperatureF)) || (!mqttSensorHumidityUpdate(avgHumidity)) || (!mqttSensorPM25Update(avgPM25)) || (!mqttSensorVOCIndexUpdate(avgVOC)) || (!mqttSensorCO2Update(avgCO2)))
debugMessage("Did not write environment data to MQTT broker",1);
#ifdef HASSIO_MQTT
debugMessage("Establishing MQTT for Home Assistant",1);
// Either configure sensors in Home Assistant's configuration.yaml file
// directly or attempt to do it via MQTT auto-discovery
// hassio_mqtt_setup(); // Config for MQTT auto-discovery
hassio_mqtt_publish(avgPM25, avgtemperatureF, avgVOC, avgHumidity);
#endif
#endif
}
// Reset sample counters
numSamples = 0;
temperatureFTotal = 0;
humidityTotal = 0;
co2Total = 0;
vocTotal = 0;
pm25Total = 0;
// save last report time
timeLastReport = millis();
}
}
#endif
}
void screenUpdate(bool firstTime)
{
switch(screenCurrent) {
case 0:
screenSaver();
break;
case 1:
screenCurrentInfo();
break;
case 2:
screenVOC();
break;
case 3:
screenColor();
break;
case 4:
screenGraph();
break;
default:
// This shouldn't happen, but if it does...
screenCurrentInfo();
debugMessage("bad screen ID",1);
break;
}
}
void screenCurrentInfo()
// Display current particulate matter, CO2, and local weather on screen
{
// screen layout assists in pixels
const uint16_t xOutdoorMargin = ((display.width() / 2) + xMargins);
const uint16_t yStatus = (display.height() * 7 / 8);
const uint16_t yTemperature = 35;
const uint8_t legendHeight = 15;
const uint8_t legendWidth = 10;
const uint16_t xLegend = ((display.width() / 2) - legendWidth);
const uint16_t yLegend = 110;
const uint16_t xIndoorPMCircle = (display.width() / 4);
const uint16_t xOutdoorPMCircle = ((display.width() / 4) * 3);
const uint16_t yPMCircle = 87;
const uint16_t circleRadius = 40;
const uint16_t xPMLabel = ((display.width() / 2) - 25);
const uint16_t yPMLabel = 125;
// const uint16_t xIndoorPMValue = xIndoorPMCircle;
// const uint16_t xOutdoorPMValue = xOutdoorPMCircle;
// const uint16_t yPMValue = yPMCircle;
const uint16_t yAQIValue = 160;
const uint16_t xWeatherIcon = ((display.width() / 4) * 3);
const uint16_t yWeatherIcon = 200;
const uint16_t yCO2 = 160;
// const uint16_t ySparkline = 40;
debugMessage("screenCurrentInfo() start", 1);
// clear screen
display.fillScreen(ILI9341_BLACK);
// borders
display.drawFastHLine(0, yStatus, display.width(), ILI9341_WHITE);
// splitting sensor vs. outside values
display.drawFastVLine((display.width() / 2), 0, (yLegend - ((legendHeight*4) + 5)), ILI9341_WHITE);
display.drawFastVLine((display.width() / 2), yLegend + 5, (yStatus-(yLegend + 5)), ILI9341_WHITE);
// screen helper routines
screenHelperWiFiStatus((display.width() - xMargins - ((5*wifiBarWidth)+(4*wifiBarSpacing))), (display.height() - (5*wifiBarHeightIncrement)), wifiBarWidth, wifiBarHeightIncrement, wifiBarSpacing);
// PM2.5 color legend
for(uint8_t loop = 0; loop < 4; loop++){
display.fillRect(xLegend,(yLegend-(loop*legendHeight)),legendWidth,legendHeight,warningColor[loop]);
}
// PM2.5 legend label
display.setTextColor(ILI9341_WHITE);
display.setFont();
display.setCursor(xPMLabel,yPMLabel);
display.print("PM2.5");
// Indoor
// Indoor temp
display.setFont(&FreeSans12pt7b);
display.setCursor(xMargins, yTemperature);
display.print(String((uint8_t)(sensorData.ambientTemperatureF + .5)));
display.setFont(&meteocons12pt7b);
display.print("+");
// Indoor humidity
display.setFont(&FreeSans12pt7b);
display.setCursor(xMargins + 60, yTemperature);
if ((sensorData.ambientHumidity<40) || (sensorData.ambientHumidity>60))
display.setTextColor(ILI9341_RED);
else
display.setTextColor(ILI9341_GREEN);
display.print(String((uint8_t)(sensorData.ambientHumidity + 0.5)));
// original icon ratio was 5:7?
display.drawBitmap(xMargins + 90, yTemperature - 21, epd_bitmap_humidity_icon_sm4, 20, 28, ILI9341_WHITE);
// Indoor PM2.5 circle
display.fillCircle(xIndoorPMCircle,yPMCircle,circleRadius,warningColor[aqiRange(sensorData.pm25)]);
// Indoor PM2.5 value
display.setFont(&FreeSans12pt7b);
display.setTextColor(ILI9341_WHITE);
display.setCursor(xIndoorPMCircle,yPMCircle);
display.print(int(sensorData.pm25+.5));
// Indoor CO2 level
// CO2 label line
display.setFont(&FreeSans12pt7b);
display.setCursor(xMargins, yCO2);
display.print("CO");
display.setCursor(xMargins + 55, yCO2);
display.setTextColor(warningColor[co2Range(sensorData.ambientCO2)]); // Use highlight color look-up table
display.print(String(warningLabels[co2Range(sensorData.ambientCO2)]));
// subscript
display.setFont(&FreeSans9pt7b);
display.setTextColor(ILI9341_WHITE);
display.setCursor(xMargins + 35, (yCO2 + 10));
display.print("2");
// CO2 value line
display.setFont();
display.setCursor((xMargins + 88), (yCO2 + 7));
display.print("(" + String(sensorData.ambientCO2) + ")");
// Outside
// do we have OWM Current data to display?
if (owmCurrentData.tempF != 10000) {
// location label
display.setFont();
display.setCursor((display.width() * 5 / 8), yMargins);
display.print(owmCurrentData.cityName);
// Outside temp
display.setFont(&FreeSans12pt7b);
display.setCursor(xOutdoorMargin, yTemperature);
display.print(String((uint8_t)(owmCurrentData.tempF + 0.5)));
display.setFont(&meteocons12pt7b);
display.print("+");
// Outside humidity
display.setFont(&FreeSans12pt7b);
display.setCursor(xOutdoorMargin + 60, yTemperature);
if ((owmCurrentData.humidity<40) || (owmCurrentData.humidity>60))
display.setTextColor(ILI9341_RED);
else
display.setTextColor(ILI9341_GREEN);
display.print(String((uint8_t)(owmCurrentData.humidity + 0.5)));
display.drawBitmap(xOutdoorMargin + 90, yTemperature - 21, epd_bitmap_humidity_icon_sm4, 20, 28, ILI9341_WHITE);
// weather icon
String weatherIcon = OWMtoMeteoconIcon(owmCurrentData.icon);
// if getMeteoIcon doesn't have a matching symbol, skip display
if (weatherIcon != ")") {
// display icon
display.setFont(&meteocons20pt7b);
display.setCursor(xWeatherIcon, yWeatherIcon);
display.print(weatherIcon);
}
}
// do we have OWM Air Quality data to display?
if (owmAirQuality.aqi != 10000) {
// Outside PM2.5
display.fillCircle(xOutdoorPMCircle,yPMCircle,circleRadius,warningColor[aqiRange(owmAirQuality.pm25)]);
// PM2.5 numeric value (displayed inside circle)
display.setFont(&FreeSans12pt7b);
display.setCursor(xOutdoorPMCircle,yPMCircle);
display.setTextColor(ILI9341_WHITE);
display.print(int(owmAirQuality.pm25+.5));
// Outside air quality index (AQI)
display.setFont(&FreeSans9pt7b);
display.setCursor(xOutdoorMargin, yAQIValue);
display.setTextColor(ILI9341_WHITE);
display.print(OWMAQILabels[(owmAirQuality.aqi)]);
display.print(" AQI");
}
debugMessage("screenCurrentInfo() end", 1);
}
void screenAlert(String messageText)
// Display error message centered on screen
{
debugMessage(String("screenAlert '") + messageText + "' start",1);
// Clear the screen
display.fillScreen(ILI9341_BLACK);
int16_t x1, y1;
uint16_t width, height;
display.setTextColor(ILI9341_WHITE);
display.setFont(&FreeSans24pt7b);
display.getTextBounds(messageText.c_str(), 0, 0, &x1, &y1, &width, &height);
if (width >= display.width()) {
debugMessage(String("ERROR: screenAlert '") + messageText + "' is " + abs(display.width()-width) + " pixels too long", 1);
}
display.setCursor(display.width() / 2 - width / 2, display.height() / 2 + height / 2);
display.print(messageText);
debugMessage("screenAlert end",1);
}
void screenGraph()
// Displays CO2 values over time as a graph
{
// screen layout assists in pixels
// const uint16_t ySparkline = 95;
// const uint16_t sparklineHeight = 40;
debugMessage("screenGraph start",1);
screenAlert("Graph");
debugMessage("screenGraph end",1);
}
void screenColor()
// Represents CO2 value on screen as a single color fill
{
debugMessage("screenColor start",1);
display.fillScreen(warningColor[co2Range(sensorData.ambientCO2)]); // Use highlight color LUT
debugMessage("screenColor end",1);
}
void screenSaver()
// Display current CO2 reading at a random location (e.g. "screen saver")
{
int16_t x, y;
debugMessage("screenSaver start",1);
display.fillScreen(ILI9341_BLACK);
display.setTextSize(1); // Needed so custom fonts scale properly
display.setFont(&FreeSans18pt7b);
// Pick a random location that'll show up
x = random(xMargins,display.width()-xMargins-64); // 64 pixels leaves room for 4 digit CO2 value
y = random(35,display.height()-yMargins); // 35 pixels leaves vertical room for text display
display.setCursor(x,y);
display.setTextColor(warningColor[co2Range(sensorData.ambientCO2)]); // Use highlight color LUT
display.println(sensorData.ambientCO2);
debugMessage("screenSaver end",1);
}
// void screenAggregateData()
// // Displays minimum, average, and maximum values for CO2, temperature and humidity
// // using a table-style layout (with labels)
// {
// const uint16_t xHeaderColumn = 10;
// const uint16_t xCO2Column = 70;
// const uint16_t xTempColumn = 130;
// const uint16_t xHumidityColumn = 200;
// const uint16_t yHeaderRow = 10;
// const uint16_t yMaxRow = 40;
// const uint16_t yAvgRow = 70;
// const uint16_t yMinRow = 100;
// // clear screen
// display.fillScreen(ST77XX_BLACK);
// // display headers
// display.setFont(); // Revert to built-in font
// display.setTextSize(2);
// display.setTextColor(ST77XX_WHITE);
// // column
// display.setCursor(xCO2Column, yHeaderRow); display.print("CO2");
// display.setCursor(xTempColumn, yHeaderRow); display.print(" F");
// display.setCursor(xHumidityColumn, yHeaderRow); display.print("RH");
// // row
// display.setCursor(xHeaderColumn, yMaxRow); display.print("Max");
// display.setCursor(xHeaderColumn, yAvgRow); display.print("Avg");
// display.setCursor(xHeaderColumn, yMinRow); display.print("Min");
// // Fill in the maximum values row
// display.setCursor(xCO2Column, yMaxRow);
// display.setTextColor(warningColor[co2Range(totalCO2.getMax())]); // Use highlight color look-up table
// display.print(totalCO2.getMax(),0);
// display.setTextColor(ST77XX_WHITE);
// display.setCursor(xTempColumn, yMaxRow); display.print(totalTemperatureF.getMax(),1);
// display.setCursor(xHumidityColumn, yMaxRow); display.print(totalHumidity.getMax(),0);
// // Fill in the average value row
// display.setCursor(xCO2Column, yAvgRow);
// display.setTextColor(warningColor[co2Range(totalCO2.getAverage())]); // Use highlight color look-up table
// display.print(totalCO2.getAverage(),0);
// display.setTextColor(ST77XX_WHITE);
// display.setCursor(xTempColumn, yAvgRow); display.print(totalTemperatureF.getAverage(),1);
// display.setCursor(xHumidityColumn, yAvgRow); display.print(totalHumidity.getAverage(),0);
// // Fill in the minimum value row
// display.setCursor(xCO2Column,yMinRow);
// display.setTextColor(warningColor[co2Range(totalCO2.getMin())]); // Use highlight color look-up table
// display.print(totalCO2.getMin(),0);
// display.setTextColor(ST77XX_WHITE);
// display.setCursor(xTempColumn,yMinRow); display.print(totalTemperatureF.getMin(),1);
// display.setCursor(xHumidityColumn,yMinRow); display.print(totalHumidity.getMin(),0);
// // Display current battery level on bottom right of screen
// //screenHelperBatteryStatus((display.width()-xMargins-batteryBarWidth-3),(display.height()-yMargins-batteryBarHeight), batteryBarWidth, batteryBarHeight);
// }
void screenVOC()
{
// screen layout assists in pixels
const uint8_t legendHeight = 20;
const uint8_t legendWidth = 10;
const uint16_t xLegend = (display.width() - xMargins - legendWidth);
const uint16_t yLegend = ((display.height() /2 ) + (legendHeight * 2));
const uint16_t circleRadius = 100;
const uint16_t xVOCCircle = (display.width() / 2);
const uint16_t yVOCCircle = (display.height() / 2);
const uint16_t xVOCLabel = (display.width() - xMargins - legendWidth);
const uint16_t yVOCLabel = ((display.height() /2 ) + (legendHeight * 2) + 25);
debugMessage("screenVOC start",1);
// clear screen
display.fillScreen(ILI9341_BLACK);
// VOC color circle
display.fillCircle(xVOCCircle,yVOCCircle,circleRadius,warningColor[vocRange(sensorData.vocIndex)]);
// VOC color legend
for(uint8_t loop = 0; loop < 4; loop++){
display.fillRect(xLegend,(yLegend-(loop*legendHeight)),legendWidth,legendHeight,warningColor[loop]);
}
// VOC legend label
display.setTextColor(ILI9341_WHITE);
display.setFont();
display.setCursor(xVOCLabel,yVOCLabel);
display.print("VOC");
// VOC value (displayed inside circle)
display.setFont(&FreeSans18pt7b);
display.setTextColor(ILI9341_WHITE);
display.setCursor(xVOCCircle,yVOCCircle);
display.print(int(sensorData.vocIndex+.5));
debugMessage("screenVOC end",1);
}
void screenHelperWiFiStatus(uint16_t initialX, uint16_t initialY, uint8_t barWidth, uint8_t barHeightIncrement, uint8_t barSpacing)
// helper function for screenXXX() routines that draws WiFi signal strength
{
if (hardwareData.rssi != 0) {
// Convert RSSI values to a 5 bar visual indicator
// >90 means no signal
uint8_t barCount = constrain((6 - ((hardwareData.rssi / 10) - 3)), 0, 5);
if (barCount > 0) {
// <50 rssi value = 5 bars, each +10 rssi value range = one less bar
// draw bars to represent WiFi strength
for (uint8_t loop = 1; loop <= barCount; loop++) {
display.fillRect((initialX + (loop * barSpacing)), (initialY - (loop * barHeightIncrement)), barWidth, loop * barHeightIncrement, ILI9341_WHITE);
}
debugMessage(String("WiFi signal strength on screen as ") + barCount + " bars", 2);
} else {
// you could do a visual representation of no WiFi strength here
debugMessage("RSSI too low, not displayed on screen", 1);
}
}
}
void screenHelperStatusMessage(uint16_t initialX, uint16_t initialY, String messageText)
// helper function for screenXXX() routines that draws a status message
// uses system default font, so text drawn x+,y+ from initialX,Y
{
// IMPROVEMENT : Screen dimension boundary checks for function parameters
#ifdef SCREEN
display.setFont(); // resets to system default monospace font (6x8 pixels)
display.setCursor(initialX, initialY);
display.print(messageText);
#endif
}
// Hardware simulation routines
#ifdef HARDWARE_SIMULATE
void OWMCurrentWeatherSimulate()
// Simulates Open Weather Map (OWM) Current Weather data
{
// Improvement - variable length names
owmCurrentData.cityName = "Pleasantville";
// Temperature
owmCurrentData.tempF = (random(sensorTempMinF,sensorTempMaxF) / 100.0);
// Humidity
owmCurrentData.humidity = random(sensorHumidityMin,sensorHumidityMax) / 100.0;
// IMPROVEMENT - variable icons
owmCurrentData.icon = "09d";
debugMessage(String("SIMULATED OWM Current Weather: ") + owmCurrentData.tempF + "F, " + owmCurrentData.humidity + "%", 1);
}
void OWMAirPollutionSimulate()
// Simulates Open Weather Map (OWM) Air Pollution data
{
owmAirQuality.aqi = random(OWMAQIMin, OWMAQIMax);
owmAirQuality.pm25 = random(OWMPM25Min, OWMPM25Max) / 100.0;
debugMessage(String("SIMULATED OWM Air Pollution PM2.5: ") + owmAirQuality.pm25 + ", AQI: " + owmAirQuality.aqi,1);
}
void networkSimulate()
// Simulates successful WiFi connection data
{
// IMPROVEMENT : simulate IP address?
hardwareData.rssi = random(networkRSSIMin, networkRSSIMax);
debugMessage(String("SIMULATED WiFi RSSI: ") + hardwareData.rssi,1);
}
void sensorPMSimulate()
// Simulates sensor reading from PMSA003I sensor
{
// tempF and humidity come from SCD4X simulation
// Common to PMSA003I and SEN5x
sensorData.pm1 = random(sensorPMMin, sensorPMMax) / 100.0;
sensorData.pm10 = random(sensorPMMin, sensorPMMax) / 100.0;
sensorData.pm25 = random(sensorPMMin, sensorPMMax) / 100.0;
// PMSA003I specific values
// SEN5x specific values
sensorData.pm4 = random(sensorPMMin, sensorPMMax) / 100.0;
sensorData.vocIndex = random(sensorVOCMin, sensorVOCMax) / 100.0;
// not supported on SEN54
//sensorData.noxIndex = random(sensorVOCMin, sensorVOCMax) / 10.0;
debugMessage(String("SIMULATED SEN5x PM2.5: ")+sensorData.pm25+" ppm, VOC index: " + sensorData.vocIndex,1);
}
void sensorCO2Simulate()
// Simulate ranged data from the SCD40
// Improvement - implement stable, rapid rise and fall
{
sensorData.ambientTemperatureF = (random(sensorTempMinF,sensorTempMaxF) / 100.0);
sensorData.ambientHumidity = random(sensorHumidityMin,sensorHumidityMax) / 100.0;
sensorData.ambientCO2 = random(sensorCO2Min, sensorCO2Max);
debugMessage(String("SIMULATED SCD40: ") + sensorData.ambientTemperatureF + "F, " + sensorData.ambientHumidity + "%, " + sensorData.ambientCO2 + " ppm",1);
}
#endif
bool OWMCurrentWeatherRead()
// Gets Open Weather Map Current Weather data
{
#ifdef HARDWARE_SIMULATE
OWMCurrentWeatherSimulate();
return true;
#else
// check for internet connectivity
if (hardwareData.rssi != 0)
{
String jsonBuffer;
// Get local weather conditions
String serverPath = String(OWM_SERVER) + OWM_WEATHER_PATH + OWM_LAT_LONG + "&units=imperial" + "&APPID=" + OWM_KEY;
jsonBuffer = networkHTTPGETRequest(serverPath.c_str());
debugMessage("Raw JSON from OWM Current Weather feed", 2);
debugMessage(jsonBuffer, 2);
if (jsonBuffer == "HTTP GET error") {
return false;
}
DynamicJsonDocument doc(2048);
DeserializationError error = deserializeJson(doc, jsonBuffer);
if (error) {
debugMessage(String("deserializeJson failed with error message: ") + error.c_str(), 1);
return false;
}
uint8_t code = (uint8_t)doc["cod"];
if (code != 200) {
debugMessage(String("OWM error: ") + (const char *)doc["message"], 1);
return false;
}
// owmCurrentData.lat = (float) doc["coord"]["lat"];
// owmCurrentData.lon = (float) doc["coord"]["lon"];
// owmCurrentData.main = (const char*) doc["weather"][0]["main"];
// owmCurrentData.description = (const char*) doc["weather"][0]["description"];
owmCurrentData.icon = (const char *)doc["weather"][0]["icon"];
owmCurrentData.cityName = (const char *)doc["name"];
// owmCurrentData.visibility = (uint16_t) doc["visibility"];
// owmCurrentData.timezone = (time_t) doc["timezone"];
// owmCurrentData.country = (const char*) doc["sys"]["country"];
// owmCurrentData.observationTime = (time_t) doc["dt"];
// owmCurrentData.sunrise = (time_t) doc["sys"]["sunrise"];
// owmCurrentData.sunset = (time_t) doc["sys"]["sunset"];
owmCurrentData.tempF = (float)doc["main"]["temp"];
// owmCurrentData.pressure = (uint16_t) doc["main"]["pressure"];
owmCurrentData.humidity = (uint8_t)doc["main"]["humidity"];
// owmCurrentData.tempMin = (float) doc["main"]["temp_min"];
// owmCurrentData.tempMax = (float) doc["main"]["temp_max"];
// owmCurrentData.windSpeed = (float) doc["wind"]["speed"];
// owmCurrentData.windDeg = (float) doc["wind"]["deg"];
debugMessage(String("OWM Current Weather: ") + owmCurrentData.tempF + "F, " + owmCurrentData.humidity + "% RH", 1);
return true;
}
return false;
#endif
}
bool OWMAirPollutionRead()
// stores local air pollution info from Open Weather Map in environment global
{
#ifdef HARDWARE_SIMULATE
OWMAirPollutionSimulate();
return true;
#else
// check for internet connectivity
if (hardwareData.rssi != 0)
{
String jsonBuffer;
// Get local AQI
String serverPath = String(OWM_SERVER) + OWM_AQM_PATH + OWM_LAT_LONG + "&APPID=" + OWM_KEY;
jsonBuffer = networkHTTPGETRequest(serverPath.c_str());
debugMessage("Raw JSON from OWM AQI feed", 2);
debugMessage(jsonBuffer, 2);
if (jsonBuffer == "HTTP GET error") {
return false;
}
DynamicJsonDocument doc(384);
DeserializationError error = deserializeJson(doc, jsonBuffer);
if (error) {
debugMessage(String("deserializeJson failed with error message: ") + error.c_str(), 1);
return false;
}
// owmAirQuality.lon = (float) doc["coord"]["lon"];
// owmAirQuality.lat = (float) doc["coord"]["lat"];
JsonObject list_0 = doc["list"][0];
owmAirQuality.aqi = list_0["main"]["aqi"];
JsonObject list_0_components = list_0["components"];
// owmAirQuality.co = (float) list_0_components["co"];
// owmAirQuality.no = (float) list_0_components["no"];
// owmAirQuality.no2 = (float) list_0_components["no2"];
// owmAirQuality.o3 = (float) list_0_components["o3"];
// owmAirQuality.so2 = (float) list_0_components["so2"];
owmAirQuality.pm25 = (float)list_0_components["pm2_5"];
// owmAirQuality.pm10 = (float) list_0_components["pm10"];
// owmAirQuality.nh3 = (float) list_0_components["nh3"];
debugMessage(String("OWM PM2.5: ") + owmAirQuality.pm25 + ", AQI: " + owmAirQuality.aqi,1);
return true;
}
return false;
#endif
}
String OWMtoMeteoconIcon(String icon)
// Maps OWM icon data to the appropropriate Meteocon font character
// https://www.alessioatzeni.com/meteocons/#:~:text=Meteocons%20is%20a%20set%20of,free%20and%20always%20will%20be.
{
if (icon == "01d") // 01d = sunny = Meteocon "B"
return "B";
if (icon == "01n") // 01n = clear night = Meteocon "C"
return "C";
if (icon == "02d") // 02d = partially sunny = Meteocon "H"
return "H";
if (icon == "02n") // 02n = partially clear night = Meteocon "4"
return "4";
if (icon == "03d") // 03d = clouds = Meteocon "N"
return "N";
if (icon == "03n") // 03n = clouds night = Meteocon "5"
return "5";
if (icon == "04d") // 04d = broken clouds = Meteocon "Y"
return "Y";
if (icon == "04n") // 04n = broken night clouds = Meteocon "%"
return "%";
if (icon == "09d") // 09d = rain = Meteocon "R"
return "R";
if (icon == "09n") // 09n = night rain = Meteocon "8"
return "8";
if (icon == "10d") // 10d = light rain = Meteocon "Q"
return "Q";
if (icon == "10n") // 10n = night light rain = Meteocon "7"
return "7";
if (icon == "11d") // 11d = thunderstorm = Meteocon "P"
return "P";
if (icon == "11n") // 11n = night thunderstorm = Meteocon "6"
return "6";