forked from ch570512/Qlockwork
-
Notifications
You must be signed in to change notification settings - Fork 3
/
OpenWeather.cpp
55 lines (51 loc) · 2.13 KB
/
OpenWeather.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
//*****************************************************************************
// OpenWeather.cpp - Get weather data from OpenWeather
//*****************************************************************************
#include "OpenWeather.h"
OpenWeather::OpenWeather() {
}
OpenWeather::~OpenWeather() {
}
uint8_t OpenWeather::getOutdoorConditions(String location, String apiKey, String langStr) {
String response;
String tempDescription;
WiFiClient client;
if (client.connect("api.openweathermap.org", 80)) {
String url = "/data/2.5/weather?q=" + String(location) + "&units=metric&appid=" + String(apiKey) + "&lang=" + langStr;
client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: api.openweathermap.org" + "\r\n" + "Connection: close\r\n\r\n");
unsigned long startMillis = millis();
while (client.available() == 0) {
if (millis() - startMillis > 5000) {
client.stop();
return 0;
}
yield();
}
while (client.available()){
response = client.readStringUntil('\r');
yield();
}
response.trim();
//response.replace('[', ' ');
//response.replace(']', ' ');
JSONVar weatherArray = JSON.parse(response);
if (JSON.typeof(weatherArray) == "undefined") {
#ifdef DEBUG
Serial.println("Parsing weatherArray failed!");
#endif
return 0;
}
description = "";
for (uint8_t i = 0; i < weatherArray["weather"].length(); i++) {
tempDescription = (const char*)weatherArray["weather"][i]["description"];
description += tempDescription + " ";
}
temperature = (double)weatherArray["main"]["temp"];
humidity = (int)weatherArray["main"]["humidity"];
pressure = (int)weatherArray["main"]["pressure"];
sunrise = (int)weatherArray["sys"]["sunrise"]; // api also provides sunrise / sunset times. Just use them as well.
sunset = (int)weatherArray["sys"]["sunset"];
return 1;
}
return 0;
}