ESPHome 2026.4.3
Loading...
Searching...
No Matches
wifi_component_esp_idf.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2
3#ifdef USE_WIFI
4#ifdef USE_ESP32
5
6#include <esp_event.h>
7#include <esp_netif.h>
8#include <esp_system.h>
9#include <esp_wifi.h>
10#include <esp_wifi_types.h>
11#include <freertos/FreeRTOS.h>
12#include <freertos/event_groups.h>
13#include <freertos/task.h>
14
15#include <algorithm>
16#include <cinttypes>
17#include <memory>
18#include <utility>
19#ifdef USE_WIFI_WPA2_EAP
20#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
21#include <esp_eap_client.h>
22#else
23#include <esp_wpa2.h>
24#endif
25#endif
26
27#ifdef USE_WIFI_AP
28#include "dhcpserver/dhcpserver.h"
29#endif // USE_WIFI_AP
30
31#ifdef USE_CAPTIVE_PORTAL
33#endif
34
35#include "lwip/apps/sntp.h"
36#include "lwip/dns.h"
37#include "lwip/err.h"
38
40#include "esphome/core/hal.h"
42#include "esphome/core/log.h"
43#include "esphome/core/util.h"
44
45namespace esphome::wifi {
46
47static const char *const TAG = "wifi_esp32";
48
49static EventGroupHandle_t s_wifi_event_group; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
51#ifdef USE_WIFI_AP
52static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
53#endif // USE_WIFI_AP
54static bool s_sta_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
55static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
56static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
57static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
58static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
59static bool s_wifi_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
60
61struct IDFWiFiEvent {
62 esp_event_base_t event_base;
63 int32_t event_id;
64 union {
65 wifi_event_sta_scan_done_t sta_scan_done;
66 wifi_event_sta_connected_t sta_connected;
67 wifi_event_sta_disconnected_t sta_disconnected;
68 wifi_event_sta_authmode_change_t sta_authmode_change;
69 wifi_event_ap_staconnected_t ap_staconnected;
70 wifi_event_ap_stadisconnected_t ap_stadisconnected;
71 wifi_event_ap_probe_req_rx_t ap_probe_req_rx;
72 wifi_event_bss_rssi_low_t bss_rssi_low;
73 ip_event_got_ip_t ip_got_ip;
74#if USE_NETWORK_IPV6
75 ip_event_got_ip6_t ip_got_ip6;
76#endif /* USE_NETWORK_IPV6 */
77#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
78 ip_event_assigned_ip_to_client_t ip_assigned_ip_to_client;
79#else
80 ip_event_ap_staipassigned_t ip_ap_staipassigned;
81#endif
82 } data;
83};
84
85// general design: event handler translates events and pushes them to a queue,
86// events get processed in the main loop
87void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
88 IDFWiFiEvent event;
89 memset(&event, 0, sizeof(IDFWiFiEvent));
90 event.event_base = event_base;
91 event.event_id = event_id;
92 if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { // NOLINT(bugprone-branch-clone)
93 // no data
94 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_STOP) { // NOLINT(bugprone-branch-clone)
95 // no data
96 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
97 memcpy(&event.data.sta_authmode_change, event_data, sizeof(wifi_event_sta_authmode_change_t));
98 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) {
99 memcpy(&event.data.sta_connected, event_data, sizeof(wifi_event_sta_connected_t));
100 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
101 memcpy(&event.data.sta_disconnected, event_data, sizeof(wifi_event_sta_disconnected_t));
102 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
103 memcpy(&event.data.ip_got_ip, event_data, sizeof(ip_event_got_ip_t));
104#if USE_NETWORK_IPV6
105 } else if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
106 memcpy(&event.data.ip_got_ip6, event_data, sizeof(ip_event_got_ip6_t));
107#endif
108 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) { // NOLINT(bugprone-branch-clone)
109 // no data
110 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
111 memcpy(&event.data.sta_scan_done, event_data, sizeof(wifi_event_sta_scan_done_t));
112 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) { // NOLINT(bugprone-branch-clone)
113 // no data
114 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STOP) { // NOLINT(bugprone-branch-clone)
115 // no data
116 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
117 memcpy(&event.data.ap_probe_req_rx, event_data, sizeof(wifi_event_ap_probe_req_rx_t));
118 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
119 memcpy(&event.data.ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t));
120 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
121 memcpy(&event.data.ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t));
122#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
123 } else if (event_base == IP_EVENT && event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
124 memcpy(&event.data.ip_assigned_ip_to_client, event_data, sizeof(ip_event_assigned_ip_to_client_t));
125#else
126 } else if (event_base == IP_EVENT && event_id == IP_EVENT_AP_STAIPASSIGNED) {
127 memcpy(&event.data.ip_ap_staipassigned, event_data, sizeof(ip_event_ap_staipassigned_t));
128#endif
129 } else {
130 // did not match any event, don't send anything
131 return;
132 }
133
134 // copy to heap — WiFi events are rare so heap alloc is fine
135 auto *to_send = new IDFWiFiEvent; // NOLINT(cppcoreguidelines-owning-memory)
136 memcpy(to_send, &event, sizeof(IDFWiFiEvent));
137 if (!global_wifi_component->event_queue_.push(to_send)) {
138 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
139 }
140}
141
143 uint8_t mac[6];
146 set_mac_address(mac);
147 }
148 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 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 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 uint16_t dropped = this->event_queue_.get_and_reset_dropped_count();
723 if (dropped > 0) {
724 ESP_LOGW(TAG, "Dropped %u WiFi events due to buffer overflow", dropped);
725 }
726
727 IDFWiFiEvent *data;
728 while ((data = this->event_queue_.pop()) != nullptr) {
730 delete data; // NOLINT(cppcoreguidelines-owning-memory)
731 }
732}
733// Events are processed from queue in main loop context, but listener notifications
734// must be deferred until after the state machine transitions (in check_connecting_finished)
735// so that conditions like wifi.connected return correct values in automations.
736void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
737 esp_err_t err;
738 if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
739 ESP_LOGV(TAG, "STA start");
740 // apply hostname
741 err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
742 if (err != ERR_OK) {
743 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
744 }
745
746 s_sta_started = true;
747 // re-apply power save mode
749#ifdef SOC_WIFI_SUPPORT_5G
751#endif
752
753 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
754 ESP_LOGV(TAG, "STA stop");
755 s_sta_started = false;
756 s_sta_connecting = false;
757
758 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
759 const auto &it = data->data.sta_authmode_change;
760 ESP_LOGV(TAG, "Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode), get_auth_mode_str(it.new_mode));
761
762 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
763 const auto &it = data->data.sta_connected;
764#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
765 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
766 format_mac_addr_upper(it.bssid, bssid_buf);
767 ESP_LOGV(TAG, "Connected ssid='%.*s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", it.ssid_len,
768 (const char *) it.ssid, bssid_buf, it.channel, get_auth_mode_str(it.authmode));
769#endif
770 s_sta_connected = true;
771#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
772 // Defer listener notification until state machine reaches STA_CONNECTED
773 // This ensures wifi.connected condition returns true in listener automations
774 this->pending_.connect_state = true;
775#endif
776 // For static IP configurations, GOT_IP event may not fire, so notify IP listeners here
777#if defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
778 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_manual_ip().has_value()) {
780 }
781#endif
782
783 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
784 const auto &it = data->data.sta_disconnected;
785 if (it.reason == WIFI_REASON_NO_AP_FOUND) {
786 ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
787 (const char *) it.ssid);
788 s_sta_connect_not_found = true;
789 } else if (it.reason == WIFI_REASON_ROAMING) {
790 ESP_LOGI(TAG, "Disconnected ssid='%.*s' reason='Station Roaming'", it.ssid_len, (const char *) it.ssid);
791 return;
792 } else {
793 char bssid_s[18];
794 format_mac_addr_upper(it.bssid, bssid_s);
795 ESP_LOGW(TAG, "Disconnected ssid='%.*s' bssid=" LOG_SECRET("%s") " reason='%s'", it.ssid_len,
796 (const char *) it.ssid, bssid_s, get_disconnect_reason_str(it.reason));
797 s_sta_connect_error = true;
798 }
799 s_sta_connected = false;
800 s_sta_connecting = false;
802 // Refresh is_connected() cache; error_from_callback_ makes it false.
804#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
806#endif
807
808 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
809 const auto &it = data->data.ip_got_ip;
810#if USE_NETWORK_IPV6
811 esp_netif_create_ip6_linklocal(s_sta_netif);
812#endif /* USE_NETWORK_IPV6 */
813 ESP_LOGV(TAG, "static_ip=" IPSTR " gateway=" IPSTR, IP2STR(&it.ip_info.ip), IP2STR(&it.ip_info.gw));
814 this->got_ipv4_address_ = true;
815#ifdef USE_WIFI_IP_STATE_LISTENERS
817#endif
818
819#if USE_NETWORK_IPV6
820 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
821 const auto &it = data->data.ip_got_ip6;
822 ESP_LOGV(TAG, "IPv6 address=" IPV6STR, IPV62STR(it.ip6_info.ip));
823 this->num_ipv6_addresses_++;
824#ifdef USE_WIFI_IP_STATE_LISTENERS
826#endif
827#endif /* USE_NETWORK_IPV6 */
828
829 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
830 ESP_LOGV(TAG, "Lost IP");
831 this->got_ipv4_address_ = false;
832
833 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
834 const auto &it = data->data.sta_scan_done;
835 ESP_LOGV(TAG, "Scan done: status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
836
837 scan_result_.clear();
838 this->scan_done_ = true;
839 if (it.status != 0) {
840 // scan error
841 return;
842 }
843
844 if (it.number == 0) {
845 // no results
846 return;
847 }
848
849 uint16_t number = it.number;
850 bool needs_full = this->needs_full_scan_results_();
851
852 // Smart reserve: full capacity if needed, small reserve otherwise
853 if (needs_full) {
854 this->scan_result_.reserve(number);
855 } else {
856 this->scan_result_.reserve(WIFI_SCAN_RESULT_FILTERED_RESERVE);
857 }
858
859#ifdef USE_ESP32_HOSTED
860 // getting records one at a time fails on P4 with hosted esp32 WiFi coprocessor
861 // Presumably an upstream bug, work-around by getting all records at once
862 // Use stack buffer (3904 bytes / ~80 bytes per record = ~48 records) with heap fallback
863 static constexpr size_t SCAN_RECORD_STACK_COUNT = 3904 / sizeof(wifi_ap_record_t);
864 SmallBufferWithHeapFallback<SCAN_RECORD_STACK_COUNT, wifi_ap_record_t> records(number);
865 err = esp_wifi_scan_get_ap_records(&number, records.get());
866 if (err != ESP_OK) {
867 esp_wifi_clear_ap_list();
868 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
869 return;
870 }
871 for (uint16_t i = 0; i < number; i++) {
872 wifi_ap_record_t &record = records.get()[i];
873#else
874 // Process one record at a time to avoid large buffer allocation
875 for (uint16_t i = 0; i < number; i++) {
876 wifi_ap_record_t record;
877 err = esp_wifi_scan_get_ap_record(&record);
878 if (err != ESP_OK) {
879 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_record failed: %s", esp_err_to_name(err));
880 esp_wifi_clear_ap_list(); // Free remaining records not yet retrieved
881 break;
882 }
883#endif // USE_ESP32_HOSTED
884
885 // Check C string first - avoid std::string construction for non-matching networks
886 const char *ssid_cstr = reinterpret_cast<const char *>(record.ssid);
887
888 // Only construct std::string and store if needed
889 if (needs_full || this->matches_configured_network_(ssid_cstr, record.bssid)) {
890 bssid_t bssid;
891 std::copy(record.bssid, record.bssid + 6, bssid.begin());
892 this->scan_result_.emplace_back(bssid, ssid_cstr, strlen(ssid_cstr), record.primary, record.rssi,
893 record.authmode != WIFI_AUTH_OPEN, ssid_cstr[0] == '\0');
894 } else {
895 this->log_discarded_scan_result_(ssid_cstr, record.bssid, record.rssi, record.primary);
896 }
897 }
898 ESP_LOGV(TAG, "Scan complete: %u found, %zu stored%s", number, this->scan_result_.size(),
899 needs_full ? "" : " (filtered)");
900#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
902#endif
903
904 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
905 ESP_LOGV(TAG, "AP start");
906 this->ap_started_ = true;
907
908 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
909 ESP_LOGV(TAG, "AP stop");
910 this->ap_started_ = false;
911
912 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
913#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
914 const auto &it = data->data.ap_probe_req_rx;
915 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
916 format_mac_addr_upper(it.mac, mac_buf);
917 ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", mac_buf, it.rssi);
918#endif
919
920 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
921#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
922 const auto &it = data->data.ap_staconnected;
923 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
924 format_mac_addr_upper(it.mac, mac_buf);
925 ESP_LOGV(TAG, "AP client connected MAC=%s", mac_buf);
926#endif
927
928 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
929#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
930 const auto &it = data->data.ap_stadisconnected;
931 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
932 format_mac_addr_upper(it.mac, mac_buf);
933 ESP_LOGV(TAG, "AP client disconnected MAC=%s", mac_buf);
934#endif
935
936#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0)
937 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_ASSIGNED_IP_TO_CLIENT) {
938 const auto &it = data->data.ip_assigned_ip_to_client;
939#else
940 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
941 const auto &it = data->data.ip_ap_staipassigned;
942#endif
943 ESP_LOGV(TAG, "AP client assigned IP " IPSTR, IP2STR(&it.ip));
944 }
945}
946
948 if (s_sta_connected && this->got_ipv4_address_) {
949#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
950 if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
952 }
953#else
955#endif /* USE_NETWORK_IPV6 */
956 }
957 if (s_sta_connect_error) {
959 }
960 if (s_sta_connect_not_found) {
962 }
963 if (s_sta_connecting) {
965 }
967}
968bool WiFiComponent::wifi_scan_start_(bool passive) {
969 // enable STA
970 if (!this->wifi_mode_(true, {}))
971 return false;
972
973 wifi_scan_config_t config{};
974 config.ssid = nullptr;
975 config.bssid = nullptr;
976 config.channel = 0;
977 config.show_hidden = true;
978 config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
979 if (passive) {
980 config.scan_time.passive = 300;
981 } else {
982 config.scan_time.active.min = 100;
983 config.scan_time.active.max = 300;
984 }
985 // When scanning while connected (roaming), return to home channel between
986 // each scanned channel to maintain the connection (helps with BLE/WiFi coexistence)
987#ifdef CONFIG_SOC_WIFI_SUPPORTED
989 config.coex_background_scan = true;
990 }
991#endif
992
993 esp_err_t err = esp_wifi_scan_start(&config, false);
994 if (err != ESP_OK) {
995 ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
996 return false;
997 }
998
999 this->scan_done_ = false;
1000 return true;
1001}
1002
1003#ifdef USE_WIFI_AP
1004bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
1005 esp_err_t err;
1006
1007 // enable AP
1008 if (!this->wifi_mode_({}, true))
1009 return false;
1010
1011 // Check if the AP interface is initialized before using it
1012 if (s_ap_netif == nullptr) {
1013 ESP_LOGW(TAG, "AP interface not initialized");
1014 return false;
1015 }
1016
1017 esp_netif_ip_info_t info;
1018 if (manual_ip.has_value()) {
1019 info.ip = manual_ip->static_ip;
1020 info.gw = manual_ip->gateway;
1021 info.netmask = manual_ip->subnet;
1022 } else {
1023 info.ip = network::IPAddress(192, 168, 4, 1);
1024 info.gw = network::IPAddress(192, 168, 4, 1);
1025 info.netmask = network::IPAddress(255, 255, 255, 0);
1026 }
1027
1028 err = esp_netif_dhcps_stop(s_ap_netif);
1029 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
1030 ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
1031 return false;
1032 }
1033
1034 err = esp_netif_set_ip_info(s_ap_netif, &info);
1035 if (err != ESP_OK) {
1036 ESP_LOGE(TAG, "esp_netif_set_ip_info failed: %d", err);
1037 return false;
1038 }
1039
1040 dhcps_lease_t lease;
1041 lease.enable = true;
1042 network::IPAddress start_address = network::IPAddress(&info.ip);
1043 start_address += 99;
1044 lease.start_ip = start_address;
1045#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1046 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1047#endif
1048 ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str_to(ip_buf));
1049 start_address += 10;
1050 lease.end_ip = start_address;
1051 ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str_to(ip_buf));
1052 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
1053
1054 if (err != ESP_OK) {
1055 ESP_LOGE(TAG, "esp_netif_dhcps_option failed: %d", err);
1056 return false;
1057 }
1058
1059#if defined(USE_CAPTIVE_PORTAL) && ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0)
1060 // Configure DHCP Option 114 (Captive Portal URI) if captive portal is enabled
1061 // This provides a standards-compliant way for clients to discover the captive portal
1063 // Buffer must be static - dhcps_set_option_info stores pointer, doesn't copy
1064 static char captive_portal_uri[24]; // "http://" (7) + IPv4 max (15) + null
1065 memcpy(captive_portal_uri, "http://", 7); // NOLINT(bugprone-not-null-terminated-result) - str_to null-terminates
1066 network::IPAddress(&info.ip).str_to(captive_portal_uri + 7);
1067 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_CAPTIVEPORTAL_URI, captive_portal_uri,
1068 strlen(captive_portal_uri));
1069 if (err != ESP_OK) {
1070 ESP_LOGV(TAG, "Failed to set DHCP captive portal URI: %s", esp_err_to_name(err));
1071 } else {
1072 ESP_LOGV(TAG, "DHCP Captive Portal URI set to: %s", captive_portal_uri);
1073 }
1074 }
1075#endif
1076
1077 err = esp_netif_dhcps_start(s_ap_netif);
1078
1079 if (err != ESP_OK) {
1080 ESP_LOGE(TAG, "esp_netif_dhcps_start failed: %d", err);
1081 return false;
1082 }
1083
1084 return true;
1085}
1086
1087bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
1088 // enable AP
1089 if (!this->wifi_mode_({}, true))
1090 return false;
1091
1092 wifi_config_t conf;
1093 memset(&conf, 0, sizeof(conf));
1094 if (ap.ssid_.size() > sizeof(conf.ap.ssid)) {
1095 ESP_LOGE(TAG, "AP SSID too long");
1096 return false;
1097 }
1098 memcpy(reinterpret_cast<char *>(conf.ap.ssid), ap.ssid_.c_str(), ap.ssid_.size());
1099 conf.ap.channel = ap.has_channel() ? ap.get_channel() : 1;
1100 conf.ap.ssid_hidden = ap.get_hidden();
1101 conf.ap.max_connection = 5;
1102 conf.ap.beacon_interval = 100;
1103
1104 if (ap.password_.empty()) {
1105 conf.ap.authmode = WIFI_AUTH_OPEN;
1106 *conf.ap.password = 0;
1107 } else {
1108 conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
1109 if (ap.password_.size() > sizeof(conf.ap.password)) {
1110 ESP_LOGE(TAG, "AP password too long");
1111 return false;
1112 }
1113 memcpy(reinterpret_cast<char *>(conf.ap.password), ap.password_.c_str(), ap.password_.size());
1114 }
1115
1116 // pairwise cipher of SoftAP, group cipher will be derived using this.
1117 conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
1118
1119 esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
1120 if (err != ESP_OK) {
1121 ESP_LOGE(TAG, "esp_wifi_set_config failed: %d", err);
1122 return false;
1123 }
1124
1125#ifdef USE_WIFI_MANUAL_IP
1126 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
1127 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed:");
1128 return false;
1129 }
1130#else
1131 if (!this->wifi_ap_ip_config_({})) {
1132 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed:");
1133 return false;
1134 }
1135#endif
1136
1137 return true;
1138}
1139
1140network::IPAddress WiFiComponent::wifi_soft_ap_ip() {
1141 esp_netif_ip_info_t ip;
1142 esp_netif_get_ip_info(s_ap_netif, &ip);
1143 return network::IPAddress(&ip.ip);
1144}
1145#endif // USE_WIFI_AP
1146
1147bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
1148
1150 bssid_t bssid{};
1151 wifi_ap_record_t info;
1152 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1153 if (err != ESP_OK) {
1154 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1155 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1156 return bssid;
1157 }
1158 std::copy(info.bssid, info.bssid + 6, bssid.begin());
1159 return bssid;
1160}
1161std::string WiFiComponent::wifi_ssid() {
1162 wifi_ap_record_t info{};
1163 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1164 if (err != ESP_OK) {
1165 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1166 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1167 return "";
1168 }
1169 auto *ssid_s = reinterpret_cast<const char *>(info.ssid);
1170 size_t len = strnlen(ssid_s, sizeof(info.ssid));
1171 return {ssid_s, len};
1172}
1173const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
1174 wifi_ap_record_t info{};
1175 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1176 if (err != ESP_OK) {
1177 buffer[0] = '\0';
1178 return buffer.data();
1179 }
1180 // info.ssid is uint8[33], but only 32 bytes are SSID data
1181 size_t len = strnlen(reinterpret_cast<const char *>(info.ssid), 32);
1182 memcpy(buffer.data(), info.ssid, len);
1183 buffer[len] = '\0';
1184 return buffer.data();
1185}
1186int8_t WiFiComponent::wifi_rssi() {
1187 wifi_ap_record_t info;
1188 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
1189 if (err != ESP_OK) {
1190 // Very verbose only: this is expected during dump_config() before connection is established (PR #9823)
1191 ESP_LOGVV(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
1192 return WIFI_RSSI_DISCONNECTED;
1193 }
1194 return info.rssi;
1195}
1197 uint8_t primary;
1198 wifi_second_chan_t second;
1199 esp_err_t err = esp_wifi_get_channel(&primary, &second);
1200 if (err != ESP_OK) {
1201 ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
1202 return 0;
1203 }
1204 return primary;
1205}
1206network::IPAddress WiFiComponent::wifi_subnet_mask_() {
1207 esp_netif_ip_info_t ip;
1208 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1209 if (err != ESP_OK) {
1210 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1211 return {};
1212 }
1213 return network::IPAddress(&ip.netmask);
1214}
1215network::IPAddress WiFiComponent::wifi_gateway_ip_() {
1216 esp_netif_ip_info_t ip;
1217 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1218 if (err != ESP_OK) {
1219 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1220 return {};
1221 }
1222 return network::IPAddress(&ip.gw);
1223}
1224network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
1225 const ip_addr_t *dns_ip = dns_getserver(num);
1226 return network::IPAddress(dns_ip);
1227}
1228
1229} // namespace esphome::wifi
1230#endif // USE_ESP32
1231#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
Definition helpers.h:1045
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:1420
uint8_t event_id
Definition tt21100.cpp:3