ESPHome 2026.6.3
Loading...
Searching...
No Matches
wifi_component_esp_idf.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2
3#ifdef USE_WIFI
4#ifdef USE_ESP32
5
6#include <esp_event.h>
7#include <esp_netif.h>
8#include <esp_system.h>
9#include <esp_wifi.h>
10#include <esp_wifi_types.h>
11#include <freertos/FreeRTOS.h>
12#include <freertos/event_groups.h>
13#include <freertos/task.h>
14
15#include <algorithm>
16#include <cinttypes>
17#include <memory>
18#include <utility>
19#ifdef USE_WIFI_WPA2_EAP
20#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
21#include <esp_eap_client.h>
22#else
23#include <esp_wpa2.h>
24#endif
25#endif
26
27#ifdef USE_WIFI_AP
28#include "dhcpserver/dhcpserver.h"
29#endif // USE_WIFI_AP
30
31#ifdef USE_CAPTIVE_PORTAL
33#endif
34
35#include "lwip/apps/sntp.h"
36#include "lwip/dns.h"
37#include "lwip/err.h"
38
40#include "esphome/core/hal.h"
42#include "esphome/core/log.h"
43#include "esphome/core/util.h"
44
45namespace esphome::wifi {
46
47static const char *const TAG = "wifi_esp32";
48
49static EventGroupHandle_t s_wifi_event_group; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
51#ifdef USE_WIFI_AP
52static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
53#endif // USE_WIFI_AP
54static bool s_sta_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
55static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
56static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
57static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
58static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
59static bool s_wifi_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
60
61struct IDFWiFiEvent {
62 esp_event_base_t event_base;
63 int32_t event_id;
64 union {
65 wifi_event_sta_scan_done_t sta_scan_done;
66 wifi_event_sta_connected_t sta_connected;
67 wifi_event_sta_disconnected_t sta_disconnected;
68 wifi_event_sta_authmode_change_t sta_authmode_change;
69 wifi_event_ap_staconnected_t ap_staconnected;
70 wifi_event_ap_stadisconnected_t ap_stadisconnected;
71 wifi_event_ap_probe_req_rx_t ap_probe_req_rx;
72 wifi_event_bss_rssi_low_t bss_rssi_low;
73 ip_event_got_ip_t ip_got_ip;
74#if USE_NETWORK_IPV6
75 ip_event_got_ip6_t ip_got_ip6;
76#endif /* USE_NETWORK_IPV6 */
77#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
78 ip_event_assigned_ip_to_client_t ip_assigned_ip_to_client;
79#else
80 ip_event_ap_staipassigned_t ip_ap_staipassigned;
81#endif
82 } data;
83};
84
85// general design: event handler translates events and pushes them to a queue,
86// events get processed in the main loop
87void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
88 IDFWiFiEvent event;
89 memset(&event, 0, sizeof(IDFWiFiEvent));
90 event.event_base = event_base;
91 event.event_id = event_id;
92 if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { // NOLINT(bugprone-branch-clone)
93 // no data
94 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_STOP) { // NOLINT(bugprone-branch-clone)
95 // no data
96 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
97 memcpy(&event.data.sta_authmode_change, event_data, sizeof(wifi_event_sta_authmode_change_t));
98 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) {
99 memcpy(&event.data.sta_connected, event_data, sizeof(wifi_event_sta_connected_t));
100 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
101 memcpy(&event.data.sta_disconnected, event_data, sizeof(wifi_event_sta_disconnected_t));
102 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
103 memcpy(&event.data.ip_got_ip, event_data, sizeof(ip_event_got_ip_t));
104#if USE_NETWORK_IPV6
105 } else if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
106 memcpy(&event.data.ip_got_ip6, event_data, sizeof(ip_event_got_ip6_t));
107#endif
108 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) { // NOLINT(bugprone-branch-clone)
109 // no data
110 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
111 memcpy(&event.data.sta_scan_done, event_data, sizeof(wifi_event_sta_scan_done_t));
112 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) { // NOLINT(bugprone-branch-clone)
113 // no data
114 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STOP) { // NOLINT(bugprone-branch-clone)
115 // no data
116 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
117 memcpy(&event.data.ap_probe_req_rx, event_data, sizeof(wifi_event_ap_probe_req_rx_t));
118 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
119 memcpy(&event.data.ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t));
120 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
121 memcpy(&event.data.ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t));
122#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
123 } else if (event_base == IP_EVENT && event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
124 memcpy(&event.data.ip_assigned_ip_to_client, event_data, sizeof(ip_event_assigned_ip_to_client_t));
125#else
126 } else if (event_base == IP_EVENT && event_id == IP_EVENT_AP_STAIPASSIGNED) {
127 memcpy(&event.data.ip_ap_staipassigned, event_data, sizeof(ip_event_ap_staipassigned_t));
128#endif
129 } else {
130 // did not match any event, don't send anything
131 return;
132 }
133
134 // copy to heap — WiFi events are rare so heap alloc is fine
135 auto *to_send = new IDFWiFiEvent; // NOLINT(cppcoreguidelines-owning-memory)
136 memcpy(to_send, &event, sizeof(IDFWiFiEvent));
137 if (!global_wifi_component->event_queue_.push(to_send)) {
138 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
139 }
140}
141
143 uint8_t mac[6];
146 set_mac_address(mac);
147 }
148 // Network interface setup handled by network component
149 s_wifi_event_group = xEventGroupCreate();
150 if (s_wifi_event_group == nullptr) {
151 ESP_LOGE(TAG, "xEventGroupCreate failed");
152 return;
153 }
154 esp_event_handler_instance_t instance_wifi_id, instance_ip_id;
155 esp_err_t err =
156 esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_wifi_id);
157 if (err != ERR_OK) {
158 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
159 return;
160 }
161 err = esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_ip_id);
162 if (err != ERR_OK) {
163 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
164 return;
165 }
166 // NOTE: netif creation + esp_wifi_init() used to live here. They allocate ~15-30KB of
167 // DMA-capable internal SRAM, which competes with W5500 SPI DMA and I2S DMA on
168 // memory-tight devices. They are now deferred to wifi_lazy_init_(), called from
169 // setup() when enable_on_boot_ is true, or from enable() on first runtime enable.
170 // This makes enable_on_boot:false genuinely skip the wifi DMA allocation.
171}
172
174 if (this->wifi_initialized_)
175 return;
176
177 // Guard each creation so partial init (e.g. a failed esp_wifi_init() below)
178 // followed by a retry via enable() does not leak the existing netif handle
179 // nor re-register the default WiFi handlers.
180 if (s_sta_netif == nullptr)
181 s_sta_netif = esp_netif_create_default_wifi_sta();
182 if (s_sta_netif == nullptr) {
183 // Allocation failed; leave wifi_initialized_ false so a later enable() retries.
184 ESP_LOGE(TAG, "esp_netif_create_default_wifi_sta failed");
185 return;
186 }
187
188#ifdef USE_WIFI_AP
189 if (s_ap_netif == nullptr)
190 s_ap_netif = esp_netif_create_default_wifi_ap();
191#endif // USE_WIFI_AP
192
193 // The WiFi driver was started (e.g. by ESP-NOW with the wifi component disabled at
194 // boot) before our STA netif existed. The default WIFI_EVENT_STA_START handler
195 // therefore ran with no netif and never called esp_wifi_register_if_rxcb() -- the
196 // only thing that points the driver's RX path at a netif (it sets
197 // s_wifi_netifs[WIFI_IF_STA]). A bare esp_netif_action_start() would stop the
198 // immediate crash (#17232) but leaves RX unbound, so the first association
199 // associates at L2 yet never receives DHCP replies and times out (#17239). Restart
200 // the driver now that the netif exists so STA_START re-runs the default handler and
201 // wires RX correctly. ESP-NOW survives the stop/start (its peer state persists).
202 // This also matches a self-retry: if esp_wifi_set_storage() below failed on a
203 // previous wifi_lazy_init_() it returned without setting wifi_initialized_, and
204 // esp_wifi_init() has since run, so esp_wifi_get_mode() now succeeds here too.
205 wifi_mode_t mode;
206 if (esp_wifi_get_mode(&mode) == ESP_OK) {
207 ESP_LOGD(TAG, "WiFi driver already started without STA netif; restarting to bind it");
208 esp_err_t err = esp_wifi_stop();
209 if (err != ESP_OK) {
210 ESP_LOGW(TAG, "esp_wifi_stop failed: %s", esp_err_to_name(err));
211 }
212 // Re-apply RAM storage; the normal init path does this, but it is skipped on
213 // the self-retry case above, which would otherwise let the driver persist
214 // credentials to NVS for the rest of the boot.
215 err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
216 if (err != ESP_OK) {
217 ESP_LOGW(TAG, "esp_wifi_set_storage failed: %s", esp_err_to_name(err));
218 }
219 err = esp_wifi_start();
220 if (err != ESP_OK) {
221 ESP_LOGE(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
222 return;
223 }
224 s_wifi_started = true;
225 this->wifi_initialized_ = true;
226 return;
227 }
228
229 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
230 if (global_preferences->nvs_handle == 0) {
231 ESP_LOGW(TAG, "starting wifi without nvs");
232 cfg.nvs_enable = false;
233 }
234 esp_err_t err = esp_wifi_init(&cfg);
235 if (err != ERR_OK) {
236 ESP_LOGE(TAG, "esp_wifi_init failed: %s", esp_err_to_name(err));
237 return;
238 }
239 err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
240 if (err != ERR_OK) {
241 ESP_LOGE(TAG, "esp_wifi_set_storage failed: %s", esp_err_to_name(err));
242 return;
243 }
244 this->wifi_initialized_ = true;
245}
246
247bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
248 esp_err_t err;
249 wifi_mode_t current_mode = WIFI_MODE_NULL;
250 if (s_wifi_started) {
251 err = esp_wifi_get_mode(&current_mode);
252 if (err != ERR_OK) {
253 ESP_LOGW(TAG, "esp_wifi_get_mode failed: %s", esp_err_to_name(err));
254 return false;
255 }
256 }
257 bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA;
258 bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA;
259
260 bool set_sta = sta.value_or(current_sta);
261 bool set_ap = ap.value_or(current_ap);
262
263 wifi_mode_t set_mode;
264 if (set_sta && set_ap) {
265 set_mode = WIFI_MODE_APSTA;
266 } else if (set_sta && !set_ap) {
267 set_mode = WIFI_MODE_STA;
268 } else if (!set_sta && set_ap) {
269 set_mode = WIFI_MODE_AP;
270 } else {
271 set_mode = WIFI_MODE_NULL;
272 }
273
274 if (current_mode == set_mode)
275 return true;
276
277 if (set_sta && !current_sta) {
278 ESP_LOGV(TAG, "Enabling STA");
279 } else if (!set_sta && current_sta) {
280 ESP_LOGV(TAG, "Disabling STA");
281 }
282 if (set_ap && !current_ap) {
283 ESP_LOGV(TAG, "Enabling AP");
284 } else if (!set_ap && current_ap) {
285 ESP_LOGV(TAG, "Disabling AP");
286 }
287
288 if (set_mode == WIFI_MODE_NULL && s_wifi_started) {
289 err = esp_wifi_stop();
290 if (err != ESP_OK) {
291 ESP_LOGV(TAG, "esp_wifi_stop failed: %s", esp_err_to_name(err));
292 return false;
293 }
294 s_wifi_started = false;
295 return true;
296 }
297
298 err = esp_wifi_set_mode(set_mode);
299 if (err != ERR_OK) {
300 ESP_LOGW(TAG, "esp_wifi_set_mode failed: %s", esp_err_to_name(err));
301 return false;
302 }
303
304 if (set_mode != WIFI_MODE_NULL && !s_wifi_started) {
305 err = esp_wifi_start();
306 if (err != ESP_OK) {
307 ESP_LOGV(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
308 return false;
309 }
310 s_wifi_started = true;
311 }
312
313 return true;
314}
315
316bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
317
318bool WiFiComponent::wifi_apply_output_power_(float output_power) {
319 int8_t val = static_cast<int8_t>(output_power * 4);
320 return esp_wifi_set_max_tx_power(val) == ESP_OK;
321}
322
324 wifi_ps_type_t power_save;
325 switch (this->power_save_) {
327 power_save = WIFI_PS_MIN_MODEM;
328 break;
330 power_save = WIFI_PS_MAX_MODEM;
331 break;
333 default:
334 power_save = WIFI_PS_NONE;
335 break;
336 }
337 bool success = esp_wifi_set_ps(power_save) == ESP_OK;
338#ifdef USE_WIFI_POWER_SAVE_LISTENERS
339 if (success) {
340 for (auto *listener : this->power_save_listeners_) {
341 listener->on_wifi_power_save(this->power_save_);
342 }
343 }
344#endif
345 return success;
346}
347
348#ifdef SOC_WIFI_SUPPORT_5G
349bool WiFiComponent::wifi_apply_band_mode_() { return esp_wifi_set_band_mode(this->band_mode_) == ESP_OK; }
350#endif
351
352bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
353 // enable STA
354 if (!this->wifi_mode_(true, {}))
355 return false;
356
357 // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
358 wifi_config_t conf;
359 memset(&conf, 0, sizeof(conf));
360 if (ap.ssid_.size() > sizeof(conf.sta.ssid)) {
361 ESP_LOGE(TAG, "SSID too long");
362 return false;
363 }
364 if (ap.password_.size() > sizeof(conf.sta.password)) {
365 ESP_LOGE(TAG, "Password too long");
366 return false;
367 }
368 memcpy(reinterpret_cast<char *>(conf.sta.ssid), ap.ssid_.c_str(), ap.ssid_.size());
369 memcpy(reinterpret_cast<char *>(conf.sta.password), ap.password_.c_str(), ap.password_.size());
370
371 // The weakest authmode to accept in the fast scan mode
372 if (ap.password_.empty()) {
373 conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
374 } else {
375 // Set threshold based on configured minimum auth mode
376 switch (this->min_auth_mode_) {
378 conf.sta.threshold.authmode = WIFI_AUTH_WPA_PSK;
379 break;
381 conf.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
382 break;
384 conf.sta.threshold.authmode = WIFI_AUTH_WPA3_PSK;
385 break;
386 }
387 }
388
389#ifdef USE_WIFI_WPA2_EAP
390 if (ap.get_eap().has_value()) {
391 conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
392 }
393#endif
394
395#ifdef USE_WIFI_11KV_SUPPORT
396 conf.sta.btm_enabled = this->btm_;
397 conf.sta.rm_enabled = this->rrm_;
398#endif
399
400 if (ap.has_bssid()) {
401 conf.sta.bssid_set = true;
402 memcpy(conf.sta.bssid, ap.get_bssid().data(), 6);
403 } else {
404 conf.sta.bssid_set = false;
405 }
406 if (ap.has_channel()) {
407 conf.sta.channel = ap.get_channel();
408 conf.sta.scan_method = WIFI_FAST_SCAN;
409 } else {
410 conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
411 }
412 // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
413 // Units: AP beacon intervals. Defaults to 3 if set to 0.
414 conf.sta.listen_interval = 0;
415
416 // Protected Management Frame
417 // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
418 conf.sta.pmf_cfg.capable = true;
419 conf.sta.pmf_cfg.required = false;
420
421 // note, we do our own filtering
422 // The minimum rssi to accept in the fast scan mode
423 conf.sta.threshold.rssi = -127;
424
425 wifi_config_t current_conf;
426 esp_err_t err;
427 err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
428 if (err != ERR_OK) {
429 ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
430 // can continue
431 }
432
433 if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
434 err = esp_wifi_disconnect();
435 if (err != ESP_OK) {
436 ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
437 return false;
438 }
439 }
440
441 err = esp_wifi_set_config(WIFI_IF_STA, &conf);
442 if (err != ESP_OK) {
443 ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
444 return false;
445 }
446
447#ifdef USE_WIFI_MANUAL_IP
448 if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
449 return false;
450 }
451#else
452 if (!this->wifi_sta_ip_config_({})) {
453 return false;
454 }
455#endif
456
457 // setup enterprise authentication if required
458#ifdef USE_WIFI_WPA2_EAP
459 const auto &eap_opt = ap.get_eap();
460 if (eap_opt.has_value()) {
461 // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
462 const EAPAuth &eap = *eap_opt;
463#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
464 err = esp_eap_client_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
465#else
466 err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
467#endif
468 if (err != ESP_OK) {
469 ESP_LOGV(TAG, "set_identity failed %d", err);
470 }
471 int ca_cert_len = strlen(eap.ca_cert);
472 int client_cert_len = strlen(eap.client_cert);
473 int client_key_len = strlen(eap.client_key);
474 if (ca_cert_len) {
475#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
476 err = esp_eap_client_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
477#else
478 err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
479#endif
480 if (err != ESP_OK) {
481 ESP_LOGV(TAG, "set_ca_cert failed %d", err);
482 }
483 }
484 // workout what type of EAP this is
485 // validation is not required as the config tool has already validated it
486 if (client_cert_len && client_key_len) {
487 // if we have certs, this must be EAP-TLS
488#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
489 err = esp_eap_client_set_certificate_and_key((uint8_t *) eap.client_cert, client_cert_len + 1,
490 (uint8_t *) eap.client_key, client_key_len + 1,
491 (uint8_t *) eap.password.c_str(), eap.password.length());
492#else
493 err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
494 (uint8_t *) eap.client_key, client_key_len + 1,
495 (uint8_t *) eap.password.c_str(), eap.password.length());
496#endif
497 if (err != ESP_OK) {
498 ESP_LOGV(TAG, "set_cert_key failed %d", err);
499 }
500 } else {
501 // in the absence of certs, assume this is username/password based
502#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
503 err = esp_eap_client_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
504#else
505 err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
506#endif
507 if (err != ESP_OK) {
508 ESP_LOGV(TAG, "set_username failed %d", err);
509 }
510#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
511 err = esp_eap_client_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
512#else
513 err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
514#endif
515 if (err != ESP_OK) {
516 ESP_LOGV(TAG, "set_password failed %d", err);
517 }
518 // set TTLS Phase 2, defaults to MSCHAPV2
519#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
520 err = esp_eap_client_set_ttls_phase2_method(eap.ttls_phase_2);
521#else
522 err = esp_wifi_sta_wpa2_ent_set_ttls_phase2_method(eap.ttls_phase_2);
523#endif
524 if (err != ESP_OK) {
525 ESP_LOGV(TAG, "set_ttls_phase2_method failed %d", err);
526 }
527 }
528#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
529 err = esp_wifi_sta_enterprise_enable();
530#else
531 err = esp_wifi_sta_wpa2_ent_enable();
532#endif
533 if (err != ESP_OK) {
534 ESP_LOGV(TAG, "enterprise_enable failed %d", err);
535 }
536 }
537#endif // USE_WIFI_WPA2_EAP
538
539 // Reset flags, do this _before_ wifi_station_connect as the callback method
540 // may be called from wifi_station_connect
541 s_sta_connecting = true;
542 s_sta_connected = false;
543 s_sta_connect_error = false;
544 s_sta_connect_not_found = false;
545 // Reset IP address flags - ensures we don't report connected before DHCP completes
546 // (IP_EVENT_STA_LOST_IP doesn't always fire on disconnect)
547 this->got_ipv4_address_ = false;
548#if USE_NETWORK_IPV6
549 this->num_ipv6_addresses_ = 0;
550#endif
551
552 err = esp_wifi_connect();
553 if (err != ESP_OK) {
554 ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
555 return false;
556 }
557
558 return true;
559}
560
561bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
562 // enable STA
563 if (!this->wifi_mode_(true, {}))
564 return false;
565
566 // Check if the STA interface is initialized before using it
567 if (s_sta_netif == nullptr) {
568 ESP_LOGW(TAG, "STA interface not initialized");
569 return false;
570 }
571
572 esp_netif_dhcp_status_t dhcp_status;
573 esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
574 if (err != ESP_OK) {
575 ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
576 return false;
577 }
578
579 if (!manual_ip.has_value()) {
580 // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
581 // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
582 // https://github.com/esphome/issues/issues/2299
583 sntp_servermode_dhcp(false);
584
585 // No manual IP is set; use DHCP client
586 if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
587 err = esp_netif_dhcpc_start(s_sta_netif);
588 if (err != ESP_OK) {
589 ESP_LOGV(TAG, "Starting DHCP client failed: %d", err);
590 }
591 return err == ESP_OK;
592 }
593 return true;
594 }
595
596 esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
597 info.ip = manual_ip->static_ip;
598 info.gw = manual_ip->gateway;
599 info.netmask = manual_ip->subnet;
600 err = esp_netif_dhcpc_stop(s_sta_netif);
601 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
602 ESP_LOGV(TAG, "Stopping DHCP client failed: %s", esp_err_to_name(err));
603 }
604
605 err = esp_netif_set_ip_info(s_sta_netif, &info);
606 if (err != ESP_OK) {
607 ESP_LOGV(TAG, "Setting manual IP info failed: %s", esp_err_to_name(err));
608 }
609
610 esp_netif_dns_info_t dns;
611 if (manual_ip->dns1.is_set()) {
612 dns.ip = manual_ip->dns1;
613 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
614 }
615 if (manual_ip->dns2.is_set()) {
616 dns.ip = manual_ip->dns2;
617 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
618 }
619
620 return true;
621}
622
624 if (!this->has_sta())
625 return {};
626 network::IPAddresses addresses;
627 esp_netif_ip_info_t ip;
628 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
629 if (err != ESP_OK) {
630 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
631 // TODO: do something smarter
632 // return false;
633 } else {
634 addresses[0] = network::IPAddress(&ip.ip);
635 }
636#if USE_NETWORK_IPV6
637 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
638 uint8_t count = 0;
639 count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s);
640 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
641 assert(count < addresses.size());
642 for (int i = 0; i < count; i++) {
643 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
644 }
645#endif /* USE_NETWORK_IPV6 */
646 return addresses;
647}
648
650 // setting is done in SYSTEM_EVENT_STA_START callback
651 return true;
652}
653const char *get_auth_mode_str(uint8_t mode) {
654 switch (mode) {
655 case WIFI_AUTH_OPEN:
656 return "OPEN";
657 case WIFI_AUTH_WEP:
658 return "WEP";
659 case WIFI_AUTH_WPA_PSK:
660 return "WPA PSK";
661 case WIFI_AUTH_WPA2_PSK:
662 return "WPA2 PSK";
663 case WIFI_AUTH_WPA_WPA2_PSK:
664 return "WPA/WPA2 PSK";
665 case WIFI_AUTH_WPA2_ENTERPRISE:
666 return "WPA2 Enterprise";
667 case WIFI_AUTH_WPA3_PSK:
668 return "WPA3 PSK";
669 case WIFI_AUTH_WPA2_WPA3_PSK:
670 return "WPA2/WPA3 PSK";
671 case WIFI_AUTH_WAPI_PSK:
672 return "WAPI PSK";
673 default:
674 return "UNKNOWN";
675 }
676}
677
678const char *get_disconnect_reason_str(uint8_t reason) {
679 switch (reason) {
680 case WIFI_REASON_AUTH_EXPIRE:
681 return "Auth Expired";
682 case WIFI_REASON_AUTH_LEAVE:
683 return "Auth Leave";
684#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
685 case WIFI_REASON_DISASSOC_DUE_TO_INACTIVITY:
686 return "Disassociated Due to Inactivity";
687#else
688 case WIFI_REASON_ASSOC_EXPIRE:
689 return "Association Expired";
690#endif
691 case WIFI_REASON_ASSOC_TOOMANY:
692 return "Too Many Associations";
693#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
694 case WIFI_REASON_CLASS2_FRAME_FROM_NONAUTH_STA:
695 return "Class 2 Frame from Non-Authenticated STA";
696 case WIFI_REASON_CLASS3_FRAME_FROM_NONASSOC_STA:
697 return "Class 3 Frame from Non-Associated STA";
698#else
699 case WIFI_REASON_NOT_AUTHED:
700 return "Not Authenticated";
701 case WIFI_REASON_NOT_ASSOCED:
702 return "Not Associated";
703#endif
704 case WIFI_REASON_ASSOC_LEAVE:
705 return "Association Leave";
706 case WIFI_REASON_ASSOC_NOT_AUTHED:
707 return "Association not Authenticated";
708 case WIFI_REASON_DISASSOC_PWRCAP_BAD:
709 return "Disassociate Power Cap Bad";
710 case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
711 return "Disassociate Supported Channel Bad";
712 case WIFI_REASON_IE_INVALID:
713 return "IE Invalid";
714 case WIFI_REASON_MIC_FAILURE:
715 return "Mic Failure";
716 case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
717 return "4-Way Handshake Timeout";
718 case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
719 return "Group Key Update Timeout";
720 case WIFI_REASON_IE_IN_4WAY_DIFFERS:
721 return "IE In 4-Way Handshake Differs";
722 case WIFI_REASON_GROUP_CIPHER_INVALID:
723 return "Group Cipher Invalid";
724 case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
725 return "Pairwise Cipher Invalid";
726 case WIFI_REASON_AKMP_INVALID:
727 return "AKMP Invalid";
728 case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
729 return "Unsupported RSN IE version";
730 case WIFI_REASON_INVALID_RSN_IE_CAP:
731 return "Invalid RSN IE Cap";
732 case WIFI_REASON_802_1X_AUTH_FAILED:
733 return "802.1x Authentication Failed";
734 case WIFI_REASON_CIPHER_SUITE_REJECTED:
735 return "Cipher Suite Rejected";
736 case WIFI_REASON_BEACON_TIMEOUT:
737 return "Beacon Timeout";
738 case WIFI_REASON_NO_AP_FOUND:
739 return "AP Not Found";
740 case WIFI_REASON_AUTH_FAIL:
741 return "Authentication Failed";
742 case WIFI_REASON_ASSOC_FAIL:
743 return "Association Failed";
744 case WIFI_REASON_HANDSHAKE_TIMEOUT:
745 return "Handshake Failed";
746 case WIFI_REASON_CONNECTION_FAIL:
747 return "Connection Failed";
748 case WIFI_REASON_AP_TSF_RESET:
749 return "AP TSF reset";
750 case WIFI_REASON_ROAMING:
751 return "Station Roaming";
752 case WIFI_REASON_ASSOC_COMEBACK_TIME_TOO_LONG:
753 return "Association comeback time too long";
754 case WIFI_REASON_SA_QUERY_TIMEOUT:
755 return "SA query timeout";
756#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
757 case WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY:
758 return "No AP found with compatible security";
759 case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD:
760 return "No AP found in auth mode threshold";
761 case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD:
762 return "No AP found in RSSI threshold";
763#endif
764 case WIFI_REASON_UNSPECIFIED:
765 default:
766 return "Unspecified";
767 }
768}
769
771 // Use pop() directly instead of empty() — pop() costs 1 memw (acquire on tail_),
772 // while empty() costs 2 memw (acquire on both head_ and tail_) on Xtensa.
773 IDFWiFiEvent *data = this->event_queue_.pop();
774 if (data == nullptr)
775 return false;
776
777 do {
779 delete data; // NOLINT(cppcoreguidelines-owning-memory)
780 } while ((data = this->event_queue_.pop()) != nullptr);
781
782 // Drops only occur when the queue is full, and only this loop drains it,
783 // so if pop() returned nullptr above we can skip this check.
784 uint16_t dropped = this->event_queue_.get_and_reset_dropped_count();
785 if (dropped > 0) {
786 ESP_LOGW(TAG, "Dropped %u WiFi events due to buffer overflow", dropped);
787 }
788 return true;
789}
790// Events are processed from queue in main loop context, but listener notifications
791// must be deferred until after the state machine transitions (in check_connecting_finished)
792// so that conditions like wifi.connected return correct values in automations.
793void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
794 esp_err_t err;
795 if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
796 ESP_LOGV(TAG, "STA start");
797 // apply hostname
798 err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
799 if (err != ERR_OK) {
800 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
801 }
802
803 s_sta_started = true;
804 // re-apply power save mode
806#ifdef SOC_WIFI_SUPPORT_5G
808#endif
809
810 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
811 ESP_LOGV(TAG, "STA stop");
812 s_sta_started = false;
813 s_sta_connecting = false;
814
815 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
816 const auto &it = data->data.sta_authmode_change;
817 ESP_LOGV(TAG, "Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode), get_auth_mode_str(it.new_mode));
818
819 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
820 const auto &it = data->data.sta_connected;
821#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
822 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
823 format_mac_addr_upper(it.bssid, bssid_buf);
824 ESP_LOGV(TAG, "Connected ssid='%.*s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", it.ssid_len,
825 (const char *) it.ssid, bssid_buf, it.channel, get_auth_mode_str(it.authmode));
826#endif
827 s_sta_connected = true;
828#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
829 // Defer listener notification until state machine reaches STA_CONNECTED
830 // This ensures wifi.connected condition returns true in listener automations
831 this->pending_.connect_state = true;
832#endif
833 // For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
834#if defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
835 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_manual_ip().has_value()) {
837 }
838#endif
839
840 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
841 const auto &it = data->data.sta_disconnected;
842 if (it.reason == WIFI_REASON_NO_AP_FOUND) {
843 ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
844 (const char *) it.ssid);
845 s_sta_connect_not_found = true;
846 } else if (it.reason == WIFI_REASON_ROAMING) {
847 ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
848 return;
849 } else {
850 char bssid_s[18];
851 format_mac_addr_upper(it.bssid, bssid_s);
852 ESP_LOGW(TAG, "Disconnected ssid='%.*s' bssid=" LOG_SECRET("%s") " reason='%s'", it.ssid_len,
853 (const char *) it.ssid, bssid_s, get_disconnect_reason_str(it.reason));
854 s_sta_connect_error = true;
855 }
856 s_sta_connected = false;
857 s_sta_connecting = false;
859 // Refresh is_connected() cache; error_from_callback_ makes it false.
861#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
863#endif
864
865 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
866 const auto &it = data->data.ip_got_ip;
867#if USE_NETWORK_IPV6
868 esp_netif_create_ip6_linklocal(s_sta_netif);
869#endif /* USE_NETWORK_IPV6 */
870 ESP_LOGV(TAG, "static_ip=" IPSTR " gateway=" IPSTR, IP2STR(&it.ip_info.ip), IP2STR(&it.ip_info.gw));
871 this->got_ipv4_address_ = true;
872#ifdef USE_WIFI_IP_STATE_LISTENERS
874#endif
875
876#if USE_NETWORK_IPV6
877 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
878 const auto &it = data->data.ip_got_ip6;
879 ESP_LOGV(TAG, "IPv6 address=" IPV6STR, IPV62STR(it.ip6_info.ip));
880 this->num_ipv6_addresses_++;
881#ifdef USE_WIFI_IP_STATE_LISTENERS
883#endif
884#endif /* USE_NETWORK_IPV6 */
885
886 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
887 ESP_LOGV(TAG, "Lost IP");
888 this->got_ipv4_address_ = false;
889
890 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
891 const auto &it = data->data.sta_scan_done;
892 ESP_LOGV(TAG, "Scan done: status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
893
894 scan_result_.clear();
895 this->scan_done_ = true;
896 if (it.status != 0) {
897 // scan error
898 return;
899 }
900
901 if (it.number == 0) {
902 // no results
903 return;
904 }
905
906 uint16_t number = it.number;
907 bool needs_full = this->needs_full_scan_results_();
908
909 // Smart reserve: full capacity if needed, small reserve otherwise
910 if (needs_full) {
911 this->scan_result_.reserve(number);
912 } else {
913 this->scan_result_.reserve(WIFI_SCAN_RESULT_FILTERED_RESERVE);
914 }
915
916#ifdef USE_ESP32_HOSTED
917 // getting records one at a time fails on P4 with hosted esp32 WiFi coprocessor
918 // Presumably an upstream bug, work-around by getting all records at once
919 // Use stack buffer (3904 bytes / ~80 bytes per record = ~48 records) with heap fallback
920 static constexpr size_t SCAN_RECORD_STACK_COUNT = 3904 / sizeof(wifi_ap_record_t);
921 SmallBufferWithHeapFallback<SCAN_RECORD_STACK_COUNT, wifi_ap_record_t> records(number);
922 err = esp_wifi_scan_get_ap_records(&number, records.get());
923 if (err != ESP_OK) {
924 esp_wifi_clear_ap_list();
925 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
926 return;
927 }
928 for (uint16_t i = 0; i < number; i++) {
929 wifi_ap_record_t &record = records.get()[i];
930#else
931 // Process one record at a time to avoid large buffer allocation
932 for (uint16_t i = 0; i < number; i++) {
933 wifi_ap_record_t record;
934 err = esp_wifi_scan_get_ap_record(&record);
935 if (err != ESP_OK) {
936 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_record failed: %s", esp_err_to_name(err));
937 esp_wifi_clear_ap_list(); // Free remaining records not yet retrieved
938 break;
939 }
940#endif // USE_ESP32_HOSTED
941
942 // Check C string first - avoid std::string construction for non-matching networks
943 const char *ssid_cstr = reinterpret_cast<const char *>(record.ssid);
944
945 // Only construct std::string and store if needed
946 if (needs_full || this->matches_configured_network_(ssid_cstr, record.bssid)) {
947 bssid_t bssid;
948 std::copy(record.bssid, record.bssid + 6, bssid.begin());
949 this->scan_result_.emplace_back(bssid, ssid_cstr, strlen(ssid_cstr), record.primary, record.rssi,
950 record.authmode != WIFI_AUTH_OPEN, ssid_cstr[0] == '\0');
951 } else {
952 this->log_discarded_scan_result_(ssid_cstr, record.bssid, record.rssi, record.primary);
953 }
954 }
955 ESP_LOGV(TAG, "Scan complete: %u found, %zu stored%s", number, this->scan_result_.size(),
956 needs_full ? "" : " (filtered)");
957#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
959#endif
960
961 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
962 ESP_LOGV(TAG, "AP start");
963 this->ap_started_ = true;
964
965 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
966 ESP_LOGV(TAG, "AP stop");
967 this->ap_started_ = false;
968
969 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
970#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
971 const auto &it = data->data.ap_probe_req_rx;
972 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
973 format_mac_addr_upper(it.mac, mac_buf);
974 ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", mac_buf, it.rssi);
975#endif
976
977 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
978#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
979 const auto &it = data->data.ap_staconnected;
980 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
981 format_mac_addr_upper(it.mac, mac_buf);
982 ESP_LOGV(TAG, "AP client connected MAC=%s", mac_buf);
983#endif
984
985 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
986#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
987 const auto &it = data->data.ap_stadisconnected;
988 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
989 format_mac_addr_upper(it.mac, mac_buf);
990 ESP_LOGV(TAG, "AP client disconnected MAC=%s", mac_buf);
991#endif
992
993#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
994 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
995 const auto &it = data->data.ip_assigned_ip_to_client;
996#else
997 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
998 const auto &it = data->data.ip_ap_staipassigned;
999#endif
1000 ESP_LOGV(TAG, "AP client assigned IP " IPSTR, IP2STR(&it.ip));
1001 }
1002}
1003
1005 if (s_sta_connected && this->got_ipv4_address_) {
1006#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
1007 if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
1009 }
1010#else
1012#endif /* USE_NETWORK_IPV6 */
1013 }
1014 if (s_sta_connect_error) {
1016 }
1017 if (s_sta_connect_not_found) {
1019 }
1020 if (s_sta_connecting) {
1022 }
1024}
1025bool WiFiComponent::wifi_scan_start_(bool passive) {
1026 // enable STA
1027 if (!this->wifi_mode_(true, {}))
1028 return false;
1029
1030 wifi_scan_config_t config{};
1031 config.ssid = nullptr;
1032 config.bssid = nullptr;
1033 config.channel = 0;
1034 config.show_hidden = true;
1035 config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
1036 if (passive) {
1037 config.scan_time.passive = 300;
1038 } else {
1039 config.scan_time.active.min = 100;
1040 config.scan_time.active.max = 300;
1041 }
1042 // When scanning while connected (roaming), return to home channel between
1043 // each scanned channel to maintain the connection (helps with BLE/WiFi coexistence)
1044#ifdef CONFIG_SOC_WIFI_SUPPORTED
1046 config.coex_background_scan = true;
1047 }
1048#endif
1049
1050 esp_err_t err = esp_wifi_scan_start(&config, false);
1051 if (err != ESP_OK) {
1052 ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
1053 return false;
1054 }
1055
1056 this->scan_done_ = false;
1057 return true;
1058}
1059
1060#ifdef USE_WIFI_AP
1061bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
1062 esp_err_t err;
1063
1064 // enable AP
1065 if (!this->wifi_mode_({}, true))
1066 return false;
1067
1068 // Check if the AP interface is initialized before using it
1069 if (s_ap_netif == nullptr) {
1070 ESP_LOGW(TAG, "AP interface not initialized");
1071 return false;
1072 }
1073
1074 esp_netif_ip_info_t info;
1075 if (manual_ip.has_value()) {
1076 info.ip = manual_ip->static_ip;
1077 info.gw = manual_ip->gateway;
1078 info.netmask = manual_ip->subnet;
1079 } else {
1080 info.ip = network::IPAddress(192, 168, 4, 1);
1081 info.gw = network::IPAddress(192, 168, 4, 1);
1082 info.netmask = network::IPAddress(255, 255, 255, 0);
1083 }
1084
1085 err = esp_netif_dhcps_stop(s_ap_netif);
1086 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
1087 ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
1088 return false;
1089 }
1090
1091 err = esp_netif_set_ip_info(s_ap_netif, &info);
1092 if (err != ESP_OK) {
1093 ESP_LOGE(TAG, "esp_netif_set_ip_info failed: %d", err);
1094 return false;
1095 }
1096
1097 dhcps_lease_t lease;
1098 lease.enable = true;
1099 network::IPAddress start_address = network::IPAddress(&info.ip);
1100 start_address += 99;
1101 lease.start_ip = start_address;
1102#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1103 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1104#endif
1105 ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str_to(ip_buf));
1106 start_address += 10;
1107 lease.end_ip = start_address;
1108 ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str_to(ip_buf));
1109 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
1110
1111 if (err != ESP_OK) {
1112 ESP_LOGE(TAG, "esp_netif_dhcps_option failed: %d", err);
1113 return false;
1114 }
1115
1116#if defined(USE_CAPTIVE_PORTAL) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
1117 // Configure DHCP Option 114 (Captive Portal URI) if captive portal is enabled
1118 // This provides a standards-compliant way for clients to discover the captive portal
1120 // Buffer must be static - dhcps_set_option_info stores pointer, doesn't copy
1121 static char captive_portal_uri[24]; // "http://" (7) + IPv4 max (15) + null
1122 memcpy(captive_portal_uri, "http://", 7); // NOLINT(bugprone-not-null-terminated-result) - str_to null-terminates
1123 network::IPAddress(&info.ip).str_to(captive_portal_uri + 7);
1124 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_CAPTIVEPORTAL_URI, captive_portal_uri,
1125 strlen(captive_portal_uri));
1126 if (err != ESP_OK) {
1127 ESP_LOGV(TAG, "Failed to set DHCP captive portal URI: %s", esp_err_to_name(err));
1128 } else {
1129 ESP_LOGV(TAG, "DHCP Captive Portal URI set to: %s", captive_portal_uri);
1130 }
1131 }
1132#endif
1133
1134 err = esp_netif_dhcps_start(s_ap_netif);
1135
1136 if (err != ESP_OK) {
1137 ESP_LOGE(TAG, "esp_netif_dhcps_start failed: %d", err);
1138 return false;
1139 }
1140
1141 return true;
1142}
1143
1144bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
1145 // enable AP
1146 if (!this->wifi_mode_({}, true))
1147 return false;
1148
1149 wifi_config_t conf;
1150 memset(&conf, 0, sizeof(conf));
1151 if (ap.ssid_.size() > sizeof(conf.ap.ssid)) {
1152 ESP_LOGE(TAG, "AP SSID too long");
1153 return false;
1154 }
1155 memcpy(reinterpret_cast<char *>(conf.ap.ssid), ap.ssid_.c_str(), ap.ssid_.size());
1156 conf.ap.channel = ap.has_channel() ? ap.get_channel() : 1;
1157 conf.ap.ssid_hidden = ap.get_hidden();
1158 conf.ap.max_connection = 5;
1159 conf.ap.beacon_interval = 100;
1160
1161 if (ap.password_.empty()) {
1162 conf.ap.authmode = WIFI_AUTH_OPEN;
1163 *conf.ap.password = 0;
1164 } else {
1165 conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
1166 if (ap.password_.size() > sizeof(conf.ap.password)) {
1167 ESP_LOGE(TAG, "AP password too long");
1168 return false;
1169 }
1170 memcpy(reinterpret_cast<char *>(conf.ap.password), ap.password_.c_str(), ap.password_.size());
1171 }
1172
1173 // pairwise cipher of SoftAP, group cipher will be derived using this.
1174 conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
1175
1176 esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
1177 if (err != ESP_OK) {
1178 ESP_LOGE(TAG, "esp_wifi_set_config failed: %d", err);
1179 return false;
1180 }
1181
1182#ifdef USE_WIFI_MANUAL_IP
1183 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
1184 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed:");
1185 return false;
1186 }
1187#else
1188 if (!this->wifi_ap_ip_config_({})) {
1189 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed:");
1190 return false;
1191 }
1192#endif
1193
1194 return true;
1195}
1196
1197network::IPAddress WiFiComponent::wifi_soft_ap_ip() {
1198 esp_netif_ip_info_t ip;
1199 esp_netif_get_ip_info(s_ap_netif, &ip);
1200 return network::IPAddress(&ip.ip);
1201}
1202#endif // USE_WIFI_AP
1203
1204bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
1205
1207 bssid_t bssid{};
1208 wifi_ap_record_t info;
1209 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1210 if (err != ESP_OK) {
1211 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1212 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1213 return bssid;
1214 }
1215 std::copy(info.bssid, info.bssid + 6, bssid.begin());
1216 return bssid;
1217}
1218std::string WiFiComponent::wifi_ssid() {
1219 wifi_ap_record_t info{};
1220 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1221 if (err != ESP_OK) {
1222 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1223 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1224 return "";
1225 }
1226 auto *ssid_s = reinterpret_cast<const char *>(info.ssid);
1227 size_t len = strnlen(ssid_s, sizeof(info.ssid));
1228 return {ssid_s, len};
1229}
1230const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
1231 wifi_ap_record_t info{};
1232 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1233 if (err != ESP_OK) {
1234 buffer[0] = '\0';
1235 return buffer.data();
1236 }
1237 // info.ssid is uint8[33], but only 32 bytes are SSID data
1238 size_t len = strnlen(reinterpret_cast<const char *>(info.ssid), 32);
1239 memcpy(buffer.data(), info.ssid, len);
1240 buffer[len] = '\0';
1241 return buffer.data();
1242}
1243int8_t WiFiComponent::wifi_rssi() {
1244 wifi_ap_record_t info;
1245 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1246 if (err != ESP_OK) {
1247 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1248 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1249 return WIFI_RSSI_DISCONNECTED;
1250 }
1251 return info.rssi;
1252}
1254 uint8_t primary;
1255 wifi_second_chan_t second;
1256 esp_err_t err = esp_wifi_get_channel(&primary, &second);
1257 if (err != ESP_OK) {
1258 ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
1259 return 0;
1260 }
1261 return primary;
1262}
1263network::IPAddress WiFiComponent::wifi_subnet_mask_() {
1264 esp_netif_ip_info_t ip;
1265 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1266 if (err != ESP_OK) {
1267 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1268 return {};
1269 }
1270 return network::IPAddress(&ip.netmask);
1271}
1272network::IPAddress WiFiComponent::wifi_gateway_ip_() {
1273 esp_netif_ip_info_t ip;
1274 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1275 if (err != ESP_OK) {
1276 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1277 return {};
1278 }
1279 return network::IPAddress(&ip.gw);
1280}
1281network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
1282 const ip_addr_t *dns_ip = dns_getserver(num);
1283 return network::IPAddress(dns_ip);
1284}
1285
1286} // namespace esphome::wifi
1287#endif // USE_ESP32
1288#endif
BedjetMode mode
BedJet operating mode.
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
uint16_t get_and_reset_dropped_count()
bool push(T *element)
constexpr const char * c_str() const
Definition string_ref.h:73
const 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
wifi_scan_vector_t< WiFiScanResult > scan_result_
void notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
bool wifi_sta_ip_config_(const optional< ManualIP > &manual_ip)
void wifi_process_event_(IDFWiFiEvent *data)
struct esphome::wifi::WiFiComponent::@191 pending_
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)
ESPDEPRECATED("Use wifi_ssid_to() instead. Removed in 2026.9.0", "2026.3.0") std const char * wifi_ssid_to(std::span< char, SSID_BUFFER_SIZE > buffer)
Write SSID to buffer without heap allocation.
network::IPAddress wifi_dns_ip_(int num)
bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const
Check if network matches any configured network (for scan result filtering) Matches by SSID when conf...
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()
uint8_t second
in_addr ip_addr_t
Definition ip_address.h:22
mopeka_std_values val[3]
CaptivePortal * global_captive_portal
const std::vector< uint8_t > & data
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:223
const char *const TAG
Definition spi.cpp:7
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
const LogString * get_disconnect_reason_str(uint8_t reason)
WiFiComponent * global_wifi_component
@ SCANNING
Scanning for better AP.
const void size_t len
Definition hal.h:64
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:110
ESPPreferences * global_preferences
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:108
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:74
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:1453
uint8_t event_id
Definition tt21100.cpp:3