Station Example

[中文]

Note

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

Example Description

The Station mode is a working mode of Wi-Fi. In this mode, the device acts as a “client” connecting to an existing Wi-Fi router or access point (AP), joining the local area network. This is one of the most common networking methods for embedded devices, widely used in IoT, smart home scenarios, etc.

This example demonstrates how to configure the device as a Wi-Fi station mode and connect to a specified router, achieving basic wireless networking functions.

Note

Whether the device can access the Internet depends on whether the router is connected to the external network: even if the device successfully connects to the local area network, it cannot access websites or cloud services if the router is not connected to the external network.

Running Method

The complete code of the example can be found at station example. The configuration instructions, build and burn process before running can be found in the README.md file in the example directory.

For custom configuration items and viewing default values, refer to the Macro Definition Description section.

Header File Description

The header files used in this example cover basic modules such as FreeRTOS task management, Wi-Fi protocol stack, system event mechanism, log output, NVS non-volatile storage, and TCP/IP protocol stack interface. It builds core functions such as task creation, Wi-Fi initialization, event registration and response, log printing, and network connection.

The header files are categorized by function as follows:

  1. FreeRTOS Task Scheduling: Provides interfaces for task management, delay control, and event registration.

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
  1. System Tools: Used for system initialization, log printing, and configuration and reading and writing of non-volatile storage.

#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
  1. Wi-Fi and Event Mechanism: Includes Wi-Fi startup and connection configuration, event loop registration and processing functions.

#include "esp_wifi.h"
#include "esp_event.h"
  1. Network Protocol Stack: Includes commonly used error code definitions and underlying system abstraction interfaces in the TCP/IP protocol stack, used for handling the status during the network connection process.

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

Macro Definition Description

The macro definitions involved in this example are mainly used to configure Wi-Fi parameters, select authentication modes, set security levels, and define flag bits in the event group.

The macro definitions are categorized by function as follows:

  1. Wi-Fi Parameter Configuration: Used to set Wi-Fi SSID, password, and maximum retry times, in order to correctly identify and connect to the specified access point.

  • SSID (Service Set Identifier) is a network name used to identify a wireless local area network, i.e., the name of Wi-Fi.

  • The parameter macros in the example actually refer to the configuration macros starting with CONFIG_, which are automatically generated by the ESP-IDF build system according to the menuconfig settings and saved in the sdkconfig file.

  1. Security Authentication Mode Setting: According to the user’s configuration in menuconfig, the Both mode is enabled by default, and the password element (PWE) generation mode and auxiliary identifier of the corresponding WPA3 SAE are selected by conditional compilation.

  • WPA3 SAE (Simultaneous Authentication of Equals) is an enhanced password authentication mechanism.

  • Password Element (PWE) is an intermediate value derived from password processing. It does not directly expose the password itself, but can be used to verify the identity of both parties and prevent the password from being eavesdropped or cracked.

  • PWE generation mode is a method of calculating passwords in WPA3 connections, determining how devices generate encryption keys based on passwords, affecting the security and compatibility of connections.

  • ESP-IDF supports three PWE generation modes, the choice of which depends on application requirements and device support:

    • Hunt-and-Peck mode: The device tries various possible PWE combinations until it finds an element that matches the other end, i.e., the communication party. This method is of the try-and-verify type, with good compatibility, suitable for environments with more relaxed hardware and firmware version support, but with relatively high computational complexity and connection latency.

    • Hash-to-Element mode: By hashing the password and the identity information of both parties, a unique PWE is directly generated. This method has lower computational complexity, faster connection speed, and higher security, but it requires both devices to support the hash algorithm. Suitable for devices with newer hardware and firmware versions and scenarios with higher security and efficiency requirements.

    • Both mode: Supports both of the above methods, can dynamically choose the most suitable password element generation method according to the capabilities of the other end device, balancing compatibility and performance.

  1. Set the minimum security level during Wi-Fi scanning: When scanning for Wi-Fi, filter out access points below the set security level (default is WIFI_AUTH_WPA2_PSK), only display or connect to networks that meet the requirements.

  • Through the conditional compilation mechanism, define the value of ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD according to the configuration in menuconfig, used to set the minimum security level during Wi-Fi scanning. The corresponding authentication mode macro will be automatically selected during compilation, no need to manually modify the code.

  • In ESP-IDF, the security levels supported by Wi-Fi are, from low to high:

    • WIFI_AUTH_OPEN: Open network, no password required, communication data is not encrypted, the lowest security.

    • WIFI_AUTH_WEP: Uses WEP encryption, known vulnerabilities exist, low security, not recommended for use.

    • WIFI_AUTH_WPA_PSK: Uses WPA protocol and Pre-Shared Key (PSK) encryption, gradually phased out.

    • WIFI_AUTH_WPA2_PSK: Uses WPA2 protocol and PSK encryption, one of the current mainstream encryption methods, good security.

    • WIFI_AUTH_WPA_WPA2_PSK: Supports both WPA and WPA2 in mixed mode, enhancing compatibility.

    • WIFI_AUTH_WPA3_PSK: Uses WPA3 protocol and PSK encryption, has stronger resistance to brute force cracking, higher security.

    • WIFI_AUTH_WPA2_WPA3_PSK: Supports both WPA2 and WPA3, automatically negotiates connection method, balancing security and compatibility.

    • WIFI_AUTH_WAPI_PSK: Uses China’s national standard WAPI protocol and PSK encryption, suitable for specific industries or regional requirements.

  1. Define flag bits in the event group: To coordinate the synchronization of Wi-Fi connection status between tasks and event callbacks with the event group mechanism, two event flag bits are defined in the example to indicate whether the connection is successful.

  • WIFI_CONNECTED_BIT: Corresponds to the 0th bit (BIT0) of the event group. When Wi-Fi is successfully connected, this bit is set to 1.

  • WIFI_FAIL_BIT: Corresponds to the 1st bit (BIT1) of the event group. When Wi-Fi connection fails, this bit is set to 1.

