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