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