General Steps

[中文]

Note

This document is automatically translated using AI. Please excuse any detailed errors. The official English version is still in progress.

This document summarizes the common implementation process of various Wi-Fi modes in ESP-IDF, covering key system and network initialization, Wi-Fi configuration and startup, event management, and common operations of related functional modules. The document lists the main tasks, involved APIs, and calling order at each stage, providing a unified implementation reference for different examples.

Mastering the content of this document helps to quickly understand the core process of each mode, reuse common code in different Wi-Fi applications, and efficiently locate mode differences and specific implementations in combination with example documents.

Wi-Fi Operation Steps

The flowcharts of Wi-Fi operation under different modes can be referred to ESP32 Wi-Fi station general case and ESP32 Wi-Fi AP general case.

Initialization Stage

  1. Create/Initialize LwIP: Initialize the underlying TCP/IP protocol stack (LwIP) and the network interface management module (esp-netif) on top of it, setting up the necessary software and hardware environment for device IP address management and network data transmission and reception.

  • The TCP/IP protocol stack is the core software module for implementing network communication, responsible for encapsulating, routing, transmitting, and receiving data according to standard protocols. Network communication must be initiated by initializing the TCP/IP protocol stack.

  • ESP32 uses LwIP as its network protocol stack implementation. LwIP is a lightweight TCP/IP protocol stack designed for resource-limited embedded systems, supporting common network protocols including IP, TCP, UDP, DHCP, etc. For further explanation of LwIP, please refer to LwIP.

  • On top of the LwIP protocol stack, esp-netif serves as the network interface management module, responsible for uniformly managing multiple network interfaces (such as Wi-Fi STA, AP, and Ethernet) and their life cycles, providing an event handling mechanism to respond to network status and IP address changes, ensuring stable and flexible communication. After initializing esp-netif, the system can effectively create and manage specific interfaces, realizing the connection between the protocol stack and physical devices. For further explanation of esp-netif, please refer to ESP-NETIF.

  • This step is completed by calling esp_netif_init().

  1. Create/Initialize Event: Build the system’s event-driven framework and create a default event loop environment.

  • An event is a high-level software signal representing changes in system or module status. Programs can perform corresponding tasks based on different events. Wi-Fi related events can be referred to ESP32 Wi-Fi Event Description.

  • The event loop is a mechanism or program structure that continuously listens and handles events, constantly checking for new events and distributing them to the corresponding handling functions or modules.

  • In Wi-Fi, the event mechanism allows the program to be aware of status changes during the connection and communication process in a timely manner, facilitating response and handling, and ensuring stable network operation.

  • This step is accomplished by calling esp_event_loop_create_default(). For more parameter descriptions, refer to Event Loop Library API.

  1. Create/Initialize Network Interface: Create a default network interface and associate it with the esp-netif network interface management module to establish a connection between the protocol stack and Wi-Fi hardware.

  • The interface object encapsulates network parameters (such as IP address, subnet mask, etc.) and serves as a bridge connecting the Wi-Fi driver and the LwIP protocol stack. After this step, the system can perform operations such as Wi-Fi scanning, connection, and data transmission.

  • For Wi-Fi STA mode, this step is accomplished by calling esp_netif_create_default_wifi_sta(). For more parameter descriptions, refer to NETIF API.

  • For Wi-Fi AP mode, this step is accomplished by calling esp_netif_create_default_wifi_ap(). For more parameter descriptions, refer to NETIF API.

  1. Create/Initialize Wi-Fi: Configure and initialize the Wi-Fi driver, start related internal tasks, and ensure the normal operation of wireless hardware and protocol stack.

  • The Wi-Fi driver is the core of Wi-Fi functionality, implementing the underlying protocols and hardware control for wireless communication.

  • Wi-Fi driver parameters are configured through the wifi_init_config_t structure, usually using WIFI_INIT_CONFIG_DEFAULT() to quickly load the default configuration.

  • The configuration covers hardware resource allocation, task priority, buffer size, and power management, etc., ensuring the performance and stability of driver initialization. For specific structure members, refer to Wi-Fi Library.

  • Call esp_wifi_init() to complete the initialization of the Wi-Fi driver, start the necessary internal tasks and resources, and pass in the configuration structure pointer. For more parameter descriptions, refer to Wi-Fi Library.

