ESPHome 2025.12.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 <cassert>
4#include <cinttypes>
5
6#ifdef USE_ESP32
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)
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
146
147static const LogString *retry_phase_to_log_string(WiFiRetryPhase phase) {
148 switch (phase) {
150 return LOG_STR("INITIAL_CONNECT");
151#ifdef USE_WIFI_FAST_CONNECT
153 return LOG_STR("FAST_CONNECT_CYCLING");
154#endif
156 return LOG_STR("EXPLICIT_HIDDEN");
158 return LOG_STR("SCAN_CONNECTING");
160 return LOG_STR("RETRY_HIDDEN");
162 return LOG_STR("RESTARTING");
163 default:
164 return LOG_STR("UNKNOWN");
165 }
166}
167
169 // If first configured network is marked hidden, we went through EXPLICIT_HIDDEN phase
170 // This means those networks were already tried and should be skipped in RETRY_HIDDEN
171 return !this->sta_.empty() && this->sta_[0].get_hidden();
172}
173
175 // Find the first network that is NOT marked hidden:true
176 // This is where EXPLICIT_HIDDEN phase would have stopped
177 for (size_t i = 0; i < this->sta_.size(); i++) {
178 if (!this->sta_[i].get_hidden()) {
179 return static_cast<int8_t>(i);
180 }
181 }
182 return -1; // All networks are hidden
183}
184
185// 2 attempts per BSSID in SCAN_CONNECTING phase
186// Rationale: This is the ONLY phase where we decrease BSSID priority, so we must be very sure.
187// Auth failures are common immediately after scan due to WiFi stack state transitions.
188// Trying twice filters out false positives and prevents unnecessarily marking a good BSSID as bad.
189// After 2 genuine failures, priority degradation ensures we skip this BSSID on subsequent scans.
190static constexpr uint8_t WIFI_RETRY_COUNT_PER_BSSID = 2;
191
192// 1 attempt per SSID in RETRY_HIDDEN phase
193// Rationale: Try hidden mode once, then rescan to get next best BSSID via priority system
194static constexpr uint8_t WIFI_RETRY_COUNT_PER_SSID = 1;
195
196// 1 attempt per AP in fast_connect mode (INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS)
197// Rationale: Fast connect prioritizes speed - try each AP once to find a working one quickly
198static constexpr uint8_t WIFI_RETRY_COUNT_PER_AP = 1;
199
202static constexpr uint32_t WIFI_COOLDOWN_DURATION_MS = 1000;
203
204static constexpr uint8_t get_max_retries_for_phase(WiFiRetryPhase phase) {
205 switch (phase) {
207#ifdef USE_WIFI_FAST_CONNECT
209#endif
210 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS both use 1 attempt per AP (fast_connect mode)
211 return WIFI_RETRY_COUNT_PER_AP;
213 // Explicitly hidden network: 1 attempt (user marked as hidden, try once then scan)
214 return WIFI_RETRY_COUNT_PER_SSID;
216 // Scan-based phase: 2 attempts per BSSID (handles transient auth failures after scan)
217 return WIFI_RETRY_COUNT_PER_BSSID;
219 // Hidden network mode: 1 attempt per SSID
220 return WIFI_RETRY_COUNT_PER_SSID;
221 default:
222 return WIFI_RETRY_COUNT_PER_BSSID;
223 }
224}
225
226static void apply_scan_result_to_params(WiFiAP &params, const WiFiScanResult &scan) {
227 params.set_hidden(false);
228 params.set_ssid(scan.get_ssid());
229 params.set_bssid(scan.get_bssid());
230 params.set_channel(scan.get_channel());
231}
232
234 // Only SCAN_CONNECTING phase needs scan results
236 return false;
237 }
238 // Need scan if we have no results or no matching networks
239 return this->scan_result_.empty() || !this->scan_result_[0].get_matches();
240}
241
242bool WiFiComponent::ssid_was_seen_in_scan_(const std::string &ssid) const {
243 // Check if this SSID is configured as hidden
244 // If explicitly marked hidden, we should always try hidden mode regardless of scan results
245 for (const auto &conf : this->sta_) {
246 if (conf.get_ssid() == ssid && conf.get_hidden()) {
247 return false; // Treat as not seen - force hidden mode attempt
248 }
249 }
250
251 // Otherwise, check if we saw it in scan results
252 for (const auto &scan : this->scan_result_) {
253 if (scan.get_ssid() == ssid) {
254 return true;
255 }
256 }
257 return false;
258}
259
260int8_t WiFiComponent::find_next_hidden_sta_(int8_t start_index) {
261 // Find next SSID that wasn't in scan results (might be hidden)
262 bool include_explicit_hidden = !this->went_through_explicit_hidden_phase_();
263 // Start searching from start_index + 1
264 for (size_t i = start_index + 1; i < this->sta_.size(); i++) {
265 const auto &sta = this->sta_[i];
266
267 // Skip networks that were already tried in EXPLICIT_HIDDEN phase
268 // Those are: networks marked hidden:true that appear before the first non-hidden network
269 // If all networks are hidden (first_non_hidden_idx == -1), skip all of them
270 if (!include_explicit_hidden && sta.get_hidden()) {
271 int8_t first_non_hidden_idx = this->find_first_non_hidden_index_();
272 if (first_non_hidden_idx < 0 || static_cast<int8_t>(i) < first_non_hidden_idx) {
273 ESP_LOGD(TAG, "Skipping " LOG_SECRET("'%s'") " (explicit hidden, already tried)", sta.get_ssid().c_str());
274 continue;
275 }
276 }
277
278 if (!this->ssid_was_seen_in_scan_(sta.get_ssid())) {
279 ESP_LOGD(TAG, "Hidden candidate " LOG_SECRET("'%s'") " at index %d", sta.get_ssid().c_str(), static_cast<int>(i));
280 return static_cast<int8_t>(i);
281 }
282 ESP_LOGD(TAG, "Skipping hidden retry for visible network " LOG_SECRET("'%s'"), sta.get_ssid().c_str());
283 }
284 // No hidden SSIDs found
285 return -1;
286}
287
289 // If first network (highest priority) is explicitly marked hidden, try it first before scanning
290 // This respects user's priority order when they explicitly configure hidden networks
291 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
292 ESP_LOGI(TAG, "Starting with explicit hidden network (highest priority)");
293 this->selected_sta_index_ = 0;
296 this->start_connecting(params);
297 } else {
298 ESP_LOGI(TAG, "Starting scan");
299 this->start_scanning();
300 }
301}
302
303#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
304static const char *eap_phase2_to_str(esp_eap_ttls_phase2_types type) {
305 switch (type) {
306 case ESP_EAP_TTLS_PHASE2_PAP:
307 return "pap";
308 case ESP_EAP_TTLS_PHASE2_CHAP:
309 return "chap";
310 case ESP_EAP_TTLS_PHASE2_MSCHAP:
311 return "mschap";
312 case ESP_EAP_TTLS_PHASE2_MSCHAPV2:
313 return "mschapv2";
314 case ESP_EAP_TTLS_PHASE2_EAP:
315 return "eap";
316 default:
317 return "unknown";
318 }
319}
320#endif
321
323
325 this->wifi_pre_setup_();
326 if (this->enable_on_boot_) {
327 this->start();
328 } else {
329#ifdef USE_ESP32
330 esp_netif_init();
331#endif
333 }
334}
335
337 ESP_LOGCONFIG(TAG,
338 "Starting\n"
339 " Local MAC: %s",
340 get_mac_address_pretty().c_str());
341 this->last_connected_ = millis();
342
343 uint32_t hash = this->has_sta() ? fnv1_hash(App.get_compilation_time()) : 88491487UL;
344
346#ifdef USE_WIFI_FAST_CONNECT
348#endif
349
350 SavedWifiSettings save{};
351 if (this->pref_.load(&save)) {
352 ESP_LOGD(TAG, "Loaded settings: %s", save.ssid);
353
354 WiFiAP sta{};
355 sta.set_ssid(save.ssid);
356 sta.set_password(save.password);
357 this->set_sta(sta);
358 }
359
360 if (this->has_sta()) {
361 this->wifi_sta_pre_setup_();
362 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
363 ESP_LOGV(TAG, "Setting Output Power Option failed");
364 }
365
366 if (!this->wifi_apply_power_save_()) {
367 ESP_LOGV(TAG, "Setting Power Save Option failed");
368 }
369
371#ifdef USE_WIFI_FAST_CONNECT
372 WiFiAP params;
373 bool loaded_fast_connect = this->load_fast_connect_settings_(params);
374 // Fast connect optimization: only use when we have saved BSSID+channel data
375 // Without saved data, try first configured network or use normal flow
376 if (loaded_fast_connect) {
377 ESP_LOGI(TAG, "Starting fast_connect (saved) " LOG_SECRET("'%s'"), params.get_ssid().c_str());
378 this->start_connecting(params);
379 } else if (!this->sta_.empty() && !this->sta_[0].get_hidden()) {
380 // No saved data, but have configured networks - try first non-hidden network
381 ESP_LOGI(TAG, "Starting fast_connect (config) " LOG_SECRET("'%s'"), this->sta_[0].get_ssid().c_str());
382 this->selected_sta_index_ = 0;
383 params = this->build_params_for_current_phase_();
384 this->start_connecting(params);
385 } else {
386 // No saved data and (no networks OR first is hidden) - use normal flow
388 }
389#else
390 // Without fast_connect: go straight to scanning (or hidden mode if all networks are hidden)
392#endif
393#ifdef USE_WIFI_AP
394 } else if (this->has_ap()) {
395 this->setup_ap_config_();
396 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
397 ESP_LOGV(TAG, "Setting Output Power Option failed");
398 }
399#ifdef USE_CAPTIVE_PORTAL
401 this->wifi_sta_pre_setup_();
402 this->start_scanning();
404 }
405#endif
406#endif // USE_WIFI_AP
407 }
408#ifdef USE_IMPROV
409 if (!this->has_sta() && esp32_improv::global_improv_component != nullptr) {
410 if (this->wifi_mode_(true, {}))
412 }
413#endif
414 this->wifi_apply_hostname_();
415}
416
418 ESP_LOGW(TAG, "Restarting adapter");
419 this->wifi_mode_(false, {});
420 // Enter cooldown state to allow WiFi hardware to stabilize after restart
421 // Don't set retry_phase_ or num_retried_ here - state machine handles transitions
423 this->action_started_ = millis();
424 this->error_from_callback_ = false;
425}
426
428 this->wifi_loop_();
429 const uint32_t now = App.get_loop_component_start_time();
430
431 if (this->has_sta()) {
432 if (this->is_connected() != this->handled_connected_state_) {
433 if (this->handled_connected_state_) {
435 } else {
436 this->connect_trigger_->trigger();
437 }
439 }
440
441 switch (this->state_) {
443 this->status_set_warning(LOG_STR("waiting to reconnect"));
444 if (now - this->action_started_ > WIFI_COOLDOWN_DURATION_MS) {
445 // After cooldown we either restarted the adapter because of
446 // a failure, or something tried to connect over and over
447 // so we entered cooldown. In both cases we call
448 // check_connecting_finished to continue the state machine.
450 }
451 break;
452 }
454 this->status_set_warning(LOG_STR("scanning for networks"));
456 break;
457 }
459 this->status_set_warning(LOG_STR("associating to network"));
461 break;
462 }
463
465 if (!this->is_connected()) {
466 ESP_LOGW(TAG, "Connection lost; reconnecting");
468 // Clear error flag before reconnecting so first attempt is not seen as immediate failure
469 this->error_from_callback_ = false;
470 this->retry_connect();
471 } else {
472 this->status_clear_warning();
473 this->last_connected_ = now;
474 }
475 break;
476 }
479 break;
481 return;
482 }
483
484#ifdef USE_WIFI_AP
485 if (this->has_ap() && !this->ap_setup_) {
486 if (this->ap_timeout_ != 0 && (now - this->last_connected_ > this->ap_timeout_)) {
487 ESP_LOGI(TAG, "Starting fallback AP");
488 this->setup_ap_config_();
489#ifdef USE_CAPTIVE_PORTAL
492#endif
493 }
494 }
495#endif // USE_WIFI_AP
496
497#ifdef USE_IMPROV
499 if (now - this->last_connected_ > esp32_improv::global_improv_component->get_wifi_timeout()) {
500 if (this->wifi_mode_(true, {}))
502 }
503 }
504
505#endif
506
507 if (!this->has_ap() && this->reboot_timeout_ != 0) {
508 if (now - this->last_connected_ > this->reboot_timeout_) {
509 ESP_LOGE(TAG, "Can't connect; rebooting");
510 App.reboot();
511 }
512 }
513 }
514}
515
517
518bool WiFiComponent::has_ap() const { return this->has_ap_; }
519bool WiFiComponent::has_sta() const { return !this->sta_.empty(); }
520#ifdef USE_WIFI_11KV_SUPPORT
521void WiFiComponent::set_btm(bool btm) { this->btm_ = btm; }
522void WiFiComponent::set_rrm(bool rrm) { this->rrm_ = rrm; }
523#endif
525 if (this->has_sta())
526 return this->wifi_sta_ip_addresses();
527
528#ifdef USE_WIFI_AP
529 if (this->has_ap())
530 return {this->wifi_soft_ap_ip()};
531#endif // USE_WIFI_AP
532
533 return {};
534}
536 if (this->has_sta())
537 return this->wifi_dns_ip_(num);
538 return {};
539}
540// set_use_address() is guaranteed to be called during component setup by Python code generation,
541// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
542const char *WiFiComponent::get_use_address() const { return this->use_address_; }
543void WiFiComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
544
545#ifdef USE_WIFI_AP
547 this->wifi_mode_({}, true);
548
549 if (this->ap_setup_)
550 return;
551
552 if (this->ap_.get_ssid().empty()) {
553 std::string name = App.get_name();
554 if (name.length() > 32) {
556 // Keep first 25 chars and last 7 chars (MAC suffix), remove middle
557 name.erase(25, name.length() - 32);
558 } else {
559 name.resize(32);
560 }
561 }
562 this->ap_.set_ssid(name);
563 }
564 this->ap_setup_ = this->wifi_start_ap_(this->ap_);
565
566 auto ip_address = this->wifi_soft_ap_ip().str();
567 ESP_LOGCONFIG(TAG,
568 "Setting up AP:\n"
569 " AP SSID: '%s'\n"
570 " AP Password: '%s'\n"
571 " IP Address: %s",
572 this->ap_.get_ssid().c_str(), this->ap_.get_password().c_str(), ip_address.c_str());
573
574#ifdef USE_WIFI_MANUAL_IP
575 auto manual_ip = this->ap_.get_manual_ip();
576 if (manual_ip.has_value()) {
577 ESP_LOGCONFIG(TAG,
578 " AP Static IP: '%s'\n"
579 " AP Gateway: '%s'\n"
580 " AP Subnet: '%s'",
581 manual_ip->static_ip.str().c_str(), manual_ip->gateway.str().c_str(),
582 manual_ip->subnet.str().c_str());
583 }
584#endif
585
586 if (!this->has_sta()) {
588 }
589}
590
592 this->ap_ = ap;
593 this->has_ap_ = true;
594}
595#endif // USE_WIFI_AP
596
598 return 10.0f; // before other loop components
599}
600
601void WiFiComponent::init_sta(size_t count) { this->sta_.init(count); }
602void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); }
604 this->clear_sta();
605 this->init_sta(1);
606 this->add_sta(ap);
607 this->selected_sta_index_ = 0;
608}
609
611 const WiFiAP *config = this->get_selected_sta_();
612 if (config == nullptr) {
613 ESP_LOGE(TAG, "No valid network config (selected_sta_index_=%d, sta_.size()=%zu)",
614 static_cast<int>(this->selected_sta_index_), this->sta_.size());
615 // Return empty params - caller should handle this gracefully
616 return WiFiAP();
617 }
618
619 WiFiAP params = *config;
620
621 switch (this->retry_phase_) {
623#ifdef USE_WIFI_FAST_CONNECT
625#endif
626 // Fast connect phases: use config-only (no scan results)
627 // BSSID/channel from config if user specified them, otherwise empty
628 break;
629
632 // Hidden network mode: clear BSSID/channel to trigger probe request
633 // (both explicit hidden and retry hidden use same behavior)
636 break;
637
639 // Scan-based phase: always use best scan result (index 0 - highest priority after sorting)
640 if (!this->scan_result_.empty()) {
641 apply_scan_result_to_params(params, this->scan_result_[0]);
642 }
643 break;
644
646 // Should not be building params during restart
647 break;
648 }
649
650 return params;
651}
652
654 const WiFiAP *config = this->get_selected_sta_();
655 return config ? *config : WiFiAP{};
656}
657void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
658 SavedWifiSettings save{}; // zero-initialized - all bytes set to \0, guaranteeing null termination
659 strncpy(save.ssid, ssid.c_str(), sizeof(save.ssid) - 1); // max 32 chars, byte 32 remains \0
660 strncpy(save.password, password.c_str(), sizeof(save.password) - 1); // max 64 chars, byte 64 remains \0
661 this->pref_.save(&save);
662 // ensure it's written immediately
664
665 WiFiAP sta{};
666 sta.set_ssid(ssid);
667 sta.set_password(password);
668 this->set_sta(sta);
669}
670
672 // Log connection attempt at INFO level with priority
673 char bssid_s[18];
674 int8_t priority = 0;
675
676 if (ap.get_bssid().has_value()) {
677 format_mac_addr_upper(ap.get_bssid().value().data(), bssid_s);
679 }
680
681 ESP_LOGI(TAG,
682 "Connecting to " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") " (priority %d, attempt %u/%u in phase %s)...",
683 ap.get_ssid().c_str(), ap.get_bssid().has_value() ? bssid_s : LOG_STR_LITERAL("any"), priority,
684 this->num_retried_ + 1, get_max_retries_for_phase(this->retry_phase_),
685 LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
686
687#ifdef ESPHOME_LOG_HAS_VERBOSE
688 ESP_LOGV(TAG, "Connection Params:");
689 ESP_LOGV(TAG, " SSID: '%s'", ap.get_ssid().c_str());
690 if (ap.get_bssid().has_value()) {
691 ESP_LOGV(TAG, " BSSID: %s", bssid_s);
692 } else {
693 ESP_LOGV(TAG, " BSSID: Not Set");
694 }
695
696#ifdef USE_WIFI_WPA2_EAP
697 if (ap.get_eap().has_value()) {
698 ESP_LOGV(TAG, " WPA2 Enterprise authentication configured:");
699 EAPAuth eap_config = ap.get_eap().value();
700 ESP_LOGV(TAG, " Identity: " LOG_SECRET("'%s'"), eap_config.identity.c_str());
701 ESP_LOGV(TAG, " Username: " LOG_SECRET("'%s'"), eap_config.username.c_str());
702 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), eap_config.password.c_str());
703#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
704 ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), eap_phase2_to_str(eap_config.ttls_phase_2));
705#endif
706 bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert);
707 bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert);
708 bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key);
709 ESP_LOGV(TAG, " CA Cert: %s", ca_cert_present ? "present" : "not present");
710 ESP_LOGV(TAG, " Client Cert: %s", client_cert_present ? "present" : "not present");
711 ESP_LOGV(TAG, " Client Key: %s", client_key_present ? "present" : "not present");
712 } else {
713#endif
714 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), ap.get_password().c_str());
715#ifdef USE_WIFI_WPA2_EAP
716 }
717#endif
718 if (ap.get_channel().has_value()) {
719 ESP_LOGV(TAG, " Channel: %u", *ap.get_channel());
720 } else {
721 ESP_LOGV(TAG, " Channel not set");
722 }
723#ifdef USE_WIFI_MANUAL_IP
724 if (ap.get_manual_ip().has_value()) {
725 ManualIP m = *ap.get_manual_ip();
726 ESP_LOGV(TAG, " Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s", m.static_ip.str().c_str(),
727 m.gateway.str().c_str(), m.subnet.str().c_str(), m.dns1.str().c_str(), m.dns2.str().c_str());
728 } else
729#endif
730 {
731 ESP_LOGV(TAG, " Using DHCP IP");
732 }
733 ESP_LOGV(TAG, " Hidden: %s", YESNO(ap.get_hidden()));
734#endif
735
736 if (!this->wifi_sta_connect_(ap)) {
737 ESP_LOGE(TAG, "wifi_sta_connect_ failed");
738 // Enter cooldown to allow WiFi hardware to stabilize
739 // (immediate failure suggests hardware not ready, different from connection timeout)
741 } else {
743 }
744 this->action_started_ = millis();
745}
746
747const LogString *get_signal_bars(int8_t rssi) {
748 // Check for disconnected sentinel value first
749 if (rssi == WIFI_RSSI_DISCONNECTED) {
750 // MULTIPLICATION SIGN
751 // Unicode: U+00D7, UTF-8: C3 97
752 return LOG_STR("\033[0;31m" // red
753 "\xc3\x97\xc3\x97\xc3\x97\xc3\x97"
754 "\033[0m");
755 }
756 // LOWER ONE QUARTER BLOCK
757 // Unicode: U+2582, UTF-8: E2 96 82
758 // LOWER HALF BLOCK
759 // Unicode: U+2584, UTF-8: E2 96 84
760 // LOWER THREE QUARTERS BLOCK
761 // Unicode: U+2586, UTF-8: E2 96 86
762 // FULL BLOCK
763 // Unicode: U+2588, UTF-8: E2 96 88
764 if (rssi >= -50) {
765 return LOG_STR("\033[0;32m" // green
766 "\xe2\x96\x82"
767 "\xe2\x96\x84"
768 "\xe2\x96\x86"
769 "\xe2\x96\x88"
770 "\033[0m");
771 } else if (rssi >= -65) {
772 return LOG_STR("\033[0;33m" // yellow
773 "\xe2\x96\x82"
774 "\xe2\x96\x84"
775 "\xe2\x96\x86"
776 "\033[0;37m"
777 "\xe2\x96\x88"
778 "\033[0m");
779 } else if (rssi >= -85) {
780 return LOG_STR("\033[0;33m" // yellow
781 "\xe2\x96\x82"
782 "\xe2\x96\x84"
783 "\033[0;37m"
784 "\xe2\x96\x86"
785 "\xe2\x96\x88"
786 "\033[0m");
787 } else {
788 return LOG_STR("\033[0;31m" // red
789 "\xe2\x96\x82"
790 "\033[0;37m"
791 "\xe2\x96\x84"
792 "\xe2\x96\x86"
793 "\xe2\x96\x88"
794 "\033[0m");
795 }
796}
797
799 bssid_t bssid = wifi_bssid();
800 char bssid_s[18];
801 format_mac_addr_upper(bssid.data(), bssid_s);
802
803 ESP_LOGCONFIG(TAG, " Local MAC: %s", get_mac_address_pretty().c_str());
804 if (this->is_disabled()) {
805 ESP_LOGCONFIG(TAG, " Disabled");
806 return;
807 }
808 for (auto &ip : wifi_sta_ip_addresses()) {
809 if (ip.is_set()) {
810 ESP_LOGCONFIG(TAG, " IP Address: %s", ip.str().c_str());
811 }
812 }
813 int8_t rssi = wifi_rssi();
814 ESP_LOGCONFIG(TAG,
815 " SSID: " LOG_SECRET("'%s'") "\n"
816 " BSSID: " LOG_SECRET("%s") "\n"
817 " Hostname: '%s'\n"
818 " Signal strength: %d dB %s\n"
819 " Channel: %" PRId32 "\n"
820 " Subnet: %s\n"
821 " Gateway: %s\n"
822 " DNS1: %s\n"
823 " DNS2: %s",
824 wifi_ssid().c_str(), bssid_s, App.get_name().c_str(), rssi, LOG_STR_ARG(get_signal_bars(rssi)),
825 get_wifi_channel(), wifi_subnet_mask_().str().c_str(), wifi_gateway_ip_().str().c_str(),
826 wifi_dns_ip_(0).str().c_str(), wifi_dns_ip_(1).str().c_str());
827#ifdef ESPHOME_LOG_HAS_VERBOSE
828 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid().has_value()) {
829 ESP_LOGV(TAG, " Priority: %d", this->get_sta_priority(*config->get_bssid()));
830 }
831#endif
832#ifdef USE_WIFI_11KV_SUPPORT
833 ESP_LOGCONFIG(TAG,
834 " BTM: %s\n"
835 " RRM: %s",
836 this->btm_ ? "enabled" : "disabled", this->rrm_ ? "enabled" : "disabled");
837#endif
838}
839
842 return;
843
844 ESP_LOGD(TAG, "Enabling");
845 this->error_from_callback_ = false;
847 this->start();
848}
849
852 return;
853
854 ESP_LOGD(TAG, "Disabling");
856 this->wifi_disconnect_();
857 this->wifi_mode_(false, false);
858}
859
861
863 this->action_started_ = millis();
864 ESP_LOGD(TAG, "Starting scan");
865 this->wifi_scan_start_(this->passive_scan_);
867}
868
902[[nodiscard]] inline static bool wifi_scan_result_is_better(const WiFiScanResult &a, const WiFiScanResult &b) {
903 // Matching networks always come before non-matching
904 if (a.get_matches() && !b.get_matches())
905 return true;
906 if (!a.get_matches() && b.get_matches())
907 return false;
908
909 // Both matching: check priority first (tracks connection failures via priority degradation)
910 // Priority is decreased when a BSSID fails to connect, so lower priority = previously failed
911 if (a.get_matches() && b.get_matches() && a.get_priority() != b.get_priority()) {
912 return a.get_priority() > b.get_priority();
913 }
914
915 // Use RSSI as tiebreaker (for equal-priority matching networks or all non-matching networks)
916 return a.get_rssi() > b.get_rssi();
917}
918
919// Helper function for insertion sort of WiFi scan results
920// Using insertion sort instead of std::stable_sort saves flash memory
921// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
922// IMPORTANT: This sort is stable (preserves relative order of equal elements)
923template<typename VectorType> static void insertion_sort_scan_results(VectorType &results) {
924 const size_t size = results.size();
925 for (size_t i = 1; i < size; i++) {
926 // Make a copy to avoid issues with move semantics during comparison
927 WiFiScanResult key = results[i];
928 int32_t j = i - 1;
929
930 // Move elements that are worse than key to the right
931 // For stability, we only move if key is strictly better than results[j]
932 while (j >= 0 && wifi_scan_result_is_better(key, results[j])) {
933 results[j + 1] = results[j];
934 j--;
935 }
936 results[j + 1] = key;
937 }
938}
939
940// Helper function to log scan results - marked noinline to prevent re-inlining into loop
941__attribute__((noinline)) static void log_scan_result(const WiFiScanResult &res) {
942 char bssid_s[18];
943 auto bssid = res.get_bssid();
944 format_mac_addr_upper(bssid.data(), bssid_s);
945
946 if (res.get_matches()) {
947 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
948 res.get_is_hidden() ? LOG_STR_LITERAL("(HIDDEN) ") : LOG_STR_LITERAL(""), bssid_s,
949 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
950 ESP_LOGD(TAG, " Channel: %2u, RSSI: %3d dB, Priority: %4d", res.get_channel(), res.get_rssi(), res.get_priority());
951 } else {
952 ESP_LOGD(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(), bssid_s,
953 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
954 }
955}
956
958 if (!this->scan_done_) {
959 if (millis() - this->action_started_ > 30000) {
960 ESP_LOGE(TAG, "Scan timeout");
961 this->retry_connect();
962 }
963 return;
964 }
965 this->scan_done_ = false;
966
967 if (this->scan_result_.empty()) {
968 ESP_LOGW(TAG, "No networks found");
969 this->retry_connect();
970 return;
971 }
972
973 ESP_LOGD(TAG, "Found networks:");
974 for (auto &res : this->scan_result_) {
975 for (auto &ap : this->sta_) {
976 if (res.matches(ap)) {
977 res.set_matches(true);
978 // Cache priority lookup - do single search instead of 2 separate searches
979 const bssid_t &bssid = res.get_bssid();
980 if (!this->has_sta_priority(bssid)) {
981 this->set_sta_priority(bssid, ap.get_priority());
982 }
983 res.set_priority(this->get_sta_priority(bssid));
984 break;
985 }
986 }
987 }
988
989 // Sort scan results using insertion sort for better memory efficiency
990 insertion_sort_scan_results(this->scan_result_);
991
992 for (auto &res : this->scan_result_) {
993 log_scan_result(res);
994 }
995
996 // SYNCHRONIZATION POINT: Establish link between scan_result_[0] and selected_sta_index_
997 // After sorting, scan_result_[0] contains the best network. Now find which sta_[i] config
998 // matches that network and record it in selected_sta_index_. This keeps the two indices
999 // synchronized so build_params_for_current_phase_() can safely use both to build connection parameters.
1000 const WiFiScanResult &scan_res = this->scan_result_[0];
1001 bool found_match = false;
1002 if (scan_res.get_matches()) {
1003 for (size_t i = 0; i < this->sta_.size(); i++) {
1004 if (scan_res.matches(this->sta_[i])) {
1005 // Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
1006 // No overflow check needed - YAML validation prevents >127 networks
1007 this->selected_sta_index_ = static_cast<int8_t>(i); // Links scan_result_[0] with sta_[i]
1008 found_match = true;
1009 break;
1010 }
1011 }
1012 }
1013
1014 if (!found_match) {
1015 ESP_LOGW(TAG, "No matching network found");
1016 // No scan results matched our configured networks - transition directly to hidden mode
1017 // Don't call retry_connect() since we never attempted a connection (no BSSID to penalize)
1019 // If no hidden networks to try, skip connection attempt (will be handled on next loop)
1020 if (this->selected_sta_index_ == -1) {
1021 return;
1022 }
1023 // Now start connection attempt in hidden mode
1025 return; // scan started, wait for next loop iteration
1026 }
1027
1028 yield();
1029
1030 WiFiAP params = this->build_params_for_current_phase_();
1031 // Ensure we're in SCAN_CONNECTING phase when connecting with scan results
1032 // (needed when scan was started directly without transition_to_phase_, e.g., initial scan)
1033 this->start_connecting(params);
1034}
1035
1037 ESP_LOGCONFIG(TAG,
1038 "WiFi:\n"
1039 " Connected: %s",
1040 YESNO(this->is_connected()));
1041 this->print_connect_params_();
1042}
1043
1045 auto status = this->wifi_sta_connect_status_();
1046
1048 if (wifi_ssid().empty()) {
1049 ESP_LOGW(TAG, "Connection incomplete");
1050 this->retry_connect();
1051 return;
1052 }
1053
1054 ESP_LOGI(TAG, "Connected");
1055 // Warn if we had to retry with hidden network mode for a network that's not marked hidden
1056 // Only warn if we actually connected without scan data (SSID only), not if scan succeeded on retry
1057 if (const WiFiAP *config = this->get_selected_sta_(); this->retry_phase_ == WiFiRetryPhase::RETRY_HIDDEN &&
1058 config && !config->get_hidden() &&
1059 this->scan_result_.empty()) {
1060 ESP_LOGW(TAG, LOG_SECRET("'%s'") " should be marked hidden", config->get_ssid().c_str());
1061 }
1062 // Reset to initial phase on successful connection (don't log transition, just reset state)
1064 this->num_retried_ = 0;
1065 // Ensure next connection attempt does not inherit error state
1066 // so when WiFi disconnects later we start fresh and don't see
1067 // the first connection as a failure.
1068 this->error_from_callback_ = false;
1069
1070 this->print_connect_params_();
1071
1072 if (this->has_ap()) {
1073#ifdef USE_CAPTIVE_PORTAL
1074 if (this->is_captive_portal_active_()) {
1076 }
1077#endif
1078 ESP_LOGD(TAG, "Disabling AP");
1079 this->wifi_mode_({}, false);
1080 }
1081#ifdef USE_IMPROV
1082 if (this->is_esp32_improv_active_()) {
1084 }
1085#endif
1086
1088 this->num_retried_ = 0;
1089
1090 // Clear priority tracking if all priorities are at minimum
1092
1093#ifdef USE_WIFI_FAST_CONNECT
1095#endif
1096
1097 // Free scan results memory unless a component needs them
1098 if (!this->keep_scan_results_) {
1099 this->scan_result_.clear();
1100 this->scan_result_.shrink_to_fit();
1101 }
1102
1103 return;
1104 }
1105
1106 uint32_t now = millis();
1107 if (now - this->action_started_ > 30000) {
1108 ESP_LOGW(TAG, "Connection timeout");
1109 this->retry_connect();
1110 return;
1111 }
1112
1113 if (this->error_from_callback_) {
1114 ESP_LOGW(TAG, "Connecting to network failed (callback)");
1115 this->retry_connect();
1116 return;
1117 }
1118
1120 return;
1121 }
1122
1124 ESP_LOGW(TAG, "Network no longer found");
1125 this->retry_connect();
1126 return;
1127 }
1128
1130 ESP_LOGW(TAG, "Connecting to network failed");
1131 this->retry_connect();
1132 return;
1133 }
1134
1135 ESP_LOGW(TAG, "Unknown connection status %d", (int) status);
1136 this->retry_connect();
1137}
1138
1146 switch (this->retry_phase_) {
1148#ifdef USE_WIFI_FAST_CONNECT
1150 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS: no retries, try next AP or fall back to scan
1151 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
1152 return WiFiRetryPhase::FAST_CONNECT_CYCLING_APS; // Move to next AP
1153 }
1154#endif
1155 // Check if we should try explicit hidden networks before scanning
1156 // This handles reconnection after connection loss where first network is hidden
1157 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
1159 }
1160 // No more APs to try, fall back to scan
1162
1164 // Try all explicitly hidden networks before scanning
1165 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1166 return WiFiRetryPhase::EXPLICIT_HIDDEN; // Keep retrying same SSID
1167 }
1168
1169 // Exhausted retries on current SSID - check for more explicitly hidden networks
1170 // Stop when we reach a visible network (proceed to scanning)
1171 size_t next_index = this->selected_sta_index_ + 1;
1172 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
1173 // Found another explicitly hidden network
1175 }
1176
1177 // No more consecutive explicitly hidden networks
1178 // If ALL networks are hidden, skip scanning and go directly to restart
1179 if (this->find_first_non_hidden_index_() < 0) {
1181 }
1182 // Otherwise proceed to scanning for non-hidden networks
1184 }
1185
1187 // If scan found no matching networks, skip to hidden network mode
1188 if (!this->scan_result_.empty() && !this->scan_result_[0].get_matches()) {
1190 }
1191
1192 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_BSSID) {
1193 return WiFiRetryPhase::SCAN_CONNECTING; // Keep retrying same BSSID
1194 }
1195
1196 // Exhausted retries on current BSSID (scan_result_[0])
1197 // Its priority has been decreased, so on next scan it will be sorted lower
1198 // and we'll try the next best BSSID.
1199 // Check if there are any potentially hidden networks to try
1200 if (this->find_next_hidden_sta_(-1) >= 0) {
1201 return WiFiRetryPhase::RETRY_HIDDEN; // Found hidden networks to try
1202 }
1203 // No hidden networks - always go through RESTARTING_ADAPTER phase
1204 // This ensures num_retried_ gets reset and a fresh scan is triggered
1205 // The actual adapter restart will be skipped if captive portal/improv is active
1207
1209 // If no hidden SSIDs to try (selected_sta_index_ == -1), skip directly to rescan
1210 if (this->selected_sta_index_ >= 0) {
1211 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1212 return WiFiRetryPhase::RETRY_HIDDEN; // Keep retrying same SSID
1213 }
1214
1215 // Exhausted retries on current SSID - check if there are more potentially hidden SSIDs to try
1216 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
1217 // Check if find_next_hidden_sta_() would actually find another hidden SSID
1218 // as it might have been seen in the scan results and we want to skip those
1219 // otherwise we will get stuck in RETRY_HIDDEN phase
1220 if (this->find_next_hidden_sta_(this->selected_sta_index_) != -1) {
1221 // More hidden SSIDs available - stay in RETRY_HIDDEN, advance will happen in retry_connect()
1223 }
1224 }
1225 }
1226 // Exhausted all potentially hidden SSIDs - always go through RESTARTING_ADAPTER
1227 // This ensures num_retried_ gets reset and a fresh scan is triggered
1228 // The actual adapter restart will be skipped if captive portal/improv is active
1230
1232 // After restart, go back to explicit hidden if we went through it initially, otherwise scan
1235 }
1236
1237 // Should never reach here
1239}
1240
1251 WiFiRetryPhase old_phase = this->retry_phase_;
1252
1253 // No-op if staying in same phase
1254 if (old_phase == new_phase) {
1255 return false;
1256 }
1257
1258 ESP_LOGD(TAG, "Retry phase: %s → %s", LOG_STR_ARG(retry_phase_to_log_string(old_phase)),
1259 LOG_STR_ARG(retry_phase_to_log_string(new_phase)));
1260
1261 this->retry_phase_ = new_phase;
1262 this->num_retried_ = 0; // Reset retry counter on phase change
1263
1264 // Phase-specific setup
1265 switch (new_phase) {
1266#ifdef USE_WIFI_FAST_CONNECT
1268 // Move to next configured AP - clear old scan data so new AP is tried with config only
1269 this->selected_sta_index_++;
1270 this->scan_result_.clear();
1271 break;
1272#endif
1273
1275 // Starting explicit hidden phase - reset to first network
1276 this->selected_sta_index_ = 0;
1277 break;
1278
1280 // Transitioning to scan-based connection
1281#ifdef USE_WIFI_FAST_CONNECT
1283 ESP_LOGI(TAG, "Fast connect exhausted, falling back to scan");
1284 }
1285#endif
1286 // Trigger scan if we don't have scan results OR if transitioning from phases that need fresh scan
1287 if (this->scan_result_.empty() || old_phase == WiFiRetryPhase::EXPLICIT_HIDDEN ||
1289 this->selected_sta_index_ = -1; // Will be set after scan completes
1290 this->start_scanning();
1291 return true; // Started scan, wait for completion
1292 }
1293 // Already have scan results - selected_sta_index_ should already be synchronized
1294 // (set in check_scanning_finished() when scan completed)
1295 // No need to reset it here
1296 break;
1297
1299 // Starting hidden mode - find first SSID that wasn't in scan results
1300 if (old_phase == WiFiRetryPhase::SCAN_CONNECTING) {
1301 // Keep scan results so we can skip SSIDs that were visible in the scan
1302 // Don't clear scan_result_ - we need it to know which SSIDs are NOT hidden
1303
1304 // If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
1305 // In that case, skip networks marked hidden:true (already tried)
1306 // Otherwise, include them (they haven't been tried yet)
1308
1309 if (this->selected_sta_index_ == -1) {
1310 ESP_LOGD(TAG, "All SSIDs visible or already tried, skipping hidden mode");
1311 }
1312 }
1313 break;
1314
1316 // Skip actual adapter restart if captive portal/improv is active
1317 // This allows state machine to reset num_retried_ and trigger fresh scan
1318 // without disrupting the captive portal/improv connection
1319 if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_()) {
1320 this->restart_adapter();
1321 }
1322 // Return true to indicate we should wait (go to COOLDOWN) instead of immediately connecting
1323 return true;
1324
1325 default:
1326 break;
1327 }
1328
1329 return false; // Did not start scan, can proceed with connection
1330}
1331
1336 if (this->sta_priorities_.empty()) {
1337 return;
1338 }
1339
1340 int8_t first_priority = this->sta_priorities_[0].priority;
1341
1342 // Only clear if all priorities have been decremented to the minimum value
1343 // At this point, all BSSIDs have been equally penalized and priority info is useless
1344 if (first_priority != std::numeric_limits<int8_t>::min()) {
1345 return;
1346 }
1347
1348 for (const auto &pri : this->sta_priorities_) {
1349 if (pri.priority != first_priority) {
1350 return; // Not all same, nothing to do
1351 }
1352 }
1353
1354 // All priorities are at minimum - clear the vector to save memory and reset
1355 ESP_LOGD(TAG, "Clearing BSSID priorities (all at minimum)");
1356 this->sta_priorities_.clear();
1357 this->sta_priorities_.shrink_to_fit();
1358}
1359
1379 // Determine which BSSID we tried to connect to
1380 optional<bssid_t> failed_bssid;
1381
1382 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
1383 // Scan-based phase: always use best result (index 0)
1384 failed_bssid = this->scan_result_[0].get_bssid();
1385 } else if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid()) {
1386 // Config has specific BSSID (fast_connect or user-specified)
1387 failed_bssid = *config->get_bssid();
1388 }
1389
1390 if (!failed_bssid.has_value()) {
1391 return; // No BSSID to penalize
1392 }
1393
1394 // Get SSID for logging
1395 std::string ssid;
1396 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
1397 ssid = this->scan_result_[0].get_ssid();
1398 } else if (const WiFiAP *config = this->get_selected_sta_()) {
1399 ssid = config->get_ssid();
1400 }
1401
1402 // Only decrease priority on the last attempt for this phase
1403 // This prevents false positives from transient WiFi stack issues
1404 uint8_t max_retries = get_max_retries_for_phase(this->retry_phase_);
1405 bool is_last_attempt = (this->num_retried_ + 1 >= max_retries);
1406
1407 // Decrease priority only on last attempt to avoid false positives from transient failures
1408 int8_t old_priority = this->get_sta_priority(failed_bssid.value());
1409 int8_t new_priority = old_priority;
1410
1411 if (is_last_attempt) {
1412 // Decrease priority, but clamp to int8_t::min to prevent overflow
1413 new_priority =
1414 (old_priority > std::numeric_limits<int8_t>::min()) ? (old_priority - 1) : std::numeric_limits<int8_t>::min();
1415 this->set_sta_priority(failed_bssid.value(), new_priority);
1416 }
1417 char bssid_s[18];
1418 format_mac_addr_upper(failed_bssid.value().data(), bssid_s);
1419 ESP_LOGD(TAG, "Failed " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") ", priority %d → %d", ssid.c_str(), bssid_s,
1420 old_priority, new_priority);
1421
1422 // After adjusting priority, check if all priorities are now at minimum
1423 // If so, clear the vector to save memory and reset for fresh start
1425}
1426
1438 WiFiRetryPhase current_phase = this->retry_phase_;
1439
1440 // Check if we need to advance to next AP/SSID within the same phase
1441#ifdef USE_WIFI_FAST_CONNECT
1442 if (current_phase == WiFiRetryPhase::FAST_CONNECT_CYCLING_APS) {
1443 // Fast connect: always advance to next AP (no retries per AP)
1444 this->selected_sta_index_++;
1445 this->num_retried_ = 0;
1446 ESP_LOGD(TAG, "Next AP in %s", LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
1447 return;
1448 }
1449#endif
1450
1451 if (current_phase == WiFiRetryPhase::EXPLICIT_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
1452 // Explicit hidden: exhausted retries on current SSID, find next explicitly hidden network
1453 // Stop when we reach a visible network (proceed to scanning)
1454 size_t next_index = this->selected_sta_index_ + 1;
1455 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
1456 this->selected_sta_index_ = static_cast<int8_t>(next_index);
1457 this->num_retried_ = 0;
1458 ESP_LOGD(TAG, "Next explicit hidden network at index %d", static_cast<int>(next_index));
1459 return;
1460 }
1461 // No more consecutive explicit hidden networks found - fall through to trigger phase change
1462 }
1463
1464 if (current_phase == WiFiRetryPhase::RETRY_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
1465 // Hidden mode: exhausted retries on current SSID, find next potentially hidden SSID
1466 // If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
1467 // In that case, skip networks marked hidden:true (already tried)
1468 // Otherwise, include them (they haven't been tried yet)
1469 int8_t next_index = this->find_next_hidden_sta_(this->selected_sta_index_);
1470 if (next_index != -1) {
1471 // Found another potentially hidden SSID
1472 this->selected_sta_index_ = next_index;
1473 this->num_retried_ = 0;
1474 return;
1475 }
1476 // No more potentially hidden SSIDs - set selected_sta_index_ to -1 to trigger phase change
1477 // This ensures determine_next_phase_() will skip the RETRY_HIDDEN logic and transition out
1478 this->selected_sta_index_ = -1;
1479 // Return early - phase change will happen on next wifi_loop() iteration
1480 return;
1481 }
1482
1483 // Don't increment retry counter if we're in a scan phase with no valid targets
1484 if (this->needs_scan_results_()) {
1485 return;
1486 }
1487
1488 // Increment retry counter to try the same target again
1489 this->num_retried_++;
1490 ESP_LOGD(TAG, "Retry attempt %u/%u in phase %s", this->num_retried_ + 1,
1491 get_max_retries_for_phase(this->retry_phase_), LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
1492}
1493
1496
1497 // Determine next retry phase based on current state
1498 WiFiRetryPhase current_phase = this->retry_phase_;
1499 WiFiRetryPhase next_phase = this->determine_next_phase_();
1500
1501 // Handle phase transitions (transition_to_phase_ handles same-phase no-op internally)
1502 if (this->transition_to_phase_(next_phase)) {
1503 return; // Scan started or adapter restarted (which sets its own state)
1504 }
1505
1506 if (next_phase == current_phase) {
1508 }
1509
1510 this->error_from_callback_ = false;
1511
1512 yield();
1513 // Check if we have a valid target before building params
1514 // After exhausting all networks in a phase, selected_sta_index_ may be -1
1515 // In that case, skip connection and let next wifi_loop() handle phase transition
1516 if (this->selected_sta_index_ >= 0) {
1517 WiFiAP params = this->build_params_for_current_phase_();
1518 this->start_connecting(params);
1519 }
1520}
1521
1522void WiFiComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
1528
1529void WiFiComponent::set_passive_scan(bool passive) { this->passive_scan_ = passive; }
1530
1532#ifdef USE_CAPTIVE_PORTAL
1534#else
1535 return false;
1536#endif
1537}
1539#ifdef USE_IMPROV
1541#else
1542 return false;
1543#endif
1544}
1545
1546#ifdef USE_WIFI_FAST_CONNECT
1548 SavedWifiFastConnectSettings fast_connect_save{};
1549
1550 if (this->fast_connect_pref_.load(&fast_connect_save)) {
1551 // Validate saved AP index
1552 if (fast_connect_save.ap_index < 0 || static_cast<size_t>(fast_connect_save.ap_index) >= this->sta_.size()) {
1553 ESP_LOGW(TAG, "AP index out of bounds");
1554 return false;
1555 }
1556
1557 // Set selected index for future operations (save, retry, etc)
1558 this->selected_sta_index_ = fast_connect_save.ap_index;
1559
1560 // Copy entire config, then override with fast connect data
1561 params = this->sta_[fast_connect_save.ap_index];
1562
1563 // Override with saved BSSID/channel from fast connect (SSID/password/etc already copied from config)
1564 bssid_t bssid{};
1565 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
1566 params.set_bssid(bssid);
1567 params.set_channel(fast_connect_save.channel);
1568 // Fast connect uses specific BSSID+channel, not hidden network probe (even if config has hidden: true)
1569 params.set_hidden(false);
1570
1571 ESP_LOGD(TAG, "Loaded fast_connect settings");
1572 return true;
1573 }
1574
1575 return false;
1576}
1577
1579 bssid_t bssid = wifi_bssid();
1580 uint8_t channel = get_wifi_channel();
1581 // selected_sta_index_ is always valid here (called only after successful connection)
1582 // Fallback to 0 is defensive programming for robustness
1583 int8_t ap_index = this->selected_sta_index_ >= 0 ? this->selected_sta_index_ : 0;
1584
1585 // Skip save if settings haven't changed (compare with previously saved settings to reduce flash wear)
1586 SavedWifiFastConnectSettings previous_save{};
1587 if (this->fast_connect_pref_.load(&previous_save) && memcmp(previous_save.bssid, bssid.data(), 6) == 0 &&
1588 previous_save.channel == channel && previous_save.ap_index == ap_index) {
1589 return; // No change, nothing to save
1590 }
1591
1592 SavedWifiFastConnectSettings fast_connect_save{};
1593 memcpy(fast_connect_save.bssid, bssid.data(), 6);
1594 fast_connect_save.channel = channel;
1595 fast_connect_save.ap_index = ap_index;
1596
1597 this->fast_connect_pref_.save(&fast_connect_save);
1598
1599 ESP_LOGD(TAG, "Saved fast_connect settings");
1600}
1601#endif
1602
1603void WiFiAP::set_ssid(const std::string &ssid) { this->ssid_ = ssid; }
1604void WiFiAP::set_bssid(bssid_t bssid) { this->bssid_ = bssid; }
1605void WiFiAP::set_bssid(optional<bssid_t> bssid) { this->bssid_ = bssid; }
1606void WiFiAP::set_password(const std::string &password) { this->password_ = password; }
1607#ifdef USE_WIFI_WPA2_EAP
1608void WiFiAP::set_eap(optional<EAPAuth> eap_auth) { this->eap_ = std::move(eap_auth); }
1609#endif
1610void WiFiAP::set_channel(optional<uint8_t> channel) { this->channel_ = channel; }
1611#ifdef USE_WIFI_MANUAL_IP
1612void WiFiAP::set_manual_ip(optional<ManualIP> manual_ip) { this->manual_ip_ = manual_ip; }
1613#endif
1614void WiFiAP::set_hidden(bool hidden) { this->hidden_ = hidden; }
1615const std::string &WiFiAP::get_ssid() const { return this->ssid_; }
1616const optional<bssid_t> &WiFiAP::get_bssid() const { return this->bssid_; }
1617const std::string &WiFiAP::get_password() const { return this->password_; }
1618#ifdef USE_WIFI_WPA2_EAP
1619const optional<EAPAuth> &WiFiAP::get_eap() const { return this->eap_; }
1620#endif
1621const optional<uint8_t> &WiFiAP::get_channel() const { return this->channel_; }
1622#ifdef USE_WIFI_MANUAL_IP
1624#endif
1625bool WiFiAP::get_hidden() const { return this->hidden_; }
1626
1627WiFiScanResult::WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth,
1628 bool is_hidden)
1629 : bssid_(bssid),
1630 channel_(channel),
1631 rssi_(rssi),
1632 ssid_(std::move(ssid)),
1633 with_auth_(with_auth),
1634 is_hidden_(is_hidden) {}
1635bool WiFiScanResult::matches(const WiFiAP &config) const {
1636 if (config.get_hidden()) {
1637 // User configured a hidden network, only match actually hidden networks
1638 // don't match SSID
1639 if (!this->is_hidden_)
1640 return false;
1641 } else if (!config.get_ssid().empty()) {
1642 // check if SSID matches
1643 if (config.get_ssid() != this->ssid_)
1644 return false;
1645 } else {
1646 // network is configured without SSID - match other settings
1647 }
1648 // If BSSID configured, only match for correct BSSIDs
1649 if (config.get_bssid().has_value() && *config.get_bssid() != this->bssid_)
1650 return false;
1651
1652#ifdef USE_WIFI_WPA2_EAP
1653 // BSSID requires auth but no PSK or EAP credentials given
1654 if (this->with_auth_ && (config.get_password().empty() && !config.get_eap().has_value()))
1655 return false;
1656
1657 // BSSID does not require auth, but PSK or EAP credentials given
1658 if (!this->with_auth_ && (!config.get_password().empty() || config.get_eap().has_value()))
1659 return false;
1660#else
1661 // If PSK given, only match for networks with auth (and vice versa)
1662 if (config.get_password().empty() == this->with_auth_)
1663 return false;
1664#endif
1665
1666 // If channel configured, only match networks on that channel.
1667 if (config.get_channel().has_value() && *config.get_channel() != this->channel_) {
1668 return false;
1669 }
1670 return true;
1671}
1672bool WiFiScanResult::get_matches() const { return this->matches_; }
1673void WiFiScanResult::set_matches(bool matches) { this->matches_ = matches; }
1674const bssid_t &WiFiScanResult::get_bssid() const { return this->bssid_; }
1675const std::string &WiFiScanResult::get_ssid() const { return this->ssid_; }
1676uint8_t WiFiScanResult::get_channel() const { return this->channel_; }
1677int8_t WiFiScanResult::get_rssi() const { return this->rssi_; }
1678bool WiFiScanResult::get_with_auth() const { return this->with_auth_; }
1679bool WiFiScanResult::get_is_hidden() const { return this->is_hidden_; }
1680
1681bool WiFiScanResult::operator==(const WiFiScanResult &rhs) const { return this->bssid_ == rhs.bssid_; }
1682
1683WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1684
1685} // namespace wifi
1686} // namespace esphome
1687#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(const Ts &...x)
Inform the parent automation that the event has triggered.
Definition automation.h:169
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
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)
bool load_fast_connect_settings_(WiFiAP &params)
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)
const WiFiAP * get_selected_sta_() const
int8_t get_sta_priority(const bssid_t bssid)
void log_and_adjust_priority_for_failed_connect_()
Log failed connection and decrease BSSID priority to avoid repeated attempts.
void save_wifi_sta(const std::string &ssid, const std::string &password)
wifi_scan_vector_t< WiFiScanResult > scan_result_
void set_sta_priority(const bssid_t bssid, int8_t priority)
void loop() override
Reconnect WiFi if required.
void start_connecting(const WiFiAP &ap)
void advance_to_next_target_or_increment_retry_()
Advance to next target (AP/SSID) within current phase, or increment retry counter Called when staying...
network::IPAddress get_dns_address(int num)
WiFiComponent()
Construct a WiFiComponent.
std::vector< WiFiSTAPriority > sta_priorities_
void set_passive_scan(bool passive)
void set_power_save_mode(WiFiPowerSaveMode power_save)
int8_t find_next_hidden_sta_(int8_t start_index)
Find next SSID that wasn't in scan results (might be hidden) Returns index of next potentially hidden...
ESPPreferenceObject fast_connect_pref_
void clear_priorities_if_all_min_()
Clear BSSID priority tracking if all priorities are at minimum (saves memory)
WiFiRetryPhase determine_next_phase_()
Determine next retry phase based on current state and failure conditions.
network::IPAddress wifi_dns_ip_(int num)
float get_loop_priority() const override
network::IPAddresses get_ip_addresses()
float get_setup_priority() const override
WIFI setup_priority.
FixedVector< WiFiAP > sta_
int8_t find_first_non_hidden_index_() const
Find the index of the first non-hidden network Returns where EXPLICIT_HIDDEN phase would have stopped...
bool ssid_was_seen_in_scan_(const std::string &ssid) const
Check if an SSID was seen in the most recent scan results Used to skip hidden mode for SSIDs we know ...
bool needs_scan_results_() const
Check if we need valid scan results for the current phase but don't have any Returns true if the phas...
bool transition_to_phase_(WiFiRetryPhase new_phase)
Transition to a new retry phase with logging Returns true if a scan was started (caller should wait),...
optional< float > output_power_
const char * get_use_address() const
WiFiSTAConnectStatus wifi_sta_connect_status_()
bool went_through_explicit_hidden_phase_() const
Check if we went through EXPLICIT_HIDDEN phase (first network is marked hidden) Used in RETRY_HIDDEN ...
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
void set_reboot_timeout(uint32_t reboot_timeout)
network::IPAddresses wifi_sta_ip_addresses()
void start_initial_connection_()
Start initial connection - either scan or connect directly to hidden networks.
void setup() override
Setup WiFi interface.
void set_use_address(const char *use_address)
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) const
bool operator==(const WiFiScanResult &rhs) const
struct @65::@66 __attribute__
uint16_t type
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)
WiFiRetryPhase
Tracks the current retry strategy/phase for WiFi connection attempts.
@ RETRY_HIDDEN
Retry networks not found in scan (might be hidden)
@ RESTARTING_ADAPTER
Restarting WiFi adapter to clear stuck state.
@ INITIAL_CONNECT
Initial connection attempt (varies based on fast_connect setting)
@ EXPLICIT_HIDDEN
Explicitly hidden networks (user marked as hidden, try before scanning)
@ FAST_CONNECT_CYCLING_APS
Fast connect mode: cycling through configured APs (config-only, no scan)
@ SCAN_CONNECTING
Scan-based: connecting to best AP from scan results.
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_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
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:621
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:146
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:640
void IRAM_ATTR HOT yield()
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.
std::string str() const
Definition ip_address.h:52
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.