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