// Private Function Definitions
static void openweathermap_send_request(void)
{
char openweathermap_url[200];
snprintf( openweathermap_url, sizeof(openweathermap_url), \
"%s%s%s", CLIENT_REQ_PRE, city_weather[city_weather_index].city_name, CLIENT_REQ_POST);
esp_http_client_config_t config =
{
.url = openweathermap_url,
.method = HTTP_METHOD_GET,
.event_handler = openweathermap_event_handler,
};
// ESP_LOGI(TAG, "URL:%s", openweathermap_url);
ESP_LOGI(TAG, "Free Heap: %lu", esp_get_free_heap_size() );
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_http_client_set_header(client, CLIENT_KEY, CLIENT_VALUE);
esp_err_t err = esp_http_client_perform(client);
if( err == ESP_OK )
{
int status = esp_http_client_get_status_code(client);
if(status == 200)
{
ESP_LOGI(TAG, "Message Sent Successfully");
}
else
{
ESP_LOGI(TAG, "Message Sent Failed");
}
}
else
{
ESP_LOGI(TAG, "Message Sent Failed");
}
esp_http_client_cleanup(client);
}
static esp_err_t openweathermap_event_handler(esp_http_client_event_t *event)
{
switch(event->event_id)
{
case HTTP_EVENT_ON_DATA:
// Copy the Data to response_data buffer
memcpy(response_data+response_data_idx, event->data, event->data_len);
// Update the Length
response_data_idx += event->data_len;
break;
case HTTP_EVENT_ON_FINISH:
// Decode/Parse the weather data from the response data
openweathermap_get_weather(response_data, &city_weather[city_weather_index]);
// reset the response buffer and also the length to initial state
openweathermap_reset_buffer();
ESP_LOGI( TAG, "City=%s, Temp=%d, Pressure=%d, Humidity=%d", \
city_weather[city_weather_index].city_name, \
city_weather[city_weather_index].temperature, \
city_weather[city_weather_index].pressure, \
city_weather[city_weather_index].humidity);
city_weather_index++;
// Reset back to Initial Position
if( city_weather_index >= NUM_OF_CITIES )
{
city_weather_index = 0;
}
// Free the system for next requests
request_in_process = false;
break;
case HTTP_EVENT_ERROR:
// In case of Error, exit
openweathermap_reset_buffer();
// Free the system for next requests
request_in_process = false;
break;
default:
break;
}
return ESP_OK;
}
static void openweathermap_get_weather(const char *json_string, weather_data_t *weather_data)
{
cJSON *root = cJSON_Parse(json_string);
cJSON *obj = cJSON_GetObjectItemCaseSensitive(root, "main");
weather_data->temperature = cJSON_GetObjectItemCaseSensitive(obj, "temp")->valueint;
weather_data->pressure = cJSON_GetObjectItemCaseSensitive(obj, "pressure")->valueint;
weather_data->humidity = cJSON_GetObjectItemCaseSensitive(obj, "humidity")->valueint;
cJSON_Delete(root);
}
No comments:
Post a Comment