WiFi
The WiFi APIs enable the ESP to connect to wireless networks in both station and access point modes.
The espp::Wifi is a singleton class which provides methods to configure and manage WiFi connections. You are able to register multiple different station and access point configurations with unique names and switch between them at runtime.
API Reference
Header File
Classes
-
class Wifi : public espp::BaseComponent
The Wifi class provides access to the ESP32 Wifi functionality.
The Wifi class is a singleton class that provides access to the ESP32 Wifi functionality. The Wifi class is a wrapper around the ESP32 Wifi API. The Wifi class provides access to the Wifi AP and Wifi STA functionality, allowing registration and switching between multiple access points and stations.
WiFi Example
auto &wifi = espp::Wifi::get(); wifi.set_log_level(espp::Logger::Verbosity::DEBUG); // Initialize the WiFi stack if (!wifi.init()) { logger.error("Failed to initialize WiFi stack"); return; } // Register multiple station configurations wifi.register_sta("home", {.ssid = "", // use whatever was saved to NVS (if any) .password = "", // use whatever was saved to NVS (if any) .num_connect_retries = CONFIG_ESP_MAXIMUM_RETRY, .on_got_ip = [&](ip_event_got_ip_t *eventdata) { logger.info("Home network - got IP: {}.{}.{}.{}", IP2STR(&eventdata->ip_info.ip)); }, .log_level = espp::Logger::Verbosity::INFO}); // set the 'home' network to be active and ensure that the backup // registration (when added) doesn't override it wifi.switch_to_sta("home"); wifi.register_sta("backup", {.ssid = "BackupNetwork", .password = "backuppassword", .num_connect_retries = CONFIG_ESP_MAXIMUM_RETRY, .on_got_ip = [&](ip_event_got_ip_t *eventdata) { logger.info("Backup network - got IP: {}.{}.{}.{}", IP2STR(&eventdata->ip_info.ip)); }, .log_level = espp::Logger::Verbosity::INFO}); // ensure that the active interface is still 'home' if (wifi.get_active_name() != "home") { logger.error("Active interface changed unexpectedly after registering backup STA"); return; } // Register an AP configuration wifi.register_ap("device_ap", {.ssid = "MyESP32-AP", .password = "esp32password", .channel = 6, .max_number_of_stations = 4, .log_level = espp::Logger::Verbosity::INFO}); // ensure that the active interface is still 'home' (STA) if (wifi.get_active_name() != "home") { logger.error("Active interface changed unexpectedly after registering AP"); return; } logger.info("Registered STA configurations: "); auto sta_names = wifi.get_registered_sta_names(); for (const auto &name : sta_names) { logger.info(" - '{}'", name); } logger.info("Registered AP configurations: "); auto ap_names = wifi.get_registered_ap_names(); for (const auto &name : ap_names) { logger.info(" - '{}'", name); } // now switch to AP logger.info("\n=== Testing switch to AP ==="); wifi.switch_to_ap("device_ap"); // Check what's currently active std::string active_name = wifi.get_active_name(); if (active_name != "device_ap") { logger.error("Active interface is not 'device_ap' after switch_to_ap"); return; } logger.info("Active interface: '{}' (is_ap={}, is_sta={})", active_name, wifi.is_active_ap(), wifi.is_active_sta()); // Wait for the active interface to be ready/connected auto *active = wifi.get_active(); if (active) { logger.info("Waiting for '{}' to be connected...", active_name); while (!active->is_connected()) { std::this_thread::sleep_for(100ms); } logger.info("'{}' is now connected!", active_name); logger.info("Checking IP address..."); // Get and display IP std::string ip; if (wifi.get_ip_address(ip)) { logger.info("IP address: {}", ip); } } std::this_thread::sleep_for(num_seconds_to_run * 1s); // Access STA instance (single instance, manages all configs) auto *home_sta = wifi.get_sta(); if (home_sta) { logger.info("STA is connected: {}", home_sta->is_connected()); } // Get AP and check connected stations auto *device_ap = wifi.get_ap(); if (device_ap) { auto stations = device_ap->get_connected_stations(); logger.info("AP has {} connected stations", stations.size()); } // Demonstrate switching to STA logger.info("\n=== Testing switch to STA ==="); wifi.switch_to_sta("home"); active_name = wifi.get_active_name(); logger.info("Active interface: '{}' (is_ap={}, is_sta={})", active_name, wifi.is_active_ap(), wifi.is_active_sta()); // Wait for STA to connect active = wifi.get_active(); if (active) { logger.info("Waiting for '{}' to be connected...", active_name); int wait_count = 0; while (!active->is_connected() && wait_count < 100) { std::this_thread::sleep_for(100ms); wait_count++; } if (active->is_connected()) { logger.info("'{}' is now connected!", active_name); std::string ip; if (wifi.get_ip_address(ip)) { logger.info("IP address: {}", ip); } } else { logger.warn("'{}' failed to connect within timeout", active_name); } } std::this_thread::sleep_for(2s); // Demonstrate switching back to AP logger.info("\n=== Testing switch back to AP ==="); wifi.switch_to_ap("device_ap"); active_name = wifi.get_active_name(); logger.info("Active interface: '{}' (is_ap={}, is_sta={})", active_name, wifi.is_active_ap(), wifi.is_active_sta()); // Wait for AP to be ready active = wifi.get_active(); if (active) { logger.info("Waiting for '{}' to be ready...", active_name); std::this_thread::sleep_for(1s); // AP starts quickly if (active->is_connected()) { // For AP, this checks if stations are connected logger.info("'{}' has stations connected", active_name); } else { logger.info("'{}' is ready (no stations connected yet)", active_name); } std::string ip; if (wifi.get_ip_address(ip)) { logger.info("IP address: {}", ip); } } std::this_thread::sleep_for(2s); // Demonstrate stop logger.info("\n=== Testing stop ==="); wifi.stop(); active_name = wifi.get_active_name(); logger.info("Active interface after stop: '{}' (empty=stopped)", active_name);
Note
This class manages the WiFi stack initialization. Call init() before registering any interfaces, and deinit() when done.
Public Functions
-
inline bool init()
Initialize the WiFi stack.
Note
This must be called before registering any WiFi interfaces. It’s safe to call multiple times - subsequent calls are no-ops.
- Returns:
True if initialization was successful, false otherwise.
-
inline bool deinit()
Deinitialize the WiFi stack.
Note
This will stop all interfaces and clear all configurations.
- Returns:
True if deinitialization was successful, false otherwise.
-
inline bool is_initialized() const
Check if the WiFi stack is initialized.
- Returns:
True if initialized, false otherwise.
-
inline esp_netif_t *get_sta_netif()
Get or create the STA network interface.
Note
If the WiFi subsystem is not initialized, logs an error and returns nullptr.
- Returns:
Pointer to the STA netif, or nullptr on error.
-
inline esp_netif_t *get_ap_netif()
Get or create the AP network interface.
Note
If the WiFi subsystem is not initialized, logs an error and returns nullptr.
- Returns:
Pointer to the AP netif, or nullptr on error.
-
inline esp_netif_t *get_active_netif()
Get the esp_netif_t of the currently active interface.
- Returns:
Pointer to the esp_netif_t of the active interface, or nullptr if no interface is active.
-
inline bool get_mode(wifi_mode_t &mode)
Get the current WiFi mode.
Note
WiFi stack must be initialized via init() before calling this.
- Parameters:
mode – Reference to a wifi_mode_t variable to store the result.
- Returns:
True if retrieval was successful, false otherwise.
-
inline bool set_storage(wifi_storage_t storage)
Set the WiFi storage type.
Note
WiFi stack must be initialized via init() before calling this.
- Parameters:
storage – The wifi_storage_t value to set. Can be WIFI_STORAGE_RAM or WIFI_STORAGE_FLASH. The default value is WIFI_STORAGE_FLASH.
- Returns:
True if setting was successful, false otherwise.
-
inline bool get_power_save(wifi_ps_type_t &ps_type)
Get the current WiFi power save type.
- Parameters:
ps_type – Reference to a wifi_ps_type_t variable to store the result.
- Returns:
True if retrieval was successful, false otherwise.
-
inline bool set_power_save(wifi_ps_type_t ps_type)
Set the WiFi power save type.
- Parameters:
ps_type – The wifi_ps_type_t value to set.
- Returns:
True if setting was successful, false otherwise.
-
inline bool get_max_tx_power_raw(int8_t &power_raw)
Get the maximum WiFi transmit power.
Note
WiFi stack must be initialized via init() before calling this.
Note
Returned value is a range [8, 84] representing power in 0.25 dBm units, i.e., 8 = 2 dBm, 84 = 21 dBm.
- Parameters:
power_raw – Reference to an int8_t variable to store the result.
- Returns:
True if retrieval was successful, false otherwise.
-
inline bool get_max_tx_power_dbm(float &power_dbm)
Get the maximum WiFi transmit power in dBm.
Note
WiFi stack must be initialized via init() before calling this.
- Parameters:
power_dbm – Reference to a float variable to store the result.
- Returns:
True if retrieval was successful, false otherwise.
-
inline bool set_max_tx_power_raw(int8_t power_raw)
Set the maximum WiFi transmit power.
Note
WiFi stack must be initialized via init() before calling this.
- Parameters:
power_raw – The maximum transmit power in 0.25 dBm units.
- Returns:
True if setting was successful, false otherwise.
-
inline bool set_max_tx_power_dbm(float power_dbm)
Set the maximum WiFi transmit power in dBm.
Note
WiFi stack must be initialized via init() before calling this.
- Parameters:
power_dbm – The maximum transmit power in dBm.
- Returns:
True if setting was successful, false otherwise.
-
inline bool register_ap(const std::string &name, const WifiAp::Config &config, bool set_active = false)
Register a new WiFi Access Point configuration.
Note
WiFi stack must be initialized via init() before calling this. Only one interface (AP or STA) can be active at a time.
- Parameters:
name – Unique identifier for this AP configuration.
config – WifiAp::Config structure with AP configuration.
set_active – If true, immediately activate this AP configuration.
- Returns:
True if registration was successful, false otherwise.
-
inline bool register_sta(const std::string &name, const WifiSta::Config &config, bool set_active = false)
Register a new WiFi Station configuration.
Note
WiFi stack must be initialized via init() before calling this. Only one interface (AP or STA) can be active at a time.
- Parameters:
name – Unique identifier for this STA configuration.
config – WifiSta::Config structure with STA configuration.
set_active – If true, immediately activate this STA configuration.
- Returns:
True if registration was successful, false otherwise.
-
inline std::vector<std::string> get_registered_sta_names()
Get all registered STA configuration names.
- Returns:
Vector of registered STA configuration names.
-
inline std::vector<std::string> get_registered_ap_names()
Get all registered AP configuration names.
- Returns:
Vector of registered AP configuration names.
-
inline std::unordered_map<std::string, WifiSta::Config> get_registered_sta_configs()
Get all registered STA configurations.
- Returns:
Unordered map of registered STA configurations.
-
inline std::unordered_map<std::string, WifiAp::Config> get_registered_ap_configs()
Get all registered AP configurations.
- Returns:
Unordered map of registered AP configurations.
-
inline bool switch_to_ap(const std::string &name)
Switch to a different registered AP configuration.
Note
This will stop any active STA interface.
- Parameters:
name – The name of the AP configuration to switch to.
- Returns:
True if the switch was successful, false otherwise.
-
inline bool switch_to_sta(const std::string &name)
Switch to a different registered STA configuration.
Note
This will stop any active AP interface.
- Parameters:
name – The name of the STA configuration to switch to.
- Returns:
True if the switch was successful, false otherwise.
-
inline WifiAp *get_ap()
Get pointer to the WiFi AP instance.
- Returns:
Pointer to the WifiAp instance, or nullptr if not created.
-
inline WifiSta *get_sta()
Get pointer to the WiFi STA instance.
- Returns:
Pointer to the WifiSta instance, or nullptr if not created.
-
inline WifiBase *get_active()
Get pointer to the currently active interface.
- Returns:
Pointer to the active WifiBase instance, or nullptr if none active.
-
inline std::string get_active_name() const
Get the name of the currently active interface (AP or STA).
- Returns:
Name of the active interface, or empty string if none active.
-
inline bool is_active_ap() const
Check if the active interface is an AP.
- Returns:
True if active interface is AP, false otherwise.
-
inline bool is_active_sta() const
Check if the active interface is a STA.
- Returns:
True if active interface is STA, false otherwise.
-
inline std::string get_active_ap_name() const
Get the name of the currently active AP configuration.
- Returns:
Name of the active AP config, or empty string if none active.
-
inline std::string get_active_sta_name() const
Get the name of the currently active STA configuration.
- Returns:
Name of the active STA config, or empty string if none active.
-
inline bool remove_ap(const std::string &name)
Remove a registered AP configuration.
- Parameters:
name – The name of the AP config to remove.
- Returns:
True if the config was removed, false if not found.
-
inline bool remove_sta(const std::string &name)
Remove a registered STA configuration.
- Parameters:
name – The name of the STA config to remove.
- Returns:
True if the config was removed, false if not found.
-
inline bool stop()
Stop the currently active interface (AP or STA).
- Returns:
True if an interface was stopped, false if none was active.
-
inline bool get_ip_address(std::string &ip_address)
Get the IP address of the active WiFi interface.
- Parameters:
ip_address – The IP address of the active WiFi interface.
- Returns:
True if the IP address was retrieved, false otherwise.
-
inline const std::string &get_name() const
Get the name of the component
Note
This is the tag of the logger
- Returns:
A const reference to the name of the component
-
inline void set_log_tag(const std::string_view &tag)
Set the tag for the logger
- Parameters:
tag – The tag to use for the logger
-
inline espp::Logger::Verbosity get_log_level() const
Get the log level for the logger
See also
See also
- Returns:
The verbosity level of the logger
-
inline void set_log_level(espp::Logger::Verbosity level)
Set the log level for the logger
See also
See also
- Parameters:
level – The verbosity level to use for the logger
-
inline void set_log_verbosity(espp::Logger::Verbosity level)
Set the log verbosity for the logger
See also
See also
See also
Note
This is a convenience method that calls set_log_level
- Parameters:
level – The verbosity level to use for the logger
-
inline espp::Logger::Verbosity get_log_verbosity() const
Get the log verbosity for the logger
See also
See also
See also
Note
This is a convenience method that calls get_log_level
- Returns:
The verbosity level of the logger
-
inline void set_log_rate_limit(std::chrono::duration<float> rate_limit)
Set the rate limit for the logger
See also
Note
Only calls to the logger that have _rate_limit suffix will be rate limited
- Parameters:
rate_limit – The rate limit to use for the logger
-
inline bool init()