#define MAX_OWM_PERIODS 24
const char* owm_api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char* owm_city_id = "xxxxxx";
const char* owm_host = "api.openweathermap.org";
const char* owm_test = "UA";
struct OWM
{
int8_t index;
time_t timew;
float temp; // С, температура
// float pressure; // mmHg,давление
// uint8_t humidity; // %, влажность
float qpf; // мм, количество осадков
float snow; // мм, снег
} owm[MAX_OWM_PERIODS];
bool update_owm()
{
if ( !pr_client) return false;
WiFiClient client;
Serial.println( "OWM start");
String url = "/data/2.5/forecast?id=";
url += owm_city_id;
url += "&APPID=";
url += owm_api_key;
url += "&units=metric&cnt=";
url += MAX_OWM_PERIODS;
Serial.printf( "URL: %s\n", url.c_str());
if ( !client.connect( owm_host, 80))
{
Serial.printf( "%s connection failed\n", owm_host);
return false;
}
String Request = "GET ";
Request += url;
Request += " HTTP/1.1\r\nHost: ";
Request += owm_host;
Request += "\r\nConnection: close\r\n\r\n";
client.print( Request);
Serial.printf( "Request: %s", Request.c_str());
// Check HTTP status
char status[32] = {0};
client.readBytesUntil('\r', status, sizeof(status));
// It should be "HTTP/1.0 200 OK" or "HTTP/1.1 200 OK"
if ( strcmp(status + 9, "200 OK") != 0)
{
Serial.printf( "Unexpected response: %s\n", status);
return false;
}
// Skip HTTP headers
char endOfHeaders[] = "\r\n\r\n";
if ( !client.find( endOfHeaders))
{
Serial.println( "Invalid response");
return false;
}
DynamicJsonDocument doc(20000);
DeserializationError error = deserializeJson( doc, client);
if (error)
{
Serial.printf( "deserializeJson() failed: %s\n", error.c_str());
return false;
}
if( doc["cnt"].as<uint8_t>() != MAX_OWM_PERIODS || strcmp(doc["city"]["country"].as<char *>(), owm_test) != 0)
{
Serial.println( "OWM error json");
return false;
}
for( uint8_t i = 0; i < MAX_OWM_PERIODS; i++)
{
owm[i].index = i;
owm[i].timew = doc["list"][i]["dt"].as<time_t>();
owm[i].temp = doc["list"][i]["main"]["temp"].as<float>();
owm[i].qpf = doc["list"][i]["rain"]["3h"].as<float>();
owm[i].snow = doc["list"][i]["snow"]["3h"].as<float>();
}
owm_time_offset = doc["city"]["timezone"].as<int32_t>();;
/*
Serial.printf( "owm_time_offset: %ld\n", owm_time_offset);
for ( int i = 0; i < MAX_OWM_PERIODS; i++)
{
Serial.printf( "index: %d\n", owm[i].index);
Serial.printf( "timew: %ld\n", owm[i].timew);
Serial.printf( "piccode: %d\n", owm[i].piccode);
Serial.print( "temp: "); Serial.println( owm[i].temp);
Serial.print( "qpf: "); Serial.println( owm[i].qpf);
Serial.print( "snow: "); Serial.println( owm[i].snow);
Serial.print( "\n\n");
}
*/
}