#include "esp_http_client.h" #include "esp_log.h" #include #include #include "buzzer.h" static const char *TAG = "WEATHER"; static bool parse_temperature_from_json(const char *json, float *out_temp) { if (!json || !out_temp) return false; // 1) ir para o bloco "current" const char *p = strstr(json, "\"current\""); if (!p) return false; // 2) procurar temperature_2m DENTRO de current p = strstr(p, "\"temperature_2m\""); if (!p) return false; // 3) ir para o valor p = strchr(p, ':'); if (!p) return false; *out_temp = strtof(p + 1, NULL); return true; } bool net_weather_update(float *out_temp) { char buf[512]; esp_http_client_config_t cfg = { .url = "http://api.open-meteo.com/v1/forecast?latitude=38.75&longitude=-9.125¤t=temperature_2m", .method = HTTP_METHOD_GET, .transport_type = HTTP_TRANSPORT_OVER_TCP, .timeout_ms = 10000, .user_agent = "esp32-weather", }; ESP_LOGI(TAG, "➡️ HTTP init"); esp_http_client_handle_t client = esp_http_client_init(&cfg); if (!client) { ESP_LOGE(TAG, "❌ http_client_init falhou"); return false; } esp_err_t err = esp_http_client_open(client, 0); if (err != ESP_OK) { ESP_LOGE(TAG, "❌ http_client_open falhou: %s", esp_err_to_name(err)); esp_http_client_cleanup(client); return false; } int content_length = esp_http_client_fetch_headers(client); ESP_LOGI(TAG, "📦 content-length = %d", content_length); int len = esp_http_client_read(client, buf, sizeof(buf) - 1); if (len <= 0) { ESP_LOGE(TAG, "❌ http_client_read falhou"); esp_http_client_close(client); esp_http_client_cleanup(client); return false; } buf[len] = 0; ESP_LOGI(TAG, "📩 JSON: %s", buf); esp_http_client_close(client); esp_http_client_cleanup(client); if (!parse_temperature_from_json(buf, out_temp)) { ESP_LOGE(TAG, "❌ parse_temperature_from_json falhou"); return false; } return true; }