Note

  • The above macro definitions will automatically synchronize and update after modifying menuconfig and rebuilding/compiling the example, no need to manually change the code.

  • You can directly edit these macros for quick testing, but configuring through menuconfig is more standard and suitable for standard development processes.

Function Description

This example completes the configuration, startup, and connection of ESP32 station mode through the wifi_init_sta() function, and implements the response processing of connection status changes through the registered callback function event_handler().

In this document, wifi_init_sta() is responsible for initializing network-related components and Wi-Fi drivers, configuring connection parameters, and starting Wi-Fi, while event_handler() is used to listen for Wi-Fi and IP events, triggering corresponding operations based on different states during the connection process.

The two work together to build a complete connection and status management process.

event_handler()

This function is an event response function. For a detailed introduction, please refer to Event Callback Function.

In this example, this function is used to handle the following three types of events based on different event_base and event_id inputs:

Event Category

event_base Setting

event_id Setting

Execution Logic

Connect to Wi-Fi

WIFI_EVENT

WIFI_EVENT_STA_START

Call esp_wifi_connect() to attempt to connect to Wi-Fi.

Reconnect to Wi-Fi

WIFI_EVENT

WIFI_EVENT_STA_DISCONNECTED

If s_retry_num is less than the set maximum retry times, call esp_wifi_connect() to connect to Wi-Fi; otherwise, set the event group failure flag.

Obtain IP

IP_EVENT

IP_EVENT_STA_GOT_IP

Get IP information from event_data and print it, set the event group connection success flag.

The xEventGroupSetBits() in the function is used to set the specified event bits to the event group, which is commonly used for event notification and synchronization between tasks. The return value indicates whether the setting operation is successful and includes the status of all event bits set in the event group. For more parameter explanations and related examples, please refer to the event group Set Event Flag section.

wifi_init_sta()

This function is used to initialize Wi-Fi station mode, complete the preparation of network connection, event registration, configuration and start Wi-Fi, and wait for the connection result.

The following are the main implementation steps of the function. Since most of the steps in the process have been detailed in General Steps, repeated content will not be repeated here, only the key implementation and differences in this example are highlighted.

  1. Create an event group:

  • Create an event group and return its handle for subsequent marking of connection status. For a detailed introduction to event groups, please refer to the Event Group document.

  • In this example, there are various possible Wi-Fi connection statuses (such as successful connection, failed connection, etc.), and the program needs to respond differently according to these statuses. Event groups synchronize different tasks and events through flags, making status detection more accurate and efficient, and are key means to implement complex status management.

  1. Initialization Stage

  2. Event Callback Function:

The events involved in this example are as shown in the following table:

event_base

event_id

Event Description

WIFI_EVENT

WIFI_EVENT_STA_START

Wi-Fi provision completed

WIFI_EVENT

WIFI_EVENT_STA_DISCONNECTED

Wi-Fi connection failed

IP_EVENT

IP_EVENT_STA_GOT_IP

IP acquisition successful

  1. Configuration Phase

  • The wifi_config_t structure uses the .sta member, i.e., station mode provision, other members are set through macro definitions, for details refer to Macro Definition Description

    Provision Item

    Description

    Configuration in Example

    .ssid

    The SSID of the Wi-Fi network to connect to

    EXAMPLE_ESP_WIFI_SSID

    .password

    The password of the corresponding Wi-Fi network

    EXAMPLE_ESP_WIFI_PASS

    .threshold.authmode

    Set the minimum authentication mode threshold for Wi-Fi connection

    ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD

    .sae_pwe_h2e

    Set the PWE generation mode of WPA3 SAE to enhance security

    ESP_WIFI_SAE_MODE

    .sae_h2e_identifier

    Optional H2E identifier when using SAE Hash-to-Element mode to enhance security.

    ESP_WIFI_SAE_MODE

    Note

    Unassigned .sta structure members will be automatically initialized to zero (or the corresponding default value), indicating the use of default behavior or disabling the corresponding function, so only key fields need to be manually defined.

  • Set the Wi-Fi operating mode to WIFI_MODE_STA, i.e., station mode.

  1. Startup Phase

  • The specific events generated during the start phase can be referred to Wi-Fi Start Phase.

  1. Connection Phase

  • This example initiates a Wi-Fi connection through the event callback function event_handler().

  • The specific events generated during the connection phase can be referred to Wi-Fi Connection Phase.

  • The blocking operation waiting for the connection result is implemented through xEventGroupWaitBits(). The program determines whether the connection is successful based on the returned event bits and outputs the corresponding logs. For a detailed introduction and parameter description of xEventGroupWaitBits(), please refer to the Waiting for Event Flag Bits section.

Main Function Description

This function serves as the program entry function, which is used to complete the initialization of non-volatile storage (NVS), set the log level, and call the Wi-Fi station mode initialization function wifi_init_sta(), to start the Wi-Fi connection process.

The steps implemented within the function are as follows:

  1. Initialize NVS

  2. Set the log level:

  • Adjust the log level of the Wi-Fi module according to the configuration parameters to increase the detail level of the debug information.

  • Call esp_log_level_set() to set the log output level of the specified module, which requires the module name and log level to be passed in. It is usually called before module initialization. For more parameter descriptions, please refer to Log Library API.

  1. Print startup information: Use log output to display Wi-Fi mode information.

  2. Start Wi-Fi initialization: Call the wifi_init_sta() function to complete the initialization and connection process of Wi-Fi station mode.