Proper way to handle WiFi reconnect

policeman0077
Posts: 11
Joined: Mon Jul 16, 2018 8:52 pm

Proper way to handle WiFi reconnect

Postby policeman0077 » Thu Aug 03, 2023 11:18 pm

I saw in programming guide about esp_wifi_connect():
3. The scanning triggered by esp_wifi_scan_start() will not be effective until connection between ESP32 and the AP is established. If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error number ESP_ERR_WIFI_STATE. If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called scan will not work. This is especially true when the AP doesn’t exist, and you still try reconnection after ESP32 received disconnect event with the reason code WIFI_REASON_NO_AP_FOUND.

And in example wifi/getting_started:

Code: Select all

static void 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_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGI(TAG, "retry to connect to the AP");
        } else {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }
        ESP_LOGI(TAG,"connect to the AP fail");
    } 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));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}
my questions are:
1. from the function description, does it mean when I call the esp_wifi_connect(), it would also trigger a esp_wifi_scan()? or it is fine as long as I don't call esp_wifi_scan() after connect? I don't quite understand why the connect retry would affect scan?
2. I saw the event handler has max retry limit and set the fail bit. But I don't know when this happened, how should I reconnect to AP? Should I call esp_wifi_disconnect(), then esp_wifi_stop then start the wifi and connect again. What is the recommended procedure?
3. does esp_wifi_connect() do a scan before connect to AP?

Who is online

Users browsing this forum: Baidu [Spider] and 81 guests