Configuration Phase

For other considerations in this phase, please refer to Wi-Fi Configuration Phase.

  1. Configure Connection Parameters: The Wi-Fi network connection parameters are configured through the wifi_config_t structure, which includes the target network’s SSID, password, authentication method, encryption type, etc., to ensure the validity and security of the connected network. For specific structure members, refer to station mode structure or AP mode structure.

  2. Configure Wi-Fi Mode: Define the role of the device and set the correct working mode. For different mode descriptions, refer to Wi-Fi mode. Call esp_wifi_set_mode() and pass in the mode to be set. For more parameter descriptions, refer to Wi-Fi library.

  3. Apply Wi-Fi Configuration: Apply the connection parameters to the specified interface to ensure that the system can recognize and use the correct configuration.

  • Only after completing the configuration can the connection and authentication process be initiated.

  • Call esp_wifi_set_config() to complete this step, specify the interface according to the Wi-Fi mode, and pass in the configuration structure pointer. For more parameter descriptions, refer to Wi-Fi library.

Startup Phase

  1. Start Wi-Fi:

  • Call esp_wifi_start() to start the initialized and configured Wi-Fi driver. For related parameter descriptions, refer to Wi-Fi library.

  • The function creates corresponding internal tasks and allocates necessary resources according to the currently set mode, and makes the driver enter the working state.

  • After successful calling, the device will enter the ready state and can perform subsequent connection, scanning, or listening operations.

  1. Wait for Events:

  • The Wi-Fi startup process is asynchronous, that is, it will return immediately after calling the startup API, and will not wait until the startup is complete.

  • The driver completes initialization and task creation in the background, and the results are reported through the event mechanism. The program should rely on events to judge the connection status.

  • After the startup is complete, the relevant events will trigger the event callback function to receive events and perform corresponding processing tasks.

Connection Phase

  1. Connect Wi-Fi:

  • Call esp_wifi_connect() to start the connection process. For related parameter descriptions, refer to Wi-Fi library.

  • The function executes internal scanning, authentication, and association operations based on the currently set interface and connection parameters.

  1. Wait for events:

  • The Wi-Fi connection process is asynchronous, the connection action is completed in the background task, and the connection result is reported through the event mechanism. The program should rely on events to judge the connection status and respond accordingly.

  • After the connection is completed, the relevant events will trigger the event callback function to receive the event and perform the corresponding processing tasks.

Obtaining IP stage

In this stage, the Wi-Fi driver will request the DHCP server to assign an IP address and return the corresponding event status. This process is automatically completed by the system, without user intervention. For details, please refer to Wi-Fi Obtaining IP Stage.

Note

A DHCP server is a service that automatically assigns IP addresses. In daily networks, routers usually act as DHCP servers, assigning available IP addresses to connected devices. In ESP32’s SoftAP mode, the device itself will also start a DHCP server, automatically assigning IP addresses to clients connected to it, enabling clients to join the network smoothly without manually setting the IP.

Event callback mechanism

The status changes during Wi-Fi and network operations (such as startup completion, successful connection, disconnection, obtaining IP, etc.) are all notified to the application in the form of events. By registering event callback functions, applications can timely receive and process these asynchronous events, achieving dynamic response and status management. The event callback mechanism ensures that the program can perform corresponding operations when an event occurs, without the need to actively poll the status, improving efficiency and real-time performance. For further content on event callbacks, please refer to Event Loop Library.

Register event callback function

In ESP-IDF, call esp_event_handler_instance_register() to register the callback function. When registering, you need to specify the event base to which the event belongs (such as Wi-Fi event base WIFI_EVENT, IP event base IP_EVENT), the specific event type, and the corresponding event processing function.

