-
-
Notifications
You must be signed in to change notification settings - Fork 368
/
Copy pathclient_utils.cpp
292 lines (267 loc) · 8.62 KB
/
client_utils.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
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
/* Client side utilities for esp32-weather-epd.
* Copyright (C) 2022-2024 Luke Marzen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// built-in C++ libraries
#include <cstring>
#include <vector>
// arduino/esp32 libraries
#include <Arduino.h>
#include <esp_sntp.h>
#include <HTTPClient.h>
#include <SPI.h>
#include <time.h>
#include <WiFi.h>
// additional libraries
#include <Adafruit_BusIO_Register.h>
#include <ArduinoJson.h>
// header files
#include "_locale.h"
#include "api_response.h"
#include "aqi.h"
#include "client_utils.h"
#include "config.h"
#include "display_utils.h"
#include "renderer.h"
#ifndef USE_HTTP
#include <WiFiClientSecure.h>
#endif
#ifdef USE_HTTP
static const uint16_t OWM_PORT = 80;
#else
static const uint16_t OWM_PORT = 443;
#endif
/* Power-on and connect WiFi.
* Takes int parameter to store WiFi RSSI, or “Received Signal Strength
* Indicator"
*
* Returns WiFi status.
*/
wl_status_t startWiFi(int &wifiRSSI, wifi_network_t wifi)
{
WiFi.mode(WIFI_STA);
Serial.printf("%s '%s'", TXT_CONNECTING_TO, wifi.ssid);
WiFi.begin(wifi.ssid, wifi.password);
// timeout if WiFi does not connect in WIFI_TIMEOUT ms from now
unsigned long timeout = millis() + WIFI_TIMEOUT;
wl_status_t connection_status = WiFi.status();
while ((connection_status != WL_CONNECTED) && (millis() < timeout))
{
Serial.print(".");
delay(50);
connection_status = WiFi.status();
}
Serial.println();
if (connection_status == WL_CONNECTED)
{
wifiRSSI = WiFi.RSSI(); // get WiFi signal strength now, because the WiFi
// will be turned off to save power!
Serial.println("IP: " + WiFi.localIP().toString());
}
else
{
Serial.printf("%s '%s'\n", TXT_COULD_NOT_CONNECT_TO, wifi.ssid);
}
return connection_status;
} // startWiFi
/* Disconnect and power-off WiFi.
*/
void killWiFi()
{
WiFi.disconnect();
WiFi.mode(WIFI_OFF);
} // killWiFi
/* Prints the local time to serial monitor.
*
* Returns true if getting local time was a success, otherwise false.
*/
bool printLocalTime(tm *timeInfo)
{
int attempts = 0;
while (!getLocalTime(timeInfo) && attempts++ < 3)
{
Serial.println(TXT_FAILED_TO_GET_TIME);
return false;
}
Serial.println(timeInfo, "%A, %B %d, %Y %H:%M:%S");
return true;
} // printLocalTime
/* Waits for NTP server time sync, adjusted for the time zone specified in
* config.cpp.
*
* Returns true if time was set successfully, otherwise false.
*
* Note: Must be connected to WiFi to get time from NTP server.
*/
bool waitForSNTPSync(tm *timeInfo)
{
// Wait for SNTP synchronization to complete
unsigned long timeout = millis() + NTP_TIMEOUT;
if ((sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET)
&& (millis() < timeout))
{
Serial.print(TXT_WAITING_FOR_SNTP);
delay(100); // ms
while ((sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET)
&& (millis() < timeout))
{
Serial.print(".");
delay(100); // ms
}
Serial.println();
}
return printLocalTime(timeInfo);
} // waitForSNTPSync
/* Perform an HTTP GET request to OpenWeatherMap's "One Call" API
* If data is received, it will be parsed and stored in the global variable
* owm_onecall.
*
* Returns the HTTP Status Code.
*/
#ifdef USE_HTTP
int getOWMonecall(WiFiClient &client, owm_resp_onecall_t &r)
#else
int getOWMonecall(WiFiClientSecure &client, owm_resp_onecall_t &r)
#endif
{
int attempts = 0;
bool rxSuccess = false;
DeserializationError jsonErr = {};
String uri = "/data/" + OWM_ONECALL_VERSION
+ "/onecall?lat=" + LAT + "&lon=" + LON + "&lang=" + OWM_LANG
+ "&units=standard&exclude=minutely";
#if !DISPLAY_ALERTS
// exclude alerts
uri += ",alerts";
#endif
// This string is printed to terminal to help with debugging. The API key is
// censored to reduce the risk of users exposing their key.
String sanitizedUri = OWM_ENDPOINT + uri + "&appid={API key}";
uri += "&appid=" + OWM_APIKEY;
Serial.print(TXT_ATTEMPTING_HTTP_REQ);
Serial.println(": " + sanitizedUri);
int httpResponse = 0;
while (!rxSuccess && attempts < 3)
{
wl_status_t connection_status = WiFi.status();
if (connection_status != WL_CONNECTED)
{
// -512 offset distinguishes these errors from httpClient errors
return -512 - static_cast<int>(connection_status);
}
HTTPClient http;
http.setConnectTimeout(HTTP_CLIENT_TCP_TIMEOUT); // default 5000ms
http.setTimeout(HTTP_CLIENT_TCP_TIMEOUT); // default 5000ms
http.begin(client, OWM_ENDPOINT, OWM_PORT, uri);
httpResponse = http.GET();
if (httpResponse == HTTP_CODE_OK)
{
jsonErr = deserializeOneCall(http.getStream(), r);
if (jsonErr)
{
// -256 offset distinguishes these errors from httpClient errors
httpResponse = -256 - static_cast<int>(jsonErr.code());
}
rxSuccess = !jsonErr;
}
client.stop();
http.end();
Serial.println(" " + String(httpResponse, DEC) + " "
+ getHttpResponsePhrase(httpResponse));
++attempts;
}
return httpResponse;
} // getOWMonecall
/* Perform an HTTP GET request to OpenWeatherMap's "Air Pollution" API
* If data is received, it will be parsed and stored in the global variable
* owm_air_pollution.
*
* Returns the HTTP Status Code.
*/
#ifdef USE_HTTP
int getOWMairpollution(WiFiClient &client, owm_resp_air_pollution_t &r)
#else
int getOWMairpollution(WiFiClientSecure &client, owm_resp_air_pollution_t &r)
#endif
{
int attempts = 0;
bool rxSuccess = false;
DeserializationError jsonErr = {};
// set start and end to appropriate values so that the last 24 hours of air
// pollution history is returned. Unix, UTC.
time_t now;
int64_t end = time(&now);
// minus 1 is important here, otherwise we could get an extra hour of history
int64_t start = end - ((3600 * OWM_NUM_AIR_POLLUTION) - 1);
char endStr[22];
char startStr[22];
sprintf(endStr, "%lld", end);
sprintf(startStr, "%lld", start);
String uri = "/data/2.5/air_pollution/history?lat=" + LAT + "&lon=" + LON
+ "&start=" + startStr + "&end=" + endStr
+ "&appid=" + OWM_APIKEY;
// This string is printed to terminal to help with debugging. The API key is
// censored to reduce the risk of users exposing their key.
String sanitizedUri = OWM_ENDPOINT +
"/data/2.5/air_pollution/history?lat=" + LAT + "&lon=" + LON
+ "&start=" + startStr + "&end=" + endStr
+ "&appid={API key}";
Serial.print(TXT_ATTEMPTING_HTTP_REQ);
Serial.println(": " + sanitizedUri);
int httpResponse = 0;
while (!rxSuccess && attempts < 3)
{
wl_status_t connection_status = WiFi.status();
if (connection_status != WL_CONNECTED)
{
// -512 offset distinguishes these errors from httpClient errors
return -512 - static_cast<int>(connection_status);
}
HTTPClient http;
http.setConnectTimeout(HTTP_CLIENT_TCP_TIMEOUT); // default 5000ms
http.setTimeout(HTTP_CLIENT_TCP_TIMEOUT); // default 5000ms
http.begin(client, OWM_ENDPOINT, OWM_PORT, uri);
httpResponse = http.GET();
if (httpResponse == HTTP_CODE_OK)
{
jsonErr = deserializeAirQuality(http.getStream(), r);
if (jsonErr)
{
// -256 offset to distinguishes these errors from httpClient errors
httpResponse = -256 - static_cast<int>(jsonErr.code());
}
rxSuccess = !jsonErr;
}
client.stop();
http.end();
Serial.println(" " + String(httpResponse, DEC) + " "
+ getHttpResponsePhrase(httpResponse));
++attempts;
}
return httpResponse;
} // getOWMairpollution
/* Prints debug information about heap usage.
*/
void printHeapUsage() {
Serial.println("[debug] Heap Size : "
+ String(ESP.getHeapSize()) + " B");
Serial.println("[debug] Available Heap : "
+ String(ESP.getFreeHeap()) + " B");
Serial.println("[debug] Min Free Heap : "
+ String(ESP.getMinFreeHeap()) + " B");
Serial.println("[debug] Max Allocatable : "
+ String(ESP.getMaxAllocHeap()) + " B");
return;
}