From cefe34c7bc34a686711ec15312b25f97615f52c7 Mon Sep 17 00:00:00 2001 From: YoungSoo Shin Date: Fri, 5 Dec 2025 12:10:06 +0900 Subject: [PATCH] sta: fix reconnect ap when ap lost Signed-off-by: YoungSoo Shin --- main/wifi/priv_wifi.h | 1 + main/wifi/sta.c | 18 ++++++++++++++++++ main/wifi/wifi.c | 16 ++++++++++++++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/main/wifi/priv_wifi.h b/main/wifi/priv_wifi.h index 1ff4bb3..ea6ced8 100644 --- a/main/wifi/priv_wifi.h +++ b/main/wifi/priv_wifi.h @@ -8,5 +8,6 @@ void wifi_init_sta(void); void wifi_init_ap(void); void initialize_sntp(void); +void wifi_set_auto_reconnect(bool enable); #endif // ODROID_POWER_MATE_PRIV_WIFI_H diff --git a/main/wifi/sta.c b/main/wifi/sta.c index 79cdd1a..9b96acd 100644 --- a/main/wifi/sta.c +++ b/main/wifi/sta.c @@ -81,6 +81,14 @@ void wifi_scan_aps(wifi_ap_record_t** ap_records, uint16_t* count) *count = 0; *ap_records = NULL; + wifi_set_auto_reconnect(false); + + wifi_ap_record_t ap_info; + if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK) + { + esp_wifi_disconnect(); + } + // Start scan, this is a blocking call if (esp_wifi_scan_start(NULL, true) == ESP_OK) { @@ -100,6 +108,16 @@ void wifi_scan_aps(wifi_ap_record_t** ap_records, uint16_t* count) } } } + + wifi_set_auto_reconnect(true); + + if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK) + { + if (!nconfig_value_is_not_set(WIFI_SSID)) + { + wifi_connect(); + } + } } esp_err_t wifi_get_current_ap_info(wifi_ap_record_t* ap_info) diff --git a/main/wifi/wifi.c b/main/wifi/wifi.c index f0c1581..ff1e0c8 100644 --- a/main/wifi/wifi.c +++ b/main/wifi/wifi.c @@ -16,9 +16,13 @@ #include "wifi.h" #include "indicator.h" +static bool s_auto_reconnect = true; static const char* TAG = "WIFI"; +void wifi_set_auto_reconnect(bool enable) { s_auto_reconnect = enable; } + + static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) { if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) @@ -46,10 +50,18 @@ static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t e } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { - led_set(LED_RED, BLINK_TRIPLE); + led_set(LED_BLU, BLINK_TRIPLE); wifi_event_sta_disconnected_t* event = (wifi_event_sta_disconnected_t*)event_data; ESP_LOGW(TAG, "Disconnected from AP, reason: %s", wifi_reason_str(event->reason)); - // ESP-IDF will automatically try to reconnect by default. + + if (event->reason != WIFI_REASON_ASSOC_LEAVE) + { + if (s_auto_reconnect && !nconfig_value_is_not_set(WIFI_SSID)) + { + ESP_LOGI(TAG, "Connection lost, attempting to reconnect..."); + esp_wifi_connect(); + } + } } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {