ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
wifi_component.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2#ifdef USE_WIFI
3#include <cinttypes>
4#include <map>
5
6#ifdef USE_ESP_IDF
7#if (ESP_IDF_VERSION_MAJOR >= 5 && ESP_IDF_VERSION_MINOR >= 1)
8#include <esp_eap_client.h>
9#else
10#include <esp_wpa2.h>
11#endif
12#endif
13
14#if defined(USE_ESP32) || defined(USE_ESP_IDF)
15#include <esp_wifi.h>
16#endif
17#ifdef USE_ESP8266
18#include <user_interface.h>
19#endif
20
21#include <algorithm>
22#include <utility>
23#include "lwip/dns.h"
24#include "lwip/err.h"
25
27#include "esphome/core/hal.h"
29#include "esphome/core/log.h"
30#include "esphome/core/util.h"
31
32#ifdef USE_CAPTIVE_PORTAL
34#endif
35
36#ifdef USE_IMPROV
38#endif
39
40namespace esphome {
41namespace wifi {
42
43static const char *const TAG = "wifi";
44
46
48 this->wifi_pre_setup_();
49 if (this->enable_on_boot_) {
50 this->start();
51 } else {
52#ifdef USE_ESP32
53 esp_netif_init();
54#endif
56 }
57}
58
60 ESP_LOGCONFIG(TAG,
61 "Starting\n"
62 " Local MAC: %s",
63 get_mac_address_pretty().c_str());
64 this->last_connected_ = millis();
65
66 uint32_t hash = this->has_sta() ? fnv1_hash(App.get_compilation_time()) : 88491487UL;
67
69 if (this->fast_connect_) {
71 }
72
73 SavedWifiSettings save{};
74 if (this->pref_.load(&save)) {
75 ESP_LOGD(TAG, "Loaded settings: %s", save.ssid);
76
77 WiFiAP sta{};
78 sta.set_ssid(save.ssid);
79 sta.set_password(save.password);
80 this->set_sta(sta);
81 }
82
83 if (this->has_sta()) {
84 this->wifi_sta_pre_setup_();
85 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
86 ESP_LOGV(TAG, "Setting Output Power Option failed");
87 }
88
89 if (!this->wifi_apply_power_save_()) {
90 ESP_LOGV(TAG, "Setting Power Save Option failed");
91 }
92
93 if (this->fast_connect_) {
95 if (!this->trying_loaded_ap_) {
96 this->ap_index_ = 0;
97 this->selected_ap_ = this->sta_[this->ap_index_];
98 }
99 this->start_connecting(this->selected_ap_, false);
100 } else {
101 this->start_scanning();
102 }
103#ifdef USE_WIFI_AP
104 } else if (this->has_ap()) {
105 this->setup_ap_config_();
106 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
107 ESP_LOGV(TAG, "Setting Output Power Option failed");
108 }
109#ifdef USE_CAPTIVE_PORTAL
111 this->wifi_sta_pre_setup_();
112 this->start_scanning();
114 }
115#endif
116#endif // USE_WIFI_AP
117 }
118#ifdef USE_IMPROV
119 if (!this->has_sta() && esp32_improv::global_improv_component != nullptr) {
120 if (this->wifi_mode_(true, {}))
122 }
123#endif
124 this->wifi_apply_hostname_();
125}
126
128 ESP_LOGW(TAG, "Restarting adapter");
129 this->wifi_mode_(false, {});
130 delay(100); // NOLINT
131 this->num_retried_ = 0;
132 this->retry_hidden_ = false;
133}
134
136 this->wifi_loop_();
137 const uint32_t now = App.get_loop_component_start_time();
138
139 if (this->has_sta()) {
140 if (this->is_connected() != this->handled_connected_state_) {
141 if (this->handled_connected_state_) {
143 } else {
144 this->connect_trigger_->trigger();
145 }
147 }
148
149 switch (this->state_) {
151 this->status_set_warning("waiting to reconnect");
152 if (millis() - this->action_started_ > 5000) {
153 if (this->fast_connect_ || this->retry_hidden_) {
154 this->start_connecting(this->selected_ap_, false);
155 } else {
156 this->start_scanning();
157 }
158 }
159 break;
160 }
162 this->status_set_warning("scanning for networks");
164 break;
165 }
168 this->status_set_warning("associating to network");
170 break;
171 }
172
174 if (!this->is_connected()) {
175 ESP_LOGW(TAG, "Connection lost; reconnecting");
177 this->retry_connect();
178 } else {
179 this->status_clear_warning();
180 this->last_connected_ = now;
181 }
182 break;
183 }
186 break;
188 return;
189 }
190
191#ifdef USE_WIFI_AP
192 if (this->has_ap() && !this->ap_setup_) {
193 if (this->ap_timeout_ != 0 && (now - this->last_connected_ > this->ap_timeout_)) {
194 ESP_LOGI(TAG, "Starting fallback AP");
195 this->setup_ap_config_();
196#ifdef USE_CAPTIVE_PORTAL
199#endif
200 }
201 }
202#endif // USE_WIFI_AP
203
204#ifdef USE_IMPROV
206 if (now - this->last_connected_ > esp32_improv::global_improv_component->get_wifi_timeout()) {
207 if (this->wifi_mode_(true, {}))
209 }
210 }
211
212#endif
213
214 if (!this->has_ap() && this->reboot_timeout_ != 0) {
215 if (now - this->last_connected_ > this->reboot_timeout_) {
216 ESP_LOGE(TAG, "Can't connect; rebooting");
217 App.reboot();
218 }
219 }
220 }
221}
222
224
225bool WiFiComponent::has_ap() const { return this->has_ap_; }
226bool WiFiComponent::has_sta() const { return !this->sta_.empty(); }
227void WiFiComponent::set_fast_connect(bool fast_connect) { this->fast_connect_ = fast_connect; }
228#ifdef USE_WIFI_11KV_SUPPORT
229void WiFiComponent::set_btm(bool btm) { this->btm_ = btm; }
230void WiFiComponent::set_rrm(bool rrm) { this->rrm_ = rrm; }
231#endif
233 if (this->has_sta())
234 return this->wifi_sta_ip_addresses();
235
236#ifdef USE_WIFI_AP
237 if (this->has_ap())
238 return {this->wifi_soft_ap_ip()};
239#endif // USE_WIFI_AP
240
241 return {};
242}
244 if (this->has_sta())
245 return this->wifi_dns_ip_(num);
246 return {};
247}
249 if (this->use_address_.empty()) {
250 return App.get_name() + ".local";
251 }
252 return this->use_address_;
253}
254void WiFiComponent::set_use_address(const std::string &use_address) { this->use_address_ = use_address; }
255
256#ifdef USE_WIFI_AP
258 this->wifi_mode_({}, true);
259
260 if (this->ap_setup_)
261 return;
262
263 if (this->ap_.get_ssid().empty()) {
264 std::string name = App.get_name();
265 if (name.length() > 32) {
267 name.erase(name.begin() + 25, name.end() - 7); // Remove characters between 25 and the mac address
268 } else {
269 name = name.substr(0, 32);
270 }
271 }
272 this->ap_.set_ssid(name);
273 }
274 ESP_LOGCONFIG(TAG,
275 "Setting up AP:\n"
276 " AP SSID: '%s'\n"
277 " AP Password: '%s'",
278 this->ap_.get_ssid().c_str(), this->ap_.get_password().c_str());
279 if (this->ap_.get_manual_ip().has_value()) {
280 auto manual = *this->ap_.get_manual_ip();
281 ESP_LOGCONFIG(TAG,
282 " AP Static IP: '%s'\n"
283 " AP Gateway: '%s'\n"
284 " AP Subnet: '%s'",
285 manual.static_ip.str().c_str(), manual.gateway.str().c_str(), manual.subnet.str().c_str());
286 }
287
288 this->ap_setup_ = this->wifi_start_ap_(this->ap_);
289 ESP_LOGCONFIG(TAG, " IP Address: %s", this->wifi_soft_ap_ip().str().c_str());
290
291 if (!this->has_sta()) {
293 }
294}
295
297 this->ap_ = ap;
298 this->has_ap_ = true;
299}
300#endif // USE_WIFI_AP
301
303 return 10.0f; // before other loop components
304}
305
306void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); }
308 this->clear_sta();
309 this->add_sta(ap);
310}
311void WiFiComponent::clear_sta() { this->sta_.clear(); }
312void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
313 SavedWifiSettings save{};
314 snprintf(save.ssid, sizeof(save.ssid), "%s", ssid.c_str());
315 snprintf(save.password, sizeof(save.password), "%s", password.c_str());
316 this->pref_.save(&save);
317 // ensure it's written immediately
319
320 WiFiAP sta{};
321 sta.set_ssid(ssid);
322 sta.set_password(password);
323 this->set_sta(sta);
324}
325
326void WiFiComponent::start_connecting(const WiFiAP &ap, bool two) {
327 ESP_LOGI(TAG, "Connecting to '%s'", ap.get_ssid().c_str());
328#ifdef ESPHOME_LOG_HAS_VERBOSE
329 ESP_LOGV(TAG, "Connection Params:");
330 ESP_LOGV(TAG, " SSID: '%s'", ap.get_ssid().c_str());
331 if (ap.get_bssid().has_value()) {
332 bssid_t b = *ap.get_bssid();
333 ESP_LOGV(TAG, " BSSID: %02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5]);
334 } else {
335 ESP_LOGV(TAG, " BSSID: Not Set");
336 }
337
338#ifdef USE_WIFI_WPA2_EAP
339 if (ap.get_eap().has_value()) {
340 ESP_LOGV(TAG, " WPA2 Enterprise authentication configured:");
341 EAPAuth eap_config = ap.get_eap().value();
342 ESP_LOGV(TAG, " Identity: " LOG_SECRET("'%s'"), eap_config.identity.c_str());
343 ESP_LOGV(TAG, " Username: " LOG_SECRET("'%s'"), eap_config.username.c_str());
344 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), eap_config.password.c_str());
345#ifdef USE_ESP_IDF
346#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
347 std::map<esp_eap_ttls_phase2_types, std::string> phase2types = {{ESP_EAP_TTLS_PHASE2_PAP, "pap"},
348 {ESP_EAP_TTLS_PHASE2_CHAP, "chap"},
349 {ESP_EAP_TTLS_PHASE2_MSCHAP, "mschap"},
350 {ESP_EAP_TTLS_PHASE2_MSCHAPV2, "mschapv2"},
351 {ESP_EAP_TTLS_PHASE2_EAP, "eap"}};
352 ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), phase2types[eap_config.ttls_phase_2].c_str());
353#endif
354#endif
355 bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert);
356 bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert);
357 bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key);
358 ESP_LOGV(TAG, " CA Cert: %s", ca_cert_present ? "present" : "not present");
359 ESP_LOGV(TAG, " Client Cert: %s", client_cert_present ? "present" : "not present");
360 ESP_LOGV(TAG, " Client Key: %s", client_key_present ? "present" : "not present");
361 } else {
362#endif
363 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), ap.get_password().c_str());
364#ifdef USE_WIFI_WPA2_EAP
365 }
366#endif
367 if (ap.get_channel().has_value()) {
368 ESP_LOGV(TAG, " Channel: %u", *ap.get_channel());
369 } else {
370 ESP_LOGV(TAG, " Channel not set");
371 }
372 if (ap.get_manual_ip().has_value()) {
373 ManualIP m = *ap.get_manual_ip();
374 ESP_LOGV(TAG, " Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s", m.static_ip.str().c_str(),
375 m.gateway.str().c_str(), m.subnet.str().c_str(), m.dns1.str().c_str(), m.dns2.str().c_str());
376 } else {
377 ESP_LOGV(TAG, " Using DHCP IP");
378 }
379 ESP_LOGV(TAG, " Hidden: %s", YESNO(ap.get_hidden()));
380#endif
381
382 if (!this->wifi_sta_connect_(ap)) {
383 ESP_LOGE(TAG, "wifi_sta_connect_ failed");
384 this->retry_connect();
385 return;
386 }
387
388 if (!two) {
390 } else {
392 }
393 this->action_started_ = millis();
394}
395
396const LogString *get_signal_bars(int8_t rssi) {
397 // LOWER ONE QUARTER BLOCK
398 // Unicode: U+2582, UTF-8: E2 96 82
399 // LOWER HALF BLOCK
400 // Unicode: U+2584, UTF-8: E2 96 84
401 // LOWER THREE QUARTERS BLOCK
402 // Unicode: U+2586, UTF-8: E2 96 86
403 // FULL BLOCK
404 // Unicode: U+2588, UTF-8: E2 96 88
405 if (rssi >= -50) {
406 return LOG_STR("\033[0;32m" // green
407 "\xe2\x96\x82"
408 "\xe2\x96\x84"
409 "\xe2\x96\x86"
410 "\xe2\x96\x88"
411 "\033[0m");
412 } else if (rssi >= -65) {
413 return LOG_STR("\033[0;33m" // yellow
414 "\xe2\x96\x82"
415 "\xe2\x96\x84"
416 "\xe2\x96\x86"
417 "\033[0;37m"
418 "\xe2\x96\x88"
419 "\033[0m");
420 } else if (rssi >= -85) {
421 return LOG_STR("\033[0;33m" // yellow
422 "\xe2\x96\x82"
423 "\xe2\x96\x84"
424 "\033[0;37m"
425 "\xe2\x96\x86"
426 "\xe2\x96\x88"
427 "\033[0m");
428 } else {
429 return LOG_STR("\033[0;31m" // red
430 "\xe2\x96\x82"
431 "\033[0;37m"
432 "\xe2\x96\x84"
433 "\xe2\x96\x86"
434 "\xe2\x96\x88"
435 "\033[0m");
436 }
437}
438
440 bssid_t bssid = wifi_bssid();
441
442 ESP_LOGCONFIG(TAG, " Local MAC: %s", get_mac_address_pretty().c_str());
443 if (this->is_disabled()) {
444 ESP_LOGCONFIG(TAG, " Disabled");
445 return;
446 }
447 ESP_LOGCONFIG(TAG, " SSID: " LOG_SECRET("'%s'"), wifi_ssid().c_str());
448 for (auto &ip : wifi_sta_ip_addresses()) {
449 if (ip.is_set()) {
450 ESP_LOGCONFIG(TAG, " IP Address: %s", ip.str().c_str());
451 }
452 }
453 int8_t rssi = wifi_rssi();
454 ESP_LOGCONFIG(TAG,
455 " BSSID: " LOG_SECRET("%02X:%02X:%02X:%02X:%02X:%02X") "\n"
456 " Hostname: '%s'\n"
457 " Signal strength: %d dB %s",
458 bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], App.get_name().c_str(), rssi,
459 LOG_STR_ARG(get_signal_bars(rssi)));
460#ifdef ESPHOME_LOG_HAS_VERBOSE
461 if (this->selected_ap_.get_bssid().has_value()) {
462 ESP_LOGV(TAG, " Priority: %.1f", this->get_sta_priority(*this->selected_ap_.get_bssid()));
463 }
464#endif
465 ESP_LOGCONFIG(TAG,
466 " Channel: %" PRId32 "\n"
467 " Subnet: %s\n"
468 " Gateway: %s\n"
469 " DNS1: %s\n"
470 " DNS2: %s",
471 get_wifi_channel(), wifi_subnet_mask_().str().c_str(), wifi_gateway_ip_().str().c_str(),
472 wifi_dns_ip_(0).str().c_str(), wifi_dns_ip_(1).str().c_str());
473#ifdef USE_WIFI_11KV_SUPPORT
474 ESP_LOGCONFIG(TAG,
475 " BTM: %s\n"
476 " RRM: %s",
477 this->btm_ ? "enabled" : "disabled", this->rrm_ ? "enabled" : "disabled");
478#endif
479}
480
483 return;
484
485 ESP_LOGD(TAG, "Enabling");
486 this->error_from_callback_ = false;
488 this->start();
489}
490
493 return;
494
495 ESP_LOGD(TAG, "Disabling");
497 this->wifi_disconnect_();
498 this->wifi_mode_(false, false);
499}
500
502
504 this->action_started_ = millis();
505 ESP_LOGD(TAG, "Starting scan");
506 this->wifi_scan_start_(this->passive_scan_);
508}
509
510// Helper function for WiFi scan result comparison
511// Returns true if 'a' should be placed before 'b' in the sorted order
512[[nodiscard]] inline static bool wifi_scan_result_is_better(const WiFiScanResult &a, const WiFiScanResult &b) {
513 // Matching networks always come before non-matching
514 if (a.get_matches() && !b.get_matches())
515 return true;
516 if (!a.get_matches() && b.get_matches())
517 return false;
518
519 if (a.get_matches() && b.get_matches()) {
520 // For APs with the same SSID, always prefer stronger signal
521 // This helps with mesh networks and multiple APs
522 if (a.get_ssid() == b.get_ssid()) {
523 return a.get_rssi() > b.get_rssi();
524 }
525
526 // For different SSIDs, check priority first
527 if (a.get_priority() != b.get_priority())
528 return a.get_priority() > b.get_priority();
529 // If priorities are equal, prefer stronger signal
530 return a.get_rssi() > b.get_rssi();
531 }
532
533 // Both don't match - sort by signal strength
534 return a.get_rssi() > b.get_rssi();
535}
536
537// Helper function for insertion sort of WiFi scan results
538// Using insertion sort instead of std::stable_sort saves flash memory
539// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
540// IMPORTANT: This sort is stable (preserves relative order of equal elements)
541static void insertion_sort_scan_results(std::vector<WiFiScanResult> &results) {
542 const size_t size = results.size();
543 for (size_t i = 1; i < size; i++) {
544 // Make a copy to avoid issues with move semantics during comparison
545 WiFiScanResult key = results[i];
546 int32_t j = i - 1;
547
548 // Move elements that are worse than key to the right
549 // For stability, we only move if key is strictly better than results[j]
550 while (j >= 0 && wifi_scan_result_is_better(key, results[j])) {
551 results[j + 1] = results[j];
552 j--;
553 }
554 results[j + 1] = key;
555 }
556}
557
559 if (!this->scan_done_) {
560 if (millis() - this->action_started_ > 30000) {
561 ESP_LOGE(TAG, "Scan timeout");
562 this->retry_connect();
563 }
564 return;
565 }
566 this->scan_done_ = false;
567
568 if (this->scan_result_.empty()) {
569 ESP_LOGW(TAG, "No networks found");
570 this->retry_connect();
571 return;
572 }
573
574 ESP_LOGD(TAG, "Found networks:");
575 for (auto &res : this->scan_result_) {
576 for (auto &ap : this->sta_) {
577 if (res.matches(ap)) {
578 res.set_matches(true);
579 if (!this->has_sta_priority(res.get_bssid())) {
580 this->set_sta_priority(res.get_bssid(), ap.get_priority());
581 }
582 res.set_priority(this->get_sta_priority(res.get_bssid()));
583 break;
584 }
585 }
586 }
587
588 // Sort scan results using insertion sort for better memory efficiency
589 insertion_sort_scan_results(this->scan_result_);
590
591 for (auto &res : this->scan_result_) {
592 char bssid_s[18];
593 auto bssid = res.get_bssid();
594 sprintf(bssid_s, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
595
596 if (res.get_matches()) {
597 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
598 res.get_is_hidden() ? "(HIDDEN) " : "", bssid_s, LOG_STR_ARG(get_signal_bars(res.get_rssi())));
599 ESP_LOGD(TAG,
600 " Channel: %u\n"
601 " RSSI: %d dB",
602 res.get_channel(), res.get_rssi());
603 } else {
604 ESP_LOGD(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(), bssid_s,
605 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
606 }
607 }
608
609 if (!this->scan_result_[0].get_matches()) {
610 ESP_LOGW(TAG, "No matching network found");
611 this->retry_connect();
612 return;
613 }
614
615 WiFiAP connect_params;
616 WiFiScanResult scan_res = this->scan_result_[0];
617 for (auto &config : this->sta_) {
618 // search for matching STA config, at least one will match (from checks before)
619 if (!scan_res.matches(config)) {
620 continue;
621 }
622
623 if (config.get_hidden()) {
624 // selected network is hidden, we use the data from the config
625 connect_params.set_hidden(true);
626 connect_params.set_ssid(config.get_ssid());
627 // don't set BSSID and channel, there might be multiple hidden networks
628 // but we can't know which one is the correct one. Rely on probe-req with just SSID.
629 } else {
630 // selected network is visible, we use the data from the scan
631 // limit the connect params to only connect to exactly this network
632 // (network selection is done during scan phase).
633 connect_params.set_hidden(false);
634 connect_params.set_ssid(scan_res.get_ssid());
635 connect_params.set_channel(scan_res.get_channel());
636 connect_params.set_bssid(scan_res.get_bssid());
637 }
638 // copy manual IP (if set)
639 connect_params.set_manual_ip(config.get_manual_ip());
640
641#ifdef USE_WIFI_WPA2_EAP
642 // copy EAP parameters (if set)
643 connect_params.set_eap(config.get_eap());
644#endif
645
646 // copy password (if set)
647 connect_params.set_password(config.get_password());
648
649 break;
650 }
651
652 yield();
653
654 this->selected_ap_ = connect_params;
655 this->start_connecting(connect_params, false);
656}
657
659 ESP_LOGCONFIG(TAG, "WiFi:");
660 this->print_connect_params_();
661}
662
664 auto status = this->wifi_sta_connect_status_();
665
667 if (wifi_ssid().empty()) {
668 ESP_LOGW(TAG, "Connection incomplete");
669 this->retry_connect();
670 return;
671 }
672
673 // We won't retry hidden networks unless a reconnect fails more than three times again
674 this->retry_hidden_ = false;
675
676 ESP_LOGI(TAG, "Connected");
677 this->print_connect_params_();
678
679 if (this->has_ap()) {
680#ifdef USE_CAPTIVE_PORTAL
681 if (this->is_captive_portal_active_()) {
683 }
684#endif
685 ESP_LOGD(TAG, "Disabling AP");
686 this->wifi_mode_({}, false);
687 }
688#ifdef USE_IMPROV
689 if (this->is_esp32_improv_active_()) {
691 }
692#endif
693
695 this->num_retried_ = 0;
696
697 if (this->fast_connect_) {
699 }
700
701 return;
702 }
703
704 uint32_t now = millis();
705 if (now - this->action_started_ > 30000) {
706 ESP_LOGW(TAG, "Connection timeout");
707 this->retry_connect();
708 return;
709 }
710
711 if (this->error_from_callback_) {
712 ESP_LOGW(TAG, "Connecting to network failed");
713 this->retry_connect();
714 return;
715 }
716
718 return;
719 }
720
722 ESP_LOGW(TAG, "Network no longer found");
723 this->retry_connect();
724 return;
725 }
726
728 ESP_LOGW(TAG, "Connecting to network failed");
729 this->retry_connect();
730 return;
731 }
732
733 ESP_LOGW(TAG, "Unknown connection status %d", (int) status);
734 this->retry_connect();
735}
736
738 if (this->selected_ap_.get_bssid()) {
739 auto bssid = *this->selected_ap_.get_bssid();
740 float priority = this->get_sta_priority(bssid);
741 this->set_sta_priority(bssid, priority - 1.0f);
742 }
743
744 delay(10);
745 if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_() &&
746 (this->num_retried_ > 3 || this->error_from_callback_)) {
747 if (this->fast_connect_) {
748 if (this->trying_loaded_ap_) {
749 this->trying_loaded_ap_ = false;
750 this->ap_index_ = 0; // Retry from the first configured AP
751 } else if (this->ap_index_ >= this->sta_.size() - 1) {
752 ESP_LOGW(TAG, "No more APs to try");
753 this->ap_index_ = 0;
754 this->restart_adapter();
755 } else {
756 // Try next AP
757 this->ap_index_++;
758 }
759 this->num_retried_ = 0;
760 this->selected_ap_ = this->sta_[this->ap_index_];
761 } else {
762 if (this->num_retried_ > 5) {
763 // If retry failed for more than 5 times, let's restart STA
764 this->restart_adapter();
765 } else {
766 // Try hidden networks after 3 failed retries
767 ESP_LOGD(TAG, "Retrying with hidden networks");
768 this->retry_hidden_ = true;
769 this->num_retried_++;
770 }
771 }
772 } else {
773 this->num_retried_++;
774 }
775 this->error_from_callback_ = false;
777 yield();
779 this->start_connecting(this->selected_ap_, true);
780 return;
781 }
782
784 this->action_started_ = millis();
785}
786
788 if (!this->has_sta() || this->state_ == WIFI_COMPONENT_STATE_DISABLED || this->ap_setup_) {
789 return true;
790 }
791 return this->is_connected();
792}
793void WiFiComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
799
800void WiFiComponent::set_passive_scan(bool passive) { this->passive_scan_ = passive; }
801
803#ifdef USE_CAPTIVE_PORTAL
805#else
806 return false;
807#endif
808}
810#ifdef USE_IMPROV
812#else
813 return false;
814#endif
815}
816
818 SavedWifiFastConnectSettings fast_connect_save{};
819
820 if (this->fast_connect_pref_.load(&fast_connect_save)) {
821 bssid_t bssid{};
822 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
823 this->ap_index_ = fast_connect_save.ap_index;
824 this->selected_ap_ = this->sta_[this->ap_index_];
825 this->selected_ap_.set_bssid(bssid);
826 this->selected_ap_.set_channel(fast_connect_save.channel);
827
828 ESP_LOGD(TAG, "Loaded fast_connect settings");
829 return true;
830 }
831
832 return false;
833}
834
836 bssid_t bssid = wifi_bssid();
837 uint8_t channel = get_wifi_channel();
838
839 if (bssid != this->selected_ap_.get_bssid() || channel != this->selected_ap_.get_channel()) {
840 SavedWifiFastConnectSettings fast_connect_save{};
841
842 memcpy(fast_connect_save.bssid, bssid.data(), 6);
843 fast_connect_save.channel = channel;
844 fast_connect_save.ap_index = this->ap_index_;
845
846 this->fast_connect_pref_.save(&fast_connect_save);
847
848 ESP_LOGD(TAG, "Saved fast_connect settings");
849 }
850}
851
852void WiFiAP::set_ssid(const std::string &ssid) { this->ssid_ = ssid; }
853void WiFiAP::set_bssid(bssid_t bssid) { this->bssid_ = bssid; }
854void WiFiAP::set_bssid(optional<bssid_t> bssid) { this->bssid_ = bssid; }
855void WiFiAP::set_password(const std::string &password) { this->password_ = password; }
856#ifdef USE_WIFI_WPA2_EAP
857void WiFiAP::set_eap(optional<EAPAuth> eap_auth) { this->eap_ = std::move(eap_auth); }
858#endif
859void WiFiAP::set_channel(optional<uint8_t> channel) { this->channel_ = channel; }
860void WiFiAP::set_manual_ip(optional<ManualIP> manual_ip) { this->manual_ip_ = manual_ip; }
861void WiFiAP::set_hidden(bool hidden) { this->hidden_ = hidden; }
862const std::string &WiFiAP::get_ssid() const { return this->ssid_; }
863const optional<bssid_t> &WiFiAP::get_bssid() const { return this->bssid_; }
864const std::string &WiFiAP::get_password() const { return this->password_; }
865#ifdef USE_WIFI_WPA2_EAP
866const optional<EAPAuth> &WiFiAP::get_eap() const { return this->eap_; }
867#endif
868const optional<uint8_t> &WiFiAP::get_channel() const { return this->channel_; }
870bool WiFiAP::get_hidden() const { return this->hidden_; }
871
872WiFiScanResult::WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth,
873 bool is_hidden)
874 : bssid_(bssid),
875 ssid_(std::move(ssid)),
876 channel_(channel),
877 rssi_(rssi),
878 with_auth_(with_auth),
879 is_hidden_(is_hidden) {}
880bool WiFiScanResult::matches(const WiFiAP &config) {
881 if (config.get_hidden()) {
882 // User configured a hidden network, only match actually hidden networks
883 // don't match SSID
884 if (!this->is_hidden_)
885 return false;
886 } else if (!config.get_ssid().empty()) {
887 // check if SSID matches
888 if (config.get_ssid() != this->ssid_)
889 return false;
890 } else {
891 // network is configured without SSID - match other settings
892 }
893 // If BSSID configured, only match for correct BSSIDs
894 if (config.get_bssid().has_value() && *config.get_bssid() != this->bssid_)
895 return false;
896
897#ifdef USE_WIFI_WPA2_EAP
898 // BSSID requires auth but no PSK or EAP credentials given
899 if (this->with_auth_ && (config.get_password().empty() && !config.get_eap().has_value()))
900 return false;
901
902 // BSSID does not require auth, but PSK or EAP credentials given
903 if (!this->with_auth_ && (!config.get_password().empty() || config.get_eap().has_value()))
904 return false;
905#else
906 // If PSK given, only match for networks with auth (and vice versa)
907 if (config.get_password().empty() == this->with_auth_)
908 return false;
909#endif
910
911 // If channel configured, only match networks on that channel.
912 if (config.get_channel().has_value() && *config.get_channel() != this->channel_) {
913 return false;
914 }
915 return true;
916}
917bool WiFiScanResult::get_matches() const { return this->matches_; }
918void WiFiScanResult::set_matches(bool matches) { this->matches_ = matches; }
919const bssid_t &WiFiScanResult::get_bssid() const { return this->bssid_; }
920const std::string &WiFiScanResult::get_ssid() const { return this->ssid_; }
921uint8_t WiFiScanResult::get_channel() const { return this->channel_; }
922int8_t WiFiScanResult::get_rssi() const { return this->rssi_; }
923bool WiFiScanResult::get_with_auth() const { return this->with_auth_; }
924bool WiFiScanResult::get_is_hidden() const { return this->is_hidden_; }
925
926bool WiFiScanResult::operator==(const WiFiScanResult &rhs) const { return this->bssid_ == rhs.bssid_; }
927
928WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
929
930} // namespace wifi
931} // namespace esphome
932#endif
uint8_t m
Definition bl0906.h:1
uint8_t status
Definition bl0942.h:8
std::string get_compilation_time() const
bool is_name_add_mac_suffix_enabled() const
const std::string & get_name() const
Get the name of this Application set by pre_setup().
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition automation.h:145
bool has_value() const
Definition optional.h:92
const optional< bssid_t > & get_bssid() const
const std::string & get_ssid() const
void set_ssid(const std::string &ssid)
const optional< uint8_t > & get_channel() const
const optional< EAPAuth > & get_eap() const
void set_channel(optional< uint8_t > channel)
const std::string & get_password() const
void set_bssid(bssid_t bssid)
optional< uint8_t > channel_
optional< EAPAuth > eap_
optional< bssid_t > bssid_
optional< ManualIP > manual_ip_
void set_eap(optional< EAPAuth > eap_auth)
void set_password(const std::string &password)
void set_manual_ip(optional< ManualIP > manual_ip)
const optional< ManualIP > & get_manual_ip() const
void set_hidden(bool hidden)
This component is responsible for managing the ESP WiFi interface.
void add_sta(const WiFiAP &ap)
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)
bool has_sta_priority(const bssid_t &bssid)
std::string get_use_address() const
void save_wifi_sta(const std::string &ssid, const std::string &password)
void loop() override
Reconnect WiFi if required.
float get_sta_priority(const bssid_t bssid)
network::IPAddress get_dns_address(int num)
WiFiComponent()
Construct a WiFiComponent.
std::vector< WiFiScanResult > scan_result_
void start_connecting(const WiFiAP &ap, bool two)
void set_passive_scan(bool passive)
void set_power_save_mode(WiFiPowerSaveMode power_save)
void set_use_address(const std::string &use_address)
ESPPreferenceObject fast_connect_pref_
float get_loop_priority() const override
network::IPAddresses get_ip_addresses()
std::vector< WiFiAP > sta_
float get_setup_priority() const override
WIFI setup_priority.
optional< float > output_power_
void set_sta_priority(const bssid_t bssid, float priority)
void set_fast_connect(bool fast_connect)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
void set_reboot_timeout(uint32_t reboot_timeout)
void setup() override
Setup WiFi interface.
const std::string & get_ssid() const
const bssid_t & get_bssid() const
WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth, bool is_hidden)
bool matches(const WiFiAP &config)
bool operator==(const WiFiScanResult &rhs) const
uint8_t priority
CaptivePortal * global_captive_portal
ESP32ImprovComponent * global_improv_component
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:144
std::array< uint8_t, 6 > bssid_t
const LogString * get_signal_bars(int8_t rssi)
WiFiComponent * global_wifi_component
@ WIFI_COMPONENT_STATE_DISABLED
WiFi is disabled.
@ WIFI_COMPONENT_STATE_AP
WiFi is in AP-only mode and internal AP is already enabled.
@ WIFI_COMPONENT_STATE_STA_CONNECTING
WiFi is in STA(+AP) mode and currently connecting to an AP.
@ WIFI_COMPONENT_STATE_OFF
Nothing has been initialized yet.
@ WIFI_COMPONENT_STATE_STA_SCANNING
WiFi is in STA-only mode and currently scanning for APs.
@ WIFI_COMPONENT_STATE_STA_CONNECTING_2
WiFi is in STA(+AP) mode and currently connecting to an AP a second time.
@ WIFI_COMPONENT_STATE_COOLDOWN
WiFi is in cooldown mode because something went wrong, scanning will begin after a short period of ti...
@ WIFI_COMPONENT_STATE_STA_CONNECTED
WiFi is in STA(+AP) mode and successfully connected.
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:134
ESPPreferences * global_preferences
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:584
void IRAM_ATTR HOT yield()
Definition core.cpp:27
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.