-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwlan_sketch.ino
287 lines (250 loc) · 6.61 KB
/
wlan_sketch.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
#include <ArduinoOTA.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <Wire.h>
#include "bme280_aggregator.hpp"
#include "debug.hpp"
#include "rtc_mem.hpp"
#include "wifi.hpp"
// Parts of this project are based on https://bitbucket.org/2msd/d1mini_sht30_mqtt/src/master/d1mini_sht30_mqtt.ino
BME280Aggregator bme;
ESaveWifi eWifi;
#define RECORD_LIMIT (STORED_RECORDS - 10)
void execSleep(uint32_t sleepTime = INTERVAL_MS) {
#ifdef USE_DEEPSLEEP
ESP.deepSleep(sleepTime * 1000);
#else
#ifdef USE_OTA
LOGF("OTAHandling: %d\n", sleepTime);
while (sleepTime > 0) {
uint32_t t1 = millis();
ArduinoOTA.handle();
uint32_t t2 = millis();
if (t2 - t1 < 50) {
delay(50);
t2 = millis();
}
if (t2 - t1 < sleepTime) {
sleepTime -= (t2 - t1);
} else {
sleepTime = 0;
}
}
#else
LOGF("Delaying: %d\n", sleepTime);
delay(sleepTime);
#endif
ESP.reset();
#endif
delay(100); // See https://www.mikrocontroller.net/topic/384345
}
void setup() {
using rtcMem::gRTC;
init_debug();
LOGINTER("start");
if (!rtcMem::read()) {
LOGLN("Reading RTC data failed.");
}
// Check if we were woken up by default_rst => reset internal structs, data is out of date
LOGF("Resetreason: %d\n", ESP.getResetInfoPtr()->reason);
if (ESP.getResetInfoPtr()->reason == REASON_EXT_SYS_RST) {
LOGLN("Ordinary Power ON, resetting stored records");
gRTC.stored_records = 0;
}
#ifdef USE_OTA
LOGLN("Starting wifi: OTA Enabled.");
eWifi.turnOn();
bool dump_stored = true;
ArduinoOTA.onStart([]() { Serial.println("Start"); });
ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); });
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); });
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR)
Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR)
Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR)
Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR)
Serial.println("Receive Failed");
else if (error == OTA_END_ERROR)
Serial.println("End Failed");
});
ArduinoOTA.begin();
#else
bool dump_stored = gRTC.stored_records > RECORD_LIMIT;
if (dump_stored) {
LOGLN("Starting wifi: Have enough stored.");
eWifi.turnOn();
}
#endif
auto retries = 0;
while (retries < 100) {
if (bme.begin(0x76)) {
break;
}
retries++;
delay(100);
execSleep();
return;
}
auto full_data = bme.readAllSensors();
// Advance gRTC records
gRTC.records[gRTC.stored_records] = full_data;
gRTC.stored_records = (gRTC.stored_records + 1) % STORED_RECORDS;
if (dump_stored && eWifi.checkStatus()) {
LOGINTER("sending");
send_records_to_influx();
#ifndef USE_OTA
eWifi.shutDown();
#endif
}
rtcMem::write();
LOGINTER("final");
auto now = millis();
#ifndef DEBUG
Serial.begin(DEBUG_BAUDRATE);
Serial.setTimeout(2000);
while (!Serial) {
delay(50);
}
Serial.printf("Final time: %d\n", now);
#endif
uint32_t sleepTime = 0;
if (now > INTERVAL_MS) {
LOGLN("Interval was too large. sleeping full length.");
sleepTime = INTERVAL_MS;
} else {
sleepTime = (INTERVAL_MS - millis());
}
execSleep(sleepTime);
}
void loop() {
LOGLN("I should not be here. I should be sleeping.");
delay(1000);
}
/*
Slighly optimized variant of the usual timespec struct for our purposes:
Carry microseconds instead of ns + store thousand seconds instead of single
*/
struct msec_timespec {
time_t tv_millionsec; /* MillionSeconds */
long tv_millisec; /* Milliseconds */
void subtract(uint32_t millisec) {
if (millisec > 1e9) {
LOGLN("Error: Can only subtract below 1M seconds");
}
if (millisec > tv_millisec) {
tv_millionsec--;
tv_millisec += 1e9;
}
tv_millisec -= millisec;
};
void add(uint32_t millisec) {
if (millisec > 1e9) {
LOGLN("Error: Can only subtract below 1M seconds");
}
tv_millisec += millisec;
if (tv_millisec > 1e9) {
tv_millionsec += 1;
tv_millisec -= 1e9;
}
}
String toString() {
char ts_string[24];
snprintf(ts_string, sizeof(ts_string), "%d%09d", tv_millionsec, tv_millisec);
return String(ts_string);
}
};
struct msec_timespec get_timestamp_from_server() {
struct msec_timespec res = {0, 0};
WiFiClient client;
HTTPClient http;
if (http.begin(client, TS_URL)) {
int httpCode = http.GET();
if (httpCode > 0) {
LOGF("[HTTP] GET TS... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
LOGLN("Received timestamp successfully.");
String data = http.getString();
data.trim();
if (data.length() != 13) {
LOGLN("Invalid length of time page. Wrong server?");
return res;
}
LOG("TS string: ");
LOGLN(data);
LOGINTER("Converting");
String micsString = data.substring(data.length() - 9);
String ksString = data.substring(0, data.length() - 9);
LOGLN(ksString);
LOGLN(micsString);
res = {ksString.toInt(), micsString.toInt()};
}
} else {
LOGF("[HTTP] GET TS... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
return res;
}
bool send_single_data_to_influx(String& data) {
LOGLN(data);
WiFiClient client;
HTTPClient http;
bool res = false;
LOGLN("Sending data...");
if (http.begin(client, DB_URL)) {
int httpCode = http.POST(data);
if (httpCode > 0) {
LOGF("[HTTP] POST... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_NO_CONTENT) {
LOGLN("Uploaded data successfully.");
res = true;
}
} else {
LOGF("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
return res;
}
void send_records_to_influx() {
using rtcMem::gRTC;
LOGINTER("Start TS");
auto ts = get_timestamp_from_server();
if (ts.tv_millionsec == 0) {
LOGLN("Failed, retrying...");
ts = get_timestamp_from_server();
if (ts.tv_millionsec == 0) {
LOGLN("Final fail.");
return;
}
}
LOGINTER("End TS");
String influx_data = "";
influx_data.reserve(80 * gRTC.stored_records);
for (int16_t i = gRTC.stored_records - 1; i >= 0; i--) {
influx_data += "bme280,host=";
influx_data += ESP.getChipId();
influx_data += " ";
influx_data += gRTC.records[i].toString();
// LOG("Reassembled ts: ");
// LOGLN(String(ts_string));
influx_data += " ";
influx_data += ts.toString();
influx_data += "000000\n";
ts.subtract(INTERVAL_MS);
if (influx_data.length() >= 512) {
send_single_data_to_influx(influx_data);
influx_data = "";
}
}
if (influx_data.length()) {
send_single_data_to_influx(influx_data);
}
// Reset our store
gRTC.stored_records = 0;
}