-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
213 lines (187 loc) · 7.18 KB
/
main.cpp
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
#include <Arduino.h>
#include <ESP8266WiFi.h> // https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html
#include <ESP8266mDNS.h> // https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266mDNS
#include <ESP8266HTTPClient.h> // https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPClient
#include <WiFiClientSecureBearSSL.h>
#include <CertStoreBearSSL.h>
#include <BearSSLHelpers.h>
#include <time.h> // NOLINT(modernize-deprecated-headers)
#include <TZ.h>
#include <FS.h>
#include <LittleFS.h>
#include <ArduinoJson.h> // https://arduinojson.org
#define _TASK_SLEEP_ON_IDLE_RUN // NOLINT(bugprone-reserved-identifier)
#include <TaskScheduler.h> // https://github.com/arkhipenko/TaskScheduler
#include "led.h"
#include "config.h"
#define SERIAL_BAUD 115200
#ifndef CFG_TZ
#define CFG_TZ TZ_America_Detroit
#endif
// Scheduler & callback method prototypes
Scheduler ts;
bool ready = false;
void connectInit();
bool onMDNSEnable();
void mDNSCallback();
void connMonitorCallback();
void httpsDemoCallback();
// HTTPS Requests Demo
#define EXT_IP_URL "https://ip.dzdz.cz"
#define HTTP_TASK_INTERVAL (TASK_SECOND*30)
//#define USE_DYNAMIC_JSON_DOC // demos ArduinoJson's DynamicJsonDoc
BearSSL::CertStore certStore;
BearSSL::Session tlsSession;
BearSSL::WiFiClientSecure wifiClient;
// LED (all times in milliseconds)
#define CONNECTED_LED_TIME_ON (TASK_SECOND/5)
#define CONNECTED_LED_TIME_OFF (TASK_SECOND*1.5)
#define CONNECTING_LED_TIME_ON (TASK_SECOND/5)
#define CONNECTING_LED_TIME_OFF CONNECTING_LED_TIME_ON
#define CERT_ERR_LED_TIME_ON (TASK_SECOND/1.5)
#define CERT_ERR_LED_TIME_OFF CERT_ERR_LED_TIME_ON
// Tasks
Task tConnect (TASK_SECOND, TASK_FOREVER, &connectInit, &ts, true); // handles waiting on initial WiFi connection
Task tMDNS (TASK_MILLISECOND*50, TASK_FOREVER, &mDNSCallback, &ts, false, &onMDNSEnable, nullptr);
Task tConnMonitor (TASK_SECOND, TASK_FOREVER, &connMonitorCallback, &ts, false);
Task tHttpsDemo (HTTP_TASK_INTERVAL, TASK_FOREVER, &httpsDemoCallback, &ts, false);
/**
* Sets the system time via NTP, as required for x.509 validation
* see https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/BearSSL_CertStore/BearSSL_CertStore.ino
*/
void setClock() {
configTime(CFG_TZ, "pool.ntp.org", "time.nist.gov");
Serial.printf_P(PSTR("%lu: Waiting for NTP time sync "), millis());
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) {
delay(250);
Serial.print(".");
now = time(nullptr);
}
Serial.print(F("\r\n"));
struct tm timeinfo; // NOLINT(cppcoreguidelines-pro-type-member-init)
gmtime_r(&now, &timeinfo);
Serial.printf_P(PSTR("Current time (UTC): %s"), asctime(&timeinfo));
localtime_r(&now, &timeinfo);
Serial.printf_P(PSTR("Current time (Local): %s"), asctime(&timeinfo));
}
void setup() {
Serial.begin(SERIAL_BAUD);
LittleFS.begin();
int numCerts = certStore.initCertStore(LittleFS, PSTR("/certs.idx"), PSTR("/certs.ar"));
Serial.printf_P(PSTR("%lu: read %d CA certs into store\r\n"), millis(), numCerts);
if (numCerts == 0) {
Serial.println(F("!!! No certs found. Did you run certs-from-mozilla.py and upload the LittleFS directory?"));
blinkLED(CERT_ERR_LED_TIME_ON, CERT_ERR_LED_TIME_OFF);
return;
}
wifiClient.setCertStore(&certStore);
wifiClient.setSession(&tlsSession);
wifiClient.setSSLVersion(BR_TLS12, BR_TLS12);
ready = true;
}
void loop() {
if (ready) { // ready flag blocks running the main program if startup tasks failed
ts.execute();
}
}
/**
* Get my external IP address and post it as the body to CFG_POST_URL.
*/
void httpsDemoCallback() {
HTTPClient httpClient;
httpClient.begin(wifiClient, EXT_IP_URL);
Serial.printf_P(PSTR("%lu: Starting GET request to %s\r\n"), millis(), EXT_IP_URL);
String getResult = "";
int respCode = httpClient.GET();
if (respCode >= 400) {
Serial.printf_P(PSTR("%lu: HTTP Error %d\r\n"), millis(), respCode);
} else if (respCode > 0) {
Serial.printf_P(PSTR("%lu: HTTP %d\r\n"), millis(), respCode);
getResult = httpClient.getString();
Serial.printf_P(PSTR("\t%s\r\n"), getResult.c_str());
} else {
Serial.printf_P(PSTR("%lu: error: %s\r\n"), millis(), HTTPClient::errorToString(respCode).c_str());
}
httpClient.end();
if (respCode < 0 || respCode >= 400) {
return;
}
yield(); // esp8266 yield allows WiFi stack to run
String jsonBody;
#ifdef USE_DYNAMIC_JSON_DOC
DynamicJsonDocument jsonDoc(96);
#else
StaticJsonDocument<96> jsonDoc;
#endif
jsonDoc["ext_ip"] = getResult;
jsonDoc["int_ip"] = WiFi.localIP().toString();
serializeJson(jsonDoc, jsonBody);
httpClient.setReuse(false); // holy hell, this took forever to figure out
httpClient.begin(wifiClient, CFG_POST_URL);
httpClient.addHeader(F("Content-Type"), F("application/json"));
Serial.printf_P(PSTR("%lu: Starting POST request to %s\r\n"), millis(), CFG_POST_URL);
respCode = httpClient.POST(jsonBody);
if (respCode >= 400) {
Serial.printf_P(PSTR("%lu: HTTP Error %d\r\n"), millis(), respCode);
} else if (respCode > 0) {
Serial.printf_P(PSTR("%lu: HTTP %d\r\n"), millis(), respCode);
} else {
Serial.printf_P(PSTR("%lu: error: %s\r\n"), millis(), HTTPClient::errorToString(respCode).c_str());
}
httpClient.end();
}
/**
Wait for initial WiFi connection, then set clock & enable connection monitor
*/
void connectWait() {
Serial.printf_P(PSTR("%lu: Waiting for initial WiFi connection\r\n"), millis());
if (WiFi.status() == WL_CONNECTED) {
Serial.printf_P(PSTR("%lu: Connected. My IP: %s\r\n"), millis(), WiFi.localIP().toString().c_str());
blinkLED(CONNECTED_LED_TIME_ON, CONNECTED_LED_TIME_OFF);
tConnect.disable();
setClock(); // blocking call to set clock for x.509 validation as soon as WiFi is connected
tMDNS.enable();
tConnMonitor.enable();
}
}
/**
Initiate connection to the WiFi network
*/
void connectInit() {
Serial.printf_P(PSTR("%lu: Connecting to WiFi (%s)\r\n"), millis(), CFG_WIFI_ESSID);
WiFi.mode(WIFI_STA);
WiFi.hostname(CFG_HOSTNAME);
WiFi.begin(CFG_WIFI_ESSID, CFG_WIFI_PASSWORD);
blinkLED(CONNECTING_LED_TIME_ON, CONNECTING_LED_TIME_OFF);
yield(); // esp8266 yield allows WiFi stack to run
tConnect.yield(&connectWait); // pass control to Scheduler; wait for initial WiFi connection
}
/**
* Start the mDNS stack.
*/
bool onMDNSEnable() {
return MDNS.begin(CFG_HOSTNAME);
}
/**
* Keep the mDNS stack running.
*/
void mDNSCallback() {
MDNS.update();
}
/**
* Check WiFi status every second and configure accordingly:
* - LED blink rate
* - Whether HTTPS requests (our "work") is enabled
*/
void connMonitorCallback() {
auto status = WiFi.status();
if (status == WL_CONNECTED) {
blinkLED(CONNECTED_LED_TIME_ON, CONNECTED_LED_TIME_OFF);
tHttpsDemo.enableIfNot();
} else {
Serial.print(millis()); Serial.print(F(": WiFi connection status: ")); Serial.println(status);
blinkLED(CONNECTING_LED_TIME_ON, CONNECTING_LED_TIME_OFF);
tHttpsDemo.disable();
}
}