The prototype of registering the event callback function is:

esp_err_t esp_event_handler_instance_register(esp_event_base_t event_base,
                                              int32_t event_id,
                                              esp_event_handler_t event_handler,
                                              void *event_handler_arg,
                                              esp_event_handler_instance_t *instance);
Parameter explanation

Input parameter

Parameter function

Parameter description

event_base

Event base, used to group events

Tells the system to which subsystem or functional module this event belongs, to avoid conflicts of the same event ID in different modules.

event_id

Identifies the specific event type

The program autonomously publishes after meeting specific conditions, all Wi-Fi events can refer to ESP32 Wi-Fi Event Description. The event ID is unique only within its event base range.

event_handler

Pointer to the event callback function

Handle corresponding events according to requirements. For further introduction to the callback function, please refer.

event_handler_arg

Custom parameter pointer passed to the event callback function

Can be used to carry context information, can pass in NULL.

instance

Returns the registered event handling instance handle, used for subsequent unregistration or event management.

If you need to use this handle, you should define the corresponding variable and pass it in before calling; when management is not needed, you can pass in NULL.

Event Callback Function

The event callback function is a function written by the user as needed. The system does not automatically generate it, and it is usually automatically called by the system or framework when an event occurs, and does not need to be actively called by the program. Its main function is to receive notifications when specified events occur and execute corresponding processing logic, such as logging, status updates, error handling, automatic reconnection, etc.

This function is executed in the event context, and the code should be as short as possible to avoid blocking, otherwise it may affect the system response.

The prototype of the event callback function is as follows, where event_handler is the function name, which can be modified at will:

void event_handler( void* arg,
                    esp_event_base_t event_base,
                    int32_t event_id,
                    void* event_data);
Parameter Explanation

Parameter

Parameter Description

Correspondence with Registration Function Parameters

arg

Custom parameter pointer

Passed in from the event_handler_arg in the registration function.

event_base

Event base, indicating the module or subsystem to which the event belongs

Consistent with the event_base specified at registration.

event_id

Specific event ID, indicating the event type

Consistent with the event_id specified at registration.

event_data

Additional data related to the event, the type and content vary depending on the event

Passed by the system when the event occurs, for the callback function to refer to and process.

Writing an event callback function allows the program to respond promptly to asynchronously occurring network events, enhancing flexibility and operational efficiency. Depending on specific requirements, implement the corresponding event handling logic in the callback function.

Non-Volatile Storage (NVS)

  1. Initialize Non-Volatile Storage:

  • Non-volatile storage is a key module in the device used to store persistent data. After enabling Wi-Fi NVS flash, it can save important information such as Wi-Fi configuration, device parameters, etc., and the data is still retained after power off.

  • Call nvs_flash_init() to initialize NVS, complete the preparation and mounting of the storage medium. For a description of related parameters, please refer to Non-Volatile Storage Library API <https://docs.espressif.com/projects/esp-idf/en/v5.4.2/esp32/api-reference/storage/nvs_flash.html#_CPPv414nvs_flash_initv>.

  1. Check the return value:

  • Timely detect potential issues during the initialization process, such as the NVS partition is full or the version is not compatible, etc. This can prevent errors from occurring when reading and writing data later, leading to functional abnormalities or even crashes.

  • If an exception is returned, call nvs_flash_erase() to erase the NVS partition. For a description of the related parameters, please refer to Non-Volatile Storage Library API.

    • ESP_ERR_NVS_NO_FREE_PAGES: Indicates that the NVS partition is full, there are no available free pages, and new data cannot be written.

    • ESP_ERR_NVS_NEW_VERSION_FOUND: Indicates that the data version of the current NVS partition does not match the version expected by the library, and it may be necessary to upgrade or format the partition.

  • After erasing the partition, you need to call the initialization function again and check the return value again to ensure successful initialization.