ESPHome 2026.11.0b6
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#include <cmath>
6#include <type_traits>
7
8#ifdef USE_ESP32
9#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
10#include <esp_eap_client.h>
11#else
12#include <esp_wpa2.h>
13#endif
14#endif
15
16#if defined(USE_ESP32)
17#include <esp_wifi.h>
18#endif
19#ifdef USE_ESP8266
20#include <user_interface.h>
21#endif
22
23#include <algorithm>
24#include <new>
25#include <utility>
26
28#include "esphome/core/hal.h"
30#include "esphome/core/log.h"
32#include "esphome/core/util.h"
33
34#ifdef USE_CAPTIVE_PORTAL
36#endif
37#ifdef USE_WEBSERVER_CAPTIVE
39#endif
40
41#ifdef USE_IMPROV_BLE
43#endif
44
45#ifdef USE_IMPROV_SERIAL
47#endif
48
49#ifdef USE_PROVISIONING
51#endif
52
53namespace esphome::wifi {
54
55ESPHOME_LOG_TAG(TAG, "wifi");
56
57// CompactString implementation
58CompactString::CompactString(const char *str, size_t len) {
59 if (len > MAX_LENGTH) {
60 len = MAX_LENGTH; // Clamp to max valid length
61 }
62
63 this->length_ = len;
64 if (len <= INLINE_CAPACITY) {
65 // Store inline with null terminator
66 this->is_heap_ = 0;
67 if (len > 0) {
68 std::memcpy(this->storage_, str, len);
69 }
70 this->storage_[len] = '\0';
71 } else {
72 // Heap allocate with null terminator
73 this->is_heap_ = 1;
74 char *heap_data = new char[len + 1]; // NOLINT(cppcoreguidelines-owning-memory)
75 std::memcpy(heap_data, str, len);
76 heap_data[len] = '\0';
77 this->set_heap_ptr_(heap_data);
78 }
79}
80
81CompactString::CompactString(const CompactString &other) : CompactString(other.data(), other.size()) {}
82
84 if (this != &other) {
85 this->~CompactString();
86 new (this) CompactString(other);
87 }
88 return *this;
89}
90
91CompactString::CompactString(CompactString &&other) noexcept : length_(other.length_), is_heap_(other.is_heap_) {
92 // Copy full storage (includes null terminator for inline, or pointer for heap). The bytes past the
93 // terminator are never read, and a fixed-size copy is 8 bytes of flash smaller than a sized one.
94 // NOLINTNEXTLINE(clang-analyzer-unix.cstring.UninitializedRead)
95 std::memcpy(this->storage_, other.storage_, INLINE_CAPACITY + 1);
96 other.length_ = 0;
97 other.is_heap_ = 0;
98 other.storage_[0] = '\0';
99}
100
102 if (this != &other) {
103 this->~CompactString();
104 new (this) CompactString(std::move(other));
105 }
106 return *this;
107}
108
110 if (this->is_heap_) {
111 delete[] this->get_heap_ptr_(); // NOLINT(cppcoreguidelines-owning-memory)
112 }
113}
114
115bool CompactString::operator==(const CompactString &other) const {
116 return this->size() == other.size() && std::memcmp(this->data(), other.data(), this->size()) == 0;
117}
118bool CompactString::operator==(const StringRef &other) const {
119 return this->size() == other.size() && std::memcmp(this->data(), other.c_str(), this->size()) == 0;
120}
121
317
318#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
319#ifdef USE_WIFI_PHY_MODE
320// Use if-chain instead of switch to avoid jump table in RODATA (wastes RAM on ESP8266)
321static const LogString *phy_mode_to_log_string(WiFi8266PhyMode mode) {
323 return LOG_STR("11B");
325 return LOG_STR("11G");
327 return LOG_STR("11N");
328 return LOG_STR("Auto");
329}
330#endif
331// Use if-chain instead of switch to avoid jump table in RODATA (wastes RAM on ESP8266)
332static const LogString *retry_phase_to_log_string(WiFiRetryPhase phase) {
334 return LOG_STR("INITIAL_CONNECT");
335#ifdef USE_WIFI_FAST_CONNECT
337 return LOG_STR("FAST_CONNECT_CYCLING");
338#endif
340 return LOG_STR("EXPLICIT_HIDDEN");
342 return LOG_STR("SCAN_CONNECTING");
343 if (phase == WiFiRetryPhase::RETRY_HIDDEN)
344 return LOG_STR("RETRY_HIDDEN");
346 return LOG_STR("RESTARTING");
347 return LOG_STR("UNKNOWN");
348}
349#endif // ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
350
352 // If first configured network is marked hidden, we went through EXPLICIT_HIDDEN phase
353 // This means those networks were already tried and should be skipped in RETRY_HIDDEN
354 return !this->sta_.empty() && this->sta_[0].get_hidden();
355}
356
358 // Find the first network that is NOT marked hidden:true
359 // This is where EXPLICIT_HIDDEN phase would have stopped
360 for (size_t i = 0; i < this->sta_.size(); i++) {
361 if (!this->sta_[i].get_hidden()) {
362 return static_cast<int8_t>(i);
363 }
364 }
365 return -1; // All networks are hidden
366}
367
368// 2 attempts per BSSID in SCAN_CONNECTING phase
369// Rationale: This is the ONLY phase where we decrease BSSID priority, so we must be very sure.
370// Auth failures are common immediately after scan due to WiFi stack state transitions.
371// Trying twice filters out false positives and prevents unnecessarily marking a good BSSID as bad.
372// After 2 genuine failures, priority degradation ensures we skip this BSSID on subsequent scans.
373static constexpr uint8_t WIFI_RETRY_COUNT_PER_BSSID = 2;
374
375// 1 attempt per SSID in RETRY_HIDDEN phase
376// Rationale: Try hidden mode once, then rescan to get next best BSSID via priority system
377static constexpr uint8_t WIFI_RETRY_COUNT_PER_SSID = 1;
378
379// 1 attempt per AP in fast_connect mode (INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS)
380// Rationale: Fast connect prioritizes speed - try each AP once to find a working one quickly
381static constexpr uint8_t WIFI_RETRY_COUNT_PER_AP = 1;
382
385static constexpr uint32_t WIFI_COOLDOWN_DURATION_MS = 500;
386#ifdef USE_WIFI_AP
388#ifdef USE_WIFI_AP_EXCLUSIVE
389static constexpr bool WIFI_AP_EXCLUSIVE = true;
390#else
391static constexpr bool WIFI_AP_EXCLUSIVE = false;
392#endif
393#endif
394#ifdef USE_WIFI_AP_EXCLUSIVE
399static constexpr uint32_t WIFI_AP_EXCLUSIVE_DWELL_MS = 300000;
402static constexpr uint32_t WIFI_AP_EXCLUSIVE_MAX_DWELL_MS = 3 * WIFI_AP_EXCLUSIVE_DWELL_MS;
403static constexpr uint32_t WIFI_AP_EXCLUSIVE_HANDOVER_MS = 1000;
404#endif
405// Every AP is a provisioning surface except a bridge without captive_portal
406#if defined(USE_WIFI_AP) && (!defined(USE_WIFI_AP_WISP) || defined(USE_WIFI_AP_WISP_PORTAL))
407#define WIFI_AP_HAS_PORTAL
408#endif
409// On an AP that stays up the portal follows the station: served while it is down, ended when it connects
410#if defined(USE_WIFI_AP_PERSISTENT) && defined(WIFI_AP_HAS_PORTAL) && \
411 (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE))
412#define WIFI_AP_PORTAL_FOLLOWS_STA
414static constexpr uint32_t WIFI_PORTAL_REOPEN_DELAY_MS = 10000;
415#endif
416
420static constexpr uint32_t WIFI_COOLDOWN_WITH_AP_ACTIVE_MS = 30000;
421
425static constexpr uint32_t WIFI_SCAN_TIMEOUT_MS = 31000;
426
435static constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 46000;
436
437static constexpr uint8_t get_max_retries_for_phase(WiFiRetryPhase phase) {
438 switch (phase) {
440#ifdef USE_WIFI_FAST_CONNECT
442#endif
443 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS both use 1 attempt per AP (fast_connect mode)
444 return WIFI_RETRY_COUNT_PER_AP;
446 // Explicitly hidden network: 1 attempt (user marked as hidden, try once then scan)
447 return WIFI_RETRY_COUNT_PER_SSID;
449 // Scan-based phase: 2 attempts per BSSID (handles transient auth failures after scan)
450 return WIFI_RETRY_COUNT_PER_BSSID;
452 // Hidden network mode: 1 attempt per SSID
453 return WIFI_RETRY_COUNT_PER_SSID;
454 default:
455 return WIFI_RETRY_COUNT_PER_BSSID;
456 }
457}
458
459static void apply_scan_result_to_params(WiFiAP &params, const WiFiScanResult &scan) {
460 params.set_hidden(false);
461 params.set_ssid(scan.get_ssid());
462 params.set_bssid(scan.get_bssid());
463 params.set_channel(scan.get_channel());
464}
465
467 // Only SCAN_CONNECTING phase needs scan results
469 return false;
470 }
471 // Need scan if we have no results or no matching networks
472 return this->scan_result_.empty() || !this->scan_result_[0].get_matches();
473}
474
476 // Check if this SSID is configured as hidden
477 // If explicitly marked hidden, we should always try hidden mode regardless of scan results
478 for (const auto &conf : this->sta_) {
479 if (conf.ssid_ == ssid && conf.get_hidden()) {
480 return false; // Treat as not seen - force hidden mode attempt
481 }
482 }
483
484 // Otherwise, check if we saw it in scan results
485 for (const auto &scan : this->scan_result_) {
486 if (scan.ssid_ == ssid) {
487 return true;
488 }
489 }
490 return false;
491}
492
494 // Components that require full scan results (for example, scan result listeners)
495 // are expected to call request_wifi_scan_results(), which sets keep_scan_results_.
496 if (this->keep_scan_results_) {
497 return true;
498 }
499
500#ifdef USE_CAPTIVE_PORTAL
501 // Captive portal needs full results when active (showing network list to user)
503 return true;
504 }
505#endif
506
507#ifdef USE_IMPROV_SERIAL
508 // Improv serial needs results during provisioning (before connected)
510 return true;
511 }
512#endif
513
514#ifdef USE_IMPROV_BLE
515 // BLE improv also needs results during provisioning
517 return true;
518 }
519#endif
520
521 return false;
522}
523
524const WiFiAP *WiFiComponent::find_configured_network_(const char *ssid, const uint8_t *bssid) const {
525 // Hidden networks in scan results have empty SSIDs - skip them
526 if (ssid[0] == '\0') {
527 return nullptr;
528 }
529 for (const auto &sta : this->sta_) {
530 // Skip hidden network configs (they don't appear in normal scans)
531 if (sta.get_hidden()) {
532 continue;
533 }
534 // For BSSID-only configs (empty SSID), match by BSSID
535 if (sta.ssid_.empty()) {
536 if (sta.has_bssid() && std::memcmp(sta.get_bssid().data(), bssid, 6) == 0) {
537 return &sta;
538 }
539 continue;
540 }
541 // Match by SSID
542 if (sta.ssid_ == ssid) {
543 return &sta;
544 }
545 }
546 return nullptr;
547}
548
550 for (auto &it : this->sta_priorities_) {
551 if (it.bssid == bssid) {
552 it.priority = priority;
553 return;
554 }
555 }
556 this->sta_priorities_.push_back(WiFiSTAPriority{
557 .bssid = bssid,
558 .priority = priority,
559 });
560}
561
562void WiFiComponent::log_discarded_scan_result_(const char *ssid, const uint8_t *bssid, int8_t rssi, uint8_t channel) {
563#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
564 // Skip logging during roaming scans to avoid log buffer overflow
565 // (roaming scans typically find many networks but only care about same-SSID APs)
566 if (this->is_roaming_scan_active()) {
567 return;
568 }
569 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
570 format_mac_addr_upper(bssid, bssid_s);
571 ESP_LOGV(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") " %ddB Ch:%u", ssid, bssid_s, rssi, channel);
572#endif
573}
574
575int8_t WiFiComponent::find_next_hidden_sta_(int8_t start_index) {
576 // Find next SSID to try in RETRY_HIDDEN phase.
577 //
578 // This function operates in two modes based on retry_hidden_mode_:
579 //
580 // 1. SCAN_BASED mode:
581 // After SCAN_CONNECTING phase, only returns networks that were NOT visible
582 // in the scan (truly hidden networks that need probe requests).
583 //
584 // 2. BLIND_RETRY mode:
585 // When captive portal/improv is active, scanning is skipped to avoid
586 // disrupting the AP. In this mode, ALL configured networks are returned
587 // as candidates, cycling through them sequentially. This allows the device
588 // to keep trying all networks while users configure WiFi via captive portal.
589 //
590 // Additionally, if EXPLICIT_HIDDEN phase was executed (first network marked hidden:true),
591 // those networks are skipped here since they were already tried.
592 //
593 bool include_explicit_hidden = !this->went_through_explicit_hidden_phase_();
594 // Start searching from start_index + 1
595 for (size_t i = start_index + 1; i < this->sta_.size(); i++) {
596 const auto &sta = this->sta_[i];
597
598 // Skip networks that were already tried in EXPLICIT_HIDDEN phase
599 // Those are: networks marked hidden:true that appear before the first non-hidden network
600 // If all networks are hidden (first_non_hidden_idx == -1), skip all of them
601 if (!include_explicit_hidden && sta.get_hidden()) {
602 int8_t first_non_hidden_idx = this->find_first_non_hidden_index_();
603 if (first_non_hidden_idx < 0 || static_cast<int8_t>(i) < first_non_hidden_idx) {
604 ESP_LOGD(TAG, "Skipping " LOG_SECRET("'%s'") " (explicit hidden, already tried)", sta.ssid_.c_str());
605 continue;
606 }
607 }
608
609 // In BLIND_RETRY mode, treat all networks as candidates
610 // In SCAN_BASED mode, only retry networks that weren't seen in the scan
612 ESP_LOGD(TAG, "Hidden candidate " LOG_SECRET("'%s'") " at index %d", sta.ssid_.c_str(), static_cast<int>(i));
613 return static_cast<int8_t>(i);
614 }
615 ESP_LOGD(TAG, "Skipping hidden retry for visible network " LOG_SECRET("'%s'"), sta.ssid_.c_str());
616 }
617 // No hidden SSIDs found
618 return -1;
619}
620
622 // If first network (highest priority) is explicitly marked hidden, try it first before scanning
623 // This respects user's priority order when they explicitly configure hidden networks
624 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
625 ESP_LOGI(TAG, "Starting with explicit hidden network (highest priority)");
626 this->selected_sta_index_ = 0;
629 this->start_connecting(params);
630 } else {
631 this->start_scanning();
632 }
633}
634
635#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
636static const char *eap_phase2_to_str(esp_eap_ttls_phase2_types type) {
637 switch (type) {
638 case ESP_EAP_TTLS_PHASE2_PAP:
639 return "pap";
640 case ESP_EAP_TTLS_PHASE2_CHAP:
641 return "chap";
642 case ESP_EAP_TTLS_PHASE2_MSCHAP:
643 return "mschap";
644 case ESP_EAP_TTLS_PHASE2_MSCHAPV2:
645 return "mschapv2";
646 case ESP_EAP_TTLS_PHASE2_EAP:
647 return "eap";
648 default:
649 return "unknown";
650 }
651}
652#endif
653
655 this->wifi_pre_setup_();
656
657#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
658 // Create semaphore for high-performance mode requests
659 // Start at 0, increment on request, decrement on release
660 this->high_performance_semaphore_ = xSemaphoreCreateCounting(UINT32_MAX, 0);
661 if (this->high_performance_semaphore_ == nullptr) {
662 ESP_LOGE(TAG, "Failed semaphore");
663 }
664
665 // Store the configured power save mode as baseline
667#endif
668
669#if defined(USE_PROVISIONING) && (defined(USE_WIFI_DPP) || defined(WIFI_AP_HAS_PORTAL))
670 // The access point, the portals on it and the DPP listen are provisioning surfaces: once the
671 // window has closed, end them (mirrors the teardown on a successful connection). The blocks in
672 // loop() that start them are gated so none of them is started again afterwards. An AP that
673 // stays up only loses its portal.
676#ifdef USE_WIFI_DPP
677 this->stop_dpp_listen_();
678#endif
679#ifdef WIFI_AP_HAS_PORTAL
680 this->end_ap_portal_(); // no-op when nothing is active, so not tied to ap_setup_
681#ifndef USE_WIFI_AP_PERSISTENT
682 if (this->ap_setup_) {
683 ESP_LOGD(TAG, "Provisioning window closed; disabling AP");
684#ifdef USE_WIFI_AP_EXCLUSIVE
685 // The networks wait while the AP runs on its own; hand them the radio
686 // now rather than at the end of the dwell.
687 if (this->state_ == WIFI_COMPONENT_STATE_AP && this->has_sta()) {
688 this->pause_exclusive_ap_();
689 return;
690 }
691#endif
692 this->disable_ap_();
693 }
694#endif // !USE_WIFI_AP_PERSISTENT
695#endif // WIFI_AP_HAS_PORTAL
696 });
697 }
698#endif
699
700 if (this->enable_on_boot_) {
701#ifdef USE_ESP32
702 this->wifi_lazy_init_();
703#endif
704 this->start();
705 } else {
707 }
708}
709
711 if (!std::isnan(this->output_power_) && !this->wifi_apply_output_power_(this->output_power_)) {
712 ESP_LOGV(TAG, "Setting Output Power Option failed");
713 }
714 if (!this->wifi_apply_power_save_()) {
715 ESP_LOGV(TAG, "Setting Power Save Option failed");
716 }
717}
718
720 ESP_LOGCONFIG(TAG, "Starting");
721 // The loop's time, not millis(): a wifi.enable from a trigger in this pass must not stamp a time after now
723
724 uint32_t hash = this->has_sta() ? App.get_config_version_hash() : 88491487UL;
725
727#ifdef USE_WIFI_FAST_CONNECT
728#ifdef USE_WIFI_FAST_CONNECT_IN_FLASH
729 const bool fast_connect_in_flash = true;
730#else
731 const bool fast_connect_in_flash = false;
732#endif
733 this->fast_connect_pref_ =
735#endif
736#ifdef USE_WIFI_LEASE_CACHE
737#ifdef USE_WIFI_LEASE_CACHE_IN_FLASH
738 const bool lease_cache_in_flash = true;
739#else
740 const bool lease_cache_in_flash = false;
741#endif
742 this->lease_cache_pref_ =
743 global_preferences->make_preference<wifi::SavedWifiLeaseSettings>(hash + 2, lease_cache_in_flash);
744#endif
745
746 SavedWifiSettings save{};
747 if (this->pref_.load(&save)) {
748 ESP_LOGD(TAG, "Loaded settings: %s", save.ssid);
749
750 WiFiAP sta{};
751 sta.set_ssid(save.ssid);
752 sta.set_password(save.password);
753 this->set_sta(sta);
754 }
755#ifdef USE_WIFI_LEASE_CACHE
756 // After the saved credentials: set_sta() clears the cache, and the lease belongs to that same network
757 this->load_lease_settings_();
758#endif
759
760 if (this->has_sta()) {
761 this->wifi_sta_pre_setup_();
762#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
763 // Synchronize power_save_ with semaphore state before applying
764 if (this->high_performance_semaphore_ != nullptr) {
765 UBaseType_t semaphore_count = uxSemaphoreGetCount(this->high_performance_semaphore_);
766 if (semaphore_count > 0) {
768 this->is_high_performance_mode_ = true;
769 } else {
771 this->is_high_performance_mode_ = false;
772 }
773 }
774#endif
775 this->apply_radio_settings_();
776
778#ifdef USE_WIFI_FAST_CONNECT
779 WiFiAP params;
780 bool loaded_fast_connect = this->load_fast_connect_settings_(params);
781 // Fast connect optimization: only use when we have saved BSSID+channel data
782 // Without saved data, try first configured network or use normal flow
783 if (loaded_fast_connect) {
784 ESP_LOGI(TAG, "Starting fast_connect (saved) " LOG_SECRET("'%s'"), params.ssid_.c_str());
785 this->start_connecting(params);
786 } else if (!this->sta_.empty() && !this->sta_[0].get_hidden()) {
787 // No saved data, but have configured networks - try first non-hidden network
788 ESP_LOGI(TAG, "Starting fast_connect (config) " LOG_SECRET("'%s'"), this->sta_[0].ssid_.c_str());
789 this->selected_sta_index_ = 0;
790 params = this->build_params_for_current_phase_();
791 this->start_connecting(params);
792 } else {
793 // No saved data and (no networks OR first is hidden) - use normal flow
795 }
796#else
797 // Without fast_connect: go straight to scanning (or hidden mode if all networks are hidden)
799#endif
800#ifdef WIFI_AP_HAS_PORTAL
801 } else if (this->has_ap()) { // a bridge without a portal waits in loop() for the upstream's resolver
802 this->setup_ap_config_();
803 this->start_portal_scan_();
804 this->start_ap_portal_();
805#endif // WIFI_AP_HAS_PORTAL
806 }
807#ifdef USE_WIFI_DPP
808 // Without networks there is nothing to try first, so listen for a configurator right away
809 if (!this->has_sta() && this->is_dpp_active_() && this->wifi_mode_(true, {}))
810 this->start_dpp_listen_(millis());
811#endif
812#ifdef USE_IMPROV_BLE
813 if (!this->has_sta() && improv_ble::global_improv_component != nullptr) {
814 if (this->wifi_mode_(true, {}))
816 }
817#endif
818 this->wifi_apply_hostname_();
819}
820
822 ESP_LOGW(TAG, "Restarting adapter");
823 this->wifi_mode_(false, {});
824 // Clear error flag here because restart_adapter() enters COOLDOWN state,
825 // and check_connecting_finished() is called after cooldown without going
826 // through start_connecting() first. Without this clear, stale errors would
827 // trigger spurious "failed (callback)" logs. The canonical clear location
828 // is in start_connecting() (ESP8266 also clears after wifi_station_connect()).
829 this->error_from_callback_ = false;
830}
831
833 bool events_processed = this->wifi_loop_();
835 // Connection state can only change when events are processed (ESP-IDF/LibreTiny)
836 // or polled (ESP8266/Pico W). Skip the expensive wifi_sta_connect_status_() call
837 // when no events arrived and we're already in steady state.
838 // Must also run when connected_ is false — after state transitions to STA_CONNECTED,
839 // connected_ won't be set until update_connected_state_() runs.
840 if (events_processed || !this->connected_) {
842 }
843
844 if (this->has_sta()) {
845#if defined(USE_WIFI_CONNECT_TRIGGER) || defined(USE_WIFI_DISCONNECT_TRIGGER)
846 if (this->is_connected() != this->handled_connected_state_) {
847#ifdef USE_WIFI_DISCONNECT_TRIGGER
848 if (this->handled_connected_state_) {
850 }
851#endif
852#ifdef USE_WIFI_CONNECT_TRIGGER
853 if (!this->handled_connected_state_) {
855 }
856#endif
858 }
859#endif // USE_WIFI_CONNECT_TRIGGER || USE_WIFI_DISCONNECT_TRIGGER
860
861 switch (this->state_) {
863 this->status_set_warning(LOG_STR("waiting to reconnect"));
864 // Credentials not tried yet: retry whatever the driver reports. The flag outlives an adapter restart,
865 // which only lands back here, and start_connecting() clears it once they are tried
866 if (this->skip_cooldown_next_cycle_) {
867 ESP_LOGD(TAG, "Exiting cooldown early due to new WiFi credentials");
868 this->retry_connect();
869 break;
870 }
871 // Use longer cooldown when a portal/improv is active to avoid disrupting a user on the AP
872 bool portal_active = this->is_provisioning_active_();
873 uint32_t cooldown_duration = portal_active ? WIFI_COOLDOWN_WITH_AP_ACTIVE_MS : WIFI_COOLDOWN_DURATION_MS;
874 if (now - this->action_started_ > cooldown_duration) {
875 // After cooldown we either restarted the adapter because of
876 // a failure, or something tried to connect over and over
877 // so we entered cooldown. In both cases we call
878 // check_connecting_finished to continue the state machine.
879 this->check_connecting_finished(now);
880 }
881 break;
882 }
884 this->status_set_warning(LOG_STR("scanning for networks"));
886 break;
887 }
889 this->status_set_warning(LOG_STR("associating to network"));
890 this->check_connecting_finished(now);
891 break;
892 }
893
895 // Use cached connected_ set unconditionally at the top of loop()
896 if (!this->connected_) {
897 ESP_LOGW(TAG, "Connection lost; reconnecting");
899 this->retry_connect();
900 } else {
901 this->status_clear_warning();
902 this->set_last_connected_(now);
903
904#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
905 // A driver-initiated roam (e.g. 802.11v BTM) re-associates without the
906 // state machine ever leaving STA_CONNECTED, so the notification the
907 // connected event marked pending would never be flushed by
908 // check_connecting_finished(). Cheap when nothing is pending: the
909 // method returns immediately on a single flag test.
911#endif
912
913 // Post-connect roaming: check for better AP. A scan may have been started by an
914 // explicit force_roam_check() even when post_connect_roaming_ is disabled, so the
915 // scan must always be consumed here to avoid leaving roaming_state_ stuck.
916 if (this->is_roaming_scan_active()) {
917 if (this->scan_done_) {
918 this->process_roaming_scan_();
919 }
920 // else: scan in progress, wait
921 } else if (this->post_connect_roaming_ && this->roaming_state_ == RoamingState::IDLE &&
924 this->check_roaming_(now);
925 }
926 }
927 break;
928 }
930#ifdef USE_WIFI_AP_EXCLUSIVE
931 // The networks are not tried while the AP is up, so it pauses for
932 // them once nobody has used it for a while. Without networks the AP
933 // is all there is and stays.
934 if (this->has_sta() && now - this->ap_changed_ > WIFI_AP_EXCLUSIVE_DWELL_MS &&
935 (this->ap_clients_ == 0 || now - this->ap_changed_ > WIFI_AP_EXCLUSIVE_MAX_DWELL_MS))
936 this->pause_exclusive_ap_();
937 break;
938#endif
940 break;
942 return;
943 }
944
945#if defined(USE_WIFI_AP) && !defined(USE_WIFI_AP_PERSISTENT)
946 // Once the provisioning window has closed, don't bring up the fallback AP (or
947 // the captive portal on it) - the device must stay unprovisionable until it is
948 // power-cycled.
949 if (this->has_ap() && !this->ap_setup_ && !this->is_provisioning_closed_()) {
950 const uint32_t since_connected = now - this->last_connected_;
951 if (this->ap_timeout_ != 0 &&
952#ifdef USE_WIFI_AP_EXCLUSIVE
953 // After a pause, or a start that failed, the networks get a full ap_timeout before the AP is tried again
954 since_connected > this->ap_timeout_ && now - this->ap_changed_ > this->ap_timeout_
955#else
956 // Tried in whole ap_timeout slots after the last connection; after UINT8_MAX slots it is no longer tried
957 this->ap_start_failures_ != UINT8_MAX && since_connected / this->ap_timeout_ > this->ap_start_failures_
958#endif
959 ) {
960 ESP_LOGI(TAG, "Starting fallback AP");
961#ifdef USE_WIFI_AP_EXCLUSIVE
962 this->ap_changed_ = now;
963#endif
964 this->setup_ap_config_();
965#ifndef USE_WIFI_AP_EXCLUSIVE
966 if (!this->ap_setup_) {
967 // Skip the next slot too, so at least a full ap_timeout passes wherever in its slot this try ran
968 uint32_t slot = since_connected / this->ap_timeout_ + 1;
969 this->ap_start_failures_ = slot < UINT8_MAX ? slot : UINT8_MAX;
970 }
971#endif
972 this->start_ap_portal_();
973 }
974 }
975#endif // USE_WIFI_AP && !USE_WIFI_AP_PERSISTENT
976#ifdef WIFI_AP_PORTAL_FOLLOWS_STA
977 if (this->ap_setup_ && !this->is_connected() && now - this->last_connected_ > WIFI_PORTAL_REOPEN_DELAY_MS &&
978 !this->is_provisioning_closed_() && !this->is_ap_portal_active_()) {
979 this->start_ap_portal_();
980 }
981#endif
982
983#ifdef USE_IMPROV_BLE
985 !improv_ble::global_improv_component->should_start()) {
986 if (now - this->last_connected_ > improv_ble::global_improv_component->get_wifi_timeout()) {
987 if (this->wifi_mode_(true, {}))
989 }
990 }
991#endif
992
993 if (this->reboot_timeout_ != 0 && now - this->last_connected_ > this->reboot_timeout_) {
994 bool suppress = false;
995#if defined(USE_WIFI_AP) && (defined(USE_RTL87XX) || defined(USE_LN882X))
996 // The Realtek driver reports no stations and the Lightning one is unverified, so a running fallback AP
997 // holds the reboot there as it always did
998 suppress = this->ap_setup_;
999#elif defined(USE_WIFI_AP)
1000 // A station on the fallback AP is using the device
1001 suppress = this->ap_setup_ && this->ap_clients_ != 0;
1002#endif
1003#ifdef USE_PROVISIONING
1004 // Don't reboot while a provisioning window is pending (device unprovisioned).
1005 // The device is legitimately waiting to be onboarded (Wi-Fi must come up
1006 // before the controller can set credentials), and an auto-reboot would reopen
1007 // the window without the deliberate power cycle / reset that is meant to be
1008 // required. Resumes normal reboot behavior once provisioned.
1009 suppress |= provisioning::global_provisioning_manager != nullptr &&
1011#endif
1012 if (!suppress) {
1013 ESP_LOGE(TAG, "Can't connect; rebooting");
1014 App.reboot();
1015 }
1016 }
1017 }
1018
1019#ifdef USE_WIFI_AP_PERSISTENT
1020 // The AP stays up next to the upstream, so it is started with any upstream; a start that failed is
1021 // tried again after ap_timeout. A bridge without a portal waits for a resolver to offer.
1022 if (!this->ap_setup_ && this->state_ != WIFI_COMPONENT_STATE_DISABLED &&
1023#if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_PORTAL)
1024 this->ap_dns_known_() &&
1025#endif
1026 (this->ap_changed_ == 0 || now - this->ap_changed_ > this->ap_timeout_)) {
1027 ESP_LOGI(TAG, "Starting AP");
1028 this->ap_changed_ = now;
1029 this->setup_ap_config_();
1030#ifdef WIFI_AP_PORTAL_FOLLOWS_STA
1031 // With a station the follows-station block serves the portal after its grace period
1032 if (!this->has_sta() && !this->is_provisioning_closed_()) {
1033 this->start_portal_scan_(); // as in start(), so credentials saved through the portal are tried
1034 this->start_ap_portal_();
1035 }
1036#endif
1037 }
1038#endif
1039
1040#ifdef USE_WIFI_DPP
1041 // Without networks no cooldown starts the listen, so a failed or abandoned enrollment is listened for again
1042 // here, at most once per timeout
1043 if (!this->has_sta() && !this->dpp_listening_ && this->state_ != WIFI_COMPONENT_STATE_DISABLED &&
1044 now - this->dpp_listen_started_ > this->dpp_timeout_ && this->is_dpp_active_() && this->wifi_mode_(true, {})) {
1045 this->start_dpp_listen_(now);
1046 }
1047#endif
1048
1049#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1050 // Check if power save mode needs to be updated based on high-performance requests
1051 if (this->high_performance_semaphore_ != nullptr) {
1052 // Semaphore count directly represents active requests (starts at 0, increments on request)
1053 UBaseType_t semaphore_count = uxSemaphoreGetCount(this->high_performance_semaphore_);
1054
1055 if (semaphore_count > 0 && !this->is_high_performance_mode_) {
1056 // Transition to high-performance mode (no power save)
1057 ESP_LOGV(TAG, "Switching to high-performance mode (%" PRIu32 " active %s)", (uint32_t) semaphore_count,
1058 semaphore_count == 1 ? LOG_STR_LITERAL("request") : LOG_STR_LITERAL("requests"));
1060 if (this->wifi_apply_power_save_()) {
1061 this->is_high_performance_mode_ = true;
1062 }
1063 } else if (semaphore_count == 0 && this->is_high_performance_mode_) {
1064 // Restore to configured power save mode
1065 ESP_LOGV(TAG, "Restoring power save mode to configured setting");
1066 this->power_save_ = this->configured_power_save_;
1067 if (this->wifi_apply_power_save_()) {
1068 this->is_high_performance_mode_ = false;
1069 }
1070 }
1071 }
1072#endif
1073}
1074
1076
1078 if (this->has_sta())
1079 return this->wifi_sta_ip_addresses();
1080
1081#ifdef USE_WIFI_AP
1082 if (this->has_ap())
1083 return {this->wifi_soft_ap_ip()};
1084#endif // USE_WIFI_AP
1085
1086 return {};
1087}
1089 if (this->has_sta())
1090 return this->wifi_dns_ip_(num);
1091 return {};
1092}
1093
1094#ifdef USE_WIFI_AP
1096#ifdef USE_WIFI_AP_EXCLUSIVE
1097 // The radio cannot run both, so STA goes off while the AP is up.
1098 if (!this->wifi_mode_(false, true))
1099 return;
1100#else
1101 this->wifi_mode_({}, true);
1102#endif
1103
1104 if (this->ap_setup_)
1105 return;
1106
1107 if (this->ap_.ssid_.empty()) {
1108 // Build AP SSID from app name without heap allocation; WiFi SSID max is 32 bytes
1109 static constexpr size_t AP_SSID_MAX_LEN = 32;
1110
1111 const auto &app_name = App.get_name();
1112 if (app_name.length() <= AP_SSID_MAX_LEN) {
1113 // Name fits, use directly
1114 this->ap_.set_ssid(app_name.c_str());
1115 } else {
1116 char ssid_buf[AP_SSID_MAX_LEN + 1];
1117 truncate_name_to(ssid_buf, sizeof(ssid_buf), app_name.c_str(), app_name.length(),
1118 App.is_name_add_mac_suffix_enabled() ? MAC_ADDRESS_SUFFIX_WITH_SEPARATOR_LEN : 0);
1119 this->ap_.set_ssid(ssid_buf);
1120 }
1121 }
1122 // Reset before the AP exists: afterwards only the platform's event path writes the counter
1123 this->ap_clients_ = 0;
1124 this->ap_setup_ = this->wifi_start_ap_(this->ap_);
1125 // The station path applied these in start(); without a station the radio only exists from here,
1126 // and credentials saved through the portal connect without another start()
1127 if (this->ap_setup_ && !this->has_sta())
1128 this->apply_radio_settings_();
1129#if defined(USE_WIFI_AP_EXCLUSIVE) || defined(USE_WIFI_AP_PERSISTENT)
1130 // A failed start must not leave the radio in AP mode: on an exclusive radio it would refuse
1131 // the STA attempts until the next try, and an AP that stays up would take clients it cannot serve.
1132 if (!this->ap_setup_)
1133 this->wifi_mode_({}, false);
1134#endif
1135
1136 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1137 ESP_LOGCONFIG(TAG,
1138 "Setting up AP:\n"
1139 " AP SSID: '%s'\n"
1140 " AP Password: '%s'\n"
1141 " IP Address: %s",
1142 this->ap_.ssid_.c_str(), this->ap_.password_.c_str(), this->wifi_soft_ap_ip().str_to(ip_buf));
1143
1144#ifdef USE_WIFI_MANUAL_IP
1145 auto manual_ip = this->ap_.get_manual_ip();
1146 if (manual_ip.has_value()) {
1147 char static_ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1148 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1149 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1150 ESP_LOGCONFIG(TAG,
1151 " AP Static IP: '%s'\n"
1152 " AP Gateway: '%s'\n"
1153 " AP Subnet: '%s'",
1154 manual_ip->static_ip.str_to(static_ip_buf), manual_ip->gateway.str_to(gateway_buf),
1155 manual_ip->subnet.str_to(subnet_buf));
1156 }
1157#endif
1158
1159 // Where the AP runs on its own, the STA state machine also waits in this
1160 // state until the AP pauses.
1161 if (!this->has_sta() || (WIFI_AP_EXCLUSIVE && this->ap_setup_)) {
1163 }
1164}
1165
1166#ifdef USE_WIFI_AP_EXCLUSIVE
1168 ESP_LOGI(TAG, "Pausing AP to try the networks");
1169 // Scanning and connecting turn STA back on.
1170 this->disable_ap_();
1172 // A fresh connection cycle, as at boot, rather than resuming the one the
1173 // AP cut short.
1175 this->num_retried_ = 0;
1177}
1178#endif
1179
1181#ifdef USE_WIFI_AP_WISP_PORTAL
1182 this->ap_offers_own_dns_ = false; // the AP goes down, so ending its portal rewrites nothing
1183 this->cancel_timeout(AP_DEAUTH_RETRY_TIMEOUT_ID); // the next AP setup works out its clients' resolver itself
1184#endif
1185 this->end_ap_portal_();
1186 // The AP may come back later; its clients dropped with it without a disconnect event for each
1187 this->ap_setup_ = false;
1188 this->ap_clients_ = 0;
1189}
1190
1192 this->forget_ap_();
1193 ESP_LOGD(TAG, "Disabling AP");
1194 this->wifi_mode_({}, false);
1195}
1196
1198 this->ap_ = ap;
1199 this->has_ap_ = true;
1200}
1201#endif // USE_WIFI_AP
1202
1203void WiFiComponent::init_sta(size_t count) { this->sta_.init(count); }
1204void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); }
1206 // Clear roaming state - no more configured networks
1207 this->clear_roaming_state_();
1208 this->sta_.clear();
1209 this->selected_sta_index_ = -1;
1210}
1212 this->clear_sta(); // Also clears roaming state
1213 this->init_sta(1);
1214 this->add_sta(ap);
1215 this->selected_sta_index_ = 0;
1216 // New credentials end the next cooldown early; start_connecting() clears this once they are tried
1217 this->skip_cooldown_next_cycle_ = true;
1218#ifdef USE_WIFI_LEASE_CACHE
1219 // Index 0 is a different network now, so its cached lease must not be re-applied
1220 this->clear_lease_settings_();
1221#endif
1222}
1223
1225 const WiFiAP *config = this->get_selected_sta_();
1226 if (config == nullptr) {
1227 ESP_LOGE(TAG, "No valid network config (selected_sta_index_=%d, sta_.size()=%zu)",
1228 static_cast<int>(this->selected_sta_index_), this->sta_.size());
1229 // Return empty params - caller should handle this gracefully
1230 return WiFiAP();
1231 }
1232
1233 WiFiAP params = *config;
1234
1235 switch (this->retry_phase_) {
1237#ifdef USE_WIFI_FAST_CONNECT
1239#endif
1240 // Fast connect phases: use config-only (no scan results)
1241 // BSSID/channel from config if user specified them, otherwise empty
1242 break;
1243
1246 // Hidden network mode: clear BSSID/channel to trigger probe request
1247 // (both explicit hidden and retry hidden use same behavior)
1248 params.clear_bssid();
1249 params.clear_channel();
1250 break;
1251
1253 // Scan-based phase: always use best scan result (index 0 - highest priority after sorting)
1254 if (!this->scan_result_.empty()) {
1255 apply_scan_result_to_params(params, this->scan_result_[0]);
1256 }
1257 break;
1258
1260 // Should not be building params during restart
1261 break;
1262 }
1263
1264 return params;
1265}
1266
1268 const WiFiAP *config = this->get_selected_sta_();
1269 return config ? *config : WiFiAP{};
1270}
1271void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
1272 this->save_wifi_sta(ssid.c_str(), password.c_str());
1273}
1274void WiFiComponent::save_wifi_sta(const char *ssid, const char *password) {
1275 SavedWifiSettings save{}; // zero-initialized - all bytes set to \0, guaranteeing null termination
1276 strncpy(save.ssid, ssid, sizeof(save.ssid) - 1); // max 32 chars, byte 32 remains \0
1277 strncpy(save.password, password, sizeof(save.password) - 1); // max 64 chars, byte 64 remains \0
1278 this->pref_.save(&save);
1279 // ensure it's written immediately
1281
1282 WiFiAP sta{};
1283 sta.set_ssid(ssid);
1284 sta.set_password(password);
1285 // No retry here: a captive portal save runs in lwIP's context on the ESP8266, where retry_connect() yields and
1286 // panics. set_sta() flags the credentials and loop() tries them
1287 this->set_sta(sta);
1288#ifdef USE_WIFI_AP_EXCLUSIVE
1289 // The AP pauses for the new credentials once its answer is out, and the STA state machine picks them up
1290 if (this->ap_setup_) {
1291 this->set_timeout(AP_HANDOVER_TIMEOUT_ID, WIFI_AP_EXCLUSIVE_HANDOVER_MS, [this]() {
1292 if (this->ap_setup_)
1293 this->pause_exclusive_ap_();
1294 });
1295 }
1296#endif
1297}
1298
1300 // Log connection attempt at INFO level with priority
1301 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1302 int8_t priority = 0;
1303
1304 if (ap.has_bssid()) {
1305 format_mac_addr_upper(ap.get_bssid().data(), bssid_s);
1306 priority = this->get_sta_priority(ap.get_bssid());
1307 }
1308
1309 ESP_LOGI(TAG,
1310 "Connecting to " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") " (priority %d, attempt %u/%u in phase %s)...",
1311 ap.ssid_.c_str(), ap.has_bssid() ? bssid_s : LOG_STR_LITERAL("any"), priority, this->num_retried_ + 1,
1312 get_max_retries_for_phase(this->retry_phase_), LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
1313
1314#ifdef ESPHOME_LOG_HAS_VERBOSE
1315 ESP_LOGV(TAG,
1316 "Connection Params:\n"
1317 " SSID: '%s'",
1318 ap.ssid_.c_str());
1319 if (ap.has_bssid()) {
1320 ESP_LOGV(TAG, " BSSID: %s", bssid_s);
1321 } else {
1322 ESP_LOGV(TAG, " BSSID: Not Set");
1323 }
1324
1325#ifdef USE_WIFI_WPA2_EAP
1326 const auto &eap_opt = ap.get_eap();
1327 if (eap_opt.has_value()) {
1328 const EAPAuth &eap_config = *eap_opt;
1329 // clang-format off
1330 ESP_LOGV(
1331 TAG,
1332 " WPA2 Enterprise authentication configured:\n"
1333 " Identity: " LOG_SECRET("'%s'") "\n"
1334 " Username: " LOG_SECRET("'%s'") "\n"
1335 " Password: " LOG_SECRET("'%s'"),
1336 eap_config.identity.c_str(), eap_config.username.c_str(), eap_config.password.c_str());
1337 // clang-format on
1338#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1339 ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), eap_phase2_to_str(eap_config.ttls_phase_2));
1340#endif
1341 bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert);
1342 bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert);
1343 bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key);
1344 ESP_LOGV(TAG,
1345 " CA Cert: %s\n"
1346 " Client Cert: %s\n"
1347 " Client Key: %s",
1348 ca_cert_present ? LOG_STR_LITERAL("present") : LOG_STR_LITERAL("not present"),
1349 client_cert_present ? LOG_STR_LITERAL("present") : LOG_STR_LITERAL("not present"),
1350 client_key_present ? LOG_STR_LITERAL("present") : LOG_STR_LITERAL("not present"));
1351 } else {
1352#endif
1353 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), ap.password_.c_str());
1354#ifdef USE_WIFI_WPA2_EAP
1355 }
1356#endif
1357 if (ap.has_channel()) {
1358 ESP_LOGV(TAG, " Channel: %u", ap.get_channel());
1359 } else {
1360 ESP_LOGV(TAG, " Channel not set");
1361 }
1362#ifdef USE_WIFI_MANUAL_IP
1363 if (const auto m = ap.get_manual_ip(); m.has_value()) {
1364 char static_ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1365 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1366 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1367 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
1368 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
1369 ESP_LOGV(TAG, " Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s", m->static_ip.str_to(static_ip_buf),
1370 m->gateway.str_to(gateway_buf), m->subnet.str_to(subnet_buf), m->dns1.str_to(dns1_buf),
1371 m->dns2.str_to(dns2_buf));
1372 } else
1373#endif
1374 {
1375 ESP_LOGV(TAG, " Using DHCP IP");
1376 }
1377 ESP_LOGV(TAG, " Hidden: %s", YESNO(ap.get_hidden()));
1378#endif
1379
1380 // Clear any stale error from previous connection attempt.
1381 // This is the canonical location for clearing the flag since all connection
1382 // attempts go through start_connecting(). restart_adapter() also clears it, as it
1383 // enters COOLDOWN without calling start_connecting(), and ESP8266 clears it again
1384 // after wifi_station_connect(), whose callbacks fire synchronously.
1385 this->error_from_callback_ = false;
1386 // Every attempt passes through here, so the credentials set_sta() flagged are tried now
1387 this->skip_cooldown_next_cycle_ = false;
1388
1389 if (!this->wifi_sta_connect_(ap)) {
1390 ESP_LOGE(TAG, "wifi_sta_connect_ failed");
1391 // Enter cooldown to allow WiFi hardware to stabilize
1392 // (immediate failure suggests hardware not ready, different from connection timeout)
1393 this->start_cooldown_();
1394 return;
1395 }
1397 this->action_started_ = millis();
1398}
1399
1402 this->action_started_ = millis();
1403#ifdef USE_WIFI_DPP
1404 // The cooldown is the configurator's window; the attempt that ends it stops the listen again
1405 if (!this->dpp_listening_ && this->is_dpp_active_() && this->wifi_mode_(true, {}))
1407#endif
1408}
1409
1410const LogString *get_signal_bars(int8_t rssi) {
1411 // LOWER ONE QUARTER BLOCK
1412 // Unicode: U+2582, UTF-8: E2 96 82
1413 // LOWER HALF BLOCK
1414 // Unicode: U+2584, UTF-8: E2 96 84
1415 // LOWER THREE QUARTERS BLOCK
1416 // Unicode: U+2586, UTF-8: E2 96 86
1417 // FULL BLOCK
1418 // Unicode: U+2588, UTF-8: E2 96 88
1419 if (rssi >= -50) {
1420 return LOG_STR("\033[0;32m" // green
1421 "\xe2\x96\x82"
1422 "\xe2\x96\x84"
1423 "\xe2\x96\x86"
1424 "\xe2\x96\x88"
1425 "\033[0m");
1426 } else if (rssi >= -65) {
1427 return LOG_STR("\033[0;33m" // yellow
1428 "\xe2\x96\x82"
1429 "\xe2\x96\x84"
1430 "\xe2\x96\x86"
1431 "\033[0;37m"
1432 "\xe2\x96\x88"
1433 "\033[0m");
1434 } else if (rssi >= -85) {
1435 return LOG_STR("\033[0;33m" // yellow
1436 "\xe2\x96\x82"
1437 "\xe2\x96\x84"
1438 "\033[0;37m"
1439 "\xe2\x96\x86"
1440 "\xe2\x96\x88"
1441 "\033[0m");
1442 } else {
1443 return LOG_STR("\033[0;31m" // red
1444 "\xe2\x96\x82"
1445 "\033[0;37m"
1446 "\xe2\x96\x84"
1447 "\xe2\x96\x86"
1448 "\xe2\x96\x88"
1449 "\033[0m");
1450 }
1451}
1452
1454 bssid_t bssid = wifi_bssid();
1455 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1456 format_mac_addr_upper(bssid.data(), bssid_s);
1457 // Use stack buffers for IP address formatting to avoid heap allocations
1458 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1459 for (auto &ip : wifi_sta_ip_addresses()) {
1460 if (ip.is_set()) {
1461 ESP_LOGCONFIG(TAG, " IP Address: %s", ip.str_to(ip_buf));
1462 }
1463 }
1464 int8_t rssi = wifi_rssi();
1465 // Use stack buffers for SSID and all IP addresses to avoid heap allocations
1466 char ssid_buf[SSID_BUFFER_SIZE];
1467 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1468 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1469 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
1470 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
1471 // clang-format off
1472 ESP_LOGCONFIG(TAG,
1473 " SSID: " LOG_SECRET("'%s'") "\n"
1474 " BSSID: " LOG_SECRET("%s") "\n"
1475 " Hostname: '%s'\n"
1476 " Signal strength: %d dB %s\n"
1477 " Channel: %" PRId32 "\n"
1478 " Subnet: %s\n"
1479 " Gateway: %s\n"
1480 " DNS1: %s\n"
1481 " DNS2: %s",
1482 wifi_ssid_to(ssid_buf), bssid_s, App.get_name().c_str(), rssi, LOG_STR_ARG(get_signal_bars(rssi)),
1483 get_wifi_channel(), wifi_subnet_mask_().str_to(subnet_buf), wifi_gateway_ip_().str_to(gateway_buf),
1484 wifi_dns_ip_(0).str_to(dns1_buf), wifi_dns_ip_(1).str_to(dns2_buf));
1485 // clang-format on
1486#ifdef ESPHOME_LOG_HAS_VERBOSE
1487 if (const WiFiAP *config = this->get_selected_sta_(); config && config->has_bssid()) {
1488 ESP_LOGV(TAG, " Priority: %d", this->get_sta_priority(config->get_bssid()));
1489 }
1490#endif
1491#ifdef USE_WIFI_11KV_SUPPORT
1492 ESP_LOGCONFIG(TAG,
1493 " BTM: %s\n"
1494 " RRM: %s",
1495 this->btm_ ? LOG_STR_LITERAL("enabled") : LOG_STR_LITERAL("disabled"),
1496 this->rrm_ ? LOG_STR_LITERAL("enabled") : LOG_STR_LITERAL("disabled"));
1497#endif
1498}
1499
1502 return;
1503
1504 ESP_LOGD(TAG, "Enabling");
1506#ifdef USE_ESP32
1507 // Idempotent — only allocates DMA buffers + netifs on the first call. After this,
1508 // start() can safely run.
1509 this->wifi_lazy_init_();
1510#endif
1511 this->start();
1512}
1513
1516 return;
1517
1518 ESP_LOGD(TAG, "Disabling");
1520#ifdef USE_WIFI_LEASE_CACHE
1521 this->cancel_timeout(LEASE_RENEW_TIMEOUT_ID);
1522#endif
1523#ifdef USE_WIFI_DPP
1524 this->stop_dpp_listen_();
1525#endif
1526 this->wifi_disconnect_();
1527#ifdef USE_WIFI_AP
1528 // The AP goes down with the radio; enable() has to configure it, and its portal, again
1529 this->forget_ap_();
1530#endif
1531 this->wifi_mode_(false, false);
1532#ifdef USE_WIFI_AP_PERSISTENT
1533 this->ap_changed_ = 0; // at once, not after ap_timeout
1534#endif
1535}
1536
1538 this->action_started_ = millis();
1539 ESP_LOGD(TAG, "Starting scan");
1540 this->wifi_scan_start_(this->passive_scan_);
1542}
1543
1577[[nodiscard]] inline static bool wifi_scan_result_is_better(const WiFiScanResult &a, const WiFiScanResult &b) {
1578 // Matching networks always come before non-matching
1579 if (a.get_matches() && !b.get_matches())
1580 return true;
1581 if (!a.get_matches() && b.get_matches())
1582 return false;
1583
1584 // Both matching: check priority first (tracks connection failures via priority degradation)
1585 // Priority is decreased when a BSSID fails to connect, so lower priority = previously failed
1586 if (a.get_matches() && b.get_matches() && a.get_priority() != b.get_priority()) {
1587 return a.get_priority() > b.get_priority();
1588 }
1589
1590 // Use RSSI as tiebreaker (for equal-priority matching networks or all non-matching networks)
1591 return a.get_rssi() > b.get_rssi();
1592}
1593
1594// Helper function for insertion sort of WiFi scan results
1595// Using insertion sort instead of std::stable_sort saves flash memory
1596// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
1597// IMPORTANT: This sort is stable (preserves relative order of equal elements)
1598//
1599// Uses raw memcpy instead of copy assignment to avoid CompactString's
1600// destructor/constructor overhead (heap delete[]/new[] for long SSIDs).
1601// Copy assignment calls ~CompactString() then placement-new for every shift,
1602// which means delete[]/new[] per shift for heap-allocated SSIDs. With 70+
1603// networks (e.g., captive portal showing full scan results), this caused
1604// event loop blocking from hundreds of heap operations in a tight loop.
1605//
1606// This is safe because we're permuting elements within the same array —
1607// each slot is overwritten exactly once, so no ownership duplication occurs.
1608// All members of WiFiScanResult are either trivially copyable (bssid, channel,
1609// rssi, priority, flags) or CompactString, which stores either inline data or
1610// a heap pointer — never a self-referential pointer (unlike std::string's SSO
1611// on some implementations). This was not possible before PR#13472 replaced
1612// std::string with CompactString, since std::string's internal layout is
1613// implementation-defined and may use self-referential pointers.
1614//
1615// TODO: If C++ standardizes std::trivially_relocatable, add the assertion for
1616// WiFiScanResult/CompactString here to formally express the memcpy safety guarantee.
1617template<typename VectorType> static void insertion_sort_scan_results(VectorType &results) {
1618 // memcpy-based sort requires no self-referential pointers or virtual dispatch.
1619 // These static_asserts guard the assumptions. If any fire, the memcpy sort
1620 // must be reviewed for safety before updating the expected values.
1621 //
1622 // No vtable pointers (memcpy would corrupt vptr)
1623 static_assert(!std::is_polymorphic<WiFiScanResult>::value, "WiFiScanResult must not have vtable");
1624 static_assert(!std::is_polymorphic<CompactString>::value, "CompactString must not have vtable");
1625 // Standard layout ensures predictable memory layout with no virtual bases
1626 // and no mixed-access-specifier reordering
1627 static_assert(std::is_standard_layout<WiFiScanResult>::value, "WiFiScanResult must be standard layout");
1628 static_assert(std::is_standard_layout<CompactString>::value, "CompactString must be standard layout");
1629 // Size checks catch added/removed fields that may need safety review
1630 static_assert(sizeof(WiFiScanResult) == 32, "WiFiScanResult size changed - verify memcpy sort is still safe");
1631 static_assert(sizeof(CompactString) == 20, "CompactString size changed - verify memcpy sort is still safe");
1632 // Alignment must match for reinterpret_cast of key_buf to be valid
1633 static_assert(alignof(WiFiScanResult) <= alignof(std::max_align_t), "WiFiScanResult alignment exceeds max_align_t");
1634 const size_t size = results.size();
1635 constexpr size_t elem_size = sizeof(WiFiScanResult);
1636 // Suppress warnings for intentional memcpy on non-trivially-copyable type.
1637 // Safety is guaranteed by the static_asserts above and the permutation invariant.
1638 // NOLINTNEXTLINE(bugprone-undefined-memory-manipulation)
1639 auto *memcpy_fn = &memcpy;
1640 for (size_t i = 1; i < size; i++) {
1641 alignas(WiFiScanResult) uint8_t key_buf[elem_size];
1642 memcpy_fn(key_buf, &results[i], elem_size);
1643 const auto &key = *reinterpret_cast<const WiFiScanResult *>(key_buf);
1644 int32_t j = i - 1;
1645
1646 // Move elements that are worse than key to the right
1647 // For stability, we only move if key is strictly better than results[j]
1648 while (j >= 0 && wifi_scan_result_is_better(key, results[j])) {
1649 memcpy_fn(&results[j + 1], &results[j], elem_size);
1650 j--;
1651 }
1652 memcpy_fn(&results[j + 1], key_buf, elem_size);
1653 }
1654}
1655
1656// Helper function to log matching scan results - marked noinline to prevent re-inlining into loop
1657//
1658// IMPORTANT: This function deliberately uses a SINGLE log call to minimize blocking.
1659// In environments with many matching networks (e.g., 18+ mesh APs), multiple log calls
1660// per network would block the main loop for an unacceptable duration. Each log call
1661// has overhead from UART transmission, so combining INFO+DEBUG into one line halves
1662// the blocking time. Do NOT split this into separate ESP_LOGI/ESP_LOGD calls.
1663__attribute__((noinline)) static void log_scan_result(const WiFiScanResult &res) {
1664 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1665 auto bssid = res.get_bssid();
1666 format_mac_addr_upper(bssid.data(), bssid_s);
1667
1668#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
1669 // Single combined log line with all details when DEBUG enabled
1670 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s Ch:%2u %3ddB P:%d", res.get_ssid().c_str(),
1671 res.get_is_hidden() ? LOG_STR_LITERAL("(HIDDEN) ") : LOG_STR_LITERAL(""), bssid_s,
1672 LOG_STR_ARG(get_signal_bars(res.get_rssi())), res.get_channel(), res.get_rssi(), res.get_priority());
1673#else
1674 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
1675 res.get_is_hidden() ? LOG_STR_LITERAL("(HIDDEN) ") : LOG_STR_LITERAL(""), bssid_s,
1676 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
1677#endif
1678}
1679
1681 if (!this->scan_done_) {
1682 if (millis() - this->action_started_ > WIFI_SCAN_TIMEOUT_MS) {
1683 ESP_LOGE(TAG, "Scan timeout");
1684 this->retry_connect();
1685 }
1686 return;
1687 }
1688 this->scan_done_ = false;
1689 // A driver filtered scan saw one SSID; a portal that started during it still needs a full scan
1692
1693 if (this->scan_result_.empty()) {
1694 ESP_LOGW(TAG, "No networks found");
1695 this->retry_connect();
1696 return;
1697 }
1698
1699 ESP_LOGD(TAG, "Found networks:");
1700 {
1701 ScanResultsLock lock(this);
1702 for (auto &res : this->scan_result_) {
1703 for (auto &ap : this->sta_) {
1704 if (res.matches(ap)) {
1705 res.set_matches(true);
1706 // Cache priority lookup - do single search instead of 2 separate searches
1707 const bssid_t &bssid = res.get_bssid();
1708 if (!this->has_sta_priority(bssid)) {
1709 this->set_sta_priority(bssid, ap.get_priority());
1710 }
1711 res.set_priority(this->get_sta_priority(bssid));
1712 break;
1713 }
1714 }
1715 }
1716
1717 // Sort scan results using insertion sort for better memory efficiency
1718 insertion_sort_scan_results(this->scan_result_);
1719 }
1720
1721 // Log matching networks (non-matching already logged at VERBOSE in scan callback)
1722 for (auto &res : this->scan_result_) {
1723 if (res.get_matches()) {
1724 log_scan_result(res);
1725 }
1726 }
1727
1728 // SYNCHRONIZATION POINT: Establish link between scan_result_[0] and selected_sta_index_
1729 // After sorting, scan_result_[0] contains the best network. Now find which sta_[i] config
1730 // matches that network and record it in selected_sta_index_. This keeps the two indices
1731 // synchronized so build_params_for_current_phase_() can safely use both to build connection parameters.
1732 const WiFiScanResult &scan_res = this->scan_result_[0];
1733 bool found_match = false;
1734 if (scan_res.get_matches()) {
1735 for (size_t i = 0; i < this->sta_.size(); i++) {
1736 if (scan_res.matches(this->sta_[i])) {
1737 // Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
1738 // No overflow check needed - YAML validation prevents >127 networks
1739 this->selected_sta_index_ = static_cast<int8_t>(i); // Links scan_result_[0] with sta_[i]
1740 found_match = true;
1741 break;
1742 }
1743 }
1744 }
1745
1746 if (!found_match) {
1747 ESP_LOGW(TAG, "No matching network found");
1748 // No scan results matched our configured networks - transition directly to hidden mode
1750 // No hidden network left: retry now instead of waiting out the scan timeout. With
1751 // selected_sta_index_ at -1, retry_connect() penalizes no BSSID.
1752 if (this->selected_sta_index_ == -1) {
1753 this->retry_connect();
1754 return;
1755 }
1756 // Now start connection attempt in hidden mode
1758 return; // scan started, wait for next loop iteration
1759 }
1760
1761 yield();
1762
1763 WiFiAP params = this->build_params_for_current_phase_();
1764 // Ensure we're in SCAN_CONNECTING phase when connecting with scan results
1765 // (needed when scan was started directly without transition_to_phase_, e.g., initial scan)
1766 this->start_connecting(params);
1767}
1768
1770 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1771 ESP_LOGCONFIG(TAG,
1772 "WiFi:\n"
1773 " Local MAC: %s\n"
1774 " Connected: %s",
1775 get_mac_address_pretty_into_buffer(mac_s), YESNO(this->is_connected()));
1776 if (this->is_disabled()) {
1777 ESP_LOGCONFIG(TAG, " Disabled");
1778 return;
1779 }
1780#ifdef USE_WIFI_DPP
1781 ESP_LOGCONFIG(TAG,
1782 " DPP channels: %s\n"
1783 " DPP timeout: %" PRIu32 " ms",
1784 this->dpp_channels_, this->dpp_timeout_);
1785#endif
1786#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
1787 const char *band_mode_s;
1788 switch (this->band_mode_) {
1789 case WIFI_BAND_MODE_2G_ONLY:
1790 band_mode_s = "2.4GHz";
1791 break;
1792 case WIFI_BAND_MODE_5G_ONLY:
1793 band_mode_s = "5GHz";
1794 break;
1795 case WIFI_BAND_MODE_AUTO:
1796 default:
1797 band_mode_s = "Auto";
1798 break;
1799 }
1800 ESP_LOGCONFIG(TAG, " Band Mode: %s", band_mode_s);
1801#endif
1802#ifdef USE_WIFI_PHY_MODE
1803 ESP_LOGCONFIG(TAG, " PHY Mode: %s", LOG_STR_ARG(phy_mode_to_log_string(this->phy_mode_)));
1804#endif
1805 if (this->is_connected()) {
1806 this->print_connect_params_();
1807 }
1808}
1809
1811 auto status = this->wifi_sta_connect_status_();
1812
1814 char ssid_buf[SSID_BUFFER_SIZE];
1815 if (wifi_ssid_to(ssid_buf)[0] == '\0') {
1816 ESP_LOGW(TAG, "Connection incomplete");
1817 this->retry_connect();
1818 return;
1819 }
1820
1821 ESP_LOGI(TAG, "Connected");
1822 // Warn if we had to retry with hidden network mode for a network that's not marked hidden
1823 // Only warn if we actually connected without scan data (SSID only), not if scan succeeded on retry
1824 if (const WiFiAP *config = this->get_selected_sta_(); this->retry_phase_ == WiFiRetryPhase::RETRY_HIDDEN &&
1825 config && !config->get_hidden() &&
1826 this->scan_result_.empty()) {
1827 ESP_LOGW(TAG, LOG_SECRET("'%s'") " should be marked hidden", config->ssid_.c_str());
1828 }
1829 // Reset to initial phase on successful connection (don't log transition, just reset state)
1831 this->num_retried_ = 0;
1832#ifdef WIFI_AP_HAS_PORTAL
1833 if (this->has_ap()) {
1834#ifdef USE_WIFI_AP_PERSISTENT
1835 this->end_ap_portal_(); // the AP stays up for its clients
1836#else
1837 this->disable_ap_();
1838#endif
1839 }
1840#endif
1841#ifdef USE_WIFI_DPP
1842 this->stop_dpp_listen_();
1843#endif
1844#ifdef USE_IMPROV_BLE
1845 if (this->is_improv_ble_active_()) {
1847 }
1848#endif
1849
1850 // The fallback and reboot checks later in this pass must see the connection, not the old timestamp
1851 this->set_last_connected_(now);
1853 // Refresh is_connected() cache; loop()'s refresh ran before this transition.
1855 this->num_retried_ = 0;
1856 this->print_connect_params_();
1857
1858 // Reset roaming state on successful connection
1859 this->roaming_last_check_ = now;
1860 // Only preserve attempts if reconnecting after a failed roam attempt
1861 // This prevents ping-pong between APs when a roam target is unreachable
1863 // Successful roam to better AP on first try - reset attempts so we can roam again later
1864 ESP_LOGD(TAG, "Roam successful");
1865 this->roaming_attempts_ = 0;
1866 } else if (this->roaming_state_ == RoamingState::RECONNECTING) {
1867 // Check if we ended up on the roam target despite needing a retry
1868 // (e.g., first connect failed but scan-based retry found and connected to the same better AP)
1869 bssid_t current_bssid = this->wifi_bssid();
1870 if (this->roaming_target_bssid_ != bssid_t{} && current_bssid == this->roaming_target_bssid_) {
1871 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1872 format_mac_addr_upper(current_bssid.data(), bssid_buf);
1873 ESP_LOGD(TAG, "Roam successful (via retry, attempt %u/%u) to %s", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS,
1874 bssid_buf);
1875 this->roaming_attempts_ = 0;
1876 } else if (this->roaming_target_bssid_ != bssid_t{}) {
1877 // Failed roam to specific target, reconnected to different AP - keep attempts to prevent ping-pong
1878 ESP_LOGD(TAG, "Reconnected after failed roam (attempt %u/%u)", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
1879 } else {
1880 // Reconnected after scan-induced disconnect (no roam target) - keep attempts
1881 ESP_LOGD(TAG, "Reconnected after roam scan (attempt %u/%u)", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
1882 }
1883 } else {
1884 // Normal connection (boot, credentials changed, etc.)
1885 this->roaming_attempts_ = 0;
1886 }
1888 this->roaming_target_bssid_ = {};
1889 this->roaming_scan_end_ = 0;
1890
1891 // Clear all priority penalties - the next reconnect will happen when an AP disconnects,
1892 // which means the landscape has likely changed and previous tracked failures are stale
1894
1895#ifdef USE_WIFI_FAST_CONNECT
1897#endif
1898
1899 this->release_scan_results_();
1900
1901#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
1902 // Notify listeners now that state machine has reached STA_CONNECTED
1903 // This ensures wifi.connected condition returns true in listener automations
1905#endif
1906
1907#if defined(USE_ESP8266) && defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
1908 // On ESP8266, GOT_IP event may not fire for static IP configurations,
1909 // so notify IP state listeners here as a fallback.
1910 if (const WiFiAP *config = this->get_selected_sta_(); config && config->has_manual_ip()) {
1912 }
1913#endif
1914
1915 return;
1916 }
1917
1918 if (now - this->action_started_ > WIFI_CONNECT_TIMEOUT_MS) {
1919 ESP_LOGW(TAG, "Connection timeout, aborting connection attempt");
1920 this->wifi_disconnect_();
1921 this->retry_connect();
1922 return;
1923 }
1924
1925 if (this->error_from_callback_) {
1926 // ESP8266: logging done in callback, listeners deferred via pending_.disconnect
1927 // Other platforms: just log generic failure message
1928#ifndef USE_ESP8266
1929 ESP_LOGW(TAG, "Connecting to network failed (callback)");
1930#endif
1931 this->retry_connect();
1932 return;
1933 }
1934
1936 return;
1937 }
1938
1940 ESP_LOGW(TAG, "Network no longer found");
1941 this->retry_connect();
1942 return;
1943 }
1944
1946 ESP_LOGW(TAG, "Connecting to network failed");
1947 this->retry_connect();
1948 return;
1949 }
1950
1951 ESP_LOGW(TAG, "Unknown connection status %d", (int) status);
1952 this->retry_connect();
1953}
1954
1962 switch (this->retry_phase_) {
1964#ifdef USE_WIFI_FAST_CONNECT
1966 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS: no retries, try next AP or fall back to scan
1967 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
1968 return WiFiRetryPhase::FAST_CONNECT_CYCLING_APS; // Move to next AP
1969 }
1970#endif
1971 // Check if we should try explicit hidden networks before scanning
1972 // This handles reconnection after connection loss where first network is hidden
1973 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
1975 }
1976 // No more APs to try, fall back to scan
1978
1980 // Try all explicitly hidden networks before scanning
1981 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1982 return WiFiRetryPhase::EXPLICIT_HIDDEN; // Keep retrying same SSID
1983 }
1984
1985 // Exhausted retries on current SSID - check for more explicitly hidden networks
1986 // Stop when we reach a visible network (proceed to scanning)
1987 size_t next_index = this->selected_sta_index_ + 1;
1988 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
1989 // Found another explicitly hidden network
1991 }
1992
1993 // No more consecutive explicitly hidden networks
1994 // If ALL networks are hidden, skip scanning and go directly to restart
1995 if (this->find_first_non_hidden_index_() < 0) {
1997 }
1998 // Otherwise proceed to scanning for non-hidden networks
2000 }
2001
2003 // If scan found no networks or no matching networks, skip to hidden network mode
2004 if (this->scan_result_.empty() || !this->scan_result_[0].get_matches()) {
2006 }
2007
2008 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_BSSID) {
2009 return WiFiRetryPhase::SCAN_CONNECTING; // Keep retrying same BSSID
2010 }
2011
2012 // Exhausted retries on current BSSID (scan_result_[0])
2013 // Its priority has been decreased, so on next scan it will be sorted lower
2014 // and we'll try the next best BSSID.
2015 // Check if there are any potentially hidden networks to try
2016 if (this->find_next_hidden_sta_(-1) >= 0) {
2017 return WiFiRetryPhase::RETRY_HIDDEN; // Found hidden networks to try
2018 }
2019 // No hidden networks - always go through RESTARTING_ADAPTER phase
2020 // This ensures num_retried_ gets reset and a fresh scan is triggered
2021 // The actual adapter restart will be skipped if DPP/captive portal/improv is active
2023
2025 // If no hidden SSIDs to try (selected_sta_index_ == -1), skip directly to rescan
2026 if (this->selected_sta_index_ >= 0) {
2027 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
2028 return WiFiRetryPhase::RETRY_HIDDEN; // Keep retrying same SSID
2029 }
2030
2031 // Exhausted retries on current SSID - check if there are more potentially hidden SSIDs to try
2032 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
2033 // Check if find_next_hidden_sta_() would actually find another hidden SSID
2034 // as it might have been seen in the scan results and we want to skip those
2035 // otherwise we will get stuck in RETRY_HIDDEN phase
2036 if (this->find_next_hidden_sta_(this->selected_sta_index_) != -1) {
2037 // More hidden SSIDs available - stay in RETRY_HIDDEN, advance will happen in retry_connect()
2039 }
2040 }
2041 }
2042 // Exhausted all potentially hidden SSIDs - always go through RESTARTING_ADAPTER
2043 // This ensures num_retried_ gets reset and a fresh scan is triggered
2044 // The actual adapter restart will be skipped if DPP/captive portal/improv is active
2046
2048 // After restart, go back to explicit hidden if we went through it initially
2051 }
2052 // Skip scanning when captive portal/improv is active to avoid disrupting AP,
2053 // BUT only if we've already completed at least one scan AFTER the portal started.
2054 // When captive portal first starts, scan results may be filtered/stale, so we need
2055 // to do one full scan to populate available networks for the captive portal UI.
2056 //
2057 // WHY SCANNING DISRUPTS AP MODE:
2058 // WiFi scanning requires the radio to leave the AP's channel and hop through
2059 // other channels to listen for beacons. During this time (even for passive scans),
2060 // the AP cannot service connected clients - they experience disconnections or
2061 // timeouts. On ESP32, even passive scans cause brief but noticeable disruptions
2062 // that break captive portal HTTP requests and DNS lookups.
2063 //
2064 // BLIND RETRY MODE:
2065 // When captive portal/improv is active, we use RETRY_HIDDEN as a "try all networks
2066 // blindly" mode. Since retry_hidden_mode_ is set to BLIND_RETRY (in RESTARTING_ADAPTER
2067 // transition), find_next_hidden_sta_() will treat ALL configured networks as
2068 // candidates, cycling through them without requiring scan results.
2069 //
2070 // This allows users to configure WiFi via captive portal while the device keeps
2071 // attempting to connect to all configured networks in sequence.
2072 // Captive portal needs scan results to show available networks.
2073 // If captive portal is active, only skip scanning if we've done a scan after it started.
2074 // If only DPP or improv is active (no captive portal), skip scanning since neither needs results.
2075 if (this->is_captive_portal_active_()) {
2078 }
2079 // Need to scan for captive portal
2080 } else if (this->is_improv_ble_active_() || this->is_dpp_active_()) {
2081 // Improv and DPP don't need scan results
2083 }
2085 }
2086
2087 // Should never reach here
2089}
2090
2101 WiFiRetryPhase old_phase = this->retry_phase_;
2102
2103 // No-op if staying in same phase
2104 if (old_phase == new_phase) {
2105 return false;
2106 }
2107
2108 ESP_LOGD(TAG, "Retry phase: %s → %s", LOG_STR_ARG(retry_phase_to_log_string(old_phase)),
2109 LOG_STR_ARG(retry_phase_to_log_string(new_phase)));
2110
2111 this->retry_phase_ = new_phase;
2112 this->num_retried_ = 0; // Reset retry counter on phase change
2113
2114 // Phase-specific setup
2115 switch (new_phase) {
2116#ifdef USE_WIFI_FAST_CONNECT
2118 // Move to next configured AP - clear old scan data so new AP is tried with config only
2119 this->selected_sta_index_++;
2120 ScanResultsLock lock(this);
2121 this->scan_result_.clear();
2122 break;
2123 }
2124#endif
2125
2127 // Starting explicit hidden phase - reset to first network
2128 this->selected_sta_index_ = 0;
2129 break;
2130
2132 // Transitioning to scan-based connection
2133#ifdef USE_WIFI_FAST_CONNECT
2135 ESP_LOGI(TAG, "Fast connect exhausted, falling back to scan");
2136 }
2137#endif
2138 // Trigger scan if we don't have scan results OR if transitioning from phases that need fresh scan
2139 if (this->scan_result_.empty() || old_phase == WiFiRetryPhase::EXPLICIT_HIDDEN ||
2141 this->selected_sta_index_ = -1; // Will be set after scan completes
2142 this->start_scanning();
2143 return true; // Started scan, wait for completion
2144 }
2145 // Already have scan results - selected_sta_index_ should already be synchronized
2146 // (set in check_scanning_finished() when scan completed)
2147 // No need to reset it here
2148 break;
2149
2151 // Always reset to first candidate when entering this phase.
2152 // This phase can be entered from:
2153 // - SCAN_CONNECTING: normal flow, find_next_hidden_sta_() skips networks visible in scan
2154 // - RESTARTING_ADAPTER: captive portal active, find_next_hidden_sta_() tries ALL networks
2155 //
2156 // The retry_hidden_mode_ controls the behavior:
2157 // - SCAN_BASED: scan_result_ is checked, visible networks are skipped
2158 // - BLIND_RETRY: scan_result_ is ignored, all networks become candidates
2159 // We don't clear scan_result_ here - the mode controls whether it's consulted.
2161
2162 if (this->selected_sta_index_ == -1) {
2163 ESP_LOGD(TAG, "All SSIDs visible or already tried, skipping hidden mode");
2164 }
2165 break;
2166
2168 // Skip actual adapter restart if a portal/improv is active
2169 // This allows state machine to reset num_retried_ and trigger fresh scan
2170 // without disrupting the portal/improv connection
2171 if (!this->is_provisioning_active_()) {
2172 this->restart_adapter();
2173 } else {
2174 // Even when skipping full restart, disconnect to clear driver state
2175 // Without this, platforms like LibreTiny may think we're still connecting
2176 this->wifi_disconnect_();
2177 // And clear the error flag, as restart_adapter() does: COOLDOWN leads to
2178 // check_connecting_finished() without start_connecting(), so a stale
2179 // error would fail a connection the driver completes meanwhile.
2180 this->error_from_callback_ = false;
2181 }
2182 // Clear scan flag - we're starting a new retry cycle
2183 // This is critical for DPP/captive portal/improv flow: when determine_next_phase_()
2184 // returns RETRY_HIDDEN (because scanning is skipped), find_next_hidden_sta_()
2185 // will see BLIND_RETRY mode and treat ALL networks as candidates,
2186 // effectively cycling through all configured networks without scan results.
2188 // Always enter cooldown after restart (or skip-restart) to allow stabilization
2189 // Use extended cooldown when AP is active to avoid constant scanning that blocks DNS
2190 this->start_cooldown_();
2191 // Return true to indicate we should wait (go to COOLDOWN) instead of immediately connecting
2192 return true;
2193
2194 default:
2195 break;
2196 }
2197
2198 return false; // Did not start scan, can proceed with connection
2199}
2200
2202 if (!this->sta_priorities_.empty()) {
2203 decltype(this->sta_priorities_)().swap(this->sta_priorities_);
2204 }
2205}
2206
2211 if (this->sta_priorities_.empty()) {
2212 return;
2213 }
2214
2215 int8_t first_priority = this->sta_priorities_[0].priority;
2216
2217 // Only clear if all priorities have been decremented to the minimum value
2218 // At this point, all BSSIDs have been equally penalized and priority info is useless
2219 if (first_priority != std::numeric_limits<int8_t>::min()) {
2220 return;
2221 }
2222
2223 for (const auto &pri : this->sta_priorities_) {
2224 if (pri.priority != first_priority) {
2225 return; // Not all same, nothing to do
2226 }
2227 }
2228
2229 // All priorities are at minimum - clear the vector to save memory and reset
2230 ESP_LOGD(TAG, "Clearing BSSID priorities (all at minimum)");
2232}
2233
2253 // Determine which BSSID we tried to connect to
2254 optional<bssid_t> failed_bssid;
2255
2256 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
2257 // Scan-based phase: always use best result (index 0)
2258 failed_bssid = this->scan_result_[0].get_bssid();
2259 } else if (const WiFiAP *config = this->get_selected_sta_(); config && config->has_bssid()) {
2260 // Config has specific BSSID (fast_connect or user-specified)
2261 failed_bssid = config->get_bssid();
2262 }
2263
2264 if (!failed_bssid.has_value()) {
2265 return; // No BSSID to penalize
2266 }
2267
2268 // Get SSID for logging (use pointer to avoid copy)
2269 const char *ssid = nullptr;
2270 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
2271 ssid = this->scan_result_[0].ssid_.c_str();
2272 } else if (const WiFiAP *config = this->get_selected_sta_()) {
2273 ssid = config->ssid_.c_str();
2274 }
2275
2276 // Only decrease priority on the last attempt for this phase
2277 // This prevents false positives from transient WiFi stack issues
2278 uint8_t max_retries = get_max_retries_for_phase(this->retry_phase_);
2279 bool is_last_attempt = (this->num_retried_ + 1 >= max_retries);
2280
2281 // Decrease priority only on last attempt to avoid false positives from transient failures
2282 int8_t old_priority = this->get_sta_priority(failed_bssid.value());
2283 int8_t new_priority = old_priority;
2284
2285 if (is_last_attempt) {
2286 // Decrease priority, but clamp to int8_t::min to prevent overflow
2287 new_priority =
2288 (old_priority > std::numeric_limits<int8_t>::min()) ? (old_priority - 1) : std::numeric_limits<int8_t>::min();
2289 this->set_sta_priority(failed_bssid.value(), new_priority);
2290 }
2291 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
2292 format_mac_addr_upper(failed_bssid.value().data(), bssid_s);
2293 ESP_LOGD(TAG, "Failed " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") ", priority %d → %d", ssid != nullptr ? ssid : "",
2294 bssid_s, old_priority, new_priority);
2295
2296 // After adjusting priority, check if all priorities are now at minimum
2297 // If so, clear the vector to save memory and reset for fresh start
2299}
2300
2312 WiFiRetryPhase current_phase = this->retry_phase_;
2313
2314 // Check if we need to advance to next AP/SSID within the same phase
2315#ifdef USE_WIFI_FAST_CONNECT
2316 if (current_phase == WiFiRetryPhase::FAST_CONNECT_CYCLING_APS) {
2317 // Fast connect: always advance to next AP (no retries per AP)
2318 this->selected_sta_index_++;
2319 this->num_retried_ = 0;
2320 ESP_LOGD(TAG, "Next AP in %s", LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
2321 return;
2322 }
2323#endif
2324
2325 if (current_phase == WiFiRetryPhase::EXPLICIT_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
2326 // Explicit hidden: exhausted retries on current SSID, find next explicitly hidden network
2327 // Stop when we reach a visible network (proceed to scanning)
2328 size_t next_index = this->selected_sta_index_ + 1;
2329 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
2330 this->selected_sta_index_ = static_cast<int8_t>(next_index);
2331 this->num_retried_ = 0;
2332 ESP_LOGD(TAG, "Next explicit hidden network at index %d", static_cast<int>(next_index));
2333 return;
2334 }
2335 // No more consecutive explicit hidden networks found - fall through to trigger phase change
2336 }
2337
2338 if (current_phase == WiFiRetryPhase::RETRY_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
2339 // Hidden mode: exhausted retries on current SSID, find next potentially hidden SSID
2340 // If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
2341 // In that case, skip networks marked hidden:true (already tried)
2342 // Otherwise, include them (they haven't been tried yet)
2343 int8_t next_index = this->find_next_hidden_sta_(this->selected_sta_index_);
2344 if (next_index != -1) {
2345 // Found another potentially hidden SSID
2346 this->selected_sta_index_ = next_index;
2347 this->num_retried_ = 0;
2348 return;
2349 }
2350 // No more potentially hidden SSIDs - set selected_sta_index_ to -1 to trigger phase change
2351 // This ensures determine_next_phase_() will skip the RETRY_HIDDEN logic and transition out
2352 this->selected_sta_index_ = -1;
2353 // Return early - phase change will happen on next wifi_loop() iteration
2354 return;
2355 }
2356
2357 // Don't increment retry counter if we're in a scan phase with no valid targets
2358 if (this->needs_scan_results_()) {
2359 return;
2360 }
2361
2362 // Increment retry counter to try the same target again
2363 this->num_retried_++;
2364 ESP_LOGD(TAG, "Retry attempt %u/%u in phase %s", this->num_retried_ + 1,
2365 get_max_retries_for_phase(this->retry_phase_), LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
2366}
2367
2369 // Handle roaming state transitions - preserve attempts counter to prevent ping-pong
2370 // to unreachable APs after ROAMING_MAX_ATTEMPTS failures
2372 // Roam connection failed - transition to reconnecting
2373 ESP_LOGD(TAG, "Roam failed, reconnecting (attempt %u/%u)", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
2375 } else if (this->is_roaming_scan_active()) {
2376 // Disconnected during roam scan - transition to RECONNECTING so the attempts
2377 // counter is preserved when reconnection succeeds (IDLE would reset it)
2378 ESP_LOGD(TAG, "Disconnected during roam scan (attempt %u/%u)", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
2380 } else if (this->roaming_state_ == RoamingState::IDLE) {
2381 // Check if a roaming scan recently completed - on ESP8266, going off-channel
2382 // during scan can cause a delayed Beacon Timeout 8-20 seconds after scan finishes.
2383 // Transition to RECONNECTING so the attempts counter is preserved on reconnect.
2385 ESP_LOGD(TAG, "Disconnect after roam scan (attempt %u/%u)", this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
2387 } else {
2388 // Not a roaming-triggered reconnect, reset state
2389 this->clear_roaming_state_();
2390 }
2391 }
2392 // RECONNECTING: keep state and counter, still trying to reconnect
2393
2395
2396 // Determine next retry phase based on current state
2397 WiFiRetryPhase current_phase = this->retry_phase_;
2398 WiFiRetryPhase next_phase = this->determine_next_phase_();
2399
2400 // Handle phase transitions (transition_to_phase_ handles same-phase no-op internally)
2401 if (this->transition_to_phase_(next_phase)) {
2402 return; // Scan started or adapter restarted (which sets its own state)
2403 }
2404
2405 if (next_phase == current_phase) {
2407 }
2408
2409 yield();
2410 // Check if we have a valid target before building params
2411 // After exhausting all networks in a phase, selected_sta_index_ may be -1
2412 // In that case, skip connection and let next wifi_loop() handle phase transition
2413 if (this->selected_sta_index_ >= 0) {
2414 WiFiAP params = this->build_params_for_current_phase_();
2415 this->start_connecting(params);
2416 }
2417}
2418
2420 this->power_save_ = power_save;
2421#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
2422 this->configured_power_save_ = power_save;
2423#endif
2424}
2425
2426#ifdef USE_WIFI_DPP
2431
2433 if (!this->dpp_listening_)
2434 return;
2435 this->wifi_dpp_stop_listen_();
2436 this->dpp_listening_ = false;
2437}
2438#endif
2439
2441#ifdef USE_WIFI_DPP
2442 // A configurator is waited for once the networks have had their timeout, or from boot without any; the retry
2443 // machine then treats DPP like a portal (blind retries, a long cooldown) whether the supplicant is listening at
2444 // this moment or not
2445 return !this->is_provisioning_closed_() &&
2447#else
2448 return false;
2449#endif
2450}
2451
2453#ifdef USE_CAPTIVE_PORTAL
2455#else
2456 return false;
2457#endif
2458}
2459
2461#ifdef USE_WEBSERVER_CAPTIVE
2462 if (web_server::global_web_server->is_captive())
2463 return true;
2464#endif
2465 return this->is_captive_portal_active_();
2466}
2467
2468// global_web_server needs no null check: codegen always instantiates WebServer when
2469// USE_WEBSERVER_CAPTIVE is defined, and the constructor assigns the global.
2471 // Only behind an AP that came up; a fallback AP (networks and an ap_timeout) is retried by loop()
2472 if (!this->ap_setup_)
2473 return;
2474#ifdef USE_CAPTIVE_PORTAL
2475 // Force one full scan now that the portal lists networks (earlier scans were filtered)
2479#endif
2480#ifdef USE_WEBSERVER_CAPTIVE
2482#endif
2483#ifdef USE_WIFI_AP_WISP_PORTAL
2484 this->apply_ap_dns_(); // point the clients at the portal; a failed refresh takes the AP down for loop() to retry
2485#endif
2486}
2487
2488#ifdef USE_WIFI_AP
2490#ifdef USE_CAPTIVE_PORTAL
2491 // Where the radio scans alongside the AP, the portal can list networks.
2492 if (captive_portal::global_captive_portal != nullptr && !WIFI_AP_EXCLUSIVE) {
2493 this->wifi_sta_pre_setup_();
2494 this->start_scanning();
2495 }
2496#endif
2497}
2498#endif
2499
2501#ifdef USE_CAPTIVE_PORTAL
2502 if (this->is_captive_portal_active_())
2504#endif
2505#ifdef USE_WEBSERVER_CAPTIVE
2507#endif
2508#ifdef USE_WIFI_AP_WISP_PORTAL
2509 if (this->ap_setup_ && this->ap_offers_own_dns_)
2510 this->apply_ap_dns_(); // hand the clients the upstream's resolver again
2511#endif
2512}
2514#ifdef USE_IMPROV_BLE
2516#else
2517 return false;
2518#endif
2519}
2520
2524
2526#ifdef USE_PROVISIONING
2527 // The device stays unprovisionable until it is power-cycled
2529#else
2530 return false;
2531#endif
2532}
2533
2534#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
2536 // Already configured for high performance - request satisfied
2538 return true;
2539 }
2540
2541 // Semaphore initialization failed
2542 if (this->high_performance_semaphore_ == nullptr) {
2543 return false;
2544 }
2545
2546 // Give the semaphore (non-blocking). This increments the count.
2547 bool success = xSemaphoreGive(this->high_performance_semaphore_) == pdTRUE;
2548
2549 // Wake the main loop so the switch to high-performance mode is applied on the
2550 // next tick instead of waiting up to loop_interval.
2551 if (success) {
2553 }
2554
2555 return success;
2556}
2557
2559 // Already configured for high performance - nothing to release
2561 return true;
2562 }
2563
2564 // Semaphore initialization failed
2565 if (this->high_performance_semaphore_ == nullptr) {
2566 return false;
2567 }
2568
2569 // Take the semaphore (non-blocking). This decrements the count.
2570 return xSemaphoreTake(this->high_performance_semaphore_, 0) == pdTRUE;
2571}
2572#endif // USE_ESP32 && USE_WIFI_RUNTIME_POWER_SAVE
2573
2574#ifdef USE_WIFI_FAST_CONNECT
2576 SavedWifiFastConnectSettings fast_connect_save{};
2577
2578 if (this->fast_connect_pref_.load(&fast_connect_save)) {
2579 // Validate saved AP index
2580 if (fast_connect_save.ap_index < 0 || static_cast<size_t>(fast_connect_save.ap_index) >= this->sta_.size()) {
2581 ESP_LOGW(TAG, "AP index out of bounds");
2582 return false;
2583 }
2584
2585 // Set selected index for future operations (save, retry, etc)
2586 this->selected_sta_index_ = fast_connect_save.ap_index;
2587
2588 // Copy entire config, then override with fast connect data
2589 params = this->sta_[fast_connect_save.ap_index];
2590
2591 // Override with saved BSSID/channel from fast connect (SSID/password/etc already copied from config)
2592 bssid_t bssid{};
2593 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
2594 params.set_bssid(bssid);
2595 params.set_channel(fast_connect_save.channel);
2596 // Fast connect uses specific BSSID+channel, not hidden network probe (even if config has hidden: true)
2597 params.set_hidden(false);
2598
2599 ESP_LOGD(TAG, "Loaded fast_connect settings");
2600#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
2601 if ((this->band_mode_ == WIFI_BAND_MODE_5G_ONLY && fast_connect_save.channel < FIRST_5GHZ_CHANNEL) ||
2602 (this->band_mode_ == WIFI_BAND_MODE_2G_ONLY && fast_connect_save.channel >= FIRST_5GHZ_CHANNEL)) {
2603 ESP_LOGW(TAG, "Saved channel %u not allowed by band mode, ignoring fast_connect", fast_connect_save.channel);
2604 this->selected_sta_index_ = -1;
2605 return false;
2606 }
2607#endif
2608 return true;
2609 }
2610
2611 return false;
2612}
2613
2614void WiFiComponent::save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel) {
2615 // selected_sta_index_ is always valid here (called only after successful connection)
2616 // Fallback to 0 is defensive programming for robustness
2617 int8_t ap_index = this->selected_sta_index_ >= 0 ? this->selected_sta_index_ : 0;
2618
2619 // Skip save if settings haven't changed (compare with previously saved settings to reduce flash wear)
2620 SavedWifiFastConnectSettings previous_save{};
2621 if (this->fast_connect_pref_.load(&previous_save) && memcmp(previous_save.bssid, bssid.data(), 6) == 0 &&
2622 previous_save.channel == channel && previous_save.ap_index == ap_index) {
2623 return; // No change, nothing to save
2624 }
2625
2626 SavedWifiFastConnectSettings fast_connect_save{};
2627 memcpy(fast_connect_save.bssid, bssid.data(), 6);
2628 fast_connect_save.channel = channel;
2629 fast_connect_save.ap_index = ap_index;
2630
2631 this->fast_connect_pref_.save(&fast_connect_save);
2632
2633 ESP_LOGD(TAG, "Saved fast_connect settings");
2634}
2635#endif
2636
2637#ifdef USE_WIFI_LEASE_CACHE
2639 if (!this->lease_cache_pref_.load(&this->cached_lease_) || this->cached_lease_.version != SAVED_WIFI_LEASE_VERSION) {
2640 this->cached_lease_ = {};
2641 return;
2642 }
2643 const uint8_t *ip = reinterpret_cast<const uint8_t *>(&this->cached_lease_.ip); // network byte order
2644 ESP_LOGD(TAG, "Loaded cached lease %u.%u.%u.%u (network %d, lease %us)", ip[0], ip[1], ip[2], ip[3],
2645 this->cached_lease_.ap_index, this->cached_lease_.lease_secs);
2646}
2647
2649 if (this->cached_lease_.version == 0)
2650 return;
2651 this->cached_lease_ = {};
2652 this->lease_cache_pref_.save(&this->cached_lease_);
2653 ESP_LOGD(TAG, "Lease cache: cleared");
2654}
2655#endif
2656
2657WiFiScanResult::WiFiScanResult(const bssid_t &bssid, const char *ssid, size_t ssid_len, uint8_t channel, int8_t rssi,
2658 bool with_auth, bool is_hidden)
2659 : bssid_(bssid),
2660 channel_(channel),
2661 rssi_(rssi),
2662 ssid_(ssid, ssid_len),
2663 with_auth_(with_auth),
2664 is_hidden_(is_hidden) {}
2665bool WiFiScanResult::matches(const WiFiAP &config) const {
2666 if (config.get_hidden()) {
2667 // User configured a hidden network, only match actually hidden networks
2668 // don't match SSID
2669 if (!this->is_hidden_)
2670 return false;
2671 } else if (!config.ssid_.empty()) {
2672 // check if SSID matches
2673 if (this->ssid_ != config.ssid_)
2674 return false;
2675 } else {
2676 // network is configured without SSID - match other settings
2677 }
2678 // If BSSID configured, only match for correct BSSIDs
2679 if (config.has_bssid() && config.get_bssid() != this->bssid_)
2680 return false;
2681
2682#ifdef USE_WIFI_WPA2_EAP
2683 // BSSID requires auth but no PSK or EAP credentials given
2684 if (this->with_auth_ && (config.password_.empty() && !config.get_eap().has_value()))
2685 return false;
2686
2687 // BSSID does not require auth, but PSK or EAP credentials given
2688 if (!this->with_auth_ && (!config.password_.empty() || config.get_eap().has_value()))
2689 return false;
2690#else
2691 // If PSK given, only match for networks with auth (and vice versa)
2692 if (config.password_.empty() == this->with_auth_)
2693 return false;
2694#endif
2695
2696 // If channel configured, only match networks on that channel.
2697 if (config.has_channel() && config.get_channel() != this->channel_) {
2698 return false;
2699 }
2700 return true;
2701}
2702bool WiFiScanResult::operator==(const WiFiScanResult &rhs) const { return this->bssid_ == rhs.bssid_; }
2703
2705 this->roaming_attempts_ = 0;
2706 this->roaming_last_check_ = 0;
2707 this->roaming_scan_end_ = 0;
2708 this->roaming_target_bssid_ = {};
2710}
2711
2712#ifdef USE_ESP32
2713void WiFiComponent::handle_driver_roam_(const bssid_t &bssid, uint8_t channel) {
2714 // A driver-initiated roam (e.g. 802.11v BTM) re-associates without the state
2715 // machine ever leaving STA_CONNECTED, so check_connecting_finished() never runs.
2716 // Redo its post-connect bookkeeping here. roaming_state_ is deliberately left
2717 // untouched so an in-flight roaming scan is not orphaned. The BSSID and
2718 // channel both come from the connected event so the saved pair is consistent:
2719 // the radio may be off-channel during a roaming scan, and a later queued
2720 // event may have moved the driver on again by the time this one is processed.
2722 this->roaming_attempts_ = 0;
2723 this->roaming_scan_end_ = 0;
2725#ifdef USE_WIFI_FAST_CONNECT
2726 this->save_fast_connect_settings_(bssid, channel);
2727#endif
2728}
2729#endif
2730
2732 if (!this->keep_scan_results_) {
2733 ScanResultsLock lock(this);
2734#if defined(USE_RP2)
2735 // std::vector - use swap trick since shrink_to_fit is non-binding
2736 decltype(this->scan_result_)().swap(this->scan_result_);
2737#else
2738 // FixedVector::release() frees all memory
2739 this->scan_result_.release();
2740#endif
2741 }
2742}
2743
2744#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
2746 if (!this->pending_.connect_state)
2747 return;
2748 this->pending_.connect_state = false;
2749 // Get current SSID and BSSID from the WiFi driver
2750 char ssid_buf[SSID_BUFFER_SIZE];
2751 const char *ssid = this->wifi_ssid_to(ssid_buf);
2752 bssid_t bssid = this->wifi_bssid();
2753 for (auto *listener : this->connect_state_listeners_) {
2754 listener->on_wifi_connect_state(StringRef(ssid, strlen(ssid)), bssid);
2755 }
2756}
2757
2759 constexpr uint8_t empty_bssid[6] = {};
2760 for (auto *listener : this->connect_state_listeners_) {
2761 listener->on_wifi_connect_state(StringRef(), empty_bssid);
2762 }
2763}
2764#endif // USE_WIFI_CONNECT_STATE_LISTENERS
2765
2766#ifdef USE_WIFI_IP_STATE_LISTENERS
2768 for (auto *listener : this->ip_state_listeners_) {
2769 listener->on_ip_state(this->wifi_sta_ip_addresses(), this->get_dns_address(0), this->get_dns_address(1));
2770 }
2771}
2772#endif // USE_WIFI_IP_STATE_LISTENERS
2773
2774#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
2776 for (auto *listener : this->scan_results_listeners_) {
2777 listener->on_wifi_scan_results(this->scan_result_);
2778 }
2779}
2780#endif // USE_WIFI_SCAN_RESULTS_LISTENERS
2781
2783 if (!this->is_connected() || this->roaming_state_ != RoamingState::IDLE || this->roaming_suppressed_()) {
2784 ESP_LOGD(TAG, "Roam check requested, but not able to check now");
2785 return;
2786 }
2787 // Reset the attempt counter so a prior run of failed roams doesn't block this explicit request
2788 // Note that this re-arms automatic roaming if enabled.
2789 this->roaming_attempts_ = 0;
2790 this->check_roaming_(millis());
2791}
2792
2794 // Guard: not for hidden networks (may not appear in scan)
2795 const WiFiAP *selected = this->get_selected_sta_();
2796 if (selected == nullptr || selected->get_hidden()) {
2797 this->roaming_attempts_ = ROAMING_MAX_ATTEMPTS; // Stop checking forever
2798 return;
2799 }
2800
2801 this->roaming_last_check_ = now;
2802 this->roaming_attempts_++;
2803
2804 // Guard: skip scan if signal is already good (no meaningful improvement possible)
2805 int8_t rssi = this->wifi_rssi();
2806 if (rssi > ROAMING_GOOD_RSSI) {
2807 ESP_LOGD(TAG, "Roam check skipped, signal good (%d dBm, attempt %u/%u)", rssi, this->roaming_attempts_,
2809 return;
2810 }
2811
2812 ESP_LOGD(TAG, "Roam scan (%d dBm, attempt %u/%u)", rssi, this->roaming_attempts_, ROAMING_MAX_ATTEMPTS);
2814 if (!this->wifi_scan_start_(this->passive_scan_)) {
2815 // Scan failed to start (e.g. busy) - don't get stuck in SCANNING forever
2816 ESP_LOGD(TAG, "Roam scan failed to start");
2818 }
2819}
2820
2822 this->scan_done_ = false;
2823 // Default to IDLE - will be set to CONNECTING if we find a better AP
2825 // Record when scan completed so delayed disconnects (e.g., ESP8266 Beacon Timeout)
2826 // can be attributed to the scan and avoid resetting the attempts counter
2827 this->roaming_scan_end_ = millis();
2828
2829 // Get current connection info
2830 int8_t current_rssi = this->wifi_rssi();
2831 // Guard: must still be connected (RSSI may have become invalid during scan)
2832 if (current_rssi == WIFI_RSSI_DISCONNECTED) {
2833 this->release_scan_results_();
2834 return;
2835 }
2836
2837 char ssid_buf[SSID_BUFFER_SIZE];
2838 StringRef current_ssid(this->wifi_ssid_to(ssid_buf));
2839 bssid_t current_bssid = this->wifi_bssid();
2840
2841 // Find best candidate: same SSID, different BSSID
2842 const WiFiScanResult *best = nullptr;
2843 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
2844
2845 for (const auto &result : this->scan_result_) {
2846 // Must be same SSID, different BSSID
2847 if (result.ssid_ != current_ssid || result.get_bssid() == current_bssid)
2848 continue;
2849
2850#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
2851 format_mac_addr_upper(result.get_bssid().data(), bssid_buf);
2852 ESP_LOGV(TAG, "Roam candidate %s %d dBm", bssid_buf, result.get_rssi());
2853#endif
2854
2855 // Track the best candidate
2856 if (best == nullptr || result.get_rssi() > best->get_rssi()) {
2857 best = &result;
2858 }
2859 }
2860
2861 // Check if best candidate meets minimum improvement threshold
2862 const WiFiAP *selected = this->get_selected_sta_();
2863 int8_t improvement = (best == nullptr) ? 0 : best->get_rssi() - current_rssi;
2864 if (selected == nullptr || improvement < ROAMING_MIN_IMPROVEMENT) {
2865 ESP_LOGV(TAG, "Roam best %+d dB (need +%d), attempt %u/%u", improvement, ROAMING_MIN_IMPROVEMENT,
2867 this->release_scan_results_();
2868 return;
2869 }
2870
2871 format_mac_addr_upper(best->get_bssid().data(), bssid_buf);
2872 ESP_LOGI(TAG, "Roaming to %s (%+d dB)", bssid_buf, improvement);
2873
2874 WiFiAP roam_params = *selected;
2875 apply_scan_result_to_params(roam_params, *best);
2876
2877 // Mark as roaming attempt - affects retry behavior if connection fails
2879 this->roaming_target_bssid_ = best->get_bssid(); // Must read before releasing scan results
2880
2881 this->release_scan_results_();
2882
2883 // Connect directly - wifi_sta_connect_ handles disconnect internally
2884 this->start_connecting(roam_params);
2885}
2886
2887#ifdef USE_WIFI_MANUAL_IP
2888optional<ManualIP> WiFiAP::get_manual_ip() const {
2889 if (!this->has_manual_ip())
2890 return {};
2891 uint8_t b[MANUAL_IP_ENTRY_SIZE];
2892 progmem_memcpy(b, MANUAL_IP_TABLE + this->manual_ip_index_ * MANUAL_IP_ENTRY_SIZE, sizeof(b));
2893 auto ip = [&b](size_t i) { return network::IPAddress(b[i], b[i + 1], b[i + 2], b[i + 3]); };
2894 return ManualIP{ip(0), ip(4), ip(8), ip(12), ip(16)};
2895}
2896#endif
2897
2898WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
2899
2900} // namespace esphome::wifi
2901#endif
BedjetMode mode
BedJet operating mode.
uint8_t m
Definition bl0906.h:1
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
bool is_name_add_mac_suffix_enabled() const
uint32_t get_config_version_hash()
Get the config hash extended with ESPHome version.
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.
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:309
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
constexpr const char * c_str() const
Definition string_ref.h:78
constexpr size_type size() const
Definition string_ref.h:79
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:557
void start_captive()
AP mode: DNS answers every name with the AP address and unknown URLs redirect to the interface.
20-byte string: 18 chars inline + null, heap for longer.
const char * data() const
CompactString & operator=(const CompactString &other)
bool operator==(const CompactString &other) const
static constexpr uint8_t INLINE_CAPACITY
const char * c_str() const
char storage_[INLINE_CAPACITY+1]
static constexpr uint8_t MAX_LENGTH
Guards WiFiComponent::scan_result_.
uint8_t get_channel() const
void set_ssid(const std::string &ssid)
const optional< EAPAuth > & get_eap() const
void set_bssid(const bssid_t &bssid)
void set_channel(uint8_t channel)
optional< ManualIP > get_manual_ip() const
void set_hidden(bool hidden)
const bssid_t & get_bssid() const
This component is responsible for managing the ESP WiFi interface.
void notify_scan_results_listeners_()
Notify scan results listeners with current scan results.
bool is_provisioning_closed_()
The provisioning window has closed, so no new provisioning surface may start.
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.
bool request_high_performance()
Request high-performance mode (no power saving) for improved WiFi latency.
void set_sta(const WiFiAP &ap)
bool roaming_suppressed_() const
Returns true if a component has requested that roaming scans be suppressed (e.g. during audio playbac...
bool has_sta_priority(const bssid_t &bssid)
const WiFiAP * get_selected_sta_() const
WiFiSTAConnectStatus wifi_sta_connect_status_() const
int8_t get_sta_priority(const bssid_t bssid)
void set_last_connected_(uint32_t now)
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)
void notify_connect_state_listeners_()
Notify connect state listeners (called after state machine reaches STA_CONNECTED)
SavedWifiLeaseSettings cached_lease_
wifi_scan_vector_t< WiFiScanResult > scan_result_
void save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel)
WiFiPowerSaveMode configured_power_save_
void set_sta_priority(bssid_t bssid, int8_t priority)
StaticVector< WiFiScanResultsListener *, ESPHOME_WIFI_SCAN_RESULTS_LISTENERS > scan_results_listeners_
void loop() override
Reconnect WiFi if required.
void notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
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...
ESPPreferenceObject lease_cache_pref_
static constexpr uint32_t ROAMING_CHECK_INTERVAL
SemaphoreHandle_t high_performance_semaphore_
bool ap_dns_known_()
Whether there is an IPv4 resolver to offer AP clients: a configured one, or the station's.
void start_cooldown_()
Wait before the next attempt; while a configurator is waited for, the wait is its listen window.
network::IPAddress get_dns_address(int num)
void pause_exclusive_ap_()
Drop the fallback AP so the networks can be tried; it comes back after ap_timeout.
void apply_ap_dns_()
Pass the station's resolvers on to AP clients when they changed.
WiFiComponent()
Construct a WiFiComponent.
std::vector< WiFiSTAPriority > sta_priorities_
void apply_radio_settings_()
Output power and power save, wherever the radio first comes up: start() with networks,...
static constexpr int8_t ROAMING_GOOD_RSSI
void notify_disconnect_state_listeners_()
Notify connect state listeners of disconnection.
void start_portal_scan_()
Scan alongside the AP so the portal can list networks, when there is no station to try.
StaticVector< WiFiConnectStateListener *, ESPHOME_WIFI_CONNECT_STATE_LISTENERS > connect_state_listeners_
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)
const char * wifi_ssid_to(std::span< char, SSID_BUFFER_SIZE > buffer)
Write SSID to buffer without heap allocation.
static constexpr uint8_t ROAMING_MAX_ATTEMPTS
void set_power_save_mode(WiFiPowerSaveMode power_save)
bool is_roaming_scan_active() const
True while a post-connect roaming scan holds the radio off-channel.
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)
bool is_ap_portal_active_()
captive_portal or the web_server AP mode is serving a user on the access point
static constexpr uint32_t ROAMING_SCAN_GRACE_PERIOD
WiFiRetryPhase determine_next_phase_()
Determine next retry phase based on current state and failure conditions.
network::IPAddress wifi_dns_ip_(int num)
network::IPAddresses get_ip_addresses()
static constexpr int8_t ROAMING_MIN_IMPROVEMENT
bool is_provisioning_active_()
A portal, improv or DPP is waiting for credentials, so the retry machine must not disturb the radio.
void disable_ap_()
End the portals and turn the AP off.
StaticVector< WiFiIPStateListener *, ESPHOME_WIFI_IP_STATE_LISTENERS > ip_state_listeners_
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...
void release_scan_results_()
Free scan results memory unless a component needs them.
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),...
bool needs_full_scan_results_() const
Check if full scan results are needed (captive portal active, improv, listeners)
void start_dpp_listen_(uint32_t now)
static constexpr uint8_t FIRST_5GHZ_CHANNEL
void forget_ap_()
End the portals and forget the AP's state, before the radio takes the AP down.
bool release_high_performance()
Release a high-performance mode request.
void force_roam_check()
Force an immediate post-connect roaming check, bypassing the periodic interval and the per-connection...
bool wifi_apply_output_power_(float output_power)
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)
network::IPAddresses wifi_sta_ip_addresses()
void check_connecting_finished(uint32_t now)
void start_initial_connection_()
Start initial connection - either scan or connect directly to hidden networks.
bool ssid_was_seen_in_scan_(const CompactString &ssid) const
Check if an SSID was seen in the most recent scan results Used to skip hidden mode for SSIDs we know ...
void handle_driver_roam_(const bssid_t &bssid, uint8_t channel)
Redo post-connect bookkeeping after a driver-initiated roam (e.g.
struct esphome::wifi::WiFiComponent::@199 pending_
const WiFiAP * find_configured_network_(const char *ssid, const uint8_t *bssid) const
The configured network a scan result belongs to, or nullptr (for scan result filtering) Matches by SS...
void setup() override
Setup WiFi interface.
void clear_all_bssid_priorities_()
Clear all BSSID priority penalties after successful connection (stale after disconnect)
WiFiScanResult(const bssid_t &bssid, const char *ssid, size_t ssid_len, uint8_t channel, int8_t rssi, bool with_auth, bool is_hidden)
const bssid_t & get_bssid() const
bool matches(const WiFiAP &config) const
bool operator==(const WiFiScanResult &rhs) const
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
Definition main_task.h:45
void yield(void)
uint8_t priority
uint8_t type
const char * key
unsigned count
Definition gif.cpp:51
CaptivePortal * global_captive_portal
ImprovBLEComponent * global_improv_component
ImprovSerialComponent * global_improv_serial_component
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:368
ProvisioningManager * global_provisioning_manager
WebServer * global_web_server
std::array< uint8_t, 6 > bssid_t
ESPHOME_LOG_TAG(TAG, "wifi")
const LogString * get_signal_bars(int8_t rssi)
@ BLIND_RETRY
Blind retry mode: scanning disabled (captive portal/improv active), try ALL configured networks seque...
@ SCAN_BASED
Normal mode: scan completed, only try networks NOT visible in scan results (truly hidden networks tha...
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
@ SCANNING
Scanning for better AP.
@ CONNECTING
Attempting to connect to better AP found in scan.
@ IDLE
Not roaming, waiting for next check interval.
@ RECONNECTING
Roam connection failed, reconnecting to any available AP.
@ 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.
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
Definition helpers.cpp:297
uint16_t uint16_t size_t elem_size
Definition helpers.cpp:35
void progmem_memcpy(void *dst, const void *src, size_t len)
Definition hal.h:56
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
ESPPreferences * global_preferences
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:854
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
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:1754
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.
SemaphoreHandle_t lock