ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
wifi_component_esp_idf.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
4
5#ifdef USE_WIFI
6#ifdef USE_ESP32
7
8#include <esp_event.h>
9#include <esp_netif.h>
10#include <esp_system.h>
11#include <esp_wifi.h>
12#include <esp_wifi_types.h>
13#include <freertos/FreeRTOS.h>
14#include <freertos/event_groups.h>
15#include <freertos/task.h>
16
17#include <algorithm>
18#include <cinttypes>
19#include <memory>
20#include <utility>
21#ifdef USE_WIFI_WPA2_EAP
22#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
23#include <esp_eap_client.h>
24#else
25#include <esp_wpa2.h>
26#endif
27#endif
28
29#ifdef USE_WIFI_DPP
30#include <esp_dpp.h>
31#endif
32
33#ifdef USE_WIFI_AP
34#include "dhcpserver/dhcpserver.h"
35#endif // USE_WIFI_AP
36
37#ifdef USE_CAPTIVE_PORTAL
39#endif
40
41#include "lwip/apps/sntp.h"
42#include "lwip/dns.h"
43#include "lwip/err.h"
44#if USE_NETWORK_IPV6 || defined(USE_WIFI_LEASE_CACHE)
45#include <esp_netif_net_stack.h> // esp_netif_get_netif_impl()
46#include "lwip/netif.h"
47#endif
48#ifdef USE_WIFI_LEASE_CACHE
49#include <esp_rtc_time.h> // esp_rtc_get_time_us() -- RTC-domain clock for lease age
50#include "lwip/dhcp.h"
51#endif
52
54#include "esphome/core/hal.h"
56#include "esphome/core/log.h"
57#include "esphome/core/util.h"
58
59namespace esphome::wifi {
60
61ESPHOME_LOG_TAG(TAG, "wifi_esp32");
62
63static EventGroupHandle_t s_wifi_event_group; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
64static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
65#ifdef USE_WIFI_AP
66static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
67#endif // USE_WIFI_AP
68static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
69static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
70static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
71static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
72static bool s_wifi_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
73
74static ExpectedDisconnect s_expected_disconnect; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
75
76#ifdef USE_WIFI_DPP
78
79static void copy_terminated(char *dst, const uint8_t *src, size_t len) {
80 memcpy(dst, src, len);
81 dst[len] = '\0';
82}
83#endif
84
85struct IDFWiFiEvent {
86 esp_event_base_t event_base;
87 int32_t event_id;
88 union {
89 wifi_event_sta_scan_done_t sta_scan_done;
90 wifi_event_sta_connected_t sta_connected;
91 wifi_event_sta_disconnected_t sta_disconnected;
92 wifi_event_sta_authmode_change_t sta_authmode_change;
93 wifi_event_ap_staconnected_t ap_staconnected;
94 wifi_event_ap_stadisconnected_t ap_stadisconnected;
95 wifi_event_ap_probe_req_rx_t ap_probe_req_rx;
96 wifi_event_bss_rssi_low_t bss_rssi_low;
97#ifdef USE_WIFI_DPP
98 SavedWifiSettings *dpp_credentials; // owned by the event; the rare 98 byte record does not widen the union
99 wifi_event_dpp_failed_t dpp_failed;
100#endif
101 ip_event_got_ip_t ip_got_ip;
102#if USE_NETWORK_IPV6
103 ip_event_got_ip6_t ip_got_ip6;
104#endif /* USE_NETWORK_IPV6 */
105#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
106 ip_event_assigned_ip_to_client_t ip_assigned_ip_to_client;
107#else
108 ip_event_ap_staipassigned_t ip_ap_staipassigned;
109#endif
110 } data;
111};
112
113// general design: event handler translates events and pushes them to a queue,
114// events get processed in the main loop
115void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
116 IDFWiFiEvent event;
117 memset(&event, 0, sizeof(IDFWiFiEvent));
118 event.event_base = event_base;
119 event.event_id = event_id;
120 if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { // NOLINT(bugprone-branch-clone)
121 // no data
122 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_STOP) { // NOLINT(bugprone-branch-clone)
123 // no data
124 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
125 memcpy(&event.data.sta_authmode_change, event_data, sizeof(wifi_event_sta_authmode_change_t));
126 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) {
127 memcpy(&event.data.sta_connected, event_data, sizeof(wifi_event_sta_connected_t));
128 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
129 memcpy(&event.data.sta_disconnected, event_data, sizeof(wifi_event_sta_disconnected_t));
130 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
131 memcpy(&event.data.ip_got_ip, event_data, sizeof(ip_event_got_ip_t));
132#if USE_NETWORK_IPV6
133 } else if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
134 memcpy(&event.data.ip_got_ip6, event_data, sizeof(ip_event_got_ip6_t));
135#endif
136#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
137 } else if (event_base == IP_EVENT &&
138 (event_id == IP_EVENT_ETH_GOT_IP || event_id == IP_EVENT_PPP_GOT_IP)) { // NOLINT(bugprone-branch-clone)
139 // no data: the bridge rereads the resolvers an ethernet or modem upstream just received
140#endif
141 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) { // NOLINT(bugprone-branch-clone)
142 // no data
143 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
144 memcpy(&event.data.sta_scan_done, event_data, sizeof(wifi_event_sta_scan_done_t));
145 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) { // NOLINT(bugprone-branch-clone)
146 // no data
147 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STOP) { // NOLINT(bugprone-branch-clone)
148 // no data
149 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
150 memcpy(&event.data.ap_probe_req_rx, event_data, sizeof(wifi_event_ap_probe_req_rx_t));
151 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
152 memcpy(&event.data.ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t));
153 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
154 memcpy(&event.data.ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t));
155#ifdef USE_WIFI_DPP
156 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_DPP_URI_READY) {
157 // Kept on the component for the whole boot; the queued event only announces it
158 const auto *uri = static_cast<const wifi_event_dpp_uri_ready_t *>(event_data);
159 const size_t len = strnlen(uri->uri, uri->uri_data_len);
160 auto copy = std::make_unique<char[]>(len + 1);
161 copy_terminated(copy.get(), reinterpret_cast<const uint8_t *>(uri->uri), len);
162 global_wifi_component->dpp_uri_ = std::move(copy);
163 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_DPP_CFG_RECVD) {
164 const auto &sta = static_cast<const wifi_event_dpp_config_received_t *>(event_data)->wifi_cfg.sta;
165 auto *credentials = new SavedWifiSettings; // NOLINT(cppcoreguidelines-owning-memory)
166 copy_terminated(credentials->ssid, sta.ssid, sizeof(sta.ssid));
167 copy_terminated(credentials->password, sta.password, sizeof(sta.password));
168 event.data.dpp_credentials = credentials;
169 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_DPP_FAILED) {
170 memcpy(&event.data.dpp_failed, event_data, sizeof(wifi_event_dpp_failed_t));
171#endif
172#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
173 } else if (event_base == IP_EVENT && event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
174 memcpy(&event.data.ip_assigned_ip_to_client, event_data, sizeof(ip_event_assigned_ip_to_client_t));
175#else
176 } else if (event_base == IP_EVENT && event_id == IP_EVENT_AP_STAIPASSIGNED) {
177 memcpy(&event.data.ip_ap_staipassigned, event_data, sizeof(ip_event_ap_staipassigned_t));
178#endif
179 } else {
180 // did not match any event, don't send anything
181 return;
182 }
183
184 // copy to heap — WiFi events are rare so heap alloc is fine
185 auto *to_send = new IDFWiFiEvent; // NOLINT(cppcoreguidelines-owning-memory)
186 memcpy(to_send, &event, sizeof(IDFWiFiEvent));
187 if (!global_wifi_component->event_queue_.push(to_send)) {
188#ifdef USE_WIFI_DPP
189 if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_DPP_CFG_RECVD)
190 delete to_send->data.dpp_credentials; // NOLINT(cppcoreguidelines-owning-memory)
191#endif
192 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
193 }
194}
195
197 // Network interface setup handled by network component
198 s_wifi_event_group = xEventGroupCreate();
199 if (s_wifi_event_group == nullptr) {
200 ESP_LOGE(TAG, "xEventGroupCreate failed");
201 return;
202 }
203 esp_event_handler_instance_t instance_wifi_id, instance_ip_id;
204 esp_err_t err =
205 esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_wifi_id);
206 if (err != ERR_OK) {
207 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
208 return;
209 }
210 err = esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_ip_id);
211 if (err != ERR_OK) {
212 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
213 return;
214 }
215 // NOTE: netif creation + esp_wifi_init() used to live here. They allocate ~15-30KB of
216 // DMA-capable internal SRAM, which competes with W5500 SPI DMA and I2S DMA on
217 // memory-tight devices. They are now deferred to wifi_lazy_init_(), called from
218 // setup() when enable_on_boot_ is true, or from enable() on first runtime enable.
219 // This makes enable_on_boot:false genuinely skip the wifi DMA allocation.
220}
221
223 if (this->wifi_initialized_)
224 return;
225
226 // Guard each creation so partial init (e.g. a failed esp_wifi_init() below)
227 // followed by a retry via enable() does not leak the existing netif handle
228 // nor re-register the default WiFi handlers.
229 if (s_sta_netif == nullptr)
230 s_sta_netif = esp_netif_create_default_wifi_sta();
231 if (s_sta_netif == nullptr) {
232 // Allocation failed; leave wifi_initialized_ false so a later enable() retries.
233 ESP_LOGE(TAG, "esp_netif_create_default_wifi_sta failed");
234 return;
235 }
236
237#ifdef USE_WIFI_AP
238 if (s_ap_netif == nullptr)
239 s_ap_netif = esp_netif_create_default_wifi_ap();
240#endif // USE_WIFI_AP
241
242 // The WiFi driver was started (e.g. by ESP-NOW with the wifi component disabled at
243 // boot) before our STA netif existed. The default WIFI_EVENT_STA_START handler
244 // therefore ran with no netif and never called esp_wifi_register_if_rxcb() -- the
245 // only thing that points the driver's RX path at a netif (it sets
246 // s_wifi_netifs[WIFI_IF_STA]). A bare esp_netif_action_start() would stop the
247 // immediate crash (#17232) but leaves RX unbound, so the first association
248 // associates at L2 yet never receives DHCP replies and times out (#17239). Restart
249 // the driver now that the netif exists so STA_START re-runs the default handler and
250 // wires RX correctly. ESP-NOW survives the stop/start (its peer state persists).
251 // This also matches a self-retry: if esp_wifi_set_storage() below failed on a
252 // previous wifi_lazy_init_() it returned without setting wifi_initialized_, and
253 // esp_wifi_init() has since run, so esp_wifi_get_mode() now succeeds here too.
254 wifi_mode_t mode;
255 if (esp_wifi_get_mode(&mode) == ESP_OK) {
256 ESP_LOGD(TAG, "WiFi driver already started without STA netif; restarting to bind it");
257 esp_err_t err = esp_wifi_stop();
258 if (err != ESP_OK) {
259 ESP_LOGW(TAG, "esp_wifi_stop failed: %s", esp_err_to_name(err));
260 }
261 // Re-apply RAM storage; the normal init path does this, but it is skipped on
262 // the self-retry case above, which would otherwise let the driver persist
263 // credentials to NVS for the rest of the boot.
264 err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
265 if (err != ESP_OK) {
266 ESP_LOGW(TAG, "esp_wifi_set_storage failed: %s", esp_err_to_name(err));
267 }
268 err = esp_wifi_start();
269 if (err != ESP_OK) {
270 ESP_LOGE(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
271 return;
272 }
273 s_wifi_started = true;
274 this->wifi_initialized_ = true;
275#ifdef USE_WIFI_DPP
276 this->wifi_dpp_init_();
277#endif
278 return;
279 }
280
281 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
282 if (global_preferences->nvs_handle == 0) {
283 ESP_LOGW(TAG, "starting wifi without nvs");
284 cfg.nvs_enable = false;
285 }
286 esp_err_t err = esp_wifi_init(&cfg);
287 if (err != ERR_OK) {
288 ESP_LOGE(TAG, "esp_wifi_init failed: %s", esp_err_to_name(err));
289 return;
290 }
291 err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
292 if (err != ERR_OK) {
293 ESP_LOGE(TAG, "esp_wifi_set_storage failed: %s", esp_err_to_name(err));
294 return;
295 }
296
297 this->wifi_initialized_ = true;
298#ifdef USE_WIFI_DPP
299 this->wifi_dpp_init_();
300#endif
301}
302
303#ifdef USE_WIFI_DPP
305 // With no callback the supplicant posts WIFI_EVENT_DPP_* events, handled with the other events
306#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
307 esp_err_t err = esp_supp_dpp_init();
308#else
309 esp_err_t err = esp_supp_dpp_init(nullptr);
310#endif
311 if (err != ESP_OK) {
312 ESP_LOGW(TAG, "%s failed: %s", LOG_STR_LITERAL("esp_supp_dpp_init"), esp_err_to_name(err));
313 return;
314 }
315 err = esp_supp_dpp_bootstrap_gen(this->dpp_channels_, DPP_BOOTSTRAP_QR_CODE, this->dpp_key_, this->dpp_device_info_);
316 if (err != ESP_OK) {
317 ESP_LOGW(TAG, "%s failed: %s", LOG_STR_LITERAL("esp_supp_dpp_bootstrap_gen"), esp_err_to_name(err));
318 }
319}
320#endif
321
322bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
323 esp_err_t err;
324 wifi_mode_t current_mode = WIFI_MODE_NULL;
325 if (s_wifi_started) {
326 err = esp_wifi_get_mode(&current_mode);
327 if (err != ERR_OK) {
328 ESP_LOGW(TAG, "esp_wifi_get_mode failed: %s", esp_err_to_name(err));
329 return false;
330 }
331 }
332 bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA;
333 bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA;
334
335 bool set_sta = sta.value_or(current_sta);
336 bool set_ap = ap.value_or(current_ap);
337
338 wifi_mode_t set_mode;
339 if (set_sta && set_ap) {
340 set_mode = WIFI_MODE_APSTA;
341 } else if (set_sta && !set_ap) {
342 set_mode = WIFI_MODE_STA;
343 } else if (!set_sta && set_ap) {
344 set_mode = WIFI_MODE_AP;
345 } else {
346 set_mode = WIFI_MODE_NULL;
347 }
348
349 if (current_mode == set_mode)
350 return true;
351
352 if (set_sta && !current_sta) {
353 ESP_LOGV(TAG, "Enabling STA");
354 } else if (!set_sta && current_sta) {
355 ESP_LOGV(TAG, "Disabling STA");
356 }
357 if (set_ap && !current_ap) {
358 ESP_LOGV(TAG, "Enabling AP");
359 } else if (!set_ap && current_ap) {
360 ESP_LOGV(TAG, "Disabling AP");
361 }
362
363 if (set_mode == WIFI_MODE_NULL && s_wifi_started) {
364 err = esp_wifi_stop();
365 if (err != ESP_OK) {
366 ESP_LOGV(TAG, "esp_wifi_stop failed: %s", esp_err_to_name(err));
367 return false;
368 }
369 s_wifi_started = false;
370 return true;
371 }
372
373 err = esp_wifi_set_mode(set_mode);
374 if (err != ERR_OK) {
375 ESP_LOGW(TAG, "esp_wifi_set_mode failed: %s", esp_err_to_name(err));
376 return false;
377 }
378
379 if (set_mode != WIFI_MODE_NULL && !s_wifi_started) {
380 err = esp_wifi_start();
381 if (err != ESP_OK) {
382 ESP_LOGV(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
383 return false;
384 }
385 s_wifi_started = true;
386 }
387
388 return true;
389}
390
391bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
392
393bool WiFiComponent::wifi_apply_output_power_(float output_power) {
394 int8_t val = static_cast<int8_t>(output_power * 4);
395 return esp_wifi_set_max_tx_power(val) == ESP_OK;
396}
397
399 wifi_ps_type_t power_save;
400 switch (this->power_save_) {
402 power_save = WIFI_PS_MIN_MODEM;
403 break;
405 power_save = WIFI_PS_MAX_MODEM;
406 break;
408 default:
409 power_save = WIFI_PS_NONE;
410 break;
411 }
412 bool success = esp_wifi_set_ps(power_save) == ESP_OK;
413#ifdef USE_WIFI_POWER_SAVE_LISTENERS
414 if (success) {
415 for (auto *listener : this->power_save_listeners_) {
416 listener->on_wifi_power_save(this->power_save_);
417 }
418 }
419#endif
420 return success;
421}
422
423#ifdef SOC_WIFI_SUPPORT_5G
424bool WiFiComponent::wifi_apply_band_mode_() { return esp_wifi_set_band_mode(this->band_mode_) == ESP_OK; }
425#endif
426
427bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
428 s_expected_disconnect.clear();
429 // enable STA
430 if (!this->wifi_mode_(true, {}))
431 return false;
432#ifdef USE_WIFI_DPP
433 // A connect attempt ends the supplicant's listen; the next cooldown starts it again
434 this->stop_dpp_listen_();
435#endif
436
437 // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
438 wifi_config_t conf;
439 memset(&conf, 0, sizeof(conf));
440 if (ap.ssid_.size() > sizeof(conf.sta.ssid)) {
441 ESP_LOGE(TAG, "SSID too long");
442 return false;
443 }
444 if (ap.password_.size() > sizeof(conf.sta.password)) {
445 ESP_LOGE(TAG, "Password too long");
446 return false;
447 }
448 memcpy(reinterpret_cast<char *>(conf.sta.ssid), ap.ssid_.c_str(), ap.ssid_.size());
449 memcpy(reinterpret_cast<char *>(conf.sta.password), ap.password_.c_str(), ap.password_.size());
450
451 // The weakest authmode to accept in the fast scan mode
452 if (ap.password_.empty()) {
453 conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
454 } else {
455 // Set threshold based on configured minimum auth mode
456 switch (this->min_auth_mode_) {
458 conf.sta.threshold.authmode = WIFI_AUTH_WPA_PSK;
459 break;
461 conf.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
462 break;
464 conf.sta.threshold.authmode = WIFI_AUTH_WPA3_PSK;
465 break;
466 }
467 }
468
469#ifdef USE_WIFI_WPA2_EAP
470 if (ap.get_eap().has_value()) {
471 conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
472 }
473#endif
474
475#ifdef USE_WIFI_11KV_SUPPORT
476 conf.sta.btm_enabled = this->btm_;
477 conf.sta.rm_enabled = this->rrm_;
478#endif
479
480 if (ap.has_bssid()) {
481 conf.sta.bssid_set = true;
482 memcpy(conf.sta.bssid, ap.get_bssid().data(), 6);
483 } else {
484 conf.sta.bssid_set = false;
485 }
486 if (ap.has_channel()) {
487 conf.sta.channel = ap.get_channel();
488 conf.sta.scan_method = WIFI_FAST_SCAN;
489 } else {
490 conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
491 }
492 // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
493 // Units: AP beacon intervals. Defaults to 3 if set to 0.
494 conf.sta.listen_interval = 0;
495
496 // Protected Management Frame
497 // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
498 conf.sta.pmf_cfg.capable = true;
499 conf.sta.pmf_cfg.required = false;
500
501 // note, we do our own filtering
502 // The minimum rssi to accept in the fast scan mode
503 conf.sta.threshold.rssi = -127;
504
505 wifi_config_t current_conf;
506 esp_err_t err;
507 err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
508 if (err != ERR_OK) {
509 ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
510 // can continue
511 }
512
513 if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
514 // Events are handled in loop(), so expecting the leave after the disconnect is in time for it
515 const bool disconnected = s_expected_disconnect.disconnect_and_expect_leave(
516 [](uint8_t *bssid) {
517 wifi_ap_record_t old_ap{};
518 if (esp_wifi_sta_get_ap_info(&old_ap) != ESP_OK)
519 return false;
520 std::copy_n(old_ap.bssid, sizeof(old_ap.bssid), bssid);
521 return true;
522 },
523 [&err]() {
524 err = esp_wifi_disconnect();
525 return err == ESP_OK;
526 });
527 if (!disconnected) {
528 ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
529 return false;
530 }
531 // The old session is gone even if configuring the next attempt fails.
532 s_sta_connecting = false;
533 this->clear_sta_session_();
534 }
535
536 err = esp_wifi_set_config(WIFI_IF_STA, &conf);
537 if (err != ESP_OK) {
538 ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
539 return false;
540 }
541
542#ifdef USE_WIFI_MANUAL_IP
543 if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
544 return false;
545 }
546#else
547 if (!this->wifi_sta_ip_config_({})) {
548 return false;
549 }
550#endif
551
552 // setup enterprise authentication if required
553#ifdef USE_WIFI_WPA2_EAP
554 const auto &eap_opt = ap.get_eap();
555 if (eap_opt.has_value()) {
556 // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
557 const EAPAuth &eap = *eap_opt;
558#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
559 err = esp_eap_client_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
560#else
561 err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
562#endif
563 if (err != ESP_OK) {
564 ESP_LOGV(TAG, "set_identity failed %d", err);
565 }
566 int ca_cert_len = strlen(eap.ca_cert);
567 int client_cert_len = strlen(eap.client_cert);
568 int client_key_len = strlen(eap.client_key);
569 if (ca_cert_len) {
570#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
571 err = esp_eap_client_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
572#else
573 err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
574#endif
575 if (err != ESP_OK) {
576 ESP_LOGV(TAG, "set_ca_cert failed %d", err);
577 }
578 }
579 // workout what type of EAP this is
580 // validation is not required as the config tool has already validated it
581 if (client_cert_len && client_key_len) {
582 // if we have certs, this must be EAP-TLS
583#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
584 err = esp_eap_client_set_certificate_and_key((uint8_t *) eap.client_cert, client_cert_len + 1,
585 (uint8_t *) eap.client_key, client_key_len + 1,
586 (uint8_t *) eap.password.c_str(), eap.password.length());
587#else
588 err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
589 (uint8_t *) eap.client_key, client_key_len + 1,
590 (uint8_t *) eap.password.c_str(), eap.password.length());
591#endif
592 if (err != ESP_OK) {
593 ESP_LOGV(TAG, "set_cert_key failed %d", err);
594 }
595 } else {
596 // in the absence of certs, assume this is username/password based
597#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
598 err = esp_eap_client_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
599#else
600 err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
601#endif
602 if (err != ESP_OK) {
603 ESP_LOGV(TAG, "set_username failed %d", err);
604 }
605#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
606 err = esp_eap_client_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
607#else
608 err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
609#endif
610 if (err != ESP_OK) {
611 ESP_LOGV(TAG, "set_password failed %d", err);
612 }
613 // set TTLS Phase 2, defaults to MSCHAPV2
614#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
615 err = esp_eap_client_set_ttls_phase2_method(eap.ttls_phase_2);
616#else
617 err = esp_wifi_sta_wpa2_ent_set_ttls_phase2_method(eap.ttls_phase_2);
618#endif
619 if (err != ESP_OK) {
620 ESP_LOGV(TAG, "set_ttls_phase2_method failed %d", err);
621 }
622 }
623#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
624 err = esp_wifi_sta_enterprise_enable();
625#else
626 err = esp_wifi_sta_wpa2_ent_enable();
627#endif
628 if (err != ESP_OK) {
629 ESP_LOGV(TAG, "enterprise_enable failed %d", err);
630 }
631 }
632#endif // USE_WIFI_WPA2_EAP
633
634 // Reset flags, do this _before_ wifi_station_connect as the callback method
635 // may be called from wifi_station_connect
636 s_sta_connecting = true;
637 s_sta_connect_error = false;
638 s_sta_connect_not_found = false;
639 // Ensures we don't report connected before DHCP completes (IP_EVENT_STA_LOST_IP doesn't always fire on disconnect)
640 this->clear_sta_session_();
641
642 err = esp_wifi_connect();
643 if (err != ESP_OK) {
644 ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
645 // An expected leave no longer clears this, so the next attempt would wait for the connect timeout
646 s_sta_connecting = false;
647 return false;
648 }
649
650 return true;
651}
652
654 s_sta_connected = false;
655 this->got_ipv4_address_ = false;
656#if USE_NETWORK_IPV6
657 this->num_ipv6_addresses_ = 0;
658#endif
659}
660
661// sntp_servermode_dhcp() is an empty macro unless lwIP takes NTP servers from DHCP; that build needs the core lock
662static void disable_dhcp_sntp() {
663#if SNTP_GET_SERVERS_FROM_DHCP || SNTP_GET_SERVERS_FROM_DHCPV6
664 LwIPLock lock;
665#endif
666 sntp_servermode_dhcp(false);
667}
668
669#ifdef USE_WIFI_LEASE_CACHE
670// Minimum lease time that must remain before a cached lease is applied.
671static constexpr uint32_t LEASE_APPLY_MARGIN_SECS = 60;
672
673// Seconds since capture on the RTC-domain clock; UINT32_MAX if the clock was reset (age unknown).
674static uint32_t lease_cache_age_secs(const SavedWifiLeaseSettings &lease) {
675 uint32_t now = static_cast<uint32_t>(esp_rtc_get_time_us() / 1000000ULL);
676 return now >= lease.saved_at ? now - lease.saved_at : UINT32_MAX;
677}
678
679// Renewal deadline (T1) from capture; half the lease when T1 is missing or invalid (RFC 2131).
680static uint32_t lease_renew_at_secs(const SavedWifiLeaseSettings &lease) {
681 uint32_t renew_at = lease.t1_renew;
682 if (renew_at == 0 || renew_at >= lease.lease_secs)
683 renew_at = lease.lease_secs / 2;
684 return renew_at;
685}
686
687// Starting the DHCP client drops the static address and DNS servers, so open connections reset
689 ESP_LOGI(TAG, "Cached lease renew deadline reached; re-acquiring the address over DHCP, connections may drop");
690 this->applied_cached_lease_ = false;
691 // Same SNTP leak guard as the DHCP path: https://github.com/esphome/issues/issues/2299
692 disable_dhcp_sntp();
693 esp_err_t err = esp_netif_dhcpc_start(s_sta_netif);
694 if (err != ESP_OK) {
695 ESP_LOGW(TAG, "Lease renew: starting DHCP client failed: %s, retrying in 60 s", esp_err_to_name(err));
696 this->set_timeout(LEASE_RENEW_TIMEOUT_ID, 60000, [this]() { this->renew_cached_lease_(); });
697 }
698}
699
701 const SavedWifiLeaseSettings &lease = this->cached_lease_;
702 if (lease.version != SAVED_WIFI_LEASE_VERSION || this->selected_sta_index_ < 0 ||
703 lease.ap_index != this->selected_sta_index_)
704 return false;
705 // The age is only known when the RTC clock survived the reset (deep sleep or software reboot).
706 esp_reset_reason_t reason = esp_reset_reason();
707 if (reason != ESP_RST_DEEPSLEEP && reason != ESP_RST_SW)
708 return false;
709 uint32_t age = lease_cache_age_secs(lease);
710 if (age == UINT32_MAX)
711 return false;
712 if (this->lease_cache_max_age_ != 0 && age > this->lease_cache_max_age_)
713 return false;
714 // Past T1 the lease needs DHCP renewal anyway.
715 if (age >= lease_renew_at_secs(lease))
716 return false;
717 // Scale the margin with the lease: the RTC RC oscillator drifts a few percent.
718 uint32_t margin = std::max<uint32_t>(LEASE_APPLY_MARGIN_SECS, lease.lease_secs / 16);
719 return lease.lease_secs > age + margin;
720}
721#endif
722
723bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
724 // enable STA
725 if (!this->wifi_mode_(true, {}))
726 return false;
727
728 // Check if the STA interface is initialized before using it
729 if (s_sta_netif == nullptr) {
730 ESP_LOGW(TAG, "STA interface not initialized");
731 return false;
732 }
733
734 esp_netif_dhcp_status_t dhcp_status;
735 esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
736 if (err != ESP_OK) {
737 ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
738 return false;
739 }
740
741#ifdef USE_WIFI_LEASE_CACHE
742 // Without a manual IP, a still-valid cached lease is applied as a static IP to skip DHCP.
743 optional<ManualIP> effective_ip = manual_ip;
744 this->applied_cached_lease_ = false;
745 this->cancel_timeout(LEASE_RENEW_TIMEOUT_ID);
746 if (!effective_ip.has_value() && this->lease_valid_for_apply_()) {
747 const SavedWifiLeaseSettings &lease = this->cached_lease_;
748 esp_ip4_addr_t ip4{lease.ip}, mask4{lease.netmask}, gw4{lease.gateway}, dns1_4{lease.dns1}, dns2_4{lease.dns2};
749 ManualIP cached;
750 cached.static_ip = network::IPAddress(&ip4);
751 cached.gateway = network::IPAddress(&gw4);
752 cached.subnet = network::IPAddress(&mask4);
753 cached.dns1 = network::IPAddress(&dns1_4);
754 cached.dns2 = network::IPAddress(&dns2_4);
755 effective_ip = cached;
756 this->applied_cached_lease_ = true;
757
758 uint32_t age = lease_cache_age_secs(lease);
759 uint32_t remaining = lease.lease_secs > age ? lease.lease_secs - age : 0;
760 ESP_LOGI(TAG, "Applying cached lease " IPSTR ", ~%" PRIu32 "s left, skipping DHCP", IP2STR(&ip4), remaining);
761
762 // Still awake at T1: switch to real DHCP. lease_valid_for_apply_() guarantees age < T1.
763 uint32_t renew_in = lease_renew_at_secs(lease) - age;
764 // Clamp below UINT32_MAX, which the scheduler treats as "don't run".
765 uint32_t renew_ms =
766 static_cast<uint32_t>(std::min<uint64_t>(static_cast<uint64_t>(renew_in) * 1000ULL, UINT32_MAX - 1));
767 this->set_timeout(LEASE_RENEW_TIMEOUT_ID, renew_ms, [this]() { this->renew_cached_lease_(); });
768 }
769#else
770 const optional<ManualIP> &effective_ip = manual_ip;
771#endif
772
773 if (!effective_ip.has_value()) {
774 // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
775 // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
776 // https://github.com/esphome/issues/issues/2299
777 disable_dhcp_sntp();
778
779 // No manual IP is set; use DHCP client
780 if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
781 err = esp_netif_dhcpc_start(s_sta_netif);
782 if (err != ESP_OK) {
783 ESP_LOGV(TAG, "Starting DHCP client failed: %d", err);
784 }
785 return err == ESP_OK;
786 }
787 return true;
788 }
789
790 esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
791 info.ip = effective_ip->static_ip;
792 info.gw = effective_ip->gateway;
793 info.netmask = effective_ip->subnet;
794 err = esp_netif_dhcpc_stop(s_sta_netif);
795 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
796 ESP_LOGV(TAG, "Stopping DHCP client failed: %s", esp_err_to_name(err));
797 }
798
799 err = esp_netif_set_ip_info(s_sta_netif, &info);
800 if (err != ESP_OK) {
801 ESP_LOGV(TAG, "Setting manual IP info failed: %s", esp_err_to_name(err));
802 }
803
804 esp_netif_dns_info_t dns;
805 if (effective_ip->dns1.is_set()) {
806 dns.ip = effective_ip->dns1;
807 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
808 }
809 if (effective_ip->dns2.is_set()) {
810 dns.ip = effective_ip->dns2;
811 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
812 }
813
814 return true;
815}
816
817#ifdef USE_WIFI_LEASE_CACHE
819 // A cached lease applied as a static IP has no DHCP timing to capture.
820 if (s_sta_netif == nullptr || this->applied_cached_lease_)
821 return;
822
823#ifdef USE_WIFI_MANUAL_IP
824 if (const WiFiAP *config = this->get_selected_sta_(); config && config->has_manual_ip())
825 return;
826#endif
827
828 esp_netif_ip_info_t info;
829 if (esp_netif_get_ip_info(s_sta_netif, &info) != ESP_OK || info.ip.addr == 0)
830 return;
831
832 SavedWifiLeaseSettings lease{};
833 lease.version = SAVED_WIFI_LEASE_VERSION;
834 lease.ap_index = this->selected_sta_index_;
835 lease.ip = info.ip.addr;
836 lease.netmask = info.netmask.addr;
837 lease.gateway = info.gw.addr;
838
839 esp_netif_dns_info_t dns;
840 if (esp_netif_get_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns) == ESP_OK && dns.ip.type == ESP_IPADDR_TYPE_V4) {
841 lease.dns1 = dns.ip.u_addr.ip4.addr;
842 }
843 if (esp_netif_get_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns) == ESP_OK && dns.ip.type == ESP_IPADDR_TYPE_V4) {
844 lease.dns2 = dns.ip.u_addr.ip4.addr;
845 }
846
847 // Lease timing is only in lwIP's internal DHCP state; without it the lease can't be aged.
848 bool have_timing = false;
849 if (auto *impl = static_cast<struct netif *>(esp_netif_get_netif_impl(s_sta_netif))) {
850 LwIPLock lock;
851 if (struct dhcp *d = netif_dhcp_data(impl)) {
852 lease.lease_secs = d->offered_t0_lease;
853 lease.t1_renew = d->offered_t1_renew;
854 have_timing = true;
855 }
856 }
857 if (!have_timing)
858 return;
859
860 lease.saved_at = static_cast<uint32_t>(esp_rtc_get_time_us() / 1000000ULL);
861
862 // On flash, skip a write that would only bump saved_at (an older one only overstates the age),
863 // unless it is from a previous RTC clock period (power cycle).
864#ifdef USE_WIFI_LEASE_CACHE_IN_FLASH
865 constexpr size_t compare_len = offsetof(SavedWifiLeaseSettings, saved_at);
866#else
867 constexpr size_t compare_len = sizeof(SavedWifiLeaseSettings);
868#endif
869 const SavedWifiLeaseSettings &previous = this->cached_lease_;
870 if (previous.saved_at <= lease.saved_at && memcmp(&previous, &lease, compare_len) == 0)
871 return;
872
873 this->lease_cache_pref_.save(&lease);
874 this->cached_lease_ = lease;
875
876 ESP_LOGD(TAG, "Lease cache: saved " IPSTR " (network %d, lease %" PRIu32 "s)", IP2STR(&info.ip), lease.ap_index,
877 lease.lease_secs);
878}
879#endif
880
881esp_netif_t *WiFiComponent::get_esp_netif_sta() { return s_sta_netif; }
882
884 if (!this->has_sta())
885 return {};
886 network::IPAddresses addresses;
887 esp_netif_ip_info_t ip;
888 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
889 if (err != ESP_OK) {
890 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
891 // TODO: do something smarter
892 // return false;
893 } else {
894 addresses[0] = network::IPAddress(&ip.ip);
895 }
896#if USE_NETWORK_IPV6
897 network::fill_ip6_addresses(s_sta_netif, addresses);
898#endif /* USE_NETWORK_IPV6 */
899 return addresses;
900}
901
903 // setting is done in SYSTEM_EVENT_STA_START callback
904 return true;
905}
906const char *get_auth_mode_str(uint8_t mode) {
907 switch (mode) {
908 case WIFI_AUTH_OPEN:
909 return "OPEN";
910 case WIFI_AUTH_WEP:
911 return "WEP";
912 case WIFI_AUTH_WPA_PSK:
913 return "WPA PSK";
914 case WIFI_AUTH_WPA2_PSK:
915 return "WPA2 PSK";
916 case WIFI_AUTH_WPA_WPA2_PSK:
917 return "WPA/WPA2 PSK";
918 case WIFI_AUTH_WPA2_ENTERPRISE:
919 return "WPA2 Enterprise";
920 case WIFI_AUTH_WPA3_PSK:
921 return "WPA3 PSK";
922 case WIFI_AUTH_WPA2_WPA3_PSK:
923 return "WPA2/WPA3 PSK";
924 case WIFI_AUTH_WAPI_PSK:
925 return "WAPI PSK";
926 default:
927 return "UNKNOWN";
928 }
929}
930
931const char *get_disconnect_reason_str(uint8_t reason) {
932 switch (reason) {
933 case WIFI_REASON_AUTH_EXPIRE:
934 return "Auth Expired";
935 case WIFI_REASON_AUTH_LEAVE:
936 return "Auth Leave";
937#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
938 case WIFI_REASON_DISASSOC_DUE_TO_INACTIVITY:
939 return "Disassociated Due to Inactivity";
940#else
941 case WIFI_REASON_ASSOC_EXPIRE:
942 return "Association Expired";
943#endif
944 case WIFI_REASON_ASSOC_TOOMANY:
945 return "Too Many Associations";
946#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
947 case WIFI_REASON_CLASS2_FRAME_FROM_NONAUTH_STA:
948 return "Class 2 Frame from Non-Authenticated STA";
949 case WIFI_REASON_CLASS3_FRAME_FROM_NONASSOC_STA:
950 return "Class 3 Frame from Non-Associated STA";
951#else
952 case WIFI_REASON_NOT_AUTHED:
953 return "Not Authenticated";
954 case WIFI_REASON_NOT_ASSOCED:
955 return "Not Associated";
956#endif
957 case WIFI_REASON_ASSOC_LEAVE:
958 return "Association Leave";
959 case WIFI_REASON_ASSOC_NOT_AUTHED:
960 return "Association not Authenticated";
961 case WIFI_REASON_DISASSOC_PWRCAP_BAD:
962 return "Disassociate Power Cap Bad";
963 case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
964 return "Disassociate Supported Channel Bad";
965 case WIFI_REASON_IE_INVALID:
966 return "IE Invalid";
967 case WIFI_REASON_MIC_FAILURE:
968 return "Mic Failure";
969 case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
970 return "4-Way Handshake Timeout";
971 case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
972 return "Group Key Update Timeout";
973 case WIFI_REASON_IE_IN_4WAY_DIFFERS:
974 return "IE In 4-Way Handshake Differs";
975 case WIFI_REASON_GROUP_CIPHER_INVALID:
976 return "Group Cipher Invalid";
977 case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
978 return "Pairwise Cipher Invalid";
979 case WIFI_REASON_AKMP_INVALID:
980 return "AKMP Invalid";
981 case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
982 return "Unsupported RSN IE version";
983 case WIFI_REASON_INVALID_RSN_IE_CAP:
984 return "Invalid RSN IE Cap";
985 case WIFI_REASON_802_1X_AUTH_FAILED:
986 return "802.1x Authentication Failed";
987 case WIFI_REASON_CIPHER_SUITE_REJECTED:
988 return "Cipher Suite Rejected";
989 case WIFI_REASON_BEACON_TIMEOUT:
990 return "Beacon Timeout";
991 case WIFI_REASON_NO_AP_FOUND:
992 return "AP Not Found";
993 case WIFI_REASON_AUTH_FAIL:
994 return "Authentication Failed";
995 case WIFI_REASON_ASSOC_FAIL:
996 return "Association Failed";
997 case WIFI_REASON_HANDSHAKE_TIMEOUT:
998 return "Handshake Failed";
999 case WIFI_REASON_CONNECTION_FAIL:
1000 return "Connection Failed";
1001 case WIFI_REASON_AP_TSF_RESET:
1002 return "AP TSF reset";
1003 case WIFI_REASON_ROAMING:
1004 return "Station Roaming";
1005 case WIFI_REASON_ASSOC_COMEBACK_TIME_TOO_LONG:
1006 return "Association comeback time too long";
1007 case WIFI_REASON_SA_QUERY_TIMEOUT:
1008 return "SA query timeout";
1009#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
1010 case WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY:
1011 return "No AP found with compatible security";
1012 case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD:
1013 return "No AP found in auth mode threshold";
1014 case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD:
1015 return "No AP found in RSSI threshold";
1016#endif
1017 case WIFI_REASON_UNSPECIFIED:
1018 default:
1019 return "Unspecified";
1020 }
1021}
1022
1023#ifdef USE_WIFI_AP
1024// The driver's own station list cannot drift, so the count is read from it rather than kept by arithmetic
1025static void read_ap_clients(uint8_t &count) {
1026 wifi_sta_list_t sta_list;
1027 if (esp_wifi_ap_get_sta_list(&sta_list) == ESP_OK)
1028 count = sta_list.num;
1029}
1030#endif
1031
1033 // Use pop() directly instead of empty() — pop() costs 1 memw (acquire on tail_),
1034 // while empty() costs 2 memw (acquire on both head_ and tail_) on Xtensa.
1035 IDFWiFiEvent *data = this->event_queue_.pop();
1036 if (data == nullptr)
1037 return false;
1038
1039 do {
1040 wifi_process_event_(data);
1041 delete data; // NOLINT(cppcoreguidelines-owning-memory)
1042 } while ((data = this->event_queue_.pop()) != nullptr);
1043
1044 // Drops only occur when the queue is full, and only this loop drains it,
1045 // so if pop() returned nullptr above we can skip this check.
1046 uint16_t dropped = this->event_queue_.get_and_reset_dropped_count();
1047 if (dropped > 0) {
1048 ESP_LOGW(TAG, "Dropped %u WiFi events due to buffer overflow", dropped);
1049 // The previous AP's leave event may be among them, so it can no longer be told apart
1050 s_expected_disconnect.clear();
1051#ifdef USE_WIFI_AP
1052 // A dropped join or leave is made up for by reading the list again
1053 if (this->ap_setup_)
1054 read_ap_clients(this->ap_clients_);
1055#endif
1056 }
1057 return true;
1058}
1059// Events are processed from queue in main loop context, but listener notifications
1060// must be deferred until after the state machine transitions (in check_connecting_finished)
1061// so that conditions like wifi.connected return correct values in automations.
1062void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
1063 esp_err_t err;
1064 if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
1065 ESP_LOGV(TAG, "STA start");
1066 // apply hostname
1067 err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
1068 if (err != ERR_OK) {
1069 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
1070 }
1071
1072 // re-apply power save mode
1074#ifdef SOC_WIFI_SUPPORT_5G
1076#endif
1077
1078 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
1079 s_expected_disconnect.clear();
1080 ESP_LOGV(TAG, "STA stop");
1081 s_sta_connecting = false;
1082
1083 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
1084 const auto &it = data->data.sta_authmode_change;
1085 ESP_LOGV(TAG, "Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode), get_auth_mode_str(it.new_mode));
1086
1087 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
1088 const auto &it = data->data.sta_connected;
1089 if (s_expected_disconnect.is_previous_ap(it.bssid)) {
1090 ESP_LOGD(TAG, "Ignoring queued connection from previous AP");
1091 return;
1092 }
1093 s_expected_disconnect.clear();
1094#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1095 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1096 format_mac_addr_upper(it.bssid, bssid_buf);
1097 ESP_LOGV(TAG, "Connected ssid='%.*s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", it.ssid_len,
1098 (const char *) it.ssid, bssid_buf, it.channel, get_auth_mode_str(it.authmode));
1099#endif
1100 s_sta_connected = true;
1101#if USE_NETWORK_IPV6
1102 // Start SLAAC on association, not after a DHCPv4 lease that may never arrive.
1103 // Not esp_netif_create_ip6_linklocal(): it returns ESP_FAIL while the netif is down, and this queued event
1104 // can be handled before esp-netif's own STA_CONNECTED handler brings the netif up. lwIP accepts the
1105 // address on a down netif and starts DAD and router solicitation once it comes up.
1106 if (auto *netif = static_cast<struct netif *>(esp_netif_get_netif_impl(s_sta_netif)); netif != nullptr) {
1107 if (esp_err_t err = esp_netif_tcpip_exec(
1108 [](void *ctx) -> esp_err_t {
1109 netif_create_ip6_linklocal_address(static_cast<struct netif *>(ctx), 1);
1110 return ESP_OK;
1111 },
1112 netif);
1113 err != ESP_OK) {
1114 ESP_LOGW(TAG, "IPv6 link-local not created: %s", esp_err_to_name(err));
1115 } else {
1116 ESP_LOGD(TAG, "IPv6 link-local address created");
1117 }
1118 } else {
1119 ESP_LOGW(TAG, "No lwIP netif, IPv6 link-local not created");
1120 }
1121#endif /* USE_NETWORK_IPV6 */
1123 // Driver-initiated roam: the WIFI_REASON_ROAMING disconnect was ignored,
1124 // so the state machine never left STA_CONNECTED.
1125#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
1126 char roam_bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1127 format_mac_addr_upper(it.bssid, roam_bssid_s);
1128 ESP_LOGI(TAG, "Roamed ssid='%.*s' bssid=" LOG_SECRET("%s") " channel=%u", it.ssid_len, (const char *) it.ssid,
1129 roam_bssid_s, it.channel);
1130#endif
1131 bssid_t roam_bssid;
1132 std::copy(it.bssid, it.bssid + 6, roam_bssid.begin());
1133 this->handle_driver_roam_(roam_bssid, it.channel);
1134 }
1135#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
1136 // Defer listener notification until state machine reaches STA_CONNECTED
1137 // This ensures wifi.connected condition returns true in listener automations
1138 this->pending_.connect_state = true;
1139#endif
1140 // For static IP configurations (manual or cached lease), GOT_IP event may not fire, so notify IP listeners here
1141#if defined(USE_WIFI_IP_STATE_LISTENERS) && (defined(USE_WIFI_MANUAL_IP) || defined(USE_WIFI_LEASE_CACHE))
1142 bool static_ip = false;
1143#ifdef USE_WIFI_MANUAL_IP
1144 const WiFiAP *config = this->get_selected_sta_();
1145 static_ip = config && config->has_manual_ip();
1146#endif
1147#ifdef USE_WIFI_LEASE_CACHE
1148 static_ip = static_ip || this->applied_cached_lease_;
1149#endif
1150 if (static_ip) {
1152 }
1153#endif
1154
1155 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
1156 const auto &it = data->data.sta_disconnected;
1157 if (it.reason == WIFI_REASON_ROAMING) {
1158 ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
1159 return;
1160 }
1161 const ExpectedLeave expected = s_expected_disconnect.consume_disconnect(
1162 it.bssid, it.reason == WIFI_REASON_ASSOC_LEAVE || it.reason == WIFI_REASON_STA_LEAVING);
1163 const bool expected_disconnect = expected != ExpectedLeave::EXPECTED_LEAVE_NONE;
1164 if (expected_disconnect) {
1165 ESP_LOGD(TAG, "Expected leave of the previous %s",
1166 expected == ExpectedLeave::EXPECTED_LEAVE_AP ? LOG_STR_LITERAL("AP") : LOG_STR_LITERAL("attempt"));
1167 } else if (it.reason == WIFI_REASON_NO_AP_FOUND) {
1168 ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
1169 (const char *) it.ssid);
1170 s_sta_connect_not_found = true;
1171 } else {
1172 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1173 format_mac_addr_upper(it.bssid, bssid_s);
1174 ESP_LOGW(TAG, "Disconnected ssid='%.*s' bssid=" LOG_SECRET("%s") " reason='%s'", it.ssid_len,
1175 (const char *) it.ssid, bssid_s, get_disconnect_reason_str(it.reason));
1176 s_sta_connect_error = true;
1177 }
1178 s_sta_connected = false;
1179 if (!expected_disconnect) {
1180 s_sta_connecting = false;
1181 this->error_from_callback_ = true;
1182 }
1183 // Refresh is_connected() cache; the old session is no longer connected.
1185#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
1186 // An attempt that never associated ended no session listeners know of
1189#endif
1190
1191#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
1192 } else if (data->event_base == IP_EVENT &&
1193 (data->event_id == IP_EVENT_ETH_GOT_IP || data->event_id == IP_EVENT_PPP_GOT_IP)) {
1194 this->apply_ap_dns_();
1195#endif
1196 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
1197 const auto &it = data->data.ip_got_ip;
1198 esp_netif_ip_info_t current_ip{};
1199 if (!s_sta_connected || !esp_netif_is_netif_up(s_sta_netif) ||
1200 esp_netif_get_ip_info(s_sta_netif, &current_ip) != ESP_OK || current_ip.ip.addr != it.ip_info.ip.addr) {
1201 ESP_LOGV(TAG, "Ignoring stale IPv4 address event");
1202 return;
1203 }
1204 ESP_LOGV(TAG, "static_ip=" IPSTR " gateway=" IPSTR, IP2STR(&it.ip_info.ip), IP2STR(&it.ip_info.gw));
1205 this->got_ipv4_address_ = true;
1206#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_STATIC_DNS)
1207 this->apply_ap_dns_();
1208#endif
1209#ifdef USE_WIFI_LEASE_CACHE
1210 this->save_lease_settings_(); // events are drained on the main loop
1211#endif
1212#ifdef USE_WIFI_IP_STATE_LISTENERS
1214#endif
1215
1216#if USE_NETWORK_IPV6
1217 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
1218 const auto &it = data->data.ip_got_ip6;
1219 if (!s_sta_connected) {
1220 ESP_LOGV(TAG, "Ignoring IPv6 address event before association");
1221 return;
1222 }
1223 esp_ip6_addr_t addresses[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
1224 {
1225 LwIPLock lock;
1226 this->num_ipv6_addresses_ = esp_netif_get_all_ip6(s_sta_netif, addresses);
1227 }
1228 ESP_LOGV(TAG, "IPv6 address=" IPV6STR, IPV62STR(it.ip6_info.ip));
1229#ifdef USE_WIFI_IP_STATE_LISTENERS
1231#endif
1232#endif /* USE_NETWORK_IPV6 */
1233
1234 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
1235 ESP_LOGV(TAG, "Lost IP");
1236 this->got_ipv4_address_ = false;
1237
1238 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
1239 const auto &it = data->data.sta_scan_done;
1240 ESP_LOGV(TAG, "Scan done: status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
1241
1242 uint16_t number = it.number;
1243 const bool filtered = this->is_scan_driver_filtered_();
1244 const bool needs_full = this->needs_full_scan_results_();
1245 {
1246 // Mutate in place under the lock; blocking a portal request is fine and
1247 // avoids scratch buffers
1248 ScanResultsLock lock(this);
1249 this->scan_result_.clear();
1250 this->scan_done_ = true;
1251 if (it.status != 0) {
1252 // scan error
1253 return;
1254 }
1255
1256 if (number == 0) {
1257 // no results
1258 return;
1259 }
1260
1261 const size_t wanted = filtered ? std::min<size_t>(number, WIFI_SCAN_RESULT_BOUND) : number;
1262 // Storage is reused across the scans of one retry cycle and freed on connect; an exhausted
1263 // heap drops this scan and the retry logic scans again
1264 if (this->scan_result_.capacity() < wanted && !this->scan_result_.try_init(wanted)) {
1265 esp_wifi_clear_ap_list();
1266 ESP_LOGW(TAG, "No memory for %zu scan results", wanted);
1267 return;
1268 }
1269
1270#ifdef USE_ESP32_HOSTED
1271 // getting records one at a time fails on P4 with hosted esp32 WiFi coprocessor
1272 // Presumably an upstream bug, work-around by getting all records at once
1273 // Use stack buffer (3904 bytes / ~80 bytes per record = ~48 records) with heap fallback
1274 static constexpr size_t SCAN_RECORD_STACK_COUNT = 3904 / sizeof(wifi_ap_record_t);
1275 SmallBufferWithHeapFallback<SCAN_RECORD_STACK_COUNT, wifi_ap_record_t> records(number);
1276 err = esp_wifi_scan_get_ap_records(&number, records.get());
1277 if (err != ESP_OK) {
1278 esp_wifi_clear_ap_list();
1279 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
1280 return;
1281 }
1282 for (uint16_t i = 0; i < number; i++) {
1283 wifi_ap_record_t &record = records.get()[i];
1284#else
1285 // Process one record at a time to avoid large buffer allocation
1286 for (uint16_t i = 0; i < number; i++) {
1287 wifi_ap_record_t record;
1288 err = esp_wifi_scan_get_ap_record(&record);
1289 if (err != ESP_OK) {
1290 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_record failed: %s", esp_err_to_name(err));
1291 esp_wifi_clear_ap_list(); // Free remaining records not yet retrieved
1292 break;
1293 }
1294#endif // USE_ESP32_HOSTED
1295
1296 const char *ssid_cstr = reinterpret_cast<const char *>(record.ssid);
1297 if (!needs_full && !this->matches_configured_network_(ssid_cstr, record.bssid)) {
1298 this->log_discarded_scan_result_(ssid_cstr, record.bssid, record.rssi, record.primary);
1299 continue;
1300 }
1301 bssid_t bssid;
1302 std::copy(record.bssid, record.bssid + 6, bssid.begin());
1303 if (this->scan_result_.size() < wanted) {
1304 this->scan_result_.emplace_back(bssid, ssid_cstr, strlen(ssid_cstr), record.primary, record.rssi,
1305 record.authmode != WIFI_AUTH_OPEN, ssid_cstr[0] == '\0');
1306 continue;
1307 }
1308 // Records arrive in scan order, not by signal, so a bounded store keeps the strongest by
1309 // replacing its weakest entry. Only SSID and signal decide here; a channel or auth constrained
1310 // network hidden behind 12 stronger APs of its own SSID is not a real deployment
1311 WiFiScanResult *weakest = &this->scan_result_[0];
1312 for (auto &res : this->scan_result_) {
1313 if (res.get_rssi() < weakest->get_rssi())
1314 weakest = &res;
1315 }
1316 if (record.rssi <= weakest->get_rssi()) {
1317 this->log_discarded_scan_result_(ssid_cstr, record.bssid, record.rssi, record.primary);
1318 continue;
1319 }
1320 // Rebuilt in place rather than assigned; assignment pulls in CompactString's operators, 104 B of flash
1321 weakest->~WiFiScanResult();
1322 new (weakest) WiFiScanResult(bssid, ssid_cstr, strlen(ssid_cstr), record.primary, record.rssi,
1323 record.authmode != WIFI_AUTH_OPEN, ssid_cstr[0] == '\0');
1324 }
1325 }
1326 ESP_LOGV(TAG, "Scan complete: %u found, %zu stored%s", number, this->scan_result_.size(),
1327 filtered ? LOG_STR_LITERAL(" (driver filtered)") : LOG_STR_LITERAL(""));
1328#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
1330#endif
1331
1332 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
1333 ESP_LOGV(TAG, "AP start");
1334 this->ap_started_ = true;
1335#ifdef USE_WIFI_AP_WISP
1336 // NAPT needs the interface up, so it cannot be part of the setup. Without it the clients have no way out, so
1337 // the AP goes down and its setup runs again, which brings it back up through this event.
1338 if (esp_err_t err = esp_netif_napt_enable(s_ap_netif); err != ESP_OK) {
1339 ESP_LOGE(TAG, "Failed to enable NAT: %s", esp_err_to_name(err));
1340 this->disable_ap_();
1341 }
1342#endif
1343
1344 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
1345 ESP_LOGV(TAG, "AP stop");
1346 this->ap_started_ = false;
1347
1348 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
1349#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
1350 const auto &it = data->data.ap_probe_req_rx;
1351 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1352 format_mac_addr_upper(it.mac, mac_buf);
1353 ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", mac_buf, it.rssi);
1354#endif
1355
1356 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
1357#ifdef USE_WIFI_AP
1358 read_ap_clients(this->ap_clients_);
1359#endif
1360#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1361 const auto &it = data->data.ap_staconnected;
1362 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1363 format_mac_addr_upper(it.mac, mac_buf);
1364 ESP_LOGV(TAG, "AP client connected MAC=%s", mac_buf);
1365#endif
1366
1367 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
1368#ifdef USE_WIFI_AP
1369 read_ap_clients(this->ap_clients_);
1370#endif
1371#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1372 const auto &it = data->data.ap_stadisconnected;
1373 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1374 format_mac_addr_upper(it.mac, mac_buf);
1375 ESP_LOGV(TAG, "AP client disconnected MAC=%s", mac_buf);
1376#endif
1377
1378#ifdef USE_WIFI_DPP
1379 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_DPP_URI_READY) {
1380 ESP_LOGD(TAG, "DPP URI: %s", this->dpp_uri_.get());
1381#ifdef USE_WIFI_DPP_URI_TRIGGER
1382 this->dpp_uri_callback_.call(this->dpp_uri_.get());
1383#endif
1384
1385 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_DPP_CFG_RECVD) {
1386 const std::unique_ptr<SavedWifiSettings> credentials(data->data.dpp_credentials);
1387 this->dpp_listening_ = false;
1388 ESP_LOGI(TAG, "DPP configured network " LOG_SECRET("'%s'"), credentials->ssid);
1389 // The reboot timer starts over for the connect attempt, as after a boot with saved credentials
1391 // Saved like portal credentials; from a cooldown this already restarts the retries
1392 this->save_wifi_sta(credentials->ssid, credentials->password);
1394 // Without networks the station machine was never started; an AP without a portal sits in AP
1395 this->start_connecting(*this->get_selected_sta_());
1396 }
1397
1398 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_DPP_FAILED) {
1399 this->dpp_listening_ = false;
1400 ESP_LOGW(TAG, "DPP failed: %s", esp_err_to_name(data->data.dpp_failed.failure_reason));
1401#endif // USE_WIFI_DPP
1402
1403#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
1404 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
1405 const auto &it = data->data.ip_assigned_ip_to_client;
1406#else
1407 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
1408 const auto &it = data->data.ip_ap_staipassigned;
1409#endif
1410 ESP_LOGV(TAG, "AP client assigned IP " IPSTR, IP2STR(&it.ip));
1411 }
1412}
1413
1415 if (s_sta_connected && this->got_ipv4_address_) {
1416#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
1417 if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
1419 }
1420#else
1422#endif /* USE_NETWORK_IPV6 */
1423 }
1424 if (s_sta_connect_error) {
1426 }
1427 if (s_sta_connect_not_found) {
1429 }
1430 if (s_sta_connecting) {
1432 }
1434}
1435bool WiFiComponent::wifi_scan_start_(bool passive) {
1436 // enable STA
1437 if (!this->wifi_mode_(true, {}))
1438 return false;
1439
1440 wifi_scan_config_t config{};
1441 config.ssid = nullptr;
1442 config.bssid = nullptr;
1443#ifndef USE_WIFI_MULTI_SSID
1444 // One configured network with an SSID: let the driver keep only its APs, so the WiFi library
1445 // holds fewer records during the scan. Full results (portal, provisioning, listeners) and a
1446 // network configured by BSSID alone still scan everything
1447 this->scan_driver_filtered_ =
1448 !this->needs_full_scan_results_() && this->sta_.size() == 1 && !this->sta_[0].get_ssid().empty();
1449 if (this->scan_driver_filtered_) {
1450 config.ssid = const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(this->sta_[0].get_ssid().c_str()));
1451 }
1452#endif
1453 config.channel = 0;
1454 config.show_hidden = true;
1455 config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
1456 if (passive) {
1457 config.scan_time.passive = 300;
1458 } else {
1459 config.scan_time.active.min = 100;
1460 config.scan_time.active.max = 300;
1461 }
1462 // When scanning while connected (roaming), return to home channel between
1463 // each scanned channel to maintain the connection (helps with BLE/WiFi coexistence)
1464#ifdef CONFIG_SOC_WIFI_SUPPORTED
1465 if (this->is_roaming_scan_active()) {
1466 config.coex_background_scan = true;
1467 }
1468#endif
1469
1470 esp_err_t err = esp_wifi_scan_start(&config, false);
1471 if (err != ESP_OK) {
1472 ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
1473 return false;
1474 }
1475
1476 this->scan_done_ = false;
1477 return true;
1478}
1479
1480#ifdef USE_WIFI_AP
1481bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
1482 esp_err_t err;
1483
1484 // Check if the AP interface is initialized before using it
1485 if (s_ap_netif == nullptr) {
1486 ESP_LOGW(TAG, "AP interface not initialized");
1487 return false;
1488 }
1489
1490 esp_netif_ip_info_t info;
1491 if (manual_ip.has_value()) {
1492 info.ip = manual_ip->static_ip;
1493 info.gw = manual_ip->gateway;
1494 info.netmask = manual_ip->subnet;
1495 } else {
1496 info.ip = network::IPAddress(192, 168, 4, 1);
1497 info.gw = network::IPAddress(192, 168, 4, 1);
1498 info.netmask = network::IPAddress(255, 255, 255, 0);
1499 }
1500
1501 err = esp_netif_dhcps_stop(s_ap_netif);
1502 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
1503 ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
1504 return false;
1505 }
1506
1507 err = esp_netif_set_ip_info(s_ap_netif, &info);
1508 if (err != ESP_OK) {
1509 ESP_LOGE(TAG, "esp_netif_set_ip_info failed: %d", err);
1510 return false;
1511 }
1512
1513 dhcps_lease_t lease;
1514 lease.enable = true;
1515 network::IPAddress start_address = network::IPAddress(&info.ip);
1516 start_address += 99;
1517 lease.start_ip = start_address;
1518#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1519 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1520#endif
1521 ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str_to(ip_buf));
1522 start_address += 10;
1523 lease.end_ip = start_address;
1524 ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str_to(ip_buf));
1525 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
1526
1527 if (err != ESP_OK) {
1528 ESP_LOGE(TAG, "esp_netif_dhcps_option failed: %d", err);
1529 return false;
1530 }
1531
1532#if (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE)) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
1533 // DHCP option 114 (captive portal URI) lets clients find the portal; either define means one exists
1534 // Buffer must be static - dhcps_set_option_info stores pointer, doesn't copy
1535 static char captive_portal_uri[24]; // "http://" (7) + IPv4 max (15) + null
1536 memcpy(captive_portal_uri, "http://", 7); // NOLINT(bugprone-not-null-terminated-result) - str_to null-terminates
1537 network::IPAddress(&info.ip).str_to(captive_portal_uri + 7);
1538 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_CAPTIVEPORTAL_URI, captive_portal_uri,
1539 strlen(captive_portal_uri));
1540 if (err != ESP_OK) {
1541 ESP_LOGV(TAG, "Failed to set DHCP captive portal URI: %s", esp_err_to_name(err));
1542 } else {
1543 ESP_LOGV(TAG, "DHCP Captive Portal URI set to: %s", captive_portal_uri);
1544 }
1545#endif
1546
1547#ifdef USE_WIFI_AP_WISP
1548 // Offer resolvers through DHCP: the configured ones, otherwise the station's (with a portal, the AP's own
1549 // address while there is none). A failure fails the setup and it is tried again.
1550 uint8_t dns_offer = 1;
1551 err =
1552 esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_DOMAIN_NAME_SERVER, &dns_offer, sizeof(dns_offer));
1553 if (err != ESP_OK) {
1554 ESP_LOGE(TAG, "Failed to enable DHCP DNS option: %s", esp_err_to_name(err));
1555 }
1556 if (err != ESP_OK || !this->write_ap_dns_())
1557 return false;
1558#endif
1559
1560 err = esp_netif_dhcps_start(s_ap_netif);
1561 // Before the access point is up, its start event brings the server up with these settings
1562 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_IF_NOT_READY) {
1563 ESP_LOGE(TAG, "esp_netif_dhcps_start failed: %d", err);
1564 return false;
1565 }
1566
1567 return true;
1568}
1569
1570bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
1571 // The address and DHCP settings go in before the access point starts: its start event starts the DHCP
1572 // server on the event task, and settings written after that race it.
1573#ifdef USE_WIFI_MANUAL_IP
1574 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
1575#else
1576 if (!this->wifi_ap_ip_config_({})) {
1577#endif
1578 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed:");
1579 return false;
1580 }
1581
1582 // enable AP
1583 if (!this->wifi_mode_({}, true))
1584 return false;
1585
1586 wifi_config_t conf;
1587 memset(&conf, 0, sizeof(conf));
1588 if (ap.ssid_.size() > sizeof(conf.ap.ssid)) {
1589 ESP_LOGE(TAG, "AP SSID too long");
1590 return false;
1591 }
1592 memcpy(reinterpret_cast<char *>(conf.ap.ssid), ap.ssid_.c_str(), ap.ssid_.size());
1593 conf.ap.channel = ap.has_channel() ? ap.get_channel() : 1;
1594 conf.ap.ssid_hidden = ap.get_hidden();
1595 conf.ap.max_connection = 5;
1596 conf.ap.beacon_interval = 100;
1597
1598 if (ap.password_.empty()) {
1599 conf.ap.authmode = WIFI_AUTH_OPEN;
1600 *conf.ap.password = 0;
1601 } else {
1602 conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
1603 if (ap.password_.size() > sizeof(conf.ap.password)) {
1604 ESP_LOGE(TAG, "AP password too long");
1605 return false;
1606 }
1607 memcpy(reinterpret_cast<char *>(conf.ap.password), ap.password_.c_str(), ap.password_.size());
1608 }
1609
1610 // pairwise cipher of SoftAP, group cipher will be derived using this.
1611 conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
1612
1613 esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
1614 if (err != ESP_OK) {
1615 ESP_LOGE(TAG, "esp_wifi_set_config failed: %d", err);
1616 return false;
1617 }
1618 return true;
1619}
1620
1621network::IPAddress WiFiComponent::wifi_soft_ap_ip() {
1622 esp_netif_ip_info_t ip;
1623 esp_netif_get_ip_info(s_ap_netif, &ip);
1624 return network::IPAddress(&ip.ip);
1625}
1626#endif // USE_WIFI_AP
1627
1628#ifdef USE_WIFI_DPP
1630 esp_err_t err = esp_supp_dpp_start_listen();
1631 if (err != ESP_OK) {
1632 ESP_LOGW(TAG, "%s failed: %s", LOG_STR_LITERAL("esp_supp_dpp_start_listen"), esp_err_to_name(err));
1633 return false;
1634 }
1635 ESP_LOGD(TAG, "DPP listening for a configurator");
1636 return true;
1637}
1638
1639void WiFiComponent::wifi_dpp_stop_listen_() { esp_supp_dpp_stop_listen(); }
1640#endif
1641
1643 // Leave the AP before esp_restart() or deep sleep stops Wi-Fi. esp_wifi_stop() while associated
1644 // makes the ESP32 retransmit its Disassociation up to the retry limit although the AP ACKs it
1645 // (32 copies with protected management frames), which some APs handle badly.
1646 // Upstream bug: https://github.com/espressif/esp-idf/issues/19443 - remove this once it is fixed
1647 // in the ESP-IDF versions we support.
1648 // Ask the driver: s_sta_connected lags until the main loop has handled the connect event.
1649 wifi_ap_record_t ap_info;
1650 if (esp_wifi_sta_get_ap_info(&ap_info) != ESP_OK)
1651 return;
1652 ESP_LOGD(TAG, "Disconnecting before powerdown");
1653 esp_wifi_disconnect();
1654 delay(100); // NOLINT: once per reboot or deep sleep, lets the disassociation go out
1655}
1656
1657bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
1658
1660 bssid_t bssid{};
1661 wifi_ap_record_t info;
1662 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1663 if (err != ESP_OK) {
1664 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1665 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1666 return bssid;
1667 }
1668 std::copy(info.bssid, info.bssid + 6, bssid.begin());
1669 return bssid;
1670}
1671const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
1672 wifi_ap_record_t info{};
1673 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1674 if (err != ESP_OK) {
1675 buffer[0] = '\0';
1676 return buffer.data();
1677 }
1678 // info.ssid is uint8[33], but only 32 bytes are SSID data
1679 size_t len = strnlen(reinterpret_cast<const char *>(info.ssid), 32);
1680 memcpy(buffer.data(), info.ssid, len);
1681 buffer[len] = '\0';
1682 return buffer.data();
1683}
1684int8_t WiFiComponent::wifi_rssi() {
1685 wifi_ap_record_t info;
1686 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1687 if (err != ESP_OK) {
1688 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1689 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1690 return WIFI_RSSI_DISCONNECTED;
1691 }
1692 return info.rssi;
1693}
1695 uint8_t primary;
1696 wifi_second_chan_t second;
1697 esp_err_t err = esp_wifi_get_channel(&primary, &second);
1698 if (err != ESP_OK) {
1699 ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
1700 return 0;
1701 }
1702 return primary;
1703}
1704network::IPAddress WiFiComponent::wifi_subnet_mask_() {
1705 esp_netif_ip_info_t ip;
1706 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1707 if (err != ESP_OK) {
1708 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1709 return {};
1710 }
1711 return network::IPAddress(&ip.netmask);
1712}
1713network::IPAddress WiFiComponent::wifi_gateway_ip_() {
1714 esp_netif_ip_info_t ip;
1715 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1716 if (err != ESP_OK) {
1717 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1718 return {};
1719 }
1720 return network::IPAddress(&ip.gw);
1721}
1722network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
1723 const ip_addr_t *dns_ip = dns_getserver(num);
1724 return network::IPAddress(dns_ip);
1725}
1726
1727#ifdef USE_WIFI_AP_WISP
1728// A DHCP server interface takes a backup resolver from ESP-IDF 6.0
1729#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
1730static constexpr size_t AP_DNS_COUNT = 2;
1731#else
1732static constexpr size_t AP_DNS_COUNT = 1;
1733#endif
1734#ifdef USE_WIFI_AP_WISP_STATIC_DNS
1735// The configured resolvers as lwIP stores them, from codegen
1736static constexpr uint32_t AP_DNS[] = {
1737 WIFI_AP_WISP_DNS_0,
1738#ifdef WIFI_AP_WISP_DNS_1
1739 WIFI_AP_WISP_DNS_1,
1740#endif
1741};
1742#endif
1743
1744static uint32_t upstream_dns(size_t i) {
1745#ifdef USE_WIFI_AP_WISP_STATIC_DNS
1746 return i < std::size(AP_DNS) ? AP_DNS[i] : 0;
1747#else
1748 return ip_addr_get_ip4_u32(dns_getserver(i));
1749#endif
1750}
1751
1752static uint32_t ap_dns_to_offer(size_t i, [[maybe_unused]] bool own) {
1753#ifdef USE_WIFI_AP_WISP_PORTAL
1754 if (own) {
1755 esp_netif_ip_info_t ip{};
1756 if (s_ap_netif != nullptr && esp_netif_get_ip_info(s_ap_netif, &ip) == ESP_OK)
1757 return ip.ip.addr;
1758 ESP_LOGW(TAG, "Failed to read the AP address to offer as resolver");
1759 return 0;
1760 }
1761 // A slot the upstream leaves empty repeats the primary, so the AP's own address is replaced there too
1762 const uint32_t addr = upstream_dns(i);
1763 return addr != 0 ? addr : upstream_dns(0);
1764#else
1765 return upstream_dns(i);
1766#endif
1767}
1768
1769bool WiFiComponent::ap_dns_known_() { return upstream_dns(0) != 0; }
1770
1771#ifdef USE_WIFI_AP_WISP_PORTAL
1773 return !this->ap_dns_known_() || (this->has_sta() && this->is_ap_portal_active_());
1774}
1775#endif
1776
1778#ifdef USE_WIFI_AP_WISP_PORTAL
1779 const bool own = this->offer_own_dns_();
1780 this->ap_offers_own_dns_ = own;
1781#else
1782 const bool own = false;
1783#endif
1784 bool ok = true;
1785 for (size_t i = 0; i < AP_DNS_COUNT; i++) {
1786 const uint32_t addr = ap_dns_to_offer(i, own);
1787 if (addr == 0) {
1788 ok = ok && !own; // the AP's own address could not be read
1789 continue;
1790 }
1791 esp_netif_dns_info_t info{};
1792 info.ip.type = ESP_IPADDR_TYPE_V4;
1793 info.ip.u_addr.ip4.addr = addr;
1794 esp_err_t err = esp_netif_set_dns_info(s_ap_netif, static_cast<esp_netif_dns_type_t>(i), &info);
1795 if (err != ESP_OK) {
1796 ESP_LOGW(TAG, "Failed to set DHCP DNS server %u: %s", (unsigned) i, esp_err_to_name(err));
1797 ok = false;
1798 } else {
1799 ESP_LOGV(TAG, "DHCP DNS server: " IPSTR, IP2STR(&info.ip.u_addr.ip4));
1800 }
1801 }
1802 return ok;
1803}
1804
1805#ifndef USE_WIFI_AP_WISP_STATIC_DNS
1807 if (!this->ap_setup_)
1808 return; // loop() brings the AP up, and its setup writes the resolvers
1809 // The DHCP server holds what it offers, so there is nothing to cache; a failed update is noticed again with the
1810 // next lease. A resolver the station lost stays offered (set_dns_info rejects an empty address), or with a
1811 // portal gives way to the AP's own address.
1812#ifdef USE_WIFI_AP_WISP_PORTAL
1813 const bool own = this->offer_own_dns_();
1814#else
1815 const bool own = false;
1816#endif
1817 bool changed = false;
1818 for (size_t i = 0; i < AP_DNS_COUNT && !changed; i++) {
1819 const uint32_t addr = ap_dns_to_offer(i, own);
1820 esp_netif_dns_info_t current{};
1821 // A missing own address goes through the setup too, which then fails and restarts the AP
1822 changed =
1823 (addr == 0 && own) ||
1824 (addr != 0 && (esp_netif_get_dns_info(s_ap_netif, static_cast<esp_netif_dns_type_t>(i), &current) != ESP_OK ||
1825 current.ip.u_addr.ip4.addr != addr));
1826 }
1827 if (!changed)
1828 return;
1829#ifdef USE_WIFI_AP_WISP_PORTAL
1830 // Clients rejoin whenever the offer switches between the AP's own address and the upstream's resolver
1831 const bool offered_own = this->ap_offers_own_dns_;
1832#endif
1833 // The IP setup programs the DHCP server from scratch without touching the soft AP, so clients stay joined
1834#ifdef USE_WIFI_MANUAL_IP
1835 const bool ok = this->wifi_ap_ip_config_(this->ap_.get_manual_ip());
1836#else
1837 const bool ok = this->wifi_ap_ip_config_({});
1838#endif
1839 if (!ok) {
1840 this->disable_ap_();
1841 return;
1842 }
1843#ifdef USE_WIFI_AP_WISP_PORTAL
1844 if (offered_own != this->ap_offers_own_dns_)
1845 this->drop_ap_clients_();
1846#endif
1847}
1848
1849#ifdef USE_WIFI_AP_WISP_PORTAL
1850void WiFiComponent::drop_ap_clients_(uint8_t attempt) {
1851 static constexpr uint8_t MAX_ATTEMPTS = 5;
1852 if (!this->ap_setup_)
1853 return;
1854 esp_err_t err = esp_wifi_deauth_sta(0);
1855 if (err == ESP_OK)
1856 return;
1857 if (attempt + 1 >= MAX_ATTEMPTS) {
1858 ESP_LOGW(TAG, "Failed to drop AP clients so they pick up the new resolver: %s; restarting AP",
1859 esp_err_to_name(err));
1860 this->disable_ap_(); // loop() starts it again, and the clients rejoin
1861 return;
1862 }
1863 ESP_LOGW(TAG, "Failed to drop AP clients so they pick up the new resolver: %s; retrying", esp_err_to_name(err));
1864 this->set_timeout(AP_DEAUTH_RETRY_TIMEOUT_ID, 1000, [this, attempt]() { this->drop_ap_clients_(attempt + 1); });
1865}
1866#endif
1867#endif // USE_WIFI_AP_WISP_STATIC_DNS
1868#endif // USE_WIFI_AP_WISP
1869
1870} // namespace esphome::wifi
1871#endif // USE_ESP32
1872#endif
BedjetMode mode
BedJet operating mode.
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
uint16_t get_and_reset_dropped_count()
bool push(T *element)
constexpr const char * c_str() const
Definition string_ref.h:78
optional< ManualIP > get_manual_ip() const
void notify_scan_results_listeners_()
Notify scan results listeners with current scan results.
void set_ap(const WiFiAP &ap)
Setup an Access Point that should be created if no connection to a station can be made.
void set_sta(const WiFiAP &ap)
const WiFiAP * get_selected_sta_() const
WiFiSTAConnectStatus wifi_sta_connect_status_() const
void set_last_connected_(uint32_t now)
void save_wifi_sta(const std::string &ssid, const std::string &password)
SavedWifiLeaseSettings cached_lease_
wifi_scan_vector_t< WiFiScanResult > scan_result_
void notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
void start_connecting(const WiFiAP &ap)
ESPPreferenceObject lease_cache_pref_
bool wifi_sta_ip_config_(const optional< ManualIP > &manual_ip)
esp_netif_t * get_esp_netif_sta()
esp_netif handle of the station interface, used by network for default-route arbitration.
bool ap_dns_known_()
Whether there is an IPv4 resolver to offer AP clients: a configured one, or the station's.
void drop_ap_clients_(uint8_t attempt=0)
Disconnect the AP clients so they rejoin with the resolver now offered; a few retries,...
void apply_ap_dns_()
Pass the station's resolvers on to AP clients when they changed.
void wifi_process_event_(IDFWiFiEvent *data)
bool lease_valid_for_apply_() const
void notify_disconnect_state_listeners_()
Notify connect state listeners of disconnection.
friend void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
void log_discarded_scan_result_(const char *ssid, const uint8_t *bssid, int8_t rssi, uint8_t channel)
Log a discarded scan result at VERBOSE level (skipped during roaming scans to avoid log overflow)
const char * wifi_ssid_to(std::span< char, SSID_BUFFER_SIZE > buffer)
Write SSID to buffer without heap allocation.
CallbackManager< void(const char *)> dpp_uri_callback_
bool is_roaming_scan_active() const
True while a post-connect roaming scan holds the radio off-channel.
bool is_ap_portal_active_()
captive_portal or the web_server AP mode is serving a user on the access point
bool offer_own_dns_()
DHCP offers the AP's own address while the portal is up for a station that is down,...
network::IPAddress wifi_dns_ip_(int num)
bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const
void disable_ap_()
End the portals and turn the AP off.
FixedVector< WiFiAP > sta_
bool wifi_ap_ip_config_(const optional< ManualIP > &manual_ip)
bool needs_full_scan_results_() const
Check if full scan results are needed (captive portal active, improv, listeners)
LockFreeQueue< IDFWiFiEvent, 17 > event_queue_
StaticVector< WiFiPowerSaveListener *, ESPHOME_WIFI_POWER_SAVE_LISTENERS > power_save_listeners_
bool wifi_apply_output_power_(float output_power)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
network::IPAddresses wifi_sta_ip_addresses()
std::unique_ptr< char[]> dpp_uri_
void handle_driver_roam_(const bssid_t &bssid, uint8_t channel)
Redo post-connect bookkeeping after a driver-initiated roam (e.g.
bool write_ap_dns_()
Hand the AP DHCP server its resolvers; false when one could not be set.
struct esphome::wifi::WiFiComponent::@199 pending_
uint8_t second
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
mopeka_std_values val[3]
const char * esp_err_to_name(esp_err_t err)
std::span< const uint8_t > data
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:368
void fill_ip6_addresses(esp_netif_t *netif, IPAddresses &addresses)
Copies the IPv6 addresses of an esp_netif into addresses[1..], warning once when some do not fit.
Definition util.cpp:13
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
ESPHOME_LOG_TAG(TAG, "wifi")
const LogString * get_disconnect_reason_str(uint8_t reason)
ExpectedLeave
Which expected leave a disconnect matched.
@ EXPECTED_LEAVE_ATTEMPT
An attempt that never associated, so no BSSID.
WiFiComponent * global_wifi_component
@ WIFI_COMPONENT_STATE_AP
WiFi is in AP-only mode and internal AP is already enabled.
@ WIFI_COMPONENT_STATE_OFF
Nothing has been initialized yet.
@ WIFI_COMPONENT_STATE_STA_CONNECTED
WiFi is in STA(+AP) mode and successfully connected.
const void size_t len
Definition hal.h:68
ESPPreferences * global_preferences
const void * src
Definition hal.h:68
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
struct esp_netif_obj esp_netif_t
static void uint32_t
uint8_t event_id
Definition tt21100.cpp:3
SemaphoreHandle_t lock