-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathair-sensor.ino
450 lines (388 loc) · 13.7 KB
/
air-sensor.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
#include <Wire.h>
#include <WiFiManager.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Adafruit_Sensor.h>
// AM2320
#include <Adafruit_AM2320.h>
// DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
// BME280
#include <Adafruit_BME280.h>
// PMS5003
#include <SoftwareSerial.h>
#include "AirGradient.h"
// DHT
#include <DHT.h>
// OLED display
#include <SSD1306Wire.h>
AirGradient ag = AirGradient();
// OLED display
SSD1306Wire display(0x3c, SDA, SCL);
// Set sensors that you do not use to false
boolean hasPM = true;
boolean hasCO2 = false;
boolean hasSHT = false;
boolean hasDHT = false;
boolean hasAM2320 = false;
boolean hasDS18B20 = true;
boolean hasBME280 = true;
boolean connectWIFI = true;
boolean exportToThingSpeak = false;
boolean exportToSensorCommunity = false;
boolean exportToNarodmon = false;
boolean exportToShopker = false;
boolean deepSleepEnabled = false;// Enable deep sleep mode. Connect D0 to RST pin.
// AM2320 sensor
Adafruit_AM2320 am2320 = Adafruit_AM2320();
// DHT sensor
#define DHTPIN D4 // What pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT12 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
// DS18B20 sensor
#define ONE_WIRE_BUS D4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
// BME280
Adafruit_BME280 bme;
Adafruit_Sensor *bme_temp = bme.getTemperatureSensor();
Adafruit_Sensor *bme_pressure = bme.getPressureSensor();
Adafruit_Sensor *bme_humidity = bme.getHumiditySensor();
const int buttonPin = D3;
int buttonState = 0;
int buttonPressedLoop = 0;
boolean buttonIsEnabled = false;
unsigned long timeMillis;
float valueTemp = 0;
float valueTempCorrection = 0;
int valueHum = 0;
float valuePr = 0;
int valuePm2 = 0;
int valuePm10 = 0;
// Intervals
int intervalDisplay = 3000;// 3 seconds
int intervalSend = 3 * 60 * 1000;// 3 minutes
// For deep sleep mode:
// int intervalSend = 30 * 1000;// 30 seconds
int sleepDurationSeconds = 2.5 * 60;// 2 minutes 30 seconds
// ThingSpeak settings
char thingSpeakApiUrl[39] = "http://api.thingspeak.com/update.json";
char thingSpeakApiKey[17] = "xxxxxxxxxxxxxxxx";
// sensor.community
char sensorCommunityApiUrl[50] = "http://api.sensor.community/v1/push-sensor-data/";
char sensorCommunitySensorId[17] = "xxxxxxx-xxxxxxx";
// Narodmon.ru settings
char apiUrl[30] = "http://narodmon.ru/json";
char apiOwnerName[20] = "andchir";
char apiSensorName[20] = "AirSensor5";
char apiSensorLat[10] = "61.784807";
char apiSensorLon[10] = "34.346085";
char apiSensorAlt[5] = "135";
// Shopker settings
char shopkerApiUrl[47] = "http://your-domain.com/api/ru/user_content/19";
char shopkerApiKey[121] = "xxxxxx";
void setup(){
timeMillis = 0;
Serial.begin(9600);
Serial.println("Initializing");
pinMode(buttonPin, INPUT);
//Wire.begin(); // join I2C bus
sensor_t sensor;
display.init();
display.flipScreenVertically();
delay(2000);
display.clear();
showTextRectangle("Init", String(ESP.getChipId(), HEX), "", "", "", true);
if (hasPM) ag.PMS_Init();
if (hasSHT) ag.TMP_RH_Init(0x45);
if (hasDHT) dht.begin();
if (hasAM2320) am2320.begin();
if (hasDS18B20) sensors.begin();
if (hasBME280) bme.begin(0x76);
if (connectWIFI) connectToWifi(digitalRead(buttonPin) == LOW);
delay(2000);
}
void loop(){
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
buttonPressedLoop = 0;
} else {
buttonPressedLoop++;
if (buttonPressedLoop == 1) {
buttonIsEnabled = !buttonIsEnabled;
}
}
if (buttonIsEnabled) {
display.displayOn();
showTextRectangle(
"T: " + String(valueTemp),
"H: " + String(valueHum),
"Pr: " + String(valuePr),
"PM2.5: " + String(valuePm2),
"PM10: " + String(valuePm10),
true
);
} else {
display.clear();
display.displayOff();
}
if (buttonPressedLoop == 8) {
buttonIsEnabled = true;
Serial.println("Reset WIFI settings");
display.displayOn();
showTextRectangle("RESET", "WIFI", "CONFIG", "", "", true);
WiFi.disconnect();
delay(3000);
ESP.restart();
delay(5000);
}
if (timeMillis % intervalDisplay == 0) {
// Read values
if (hasPM) {
PMS_DATA data;
if (ag.getPM_Data(data)) {
valuePm2 = data.PM_AE_UG_2_5;
valuePm10 = data.PM_AE_UG_10_0;
} else {
Serial.println("Could not read from PM sensor");
ag.wakeUp();
delay(10000);// Delay for fan spin-up
//showTextRectangle("No PM data", "", "", "", "", true);
}
}
if (hasSHT) {
TMP_RH result = ag.periodicFetchData();
if (result.error == SHT3XD_NO_ERROR) {
valueTemp = result.t - valueTempCorrection;
valueHum = result.rh;
} else {
Serial.println("Could not read from SHT sensor");
Serial.println("Error code: " + String(result.error));
}
}
if (hasDHT) {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
} else {
valueTemp = t - valueTempCorrection;
valueHum = h;
}
}
if (hasAM2320) {
valueTemp = am2320.readTemperature() - valueTempCorrection;
valueHum = am2320.readHumidity();
}
if (hasDS18B20) {
sensors.requestTemperatures();
valueTemp = sensors.getTempCByIndex(0);
}
if (hasBME280) {
sensors_event_t temp_event, pressure_event, humidity_event;
bme_temp->getEvent(&temp_event);
bme_pressure->getEvent(&pressure_event);
bme_humidity->getEvent(&humidity_event);
valuePr = pressure_event.pressure / 1.333;// mmHg (мм.рт.ст.)
valueHum = humidity_event.relative_humidity;
if (!hasDS18B20) {
valueTemp = temp_event.temperature;
}
}
Serial.println("Temperature: " + String(valueTemp));
Serial.println("Humidity: " + String(valueHum));
Serial.println("Pressure: " + String(valuePr));
Serial.println("PM2.5: " + String(valuePm2));
Serial.println("PM10: " + String(valuePm10));
// Display data on OLED
if (buttonIsEnabled) {
Serial.println("Display data update");
showTextRectangle(
"T: " + String(valueTemp),
"H: " + String(valueHum),
"Pr: " + String(valuePr),
"PM2.5: " + String(valuePm2),
"PM10: " + String(valuePm10),
true
);
}
}
// Send data by API
if (timeMillis > 0 && timeMillis % intervalSend == 0) {
if (connectWIFI){
Serial.println("Send data by API");
if (exportToNarodmon) {
sendDataToNarodmon(valueTemp, valueHum, valuePm2, valuePm10, valuePr);
}
if (exportToShopker) {
sendDataToShopker(valueTemp, valueHum, valuePm2, valuePm10, valuePr);
}
if (exportToThingSpeak) {
sendDataToThingSpeak(valueTemp, valueHum, valuePm2, valuePm10, valuePr);
}
if (exportToSensorCommunity) {
sendDataToSensorCommunity(valueTemp, valueHum, valuePm2, valuePm10, valuePr);
}
if (deepSleepEnabled && !buttonIsEnabled) {
Serial.println("Go to deep sleep");
if (hasPM) ag.sleep();
delay(2000);
ESP.deepSleep(sleepDurationSeconds * 1000000);
}
}
timeMillis = 0;
}
delay(500);
timeMillis += 500;
}
void sendDataToNarodmon(float temp, float hum, int pm2, int pm10, float pr) {
Serial.println("API URL: " + String(apiUrl));
Serial.println("API owner: " + String(apiOwnerName));
String jsonString = "{\"devices\":[{\"mac\":\"" + WiFi.macAddress() + "\", \"name\":\"" + String(apiSensorName) + "\", ";
jsonString += "\"owner\":\"" + String(apiOwnerName) + "\", ";
//jsonString += "\"lat\":" + String(apiSensorLat) + ", ";
//jsonString += "\"lon\":" + String(apiSensorLon) + ", ";
//jsonString += "\"alt\":" + String(apiSensorAlt) + ", ";
jsonString += "\"sensors\": [";
jsonString += "{\"id\":\"T1\", \"name\":\"Температура\", \"value\":" + String(temp) + ", \"unit\":\"C\"},";
jsonString += "{\"id\":\"H1\", \"name\":\"Влажность\", \"value\":" + String(hum) + ", \"unit\":\"%\"},";
jsonString += "{\"id\":\"P1\", \"name\":\"Микрочастицы PM2.5\", \"value\":" + String(pm2) + ", \"unit\":\"мкг/м3\"},";
jsonString += "{\"id\":\"P2\", \"name\":\"Пыль PM10\", \"value\":" + String(pm10) + ", \"unit\":\"мкг/м3\"},";
jsonString += "{\"id\":\"Pr1\", \"name\":\"Давление\", \"value\":" + String(pr) + ", \"unit\":\"мм.рт.ст.\"}";
jsonString += "]}]}";
Serial.println(jsonString);
HTTPClient http;
http.begin(apiUrl);
http.addHeader("Host", "narodmon.ru");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.addHeader("Content-Length", String(jsonString.length()));
int httpCode = http.POST(jsonString);
String response = http.getString();
Serial.println("Response code: " + String(httpCode));
Serial.println("Response: " + response);
http.end();
}
void sendDataToShopker(float temp, float hum, int pm2, int pm10, float pr) {
Serial.println("API URL: " + String(shopkerApiUrl));
String jsonString = "{";
jsonString += "\"temperature\":" + String(temp) + ", ";
jsonString += "\"humidity\":" + String(hum) + ", ";
jsonString += "\"pm25\":" + String(pm2) + ", ";
jsonString += "\"pm10\":" + String(pm10) + ", ";
jsonString += "\"pr\":" + String(pr);
jsonString += "}";
Serial.println(jsonString);
HTTPClient http;
http.begin(shopkerApiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept", "application/json");
http.addHeader("Content-Length", String(jsonString.length()));
http.addHeader("X-AUTH-TOKEN", String(shopkerApiKey));
int httpCode = http.POST(jsonString);
String response = http.getString();
Serial.println("Response code: " + String(httpCode));
Serial.println("Response: " + response);
http.end();
}
void sendDataToThingSpeak(float temp, float hum, int pm2, int pm10, float pr) {
Serial.println("API URL: " + String(thingSpeakApiUrl));
String jsonString = "{";
jsonString += "\"api_key\":\"" + String(thingSpeakApiKey) + "\", ";
jsonString += "\"field1\":" + String(temp) + ", ";
jsonString += "\"field2\":" + String(hum) + ", ";
jsonString += "\"field3\":" + String(pm2) + ", ";
jsonString += "\"field4\":" + String(pm10) + ", ";
jsonString += "\"field5\":" + String(pr);
jsonString += "}";
Serial.println(jsonString);
HTTPClient http;
http.begin(thingSpeakApiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept", "application/json");
http.addHeader("Content-Length", String(jsonString.length()));
int httpCode = http.POST(jsonString);
String response = http.getString();
Serial.println("Response code: " + String(httpCode));
Serial.println("Response: " + response);
http.end();
}
void sendDataToSensorCommunity(float temp, float hum, int pm2, int pm10, float pr) {
Serial.println("API URL: " + String(sensorCommunityApiUrl));
String jsonString = "{\"software_version\":\"V2\", ";
jsonString += "\"sensordatavalues\":[";
jsonString += "{\"value_type\":\"P1\",\"value\":\"" + String(pm2) + "\"}, ";
jsonString += "{\"value_type\":\"P2\",\"value\":\"" + String(pm10) + "\"}";
jsonString += "]}";
Serial.println(jsonString);
HTTPClient http;
http.begin(sensorCommunityApiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept", "application/json");
http.addHeader("X-Pin", "1");
http.addHeader("X-Sensor", String(sensorCommunitySensorId));
http.addHeader("Content-Length", String(jsonString.length()));
int httpCode = http.POST(jsonString);
String response = http.getString();
Serial.println("Response code: " + String(httpCode));
Serial.println("Response: " + response);
http.end();
}
// DISPLAY
void showTextRectangle(String ln1, String ln2, String ln3, String ln4, String ln5, boolean small) {
//display.clearDisplay();
display.clear();
display.setTextAlignment(TEXT_ALIGN_LEFT);
int fontSize;
if (small) {
fontSize = 10;
display.setFont(ArialMT_Plain_10);
} else {
fontSize = 16;
display.setFont(ArialMT_Plain_16);
}
display.drawString(32, 14, ln1);
display.drawString(32, 14 + fontSize, ln2);
display.drawString(32, 14 + fontSize * 2, ln3);
display.drawString(32, 14 + fontSize * 3, ln4);
display.drawString(32, 14 + fontSize * 4, ln5);
display.display();
}
// Wifi Manager
void connectToWifi(bool buttonIsEnabled){
Serial.println("WIFI connection..." + String(buttonIsEnabled ? " button pressed" : "button NOT pressed"));
WiFiManager wifiManager;
// Custom fields
// WiFiManagerParameter custom_api_server("api_server", "API server", apiUrl, 30);
// WiFiManagerParameter custom_api_owner("api_owner", "API user", apiOwnerName, 30);
// wifiManager.addParameter(&custom_api_server);
// wifiManager.addParameter(&custom_api_owner);
String HOTSPOT = "AIR-SENSOR-" + String(ESP.getChipId(), HEX);
wifiManager.setTimeout(120);
if(!wifiManager.autoConnect((const char*)HOTSPOT.c_str())) {
Serial.println("failed to connect and hit timeout");
if (buttonIsEnabled) {
WiFi.disconnect();
}
delay(3000);
ESP.restart();
delay(5000);
} else {
// strcpy(apiUrl, custom_api_server.getValue());
// strcpy(apiOwnerName, custom_api_owner.getValue());
Serial.println("MAC address: " + WiFi.macAddress());
if (exportToNarodmon) {
Serial.println("API URL: " + String(apiUrl));
Serial.println("API user: " + String(apiOwnerName));
}
if (exportToShopker) {
Serial.println("API URL: " + String(shopkerApiUrl));
}
if (exportToThingSpeak) {
Serial.println("API URL: " + String(thingSpeakApiUrl));
}
}
}