From af307fd403997840a59fd52da3081e856498d998d21c9e1bdb7a248b6e8fe785 Mon Sep 17 00:00:00 2001 From: localhorst Date: Fri, 9 Jan 2026 23:35:44 +0100 Subject: [PATCH] handle reconnect --- main/wifi.c | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/main/wifi.c b/main/wifi.c index d1fd0c1..6a4b806 100644 --- a/main/wifi.c +++ b/main/wifi.c @@ -13,10 +13,15 @@ #define WIFI_CONNECTED_BIT BIT0 #define WIFI_FAIL_BIT BIT1 +#define MAX_RETRY_COUNT 10 +#define RETRY_DELAY_MS 1000 static const char *TAG = "smart-oil-heater-control-system-wifi"; static EventGroupHandle_t s_wifi_event_group; +static int s_retry_num = 0; +static bool s_initial_connect = true; + static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data); @@ -84,7 +89,9 @@ void initWifi(void) { ESP_LOGE(TAG, "Unexpected event"); } - vEventGroupDelete(s_wifi_event_group); + + // Mark initial connection phase complete - do NOT delete the event group + s_initial_connect = false; } static void event_handler(void *arg, esp_event_base_t event_base, @@ -96,13 +103,46 @@ static void event_handler(void *arg, esp_event_base_t event_base, } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { - esp_wifi_connect(); - ESP_LOGI(TAG, "Retry to connect to the AP"); + wifi_event_sta_disconnected_t *event = (wifi_event_sta_disconnected_t *)event_data; + ESP_LOGW(TAG, "Disconnected from AP (reason: %d)", event->reason); + + if (s_initial_connect) + { + // During initial connection phase, use retry limit + if (s_retry_num < MAX_RETRY_COUNT) + { + vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS)); + esp_wifi_connect(); + s_retry_num++; + ESP_LOGI(TAG, "Retry to connect to the AP (%d/%d)", s_retry_num, MAX_RETRY_COUNT); + } + else + { + xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT); + ESP_LOGE(TAG, "Failed to connect after %d attempts", MAX_RETRY_COUNT); + } + } + else + { + // After initial connection, always try to reconnect with delay + vTaskDelay(pdMS_TO_TICKS(RETRY_DELAY_MS)); + esp_wifi_connect(); + ESP_LOGI(TAG, "Attempting to reconnect to the AP..."); + } } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; ESP_LOGI(TAG, "Got ip:" IPSTR, IP2STR(&event->ip_info.ip)); - xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + s_retry_num = 0; + + if (s_initial_connect) + { + xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT); + } + else + { + ESP_LOGI(TAG, "Successfully reconnected to AP"); + } } -} \ No newline at end of file +}