-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetWeather.h
More file actions
206 lines (189 loc) · 5.4 KB
/
getWeather.h
File metadata and controls
206 lines (189 loc) · 5.4 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
#include <SPI.h>
#include <WiFiNINA.h>
#include <ArduinoJson.h>
WiFiSSLClient client;
StaticJsonDocument<200> getWeather(String apiKey, String location) {
char host[] = "api.openweathermap.org";
String path = "/data/2.5/weather?q=" + location + "&cnt=1&appid=" + apiKey;
int pingResult;
pingResult = WiFi.ping(host);
if (WiFi.ping(host) >= 0) {
Serial.print("Successfully pinged ");
Serial.print(host);
Serial.print(" in ");
Serial.print(pingResult);
Serial.println("ms");
} else {
Serial.print("Could not ping ");
Serial.println(host);
Serial.println("Restarting in case it's an issue with the WiFi");
restart();
}
Serial.println();
Serial.print("Starting connection to ");
Serial.println(host);
if (client.connect(host, 443)) {
Serial.println("connected to host");
// Make a HTTP request:
client.println("GET " + path + " HTTP/1.1");
client.println("Host: api.openweathermap.org");
client.println("Connection: close");
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return;
}
} else {
Serial.println("Could not connect to host");
return;
}
Serial.print("Waiting for response");
int timeout = 0;
while (!client.available() && timeout < 1000) {
Serial.print(".");
delay(50);
}
Serial.println();
if (!client.available()) {
Serial.println("No response received");
return;
}
// Check HTTP status
char status[32] = {0};
client.readBytesUntil('\r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
// Get time from response headers (because the board has no clock)
String dateHeader;
while (client.connected()) {
String dateHeaderKey = "Date: ";
String line = client.readStringUntil('\n');
if (line.indexOf(dateHeaderKey) != -1) {
dateHeader = line.substring(sizeof(dateHeaderKey));
Serial.println("dateHeader: " + dateHeader);
break;
}
}
if (sizeof(dateHeader) == 0) {
Serial.print(F("Could not extract date header"));
return;
}
long epochTime = 0;
long aYearInSeconds = 31536000;
long aDayInSeconds = 86400;
long anHourInSeconds = 3600;
long aMinuteInSeconds = 60;
// Years
int yearsSinceEpoch = (dateHeader.substring(16, 12).toInt() - 1970);
epochTime += yearsSinceEpoch * aYearInSeconds;
// Days
int dayOfMonth = dateHeader.substring(7, 5).toInt();
int monthNum;
String monthString = dateHeader.substring(11, 8);
if (monthString == "Jan") {
monthNum = 1;
} else if (monthString == "Feb") {
monthNum = 2;
} else if (monthString == "Mar") {
monthNum = 3;
} else if (monthString == "Apr") {
monthNum = 4;
} else if (monthString == "May") {
monthNum = 5;
} else if (monthString == "Jun") {
monthNum = 6;
} else if (monthString == "Jul") {
monthNum = 7;
} else if (monthString == "Aug") {
monthNum = 8;
} else if (monthString == "Sep") {
monthNum = 9;
} else if (monthString == "Oct") {
monthNum = 10;
} else if (monthString == "Nov") {
monthNum = 11;
} else if (monthString == "Dec") {
monthNum = 12;
}
if (monthNum > 1) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 2) {
epochTime += 28 * aDayInSeconds;
}
if (monthNum > 3) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 4) {
epochTime += 30 * aDayInSeconds;
}
if (monthNum > 5) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 6) {
epochTime += 30 * aDayInSeconds;
}
if (monthNum > 7) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 8) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 9) {
epochTime += 30 * aDayInSeconds;
}
if (monthNum > 10) {
epochTime += 31 * aDayInSeconds;
}
if (monthNum > 11) {
epochTime += 30 * aDayInSeconds;
}
epochTime += (dayOfMonth - 1) * aDayInSeconds;
Serial.println(epochTime);
// Leap years
int numberOfLeapYears = ((yearsSinceEpoch - 2) / 4) + 1;
epochTime += numberOfLeapYears * aDayInSeconds;
// Hours
epochTime += dateHeader.substring(19, 17).toInt() * anHourInSeconds;
// Minutes
epochTime += dateHeader.substring(22, 20).toInt() * aMinuteInSeconds;
// Seconds
epochTime += dateHeader.substring(25, 23).toInt();
Serial.print("Epoch time: ");
Serial.println(epochTime);
// Skip rest of HTTP headers
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
// Get the response body
char response[2000];
int pointer = 0;
while (client.connected() || client.available()) {
char character = client.read();
response[pointer] = character;
pointer++;
}
client.stop();
// Deserialise the JSON
StaticJsonDocument<2000> jsonDocument;
DeserializationError error = deserializeJson(jsonDocument, response);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
Serial.println("Streamlining the JSON");
StaticJsonDocument<200> tidyJSON;
String city = jsonDocument["name"];
String country = jsonDocument["sys"]["country"];
tidyJSON["location"] = city + ", " + country;
tidyJSON["sunrise"] = jsonDocument["sys"]["sunrise"];
tidyJSON["sunset"] = jsonDocument["sys"]["sunset"];
tidyJSON["cloudiness"] = jsonDocument["clouds"]["all"];
tidyJSON["now"] = epochTime;
return tidyJSON;
}