-
Notifications
You must be signed in to change notification settings - Fork 0
/
AirGradient_Prometheus_DIY_PRO_V4_2.ino
569 lines (486 loc) · 13.8 KB
/
AirGradient_Prometheus_DIY_PRO_V4_2.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
/*
airgradient-pro-prometheus-pushgateway note: This code combines the AirGradient Pro 4.2 base code (https://github.com/airgradienthq/arduino/blob/master/examples/DIY_PRO_V4_2/DIY_PRO_V4_2.ino) with elements of https://github.com/geerlingguy/airgradient-prometheus.
Original comment:
Important: This code is only for the DIY PRO PCB Version 4.2 that has a push button mounted.
This is the code for the AirGradient DIY PRO Air Quality Sensor with an ESP8266 Microcontroller with the SGP40 TVOC module from AirGradient.
It is a high quality sensor showing PM2.5, CO2, Temperature and Humidity on a small display and can send data over Wifi.
Build Instructions: https://www.airgradient.com/open-airgradient/instructions/diy-pro-v42/
Kits (including a pre-soldered version) are available: https://www.airgradient.com/open-airgradient/kits/
The codes needs the following libraries installed:
“WifiManager by tzapu, tablatronix” tested with version 2.0.11-beta
“U8g2” by oliver tested with version 2.32.15
"Sensirion I2C SGP41" by Sensation Version 0.1.0
"Sensirion Gas Index Algorithm" by Sensation Version 3.2.1
"Arduino-SHT" by Johannes Winkelmann Version 1.2.2
Configuration:
Please set in the code below the configuration parameters.
If you have any questions please visit our forum at https://forum.airgradient.com/
If you are a school or university contact us for a free trial on the AirGradient platform.
https://www.airgradient.com/
CC BY-SA 4.0 Attribution-ShareAlike 4.0 International License
*/
#include <AirGradient.h>
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>
#include "certs.h"
#include <WiFiClient.h>
#include <EEPROM.h>
#include "SHTSensor.h"
// #include "SGP30.h"
#include <SensirionI2CSgp41.h>
#include <NOxGasIndexAlgorithm.h>
#include <VOCGasIndexAlgorithm.h>
#include <U8g2lib.h>
AirGradient ag = AirGradient();
SensirionI2CSgp41 sgp41;
VOCGasIndexAlgorithm voc_algorithm;
NOxGasIndexAlgorithm nox_algorithm;
SHTSensor sht;
// time in seconds needed for NOx conditioning
uint16_t conditioning_s = 10;
// for peristent saving and loading
int addr = 4;
byte value;
// Display bottom right
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);
// Replace above if you have display on top left
// U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R2, /* reset=*/ U8X8_PIN_NONE);
// CONFIGURATION START
// set to true to switch from Celcius to Fahrenheit
boolean inF = false;
// PM2.5 in US AQI (default ug/m3)
boolean inUSAQI = false;
// Display Position
boolean displayTop = true;
// set to true if you want to connect to wifi. You have 60 seconds to connect. Then it will go into an offline mode.
boolean connectWIFI = true;
String pushgateway_host = "https://example.com";
// Uncomment the lines below to configure basic auth.
// #define prometheus_http_basic_auth
#ifdef prometheus_http_basic_auth
const char *pushgateway_user = "user";
const char *pushgateway_password = "password";
#endif
// CONFIGURATION END
unsigned long currentMillis = 0;
const int oledInterval = 5000;
unsigned long previousOled = 0;
const int sendToServerInterval = 10000;
unsigned long previoussendToServer = 0;
const int tvocInterval = 1000;
unsigned long previousTVOC = 0;
int TVOC = 0;
int NOX = 0;
const int co2Interval = 5000;
unsigned long previousCo2 = 0;
int Co2 = 0;
const int pmInterval = 5000;
unsigned long previousPm = 0;
int pm25 = 0;
int pm01 = 0;
int pm10 = 0;
int pm03PCount = 0;
const int tempHumInterval = 2500;
unsigned long previousTempHum = 0;
float temp = 0;
int hum = 0;
int buttonConfig = 0;
int lastState = LOW;
int currentState;
unsigned long pressedTime = 0;
unsigned long releasedTime = 0;
void setup()
{
Serial.begin(115200);
Serial.println("Hello");
u8g2.begin();
sht.init();
sht.setAccuracy(SHTSensor::SHT_ACCURACY_MEDIUM);
// u8g2.setDisplayRotation(U8G2_R0);
EEPROM.begin(512);
delay(500);
buttonConfig = String(EEPROM.read(addr)).toInt();
if (buttonConfig > 3)
buttonConfig = 0;
delay(400);
setConfig();
Serial.println("buttonConfig: " + String(buttonConfig));
updateOLED2("Press Button", "Now for", "Config Menu");
delay(2000);
pinMode(D7, INPUT_PULLUP);
currentState = digitalRead(D7);
if (currentState == LOW)
{
updateOLED2("Entering", "Config Menu", "");
delay(3000);
lastState = HIGH;
setConfig();
inConf();
}
if (connectWIFI)
{
connectToWifi();
}
updateOLED2("Warming Up", "Serial Number:", String(ESP.getChipId(), HEX));
sgp41.begin(Wire);
ag.CO2_Init();
ag.PMS_Init();
ag.TMP_RH_Init(0x44);
}
void loop()
{
currentMillis = millis();
updateTVOC();
updateOLED();
updateCo2();
updatePm();
updateTempHum();
sendToServer();
}
void inConf()
{
setConfig();
currentState = digitalRead(D7);
if (currentState)
{
Serial.println("currentState: high");
}
else
{
Serial.println("currentState: low");
}
if (lastState == HIGH && currentState == LOW)
{
pressedTime = millis();
}
else if (lastState == LOW && currentState == HIGH)
{
releasedTime = millis();
long pressDuration = releasedTime - pressedTime;
if (pressDuration < 1000)
{
buttonConfig = buttonConfig + 1;
if (buttonConfig > 3)
buttonConfig = 0;
}
}
if (lastState == LOW && currentState == LOW)
{
long passedDuration = millis() - pressedTime;
if (passedDuration > 4000)
{
// to do
// if (buttonConfig==4) {
// updateOLED2("Saved", "Release", "Button Now");
// delay(1000);
// updateOLED2("Starting", "CO2", "Calibration");
// delay(1000);
// Co2Calibration();
// } else {
updateOLED2("Saved", "Release", "Button Now");
delay(1000);
updateOLED2("Rebooting", "in", "5 seconds");
delay(5000);
EEPROM.write(addr, char(buttonConfig));
EEPROM.commit();
delay(1000);
ESP.restart();
// }
}
}
lastState = currentState;
delay(100);
inConf();
}
void setConfig()
{
if (buttonConfig == 0)
{
updateOLED2("Temp. in C", "PM in ug/m3", "Long Press Saves");
u8g2.setDisplayRotation(U8G2_R0);
inF = false;
inUSAQI = false;
}
if (buttonConfig == 1)
{
updateOLED2("Temp. in C", "PM in US AQI", "Long Press Saves");
u8g2.setDisplayRotation(U8G2_R0);
inF = false;
inUSAQI = true;
}
else if (buttonConfig == 2)
{
updateOLED2("Temp. in F", "PM in ug/m3", "Long Press Saves");
u8g2.setDisplayRotation(U8G2_R0);
inF = true;
inUSAQI = false;
}
else if (buttonConfig == 3)
{
updateOLED2("Temp. in F", "PM in US AQI", "Long Press Saves");
u8g2.setDisplayRotation(U8G2_R0);
inF = true;
inUSAQI = true;
}
// to do
// if (buttonConfig == 8) {
// updateOLED2("CO2", "Manual", "Calibration");
// }
}
void updateTVOC()
{
uint16_t error;
char errorMessage[256];
uint16_t defaultRh = 0x8000;
uint16_t defaultT = 0x6666;
uint16_t srawVoc = 0;
uint16_t srawNox = 0;
uint16_t defaultCompenstaionRh = 0x8000; // in ticks as defined by SGP41
uint16_t defaultCompenstaionT = 0x6666; // in ticks as defined by SGP41
uint16_t compensationRh = 0; // in ticks as defined by SGP41
uint16_t compensationT = 0; // in ticks as defined by SGP41
delay(1000);
compensationT = static_cast<uint16_t>((temp + 45) * 65535 / 175);
compensationRh = static_cast<uint16_t>(hum * 65535 / 100);
if (conditioning_s > 0)
{
error = sgp41.executeConditioning(compensationRh, compensationT, srawVoc);
conditioning_s--;
}
else
{
error = sgp41.measureRawSignals(compensationRh, compensationT, srawVoc,
srawNox);
}
if (currentMillis - previousTVOC >= tvocInterval)
{
previousTVOC += tvocInterval;
TVOC = voc_algorithm.process(srawVoc);
NOX = nox_algorithm.process(srawNox);
Serial.println(String(TVOC));
}
}
void updateCo2()
{
if (currentMillis - previousCo2 >= co2Interval)
{
previousCo2 += co2Interval;
Co2 = ag.getCO2_Raw();
Serial.println(String(Co2));
}
}
void updatePm()
{
if (currentMillis - previousPm >= pmInterval)
{
previousPm += pmInterval;
pm01 = ag.getPM1_Raw();
pm25 = ag.getPM2_Raw();
pm10 = ag.getPM10_Raw();
pm03PCount = ag.getPM0_3Count();
Serial.println(String(pm25));
}
}
void updateTempHum()
{
if (currentMillis - previousTempHum >= tempHumInterval)
{
previousTempHum += tempHumInterval;
if (sht.readSample())
{
Serial.print("SHT:\n");
Serial.print(" RH: ");
Serial.print(sht.getHumidity(), 2);
Serial.print("\n");
Serial.print(" T: ");
Serial.print(sht.getTemperature(), 2);
Serial.print("\n");
temp = sht.getTemperature();
hum = sht.getHumidity();
}
else
{
Serial.print("Error in readSample()\n");
}
Serial.println(String(temp));
}
}
void updateOLED()
{
if (currentMillis - previousOled >= oledInterval)
{
previousOled += oledInterval;
String ln3;
String ln1;
if (inUSAQI)
{
ln1 = "AQI:" + String(PM_TO_AQI_US(pm25)) + " CO2:" + String(Co2);
}
else
{
ln1 = "PM:" + String(pm25) + " CO2:" + String(Co2);
}
String ln2 = "TVOC:" + String(TVOC) + " NOX:" + String(NOX);
if (inF)
{
ln3 = "F:" + String((temp * 9 / 5) + 32) + " H:" + String(hum) + "%";
}
else
{
ln3 = "C:" + String(temp) + " H:" + String(hum) + "%";
}
updateOLED2(ln1, ln2, ln3);
}
}
void updateOLED2(String ln1, String ln2, String ln3)
{
char buf[9];
u8g2.firstPage();
u8g2.firstPage();
do
{
u8g2.setFont(u8g2_font_t0_16_tf);
u8g2.drawStr(1, 10, String(ln1).c_str());
u8g2.drawStr(1, 30, String(ln2).c_str());
u8g2.drawStr(1, 50, String(ln3).c_str());
} while (u8g2.nextPage());
}
void sendToServer()
{
if (currentMillis - previoussendToServer >= sendToServerInterval)
{
previoussendToServer += sendToServerInterval;
if (WiFi.status() == WL_CONNECTED)
{
postMetricsToPushgateway();
}
else
{
Serial.println("WiFi Disconnected");
}
}
}
// Wifi Manager
void connectToWifi()
{
WiFiManager wifiManager;
// WiFi.disconnect(); //to delete previous saved hotspot
String HOTSPOT = "AG-" + String(ESP.getChipId(), HEX);
updateOLED2("90s to connect", "to Wifi Hotspot", HOTSPOT);
wifiManager.setTimeout(90);
if (!wifiManager.autoConnect((const char *)HOTSPOT.c_str()))
{
updateOLED2("booting into", "offline mode", "");
Serial.println("failed to connect and hit timeout");
delay(6000);
}
}
// Calculate PM2.5 US AQI
int PM_TO_AQI_US(int pm02)
{
if (pm02 <= 12.0)
return ((50 - 0) / (12.0 - .0) * (pm02 - .0) + 0);
else if (pm02 <= 35.4)
return ((100 - 50) / (35.4 - 12.0) * (pm02 - 12.0) + 50);
else if (pm02 <= 55.4)
return ((150 - 100) / (55.4 - 35.4) * (pm02 - 35.4) + 100);
else if (pm02 <= 150.4)
return ((200 - 150) / (150.4 - 55.4) * (pm02 - 55.4) + 150);
else if (pm02 <= 250.4)
return ((300 - 200) / (250.4 - 150.4) * (pm02 - 150.4) + 200);
else if (pm02 <= 350.4)
return ((400 - 300) / (350.4 - 250.4) * (pm02 - 250.4) + 300);
else if (pm02 <= 500.4)
return ((500 - 400) / (500.4 - 350.4) * (pm02 - 350.4) + 400);
else
return 500;
};
void postMetricsToPushgateway()
{
String message = "";
if (Co2 >= 0)
{
message += "# HELP rco2 CO2 value, in ppm\n";
message += "# TYPE rco2 gauge\n";
message += "rco2 " + String(Co2);
message += "\n";
}
if (pm01 >= 0)
{
message += "# HELP pm01 Particulate Matter PM1.0 value (ug/m3)\n";
message += "# TYPE pm01 gauge\n";
message += "pm01 " + String(pm01);
message += "\n";
}
if (pm25 >= 0)
{
message += "# HELP pm02 Particulate Matter PM2.5 value (ug/m3)\n";
message += "# TYPE pm02 gauge\n";
message += "pm02 " + String(pm25);
message += "\n";
}
if (pm10 >= 0)
{
message += "# HELP pm10 Particulate Matter PM10 value (ug/m3)\n";
message += "# TYPE pm10 gauge\n";
message += "pm10 " + String(pm10);
message += "\n";
}
if (pm03PCount >= 0)
{
message += "# HELP pm003_cnt Particulate Matter value (count in 0.1L of air)\n";
message += "# TYPE pm003_cnt gauge\n";
message += "pm003_cnt " + String(pm03PCount);
message += "\n";
}
if (TVOC >= 0)
{
message += "# HELP tvoc_index Total Volatile Organic Compounds (TVOC) index\n";
message += "# TYPE tvoc_index gauge\n";
message += "tvoc_index " + String(TVOC);
message += "\n";
}
if (NOX >= 0)
{
message += "# HELP nox_index Nitrogen Oxides (NOx) index\n";
message += "# TYPE nox_index gauge\n";
message += "nox_index " + String(NOX);
message += "\n";
}
message += "# HELP atmp Temperature, in degrees Celsius\n";
message += "# TYPE atmp gauge\n";
message += "atmp " + String(temp);
if (hum >= 0)
{
message += "\n# HELP rhum Relative humidity, in percent\n";
message += "# TYPE rhum gauge\n";
message += "rhum " + String(hum);
message += "\n";
}
std::unique_ptr<BearSSL::WiFiClientSecure> sslClient(new BearSSL::WiFiClientSecure);
sslClient->setFingerprint(fingerprint_pushgateway_domain);
HTTPClient http;
WiFiClient wifi;
String url = pushgateway_host + "/metrics/job/AirGradient-" + String(ESP.getChipId(), HEX) + "/instance/" + WiFi.macAddress().c_str();
Serial.println("Posting metrics to " + url);
Serial.println(message);
http.addHeader("Content-Type", "text/plain");
#ifdef prometheus_http_basic_auth
http.setAuthorization(pushgateway_user, pushgateway_password);
#endif
http.setReuse(true);
http.begin(*sslClient, url.c_str());
int httpResponseCode = http.POST(message);
http.end();
if (httpResponseCode == 200)
{
Serial.println("Metrics posted successfully");
}
else
{
Serial.print("Error posting metrics: ");
Serial.println(httpResponseCode);
}
}