-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenWeather.cpp
More file actions
280 lines (225 loc) · 6.97 KB
/
Copy pathOpenWeather.cpp
File metadata and controls
280 lines (225 loc) · 6.97 KB
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
//=====================================================================================
// A class definition for OpenWeather
// https://openweathermap.org/forecast5?collection=current_forecast
//=====================================================================================
#include <Arduino.h>
#include <ArduinoJson.h>
#include "config.h"
#include "rtcntp.h"
#include "OpenWeather.h"
#include "gfx.h"
#include "root_ca.hpp"
// Select the libraries to use
#define USE_HTTP_CLIENT false
#define USE_SECURE_CLIENT true
// Select a method for deserializing JSON data
#define TYPE_STATIC_DAT 0 // response_forecast.hpp
#define TYPE_GET_STRING 1 // Output to Serial Monitor
#define TYPE_RAW_STREAM 2 // Deserialize by ArduinoJson
#define DESERIALIZATION_TYPE TYPE_RAW_STREAM
// Format of an HTTP request to OpenWeather
static constexpr char host[] = HOST;
static constexpr char path[] = PATH "?lang=" LANGUAGE "&lat=" LATITUDE "&lon=" LONGITUDE "&units=" UNITS "&appid=" API_KEY;
#if defined(ARDUINO_UNOR4_WIFI)
#include "WiFiS3.h"
#if USE_SECURE_CLIENT
WiFiSSLClient client;
#define PORT 443
#else
WiFiClient client;
#define PORT 80
#endif
#if USE_HTTP_CLIENT
#include <HttpClient.h>
HttpClient http(client, host, PORT);
#endif
#else // ESP32
#if USE_SECURE_CLIENT
#include <NetworkClientSecure.h>
NetworkClientSecure client;
#define PORT 443
#else
#include <NetworkClient.h>
NetworkClient client;
#define PORT 80
#endif
#if USE_HTTP_CLIENT
#include <HTTPClient.h>
HTTPClient http;
#endif
#endif
//-------------------------------------------------------------------------------------
// Initialization
//-------------------------------------------------------------------------------------
void OpenWeather::Init(void) {
// Configure the root CA certificate
#if USE_SECURE_CLIENT
#ifdef _ROOT_CA_CERTIFICATE_HPP_
client.setCACert(root_ca);
#elif defined(ESP32)
client.setInsecure(); // ignore server's certificate
#endif
#endif
}
//-------------------------------------------------------------------------------------
// HTTP request
//-------------------------------------------------------------------------------------
bool OpenWeather::RequestWeatherData(void) {
bool ret = false;
#if (DESERIALIZATION_TYPE == TYPE_STATIC_DAT)
// Pass 'Serial' as a dummy argument
ret = readResponse(Serial);
#elif (USE_HTTP_CLIENT)
gfxDrawMessage("\nConnecting to server...");
#if defined(ARDUINO_UNOR4_WIFI)
// Send HTTP request
int status = http.get(path);
// https://github.com/espressif/arduino-esp32/blob/master/libraries/HTTPClient/src/HTTPClient.h#L46-L123
DBG_EXEC(Serial.println("GET status: " + String(status)));
if (status == HTTP_SUCCESS) {
// Read status code in response
status = http.responseStatusCode();
DBG_EXEC(Serial.println("HTTP status: " + String(status)));
gfxDrawMessage("Receiving response...");
if (200 <= status && status < 300) {
// Read response header section
if (http.skipResponseHeaders() == HTTP_SUCCESS) {
// Read response body section
ret = readResponse(http);
gfxDrawMessage("Done.\n");
} else {
gfxDrawMessage("Bad response.\n");
}
}
}
http.stop(); // Disconnect
#else // USE_HTTP_CLIENT for ESP32
// Initialize the SSL library
#if USE_SECURE_CLIENT
String scheme = "https://";
#else
String scheme = "http://";
#endif
http.begin(client, scheme + host + path);
int status = http.GET();
// https://github.com/espressif/arduino-esp32/blob/master/libraries/HTTPClient/src/HTTPClient.h#L46-L123
DBG_EXEC(Serial.println("HTTP status: " + String(status) + http.errorToString(status)));
gfxDrawMessage("Receiving response...");
if (200 <= status && status < 300) {
// Read response body section
Stream &stream = http.getStream();
ret = readResponse(stream);
gfxDrawMessage("Done.\n");
} else {
gfxDrawMessage("Bad response.\n");
}
http.end(); // Disconnect
#endif // USE_HTTP_CLIENT for UNO R4 WiFi or ESP32
#else // ! USE_HTTP_CLIENT for UNO R4 WiFi and ESP32
gfxDrawMessage("\nConnecting to server...");
if (!client.connect(host, PORT)) {
gfxDrawMessage("failed.\n", false);
client.stop(); // it takes seceral seconds
return false;
}
gfxDrawMessage("done.\n", false);
// Send HTTP request
// Note: If the header "Transfer-Encoding" is "chunked", use "HTTP/1.0".
// https://arduinojson.org/v7/how-to/use-arduinojson-with-httpclient/
client.println(String("GET ") + path + " HTTP/1.1");
client.println(String("Host: ") + host);
client.println("Connection: close");
client.println();
gfxDrawMessage("Receiving response...");
// Read response headers until "\r\n\r\n" is detected.
bool detected = false;
while (client.connected()) {
String header = client.readStringUntil('\n');
gfxDrawMessage(".", false);
DBG_EXEC(Serial.println(header));
if (header == "\r") {
DBG_EXEC(Serial.println("End of headers."));
detected = true;
break;
}
}
// Read response body section
if (detected && client.available()) {
ret = readResponse(client);
gfxDrawMessage("Done.\n");
} else {
gfxDrawMessage("Bad response.\n");
}
client.stop();
#endif
return ret;
}
//-------------------------------------------------------------------------------------
//
//-------------------------------------------------------------------------------------
static constexpr char filter_template[] = R"(
{
"cnt": true,
"list": [
{
"dt": true,
"main": {
"temp": true,
"humidity": true
},
"weather": [
{
"id": true
}
],
"clouds": {
"all": true
},
"wind": {
"speed": true,
"deg": true
},
"pop": true
}
],
"city": {
"timezone": true,
"sunrise": true,
"sunset": true
}
}
)";
//-------------------------------------------------------------------------------------
// Read HTTP response body and build JsonDocument
//-------------------------------------------------------------------------------------
bool OpenWeather::readResponse(Stream &stream) {
#if (DESERIALIZATION_TYPE == TYPE_STATIC_DAT)
constexpr char response[] =
#include "samples/response_forecast.h"
;
#else
Stream &response = stream;
#endif
#if (DESERIALIZATION_TYPE == TYPE_GET_STRING)
while (response.available()) {
char c = response.read();
DBG_EXEC(Serial.write(c));
}
DBG_EXEC(Serial.println());
return true;
#else
JsonDocument filter;
deserializeJson(filter, filter_template);
auto error = deserializeJson(data, response, DeserializationOption::Filter(filter));
if (error) {
DBG_EXEC(Serial.print("deserializeJson() failed: "));
DBG_EXEC(Serial.println(error.c_str()));
return false;
}
DBG_EXEC({
serializeJson(data, Serial);
Serial.println();
});
return true;
#endif
}