-
Notifications
You must be signed in to change notification settings - Fork 2
/
pm2.5-nodeMCU.ino
277 lines (228 loc) · 8.75 KB
/
pm2.5-nodeMCU.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
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <FS.h>
#include <NtpClientLib.h>
#include <WiFiUdp.h>
uint32 pm1 = UINT32_MAX;
uint32 pm2_5 = UINT32_MAX;
uint32 pm10 = UINT32_MAX;
unsigned int sleepWakeCycles = 0;
unsigned long rtcSystemTime = 0;
unsigned long startupMillis = 0;
#include "debug.h"
#include "config.h"
#include "LEDs.h"
#include "PMS3003.h"
// #include "SensorWeb.h"
// used by date_ISO8601() in utils.h
#include "utils.h"
#include "AirCasting.h"
#include "RTC.h"
bool ntpInitialSync = false;
bool readyForNTP = false;
bool ntpRunning = false;
unsigned int ntpErrors = 0;
double ntpStartTime = 0;
double ntpWaitTime = 0;
ESP8266WiFiMulti* WiFiMulti;
void ntpSyncEventHandler(NTPSyncEvent_t error) {
if (!ntpRunning) {
serialUdpDebug("NTPSyncEvent: Ignoring stale event, expected with dayLight=true");
/**
* 23:07:52.019 -> NTPSyncEvent: Stale event, expected with dayLight=true
* 23:07:52.085 -> NTPSyncEvent: 07:28:16 07/02/2036
* 23:07:52.119 -> NTPSyncEvent: actualRuntime=2.27 -- bootTime=325
* 23:07:52.152 -> NTPSyncEvent: actualSystemTime=2036-02-07T07:28:16.000+01:00 -- expectedSystemTime=2019-01-29T23:08:08.000+01:00
* 23:07:52.285 -> NTPSyncEvent: deltaTime=-537178804.94200 => slowDownFactor=-1790595.01647
*/
return;
}
ntpRunning = false;
if (error) {
ntpErrors += 1;
if (error == noResponse) {
serialUdpDebug("NTPSyncEvent: server not reachable");
} else if (error == invalidAddress) {
serialUdpDebug("NTPSyncEvent: invalid server address");
} else {
serialUdpDebug("NTPSyncEvent: " + String(error));
}
} else {
ntpErrors = 0;
serialUdpDebug("NTPSyncEvent: " + NTP.getTimeDateString(NTP.getLastNTPSync()));
if (!ntpInitialSync) {
// serialUdpDebug("NTPSyncEvent: set ntpInitialSync");
ntpInitialSync = true;
}
ntpWaitTime = millis() - ntpStartTime;
// If we receive a ntpSyncEvent for sleepWakeCycles=1 then we
// are there to compute slowdown factor.
if (sleepWakeCycles == sleepWakeCyclesSlowDownCompute) {
double actualSystemTime = NTP.getLastNTPSync();
double actualRuntime = getCurrentExecutionTime();
double expectedSystemTime = rtcSystemTime + actualRuntime;
double deltaTime = expectedSystemTime - actualSystemTime + (bootTime / 1000.0) + (ntpWaitTime / 1000.0);
slowDownFactor = 1.0 + (deltaTime / execInterval);
serialUdpDebug("NTPSyncEvent: actualRuntime=" + String(actualRuntime) + " -- bootTime=" + String(bootTime));
serialUdpDebug("NTPSyncEvent: actualSystemTime=" + date_ISO8601(actualSystemTime) + " -- expectedSystemTime=" + date_ISO8601(expectedSystemTime));
serialUdpDebug("NTPSyncEvent: deltaTime=" + String(deltaTime, 5) + " => slowDownFactor=" + String(slowDownFactor, 5));
}
}
}
void startNtp() {
if (!ntpRunning) {
ntpRunning = true;
NtpConfig* ntpConfig = NtpConfig::getInstance();
NTP.onNTPSyncEvent(ntpSyncEventHandler);
NTP.begin(ntpConfig->ntpServer, ntpConfig->ntpTZOffset, ntpConfig->ntpDayLight);
NTP.setInterval(ntpFirstSync, ntpInterval);
serialUdpIntDebug("NTP: NTP.begin(" + ntpConfig->ntpServer + ", " + ntpConfig->ntpTZOffset + ", " + ntpConfig->ntpDayLight + ")");
ntpStartTime = millis();
} else {
serialUdpIntDebug("NTP: not starting because ntpRunning=true");
}
}
void stopNtp() {
ntpRunning = false;
NTP.stop();
}
void wifiHasIpAddress(WiFiEventStationModeGotIP evt) {
serialUdpIntDebug("UP: " + VERSION + ":" + (BUILD_DATE + " " + BUILD_TIME) + "@" + evt.ip.toString());
// Only schedule NTP sync when we do need it.
if (sleepWakeCycles <= sleepWakeCyclesSlowDownCompute) {
readyForNTP = true;
}
}
void wifiConnected(WiFiEventStationModeConnected evt) {
serialUdpIntDebug("Connected to SSID: " + evt.ssid);
}
void wifiDisconnected(WiFiEventStationModeDisconnected evt) {
DEBUG_SERIAL("Disconnected from SSID: " + evt.ssid + "; reason: " + evt.reason);
DEBUG_SERIAL("Reason: " + evt.reason);
readyForNTP = false;
if (sleepWakeCycles <= sleepWakeCyclesSlowDownCompute) {
stopNtp();
}
}
void setup() {
static WiFiEventHandler connectEvent, hasIpEvent, disconnectEvent;
startupMillis = millis();
WiFi.persistent(true);
WiFi.mode(WIFI_STA);
// Measure how much power we can save there ...
// According to ESP docs:
// 802.11b: TX ~170mA, RX ~50mA
// 802.11g: TX ~140mA, RX ~56mA
// 802.11n: TX ~120mA, RX ~56mA
WiFi.setPhyMode(WIFI_PHY_MODE_11N);
const rst_info * resetInfo = system_get_rst_info();
if (resetInfo->reason == REASON_DEEP_SLEEP_AWAKE) {
if (readTimeFromRTC()) {
// If we wake up from deep sleep AND sleepWakeCycles is one
// it means we did a first NTP sync. Let's do a second one.
if (sleepWakeCycles < forceResync) {
if (sleepWakeCycles > sleepWakeCyclesSlowDownCompute) {
ntpInitialSync = true;
}
} else {
sleepWakeCycles = 0;
slowDownFactor = 1.0;
}
}
}
// Reconfigure watchdog at least twice expected secs.
ESP.wdtEnable(30 * 1000);
PM_SERIAL.begin(9600);
DEBUG_SERIAL("Booting ...");
#if LWIP_IPV6
DEBUG_SERIAL("IPV6 is enabled\n");
#else
DEBUG_SERIAL("IPV6 is not enabled\n");
#endif
configure_leds();
configure_pms3003_pin();
// put PMS3003 into standby for now
power_pms3003(false);
hasIpEvent = WiFi.onStationModeGotIP(wifiHasIpAddress);
connectEvent = WiFi.onStationModeConnected(wifiConnected);
disconnectEvent = WiFi.onStationModeDisconnected(wifiDisconnected);
ntpRunning = false;
NTP.stop();
WiFiMulti = new ESP8266WiFiMulti();
WifiConfig wifiConfig;
for(int itCreds = 0 ; itCreds < wifiConfig.creds.size(); itCreds++ ) {
WifiCreds c = wifiConfig.creds[itCreds];
if (c.pass().length() > 0) {
WiFiMulti->addAP(c.ssid().c_str(), c.pass().c_str());
DEBUG_SERIAL("WifiConfig: Adding WiFi for protected " + c.ssid());
} else {
WiFiMulti->addAP(c.ssid().c_str());
DEBUG_SERIAL("WifiConfig: Adding WiFi for open " + c.ssid());
}
}
BLINK_LED_BOOT;
}
void loop() {
// Let's take a few (extra) seconds and make sure brand new devices can connect.
// Doing that always will cripple boot time:
// - with WiFiMulti->run() checking, we get IP ~7 secs after boot
// - without, we get IP ~2.9 secs after boot
if (sleepWakeCycles == 0) {
if (WiFiMulti->run() != WL_CONNECTED) {
DEBUG_SERIAL("WifiConfig: not connected, waiting ...");
delay(500);
return;
}
}
if (readyForNTP) {
startNtp();
}
// Wait for NTP sync at least 3*45 secs
// If we get nothing, go to sleep. Let's hope it is a transient issue.
String timeNow = date_ISO8601(now(), false, false);
if (!ntpInitialSync && (ntpErrors < 3)) {
serialUdpDebug("Loop: no NTP initial sync, waiting ... sleepWakeCycles=" + String(sleepWakeCycles) + " ntpErrors=" + String(ntpErrors));
delay(1250);
return;
}
// Do not try to collect or send data if we have not received any NTP sync event.
if (ntpErrors < 3) {
AirCasting ac;
String sessionUUID = ac.getSessionUUID();
serialUdpDebug("SessionUUID: " + sessionUUID);
serialUdpDebug("NTP: " + timeNow);
// Read values from the PMS3003 connected sensor
collect_pms3003_sensor();
// Send even if value is 0 ; it just means sensor detected nothing.
if(pm2_5 < UINT32_MAX && sessionUUID.length() > 0) {
bool sent = ac.push(timeNow, pm2_5);
serialUdpDebug("NTP: " + timeNow + " PM2.5: " + String(pm2_5) + " UUID:" + sessionUUID + " sent:" + sent);
}
} else {
serialUdpDebug("Loop: too many NTP errors. Aborting.");
}
double executionTime = getCurrentExecutionTime();
double nextInterval = ((double)execInterval - (double)executionTime) * 1.0;
// Ensure that we have something within range of [1; execInterval]
nextInterval = MAX(1, MIN(nextInterval, execInterval));
serialUdpDebug("Loop: deepSleep: nextInterval=" + String(nextInterval) +
"; executionTime=" + String(executionTime) +
" ; slowDownFactor=" + String(slowDownFactor, 5) +
"; deepSleep(" + String(nextInterval * slowDownFactor) + ")");
// Write time to RTC only if we could get some valid.
// e.g., no ntp works during first boot of the system
// then goes to sleep writing time to RTC
// When it wakes up it would restore time as if it was good
// => you end up in the 1970s
if (ntpInitialSync) {
writeTimeToRTC(now(), nextInterval);
}
// with WAKE_RF_DEFAULT, deep sleep current ~8.2mA
// with WAKE_NO_RFCAL, deep sleep current ~8.2mA
// with WAKE_RF_DISABLED, no wifi on return from sleep, and deep sleep current ~8.2mA
ESP.deepSleep(nextInterval * slowDownFactor * 1e6, WAKE_NO_RFCAL);
return;
}