esp_wifi_connect() working / nor working

jpquan
Posts: 11
Joined: Wed Feb 09, 2022 10:04 am

esp_wifi_connect() working / nor working

Postby jpquan » Wed Feb 09, 2022 12:10 pm

Hello! First I'd like to tell I started ESP32 very recently so please be kind with my issue / question ;)

I was trying to have one example of esp-idf-4.4 work, the one on Wifi / Get Started / Station, located here: esp-idf-v4.4/examples/wifi/getting_started/station
on a dev kit (ESP32-WROVER)

Full original example is the following:

Code: Select all

/* WiFi station Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sys.h"

/* The examples use WiFi configuration that you can set via project configuration menu

   If you'd rather not, just change the below entries to strings with
   the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
*/
#define EXAMPLE_ESP_WIFI_SSID      CONFIG_ESP_WIFI_SSID
#define EXAMPLE_ESP_WIFI_PASS      CONFIG_ESP_WIFI_PASSWORD
#define EXAMPLE_ESP_MAXIMUM_RETRY  CONFIG_ESP_MAXIMUM_RETRY

/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event, but we only care about two events:
 * - we are connected to the AP with an IP
 * - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

static const char *TAG = "wifi station";

static int s_retry_num = 0;

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);
    }
}

void wifi_init_sta(void)
{
    s_wifi_event_group = xEventGroupCreate();

    ESP_ERROR_CHECK(esp_netif_init());

    ESP_ERROR_CHECK(esp_event_loop_create_default());
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = EXAMPLE_ESP_WIFI_SSID,
            .password = EXAMPLE_ESP_WIFI_PASS,
            /* Setting a password implies station will connect to all security modes including WEP/WPA.
             * However these modes are deprecated and not advisable to be used. Incase your Access point
             * doesn't support WPA2, these mode can be enabled by commenting below line */
	     .threshold.authmode = WIFI_AUTH_WPA2_PSK,

            .pmf_cfg = {
                .capable = true,
                .required = false
            },
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
    ESP_ERROR_CHECK(esp_wifi_start() );

    ESP_LOGI(TAG, "wifi_init_sta finished.");

    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
            WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
            pdFALSE,
            pdFALSE,
            portMAX_DELAY);

    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if (bits & WIFI_CONNECTED_BIT) {
        ESP_LOGI(TAG, "connected to ap SSID:%s password:%s",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else if (bits & WIFI_FAIL_BIT) {
        ESP_LOGI(TAG, "Failed to connect to SSID:%s, password:%s",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else {
        ESP_LOGE(TAG, "UNEXPECTED EVENT");
    }

    /* The event will not be processed after unregister */
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
    vEventGroupDelete(s_wifi_event_group);
}

void app_main(void)
{
    //Initialize NVS
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
      ESP_ERROR_CHECK(nvs_flash_erase());
      ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
    wifi_init_sta();
}
I use it under Eclipse 2021-06, using ESP-IDF plugin for Eclipse, and compiled as C++, not C.

I have a strange behavior that I cannot explain to myself, relating to this portion of the code (event handler):

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);
    }
}
If I let it as it is shown, Wifi connection does not happen in my case. Full log from console:

Code: Select all

