-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIndoorAirQualityMonitor.ino
602 lines (508 loc) · 14.7 KB
/
IndoorAirQualityMonitor.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
// Indoor Air Quality monitor
//
// Temperature, Humidity and Air Quality for Indoor use
// with WeMOS D1 mini lite, BME280 and MQ135
//
// Written by Michele <o-zone@zerozone.it> Pinassi
// Released under GPLv3 - No any warranty
//
// Tested with WeMos D1 mini Lite
// Flash size: 1MB (256KB SPIFFS)
//
// 11 GPIO pins, all except D0, support interrupt/PWM/I2C/one-wire
// 1 analog input (3.2V max input)
// 1 Micro USB connection
// 1MB Flash
// 500mA resettable fuse
//
// Pin Function ESP-8266 Pin
// TX TXD TXD
// RX RXD RXD
// A0 Analog input, max 3.3V input A0
// D0 IO GPIO16
// D1 IO, SCL GPIO5
// D2 IO, SDA GPIO4
// D3 IO, 10k Pull-up GPIO0
// D4 IO, 10k Pull-up, BUILTIN_LED GPIO2
// D5 IO, SCK GPIO14
// D6 IO, MISO GPIO12
// D7 IO, MOSI GPIO13
// D8 IO, 10k Pull-down, SS GPIO15
// G Ground GND
// 5V 5V -
// 3V3 3.3V 3.3V
// RST Reset RST
// All of the IO pins have interrupt/pwm/I2C/one-wire support except D0.
// All of the IO pins run at 3.3V.
//
// v0.2.0 - 12.07.2021
// - WEB GUI completely rewritten using purecss and self-hosted libs
// - MQTT re-engineered for better handling
// - Change NTP client library
// - More natural LED fading
//
// v0.1.2 - 12.11.2020
// - library updates
// - MQTT tasks
// - remove unused syslog related stuff
//
// v0.1.1 - 13.10.2019
// - added ota_enable to prevent accidental or unwanted OTA updates (true if OTA is enables, false otherwise)
// - change MQTT messages
//
// v0.1.0 - 03.07.2019
// - added alarm for temp, humidity, air quality and humixed indexes
// - some minor fixes
//
// v0.0.6
// - hardware improvements: BME280
// - piezo buzzer
//
// v0.0.5
// - Update to ArduinoJson 6
// - move from REST to MQTT
//
// v0.0.4
// - Added reboot and WiFI RSSI config parameters
// - Fixed an error on datetime print
//
// v0.0.3
// - Fixed an issue with RestClient object: now will be instantiated only when needed. Removed global object.
#define __DEBUG__
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoOTA.h>
#include <ESP8266httpUpdate.h>
#include <EEPROM.h>
#include <ESPAsyncTCP.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
// TaskScheduler
// https://github.com/arkhipenko/TaskScheduler
#include <TaskScheduler.h>
Scheduler runner;
// ArduinoJson
// https://arduinojson.org/
#include <ArduinoJson.h>
// MQTT PubSub client
// https://github.com/knolleary/pubsubclient
#include <PubSubClient.h>
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
// MQ135
// https://github.com/GeorgK/MQ135.git
#include <MQ135.h>
// I2C BME280
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme;
// NTP ClientLib
// https://github.com/taranais/NTPClient
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// File System
#include <FS.h>
// Format SPIFFS if mount failed
#define FORMAT_SPIFFS_IF_FAILED 1
// Firmware data
const char BUILD[] = __DATE__ " " __TIME__;
#define FW_NAME "iaq-monitor"
#define FW_VERSION "0.2.0"
#define ANALOGPIN A0
#define BUZZER 0 // D3
// RGB Led Pinout - Common Anode (light when LOW)
#define PWMRANGE 100
#define LED_B 13 // D7
#define LED_G 12 // D5
#define LED_R 14 // D6
// Define to which analog pin MQ135 was connected...
MQ135 mq135 = MQ135(ANALOGPIN);
bool mq135ready=false;
// Define tasks and callbacks
#define MQ135_INTERVAL 60000*15 // 15 mins delay before getting MQ135 values
void mq135Callback();
Task mq135Task(MQ135_INTERVAL, TASK_FOREVER, &mq135Callback);
#define ENV_INTERVAL 60000 // Every minute
void envCallback();
Task envTask(ENV_INTERVAL, TASK_FOREVER, &envCallback);
#define MQTT_INTERVAL 60000*5 // Every 5 minutes
void mqttCallback();
Task mqttTask(MQTT_INTERVAL, TASK_FOREVER, &mqttCallback);
// Web server
AsyncWebServer server(80);
// Config
struct Config {
// WiFi config
char wifi_essid[16];
char wifi_password[16];
// MQTT config
char broker_host[32];
unsigned int broker_port;
unsigned int broker_timeout;
char client_id[18];
// Host config
bool ota_enable;
char hostname[16];
//
uint8_t alarm_temp;
uint8_t alarm_hum;
uint8_t alarm_vocs;
uint8_t alarm_hdex;
};
#define CONFIG_FILE "/config.json"
File configFile;
Config config; // Global config object
static int last; // millis counter
float temperature=0, humidity=0, pressure=0, vocs=0, humidex=0, altitude=0;
DynamicJsonDocument env(256);
bool isSetupMode=false;
bool isDataReady=false; // True if environmental data is ready to be sent!
uint8_t isAlarm=0; // >0 if on alarm, and buzzer just beep until
// https://diarmuid.ie/blog/pwm-exponential-led-fading-on-arduino-or-other-platforms
float R; // Brightness constant for led fading
// ************************************
// DEBUG()
//
// send message via RSyslog (if enabled) or fallback on Serial
// ************************************
void DEBUG(String message) {
#ifdef __DEBUG__
Serial.println(message);
#endif
}
// ************************************
// md135Callback()
//
// after 24h, enable measurements for MD135
// ************************************
void mq135Callback() {
if(!mq135Task.isFirstIteration()) {
DEBUG("[DEBUG] Enable MQ135 after warm up...");
mq135ready=true;
mq135Task.disable();
}
}
// ************************************
// mqttConnect()
//
//
// ************************************
void mqttConnect() {
uint8_t timeout=10;
if(strlen(config.broker_host) > 0) {
DEBUG("[MQTT] Attempting connection to "+String(config.broker_host)+":"+String(config.broker_port));
while((!mqttClient.connected())&&(timeout > 0)) {
// Attempt to connect
if (mqttClient.connect(config.client_id)) {
// Once connected, publish an announcement...
DEBUG("[MQTT] Connected as "+String(config.client_id));
} else {
timeout--;
delay(500);
}
}
if(!mqttClient.connected()) {
DEBUG("[MQTT] Connection failed");
}
}
}
void mqttInCallback(char* topic, byte* payload, unsigned int length) {
DEBUG("Message arrived: "+String(topic));
}
bool mqttPublish(char *topic, char *payload) {
if (mqttClient.connected()) {
}
}
void mqttCallback() {
char topic[32],value[16];
if(isDataReady) {
if(WiFi.status() != WL_CONNECTED) {
connectToWifi();
}
// MQTT not connected? Connect!
if (!mqttClient.connected()) {
mqttConnect();
}
JsonObject root = env.as<JsonObject>();
for (JsonPair keyValue : root) {
sprintf(topic,"%s/%s",config.client_id,keyValue.key().c_str());
if(keyValue.key().c_str()[0] != '_') {
String value = keyValue.value().as<String>();
if(mqttClient.publish(topic,value.c_str())) {
DEBUG("[MQTT] Publish "+String(topic)+":"+value);
isDataReady=false;
env["status"] = "Data published via MQTT";
} else {
DEBUG("[MQTT] Publish failed!");
}
}
}
}
}
// ************************************
// runWifiAP()
//
// run Wifi AccessPoint, to let user configure iHot without a WiFi
// ************************************
#define DEFAULT_WIFI_ESSID "IHOT_AP"
#define DEFAULT_WIFI_PASSWORD "12345678"
void runWifiAP() {
DEBUG("[DEBUG] runWifiAP() ");
WiFi.mode(WIFI_AP);
WiFi.softAP(DEFAULT_WIFI_ESSID,DEFAULT_WIFI_PASSWORD);
IPAddress myIP = WiFi.softAPIP(); //Get IP address
Serial.println("");
Serial.print("WiFi Hotspot ESSID: ");
Serial.println(DEFAULT_WIFI_ESSID);
Serial.print("WiFi password: ");
Serial.println(DEFAULT_WIFI_PASSWORD);
Serial.print("Server IP: ");
Serial.println(myIP);
WiFi.printDiag(Serial);
if (MDNS.begin(config.hostname)) {
Serial.print("MDNS responder started for hostname ");
Serial.println(config.hostname);
}
isSetupMode=true;
}
// ************************************
// connectToWifi()
//
// connect to configured WiFi network
// ************************************
bool connectToWifi() {
uint8_t timeout=0;
if(isSetupMode) {
DEBUG("Setup mode: connect to AP and configure!");
return false;
}
if(strlen(config.wifi_essid) > 0) {
Serial.print("[INIT] Connecting to ");
Serial.print(config.wifi_essid);
WiFi.mode(WIFI_STA);
WiFi.begin(config.wifi_essid, config.wifi_password);
while((WiFi.status() != WL_CONNECTED)&&(timeout < 10)) {
setLedRGB(PWMRANGE,0,0);
delay(250);
Serial.print(".");
setLedRGB(0,0,0);
delay(250);
timeout++;
}
if(WiFi.status() == WL_CONNECTED) {
DEBUG("OK. IP:"+WiFi.localIP().toString());
if (MDNS.begin(config.hostname)) {
Serial.println("[INIT] MDNS responder started");
// Add service to MDNS-SD
MDNS.addService("http", "tcp", 80);
}
// NTP
timeClient.begin();
// Setup MQTT connection
mqttClient.setServer(config.broker_host, config.broker_port);
mqttClient.setCallback(mqttInCallback);
return true;
} else {
Serial.println("[ERROR] Failed to connect to WiFi");
return false;
}
} else {
Serial.println("[ERROR] Please configure Wifi");
runWifiAP();
return false;
}
}
// ************************************
// setup()
//
// setup routine
// ************************************
void setup() {
unsigned status;
Serial.begin(115200);
delay(1000);
env["status"]="Booting...";
// Define led ports as OUTPUT and turn it off
pinMode(LED_R, OUTPUT);
pinMode(LED_G, OUTPUT);
pinMode(LED_B, OUTPUT);
setLedRGB(0,0,0);
pinMode(BUZZER, OUTPUT);
analogWrite(BUZZER, 205);
delay(500);
analogWrite(BUZZER, 0);
// print firmware and build data
Serial.println();
Serial.println();
Serial.print(FW_NAME);
Serial.print("");
Serial.print(FW_VERSION);
Serial.print("");
Serial.println(BUILD);
// Start scheduler
runner.init();
// Initialize SPIFFS
if(!SPIFFS.begin()){
DEBUG("[ERROR] SPIFFS Mount Failed. Try formatting...");
if(SPIFFS.format()) {
Serial.println("[INIT] SPIFFS initialized successfully");
} else {
Serial.println("[FATAL] SPIFFS error");
ESP.restart();
}
} else {
DEBUG("SPIFFS done");
}
// Load configuration
loadConfigFile();
// Setup I2C...
DEBUG("[INIT] Initializing I2C bus...");
Wire.begin(SDA, SCL);
i2c_status();
DEBUG("[INIT] Initializing BME280...");
status=bme.begin(0x77);
if(!status) {
Serial.print("[ERROR] BME280 error!");
delay(1000);
ESP.restart();
}
bme.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X1, // temperature
Adafruit_BME280::SAMPLING_X1, // pressure
Adafruit_BME280::SAMPLING_X1, // humidity
Adafruit_BME280::FILTER_OFF);
// Connect to WiFi network
connectToWifi();
// Setup OTA
ArduinoOTA.onStart([]() {
Serial.println("[OTA] Update Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("[OTA] Update End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
char p[32];
sprintf(p, "[OTA] Progress: %u%%\n", (progress/(total/100)));
Serial.println(p);
});
ArduinoOTA.onError([](ota_error_t error) {
if(error == OTA_AUTH_ERROR) Serial.println("[OTA] Auth Failed");
else if(error == OTA_BEGIN_ERROR) Serial.println("[OTA] Begin Failed");
else if(error == OTA_CONNECT_ERROR) Serial.println("[OTA] Connect Failed");
else if(error == OTA_RECEIVE_ERROR) Serial.println("[OTA] Recieve Failed");
else if(error == OTA_END_ERROR) Serial.println("[OTA] End Failed");
});
ArduinoOTA.setHostname(config.hostname);
ArduinoOTA.begin();
// Enable runner tasks
// MQ135 VOCs task
runner.addTask(mq135Task);
mq135Task.enable();
// Environment task
runner.addTask(envTask);
envTask.enable();
// MQTT task
runner.addTask(mqttTask);
mqttTask.setInterval(config.broker_timeout*1000);
mqttTask.enable();
// Initialize web server on port 80
initWebServer();
// Adjust analog write rage for LED PWM fading
analogWriteRange(PWMRANGE);
R = (PWMRANGE * log10(2))/(log10(255));
// Go!
env["uptime"] = 0;
env["status"] = "Go!";
}
unsigned int led_R=0,led_G=0,led_B=0,led_max_R=PWMRANGE,led_max_G=PWMRANGE,led_max_B=PWMRANGE,led_sense=0;
unsigned int ledBrightness(unsigned int interval) {
return PWMRANGE - (pow (2, (interval / R)) - 1);
}
void setLedRGB(unsigned int led_R,unsigned int led_G,unsigned int led_B) {
analogWrite(LED_R, ledBrightness(led_R));
analogWrite(LED_G, ledBrightness(led_G));
analogWrite(LED_B, ledBrightness(led_B));
}
void setLed(unsigned int led_R,unsigned int led_G,unsigned int led_B) {
led_max_R = led_R;
led_max_G = led_G;
led_max_B = led_B;
}
void ledLoop() {
if(led_sense == 0) {
if((led_R >= led_max_R)&&(led_G >= led_max_G)&&(led_B >= led_max_B)) {
led_sense = 1;
} else {
if(led_R < led_max_R) led_R++;
if(led_G < led_max_G) led_G++;
if(led_B < led_max_B) led_B++;
}
} else {
if((led_R < 1)&&(led_G < 1)&&(led_B < 1)) {
led_sense = 0;
} else {
if(led_R > 0) led_R--;
if(led_G > 0) led_G--;
if(led_B > 0) led_B--;
}
}
setLedRGB(led_R,led_G,led_B);
}
// ************************************
// loop()
//
// loop routine
// ************************************
void loop() {
if(config.ota_enable) {
// Handle OTA
ArduinoOTA.handle();
}
// Scheduler
runner.execute();
if((millis() - last) > 5100) {
if(isSetupMode) {
Serial.printf("Stations connected to soft-AP = %d\n", WiFi.softAPgetStationNum());
}
if(isAlarm) {
analogWrite(BUZZER, 200);
delay(100);
analogWrite(BUZZER, 300);
delay(100);
analogWrite(BUZZER, 0);
isAlarm--;
}
// NTP Sync
timeClient.update();
last = millis();
}
if(!isAlarm) {
if((config.alarm_temp > 0)&&(temperature > config.alarm_temp)) {
DEBUG("[ALARM] Alarm: temperature triggered!");
env["status"]="Temperature ALARM triggered";
isAlarm=10;
} else if((config.alarm_hum > 0)&&(humidity > config.alarm_hum)) {
DEBUG("[ALARM] Alarm: humidity triggered!");
env["status"]="Humidity ALARM triggered";
isAlarm=10;
} else if((config.alarm_vocs > 0)&&(vocs > config.alarm_vocs)) {
DEBUG("[ALARM] Alarm: AirQuality triggered!");
env["status"]="Air Quality ALARM triggered";
isAlarm=10;
} else if((config.alarm_hdex > 0)&&(humidex > config.alarm_hdex)) {
DEBUG("[ALARM] Alarm: Humidex triggered!");
env["status"]="Humidex ALARM triggered";
isAlarm=10;
} else {
env["status"]="System up and running";
}
}
ledLoop();
env["uptime"] = millis() / 1000;
delay(10);
}