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