rst:0x1 (POWERON_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:6612
load:0x40078000,len:14780
load:0x40080400,len:3792
0x40080400: _init at ??:?

entry 0x40080694
I (27) boot: ESP-IDF v4.4-dirty 2nd stage bootloader
I (27) boot: compile time 07:52:46
I (27) boot: chip revision: 1
I (30) boot_comm: chip revision: 1, min. bootloader chip revision: 0
I (37) boot.esp32: SPI Speed      : 40MHz
I (42) boot.esp32: SPI Mode       : DIO
I (46) boot.esp32: SPI Flash Size : 2MB
I (51) boot: Enabling RNG early entropy source...
I (56) boot: Partition Table:
I (60) boot: ## Label            Usage          Type ST Offset   Length
I (67) boot:  0 nvs              WiFi data        01 02 00009000 00006000
I (74) boot:  1 phy_init         RF data          01 01 0000f000 00001000
I (82) boot:  2 factory          factory app      00 00 00010000 00100000
I (89) boot: End of partition table
I (94) boot_comm: chip revision: 1, min. application chip revision: 0
I (101) esp_image: segment 0: paddr=00010020 vaddr=3f400020 size=134a8h ( 79016) map
I (138) esp_image: segment 1: paddr=000234d0 vaddr=3ffb0000 size=03804h ( 14340) load
I (144) esp_image: segment 2: paddr=00026cdc vaddr=40080000 size=0933ch ( 37692) load
I (159) esp_image: segment 3: paddr=00030020 vaddr=400d0020 size=6d690h (448144) map
I (322) esp_image: segment 4: paddr=0009d6b8 vaddr=4008933c size=0afa8h ( 44968) load
I (341) esp_image: segment 5: paddr=000a8668 vaddr=50000000 size=00010h (    16) load
I (351) boot: Loaded app from partition at offset 0x10000
I (351) boot: Disabling RNG early entropy source...
I (363) cpu_start: Pro cpu up.
I (363) cpu_start: Starting app cpu, entry point is 0x40081174
0x40081174: call_start_cpu1 at /Dev/ESP32/esp-idf-eclipse/esp-idf-v4.4/components/esp_system/port/cpu_start.c:156

I (0) cpu_start: App cpu up.
I (377) cpu_start: Pro cpu start user code
I (377) cpu_start: cpu freq: 160000000
I (377) cpu_start: Application information:
I (382) cpu_start: Project name:     Esp32Blink
I (387) cpu_start: App version:      1
I (391) cpu_start: Compile time:     Feb  9 2022 07:56:20
I (398) cpu_start: ELF file SHA256:  dde9b6e1dcbae094...
I (404) cpu_start: ESP-IDF:          v4.4-dirty
I (409) heap_init: Initializing. RAM available for dynamic allocation:
I (416) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (422) heap_init: At 3FFB74A8 len 00028B58 (162 KiB): DRAM
I (428) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (435) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (441) heap_init: At 400942E4 len 0000BD1C (47 KiB): IRAM
I (448) spi_flash: detected chip: gd
I (452) spi_flash: flash io: dio
W (455) spi_flash: Detected size(4096k) larger than the size in the binary image header(2048k). Using the size in the binary image header.
I (470) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (563) wifi station: ESP_WIFI_MODE_STA
I (583) wifi:wifi driver task: 3ffc06cc, prio:23, stack:6656, core=0
I (583) system_api: Base MAC address is not set
I (583) system_api: read default base MAC address from EFUSE
I (613) wifi:wifi firmware version: 7679c42
I (613) wifi:wifi certification version: v7.0
I (613) wifi:config NVS flash: enabled
I (613) wifi:config nano formating: disabled
I (613) wifi:Init data frame dynamic rx buffer num: 32
I (613) wifi:Init management frame dynamic rx buffer num: 32
I (623) wifi:Init management short buffer num: 32
I (623) wifi:Init dynamic tx buffer num: 32
I (633) wifi:Init static rx buffer size: 1600
I (633) wifi:Init static rx buffer num: 10
I (643) wifi:Init dynamic rx buffer num: 32
I (643) wifi_init: rx ba win: 6
I (643) wifi_init: tcpip mbox: 32
I (653) wifi_init: udp mbox: 6
I (653) wifi_init: tcp mbox: 6
I (663) wifi_init: tcp tx win: 5744
I (663) wifi_init: tcp rx win: 5744
I (663) wifi_init: tcp mss: 1440
I (673) wifi_init: WiFi IRAM OP enabled
I (673) wifi_init: WiFi RX IRAM OP enabled
I (703) phy_init: phy_version 4670,719f9f6,Feb 18 2021,17:07:07
I (793) wifi:mode : sta (c8:c9:a3:d8:15:1c)
I (793) wifi:enable tsf
I (803) wifi station: wifi_init_sta finished.
I (2853) wifi station: retry to connect to the AP
I (2853) wifi station: connect to the AP fail
I (4903) wifi station: retry to connect to the AP
I (4903) wifi station: connect to the AP fail
I (6953) wifi station: retry to connect to the AP
I (6953) wifi station: connect to the AP fail
I (9003) wifi station: retry to connect to the AP
I (9003) wifi station: connect to the AP fail
I (11053) wifi station: retry to connect to the AP
I (11053) wifi station: connect to the AP fail
I (13103) wifi station: connect to the AP fail
I (13103) wifi station: Failed to connect to SSID:...
If I put a log, for instance

Code: Select all

ESP_LOGI(TAG, "event_handler just processed event %s %d", event_base, event_id);
at the end of the handler, connection works. It works from the moment I put a ESP_LOGI call in the code of the handler, whatever the place. Full log shows the difference:

Code: Select all

rst:0x1 (POWERON_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:6612
load:0x40078000,len:14780
load:0x40080400,len:3792
0x40080400: _init at ??:?

entry 0x40080694
I (27) boot: ESP-IDF v4.4-dirty 2nd stage bootloader
I (27) boot: compile time 07:52:46
I (27) boot: chip revision: 1
I (30) boot_comm: chip revision: 1, min. bootloader chip revision: 0
I (37) boot.esp32: SPI Speed      : 40MHz
I (42) boot.esp32: SPI Mode       : DIO
I (46) boot.esp32: SPI Flash Size : 2MB
I (51) boot: Enabling RNG early entropy source...
I (56) boot: Partition Table:
I (60) boot: ## Label            Usage          Type ST Offset   Length
I (67) boot:  0 nvs              WiFi data        01 02 00009000 00006000
I (74) boot:  1 phy_init         RF data          01 01 0000f000 00001000
I (82) boot:  2 factory          factory app      00 00 00010000 00100000
I (89) boot: End of partition table
I (94) boot_comm: chip revision: 1, min. application chip revision: 0
I (101) esp_image: segment 0: paddr=00010020 vaddr=3f400020 size=134a8h ( 79016) map
I (138) esp_image: segment 1: paddr=000234d0 vaddr=3ffb0000 size=03804h ( 14340) load
I (144) esp_image: segment 2: paddr=00026cdc vaddr=40080000 size=0933ch ( 37692) load
I (159) esp_image: segment 3: paddr=00030020 vaddr=400d0020 size=6d690h (448144) map
I (322) esp_image: segment 4: paddr=0009d6b8 vaddr=4008933c size=0afa8h ( 44968) load
I (341) esp_image: segment 5: paddr=000a8668 vaddr=50000000 size=00010h (    16) load
I (351) boot: Loaded app from partition at offset 0x10000
I (351) boot: Disabling RNG early entropy source...
I (363) cpu_start: Pro cpu up.
I (363) cpu_start: Starting app cpu, entry point is 0x40081174
0x40081174: call_start_cpu1 at /Dev/ESP32/esp-idf-eclipse/esp-idf-v4.4/components/esp_system/port/cpu_start.c:156

I (0) cpu_start: App cpu up.
I (377) cpu_start: Pro cpu start user code
I (377) cpu_start: cpu freq: 160000000
I (377) cpu_start: Application information:
I (382) cpu_start: Project name:     Esp32Blink
I (387) cpu_start: App version:      1
I (391) cpu_start: Compile time:     Feb  9 2022 07:56:20
I (398) cpu_start: ELF file SHA256:  dde9b6e1dcbae094...
I (404) cpu_start: ESP-IDF:          v4.4-dirty
I (409) heap_init: Initializing. RAM available for dynamic allocation:
I (416) heap_init: At 3FFAE6E0 len 00001920 (6 KiB): DRAM
I (422) heap_init: At 3FFB74A8 len 00028B58 (162 KiB): DRAM
I (428) heap_init: At 3FFE0440 len 00003AE0 (14 KiB): D/IRAM
I (435) heap_init: At 3FFE4350 len 0001BCB0 (111 KiB): D/IRAM
I (441) heap_init: At 400942E4 len 0000BD1C (47 KiB): IRAM
I (448) spi_flash: detected chip: gd
I (452) spi_flash: flash io: dio
W (455) spi_flash: Detected size(4096k) larger than the size in the binary image header(2048k). Using the size in the binary image header.
I (470) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (563) wifi station: ESP_WIFI_MODE_STA
I (583) wifi:wifi driver task: 3ffc06cc, prio:23, stack:6656, core=0
I (583) system_api: Base MAC address is not set
I (583) system_api: read default base MAC address from EFUSE
I (613) wifi:wifi firmware version: 7679c42
I (613) wifi:wifi certification version: v7.0
I (613) wifi:config NVS flash: enabled
I (613) wifi:config nano formating: disabled
I (613) wifi:Init data frame dynamic rx buffer num: 32
I (613) wifi:Init management frame dynamic rx buffer num: 32
I (623) wifi:Init management short buffer num: 32
I (623) wifi:Init dynamic tx buffer num: 32
I (633) wifi:Init static rx buffer size: 1600
I (633) wifi:Init static rx buffer num: 10
I (643) wifi:Init dynamic rx buffer num: 32
I (643) wifi_init: rx ba win: 6
I (643) wifi_init: tcpip mbox: 32
I (653) wifi_init: udp mbox: 6
I (653) wifi_init: tcp mbox: 6
I (663) wifi_init: tcp tx win: 5744
I (663) wifi_init: tcp rx win: 5744
I (663) wifi_init: tcp mss: 1440
I (673) wifi_init: WiFi IRAM OP enabled
I (673) wifi_init: WiFi RX IRAM OP enabled
I (703) phy_init: phy_version 4670,719f9f6,Feb 18 2021,17:07:07
I (793) wifi:mode : sta (c8:c9:a3:d8:15:1c)
I (793) wifi:enable tsf
I (803) wifi station: wifi_init_sta finished.
I (2853) wifi station: retry to connect to the AP
I (2853) wifi station: connect to the AP fail
I (4903) wifi station: retry to connect to the AP
I (4903) wifi station: connect to the AP fail
I (6953) wifi station: retry to connect to the AP
I (6953) wifi station: connect to the AP fail
I (9003) wifi station: retry to connect to the AP
I (9003) wifi station: connect to the AP fail
I (11053) wifi station: retry to connect to the AP
I (11053) wifi station: connect to the AP fail
I (13103) wifi station: connect to the AP fail
I (13103) wifi station: Failed to connect to SSID:...
I tried to set some delay before or after esp_wifi_connect() call using vTaskDelay but there is no change.

Any explanation or advice anybody?

jpquan
Posts: 11
Joined: Wed Feb 09, 2022 10:04 am

Re: esp_wifi_connect() working / nor working

Postby jpquan » Tue Feb 15, 2022 1:40 pm

Hello again! I did some investigations, and at last I could narrow down the issue.

First I got some additional information about the disconnected reason: added this line of code in the event_handler:

Code: Select all

wifi_event_sta_disconnected_t *event = (wifi_event_sta_disconnected_t *) event_data;
and got reason 201, which means "AP_NOT_FOUND".

At connect there is a scan, and the scan cannot find my AP.

Then I implemented Wifi scans from the examples, and I could see that my AP was listed :shock: .

For the moment, I think this may be due to random values in memory when wifi_sta_config_t is created, so I carefully zeroed or set every possible value; here is my code (in C++):

Code: Select all

    wifi_sta_config_t wifi_sta;
    for (int i=0; i<32; i++) {
    	wifi_sta.ssid[i] = 0;
    }
    for (int i=0; i<64; i++) {
    	wifi_sta.password[i] = 0;
    }
    memcpy(wifi_sta.ssid, EXAMPLE_ESP_WIFI_SSID, strlen(EXAMPLE_ESP_WIFI_SSID)+1);
    memcpy(wifi_sta.password, EXAMPLE_ESP_WIFI_PASS, strlen(EXAMPLE_ESP_WIFI_PASS)+1);
    wifi_sta.bssid_set = 0;
    wifi_sta.channel = 0;
    wifi_sta.scan_method = WIFI_FAST_SCAN;
    for(int i=0; i<6; i++) {
    	wifi_sta.bssid[i] = 0;
    }
    wifi_pmf_config_t wifi_pmf;
    wifi_pmf.capable = true;
    wifi_pmf.required = false;
    wifi_sta.pmf_cfg = wifi_pmf;
    wifi_scan_threshold_t wifi_scan_threshold;
    wifi_scan_threshold.authmode = WIFI_AUTH_WPA_PSK;
    wifi_sta.threshold = wifi_scan_threshold;
    wifi_config_t wifi_config;
    wifi_config.sta = wifi_sta;
Now it seems to connect OK, but I still have to confirm that over time.

glrtheil
Posts: 61
Joined: Tue Dec 07, 2021 2:48 pm

Re: esp_wifi_connect() working / nor working

Postby glrtheil » Thu Feb 17, 2022 3:23 pm

Have you tried using the blufi example to configure and connect your device to wifi? I found it to be the best example of how to make wifi work properly, with the least amount of code.

Who is online

Users browsing this forum: federicolonghin and 82 guests