ESPHome 2025.12.5
Loading...
Searching...
No Matches
wifi_component.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2#ifdef USE_WIFI
3#include <cassert>
4#include <cinttypes>
5
6#ifdef USE_ESP32
7#if (ESP_IDF_VERSION_MAJOR >= 5 && ESP_IDF_VERSION_MINOR >= 1)
8#include <esp_eap_client.h>
9#else
10#include <esp_wpa2.h>
11#endif
12#endif
13
14#if defined(USE_ESP32)
15#include <esp_wifi.h>
16#endif
17#ifdef USE_ESP8266
18#include <user_interface.h>
19#endif
20
21#include <algorithm>
22#include <utility>
23#include "lwip/dns.h"
24#include "lwip/err.h"
25
27#include "esphome/core/hal.h"
29#include "esphome/core/log.h"
30#include "esphome/core/util.h"
31
32#ifdef USE_CAPTIVE_PORTAL
34#endif
35
36#ifdef USE_IMPROV
38#endif
39
40namespace esphome::wifi {
41
42static const char *const TAG = "wifi";
43
145
146static const LogString *retry_phase_to_log_string(WiFiRetryPhase phase) {
147 switch (phase) {
149 return LOG_STR("INITIAL_CONNECT");
150#ifdef USE_WIFI_FAST_CONNECT
152 return LOG_STR("FAST_CONNECT_CYCLING");
153#endif
155 return LOG_STR("EXPLICIT_HIDDEN");
157 return LOG_STR("SCAN_CONNECTING");
159 return LOG_STR("RETRY_HIDDEN");
161 return LOG_STR("RESTARTING");
162 default:
163 return LOG_STR("UNKNOWN");
164 }
165}
166
168 // If first configured network is marked hidden, we went through EXPLICIT_HIDDEN phase
169 // This means those networks were already tried and should be skipped in RETRY_HIDDEN
170 return !this->sta_.empty() && this->sta_[0].get_hidden();
171}
172
174 // Find the first network that is NOT marked hidden:true
175 // This is where EXPLICIT_HIDDEN phase would have stopped
176 for (size_t i = 0; i < this->sta_.size(); i++) {
177 if (!this->sta_[i].get_hidden()) {
178 return static_cast<int8_t>(i);
179 }
180 }
181 return -1; // All networks are hidden
182}
183
184// 2 attempts per BSSID in SCAN_CONNECTING phase
185// Rationale: This is the ONLY phase where we decrease BSSID priority, so we must be very sure.
186// Auth failures are common immediately after scan due to WiFi stack state transitions.
187// Trying twice filters out false positives and prevents unnecessarily marking a good BSSID as bad.
188// After 2 genuine failures, priority degradation ensures we skip this BSSID on subsequent scans.
189static constexpr uint8_t WIFI_RETRY_COUNT_PER_BSSID = 2;
190
191// 1 attempt per SSID in RETRY_HIDDEN phase
192// Rationale: Try hidden mode once, then rescan to get next best BSSID via priority system
193static constexpr uint8_t WIFI_RETRY_COUNT_PER_SSID = 1;
194
195// 1 attempt per AP in fast_connect mode (INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS)
196// Rationale: Fast connect prioritizes speed - try each AP once to find a working one quickly
197static constexpr uint8_t WIFI_RETRY_COUNT_PER_AP = 1;
198
201static constexpr uint32_t WIFI_COOLDOWN_DURATION_MS = 500;
202
206static constexpr uint32_t WIFI_COOLDOWN_WITH_AP_ACTIVE_MS = 30000;
207
211static constexpr uint32_t WIFI_SCAN_TIMEOUT_MS = 31000;
212
221static constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 46000;
222
223static constexpr uint8_t get_max_retries_for_phase(WiFiRetryPhase phase) {
224 switch (phase) {
226#ifdef USE_WIFI_FAST_CONNECT
228#endif
229 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS both use 1 attempt per AP (fast_connect mode)
230 return WIFI_RETRY_COUNT_PER_AP;
232 // Explicitly hidden network: 1 attempt (user marked as hidden, try once then scan)
233 return WIFI_RETRY_COUNT_PER_SSID;
235 // Scan-based phase: 2 attempts per BSSID (handles transient auth failures after scan)
236 return WIFI_RETRY_COUNT_PER_BSSID;
238 // Hidden network mode: 1 attempt per SSID
239 return WIFI_RETRY_COUNT_PER_SSID;
240 default:
241 return WIFI_RETRY_COUNT_PER_BSSID;
242 }
243}
244
245static void apply_scan_result_to_params(WiFiAP &params, const WiFiScanResult &scan) {
246 params.set_hidden(false);
247 params.set_ssid(scan.get_ssid());
248 params.set_bssid(scan.get_bssid());
249 params.set_channel(scan.get_channel());
250}
251
253 // Only SCAN_CONNECTING phase needs scan results
255 return false;
256 }
257 // Need scan if we have no results or no matching networks
258 return this->scan_result_.empty() || !this->scan_result_[0].get_matches();
259}
260
261bool WiFiComponent::ssid_was_seen_in_scan_(const std::string &ssid) const {
262 // Check if this SSID is configured as hidden
263 // If explicitly marked hidden, we should always try hidden mode regardless of scan results
264 for (const auto &conf : this->sta_) {
265 if (conf.get_ssid() == ssid && conf.get_hidden()) {
266 return false; // Treat as not seen - force hidden mode attempt
267 }
268 }
269
270 // Otherwise, check if we saw it in scan results
271 for (const auto &scan : this->scan_result_) {
272 if (scan.get_ssid() == ssid) {
273 return true;
274 }
275 }
276 return false;
277}
278
279int8_t WiFiComponent::find_next_hidden_sta_(int8_t start_index) {
280 // Find next SSID that wasn't in scan results (might be hidden)
281 bool include_explicit_hidden = !this->went_through_explicit_hidden_phase_();
282 // Start searching from start_index + 1
283 for (size_t i = start_index + 1; i < this->sta_.size(); i++) {
284 const auto &sta = this->sta_[i];
285
286 // Skip networks that were already tried in EXPLICIT_HIDDEN phase
287 // Those are: networks marked hidden:true that appear before the first non-hidden network
288 // If all networks are hidden (first_non_hidden_idx == -1), skip all of them
289 if (!include_explicit_hidden && sta.get_hidden()) {
290 int8_t first_non_hidden_idx = this->find_first_non_hidden_index_();
291 if (first_non_hidden_idx < 0 || static_cast<int8_t>(i) < first_non_hidden_idx) {
292 ESP_LOGD(TAG, "Skipping " LOG_SECRET("'%s'") " (explicit hidden, already tried)", sta.get_ssid().c_str());
293 continue;
294 }
295 }
296
297 // If we didn't scan this cycle, treat all networks as potentially hidden
298 // Otherwise, only retry networks that weren't seen in the scan
299 if (!this->did_scan_this_cycle_ || !this->ssid_was_seen_in_scan_(sta.get_ssid())) {
300 ESP_LOGD(TAG, "Hidden candidate " LOG_SECRET("'%s'") " at index %d", sta.get_ssid().c_str(), static_cast<int>(i));
301 return static_cast<int8_t>(i);
302 }
303 ESP_LOGD(TAG, "Skipping hidden retry for visible network " LOG_SECRET("'%s'"), sta.get_ssid().c_str());
304 }
305 // No hidden SSIDs found
306 return -1;
307}
308
310 // If first network (highest priority) is explicitly marked hidden, try it first before scanning
311 // This respects user's priority order when they explicitly configure hidden networks
312 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
313 ESP_LOGI(TAG, "Starting with explicit hidden network (highest priority)");
314 this->selected_sta_index_ = 0;
317 this->start_connecting(params);
318 } else {
319 ESP_LOGI(TAG, "Starting scan");
320 this->start_scanning();
321 }
322}
323
324#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
325static const char *eap_phase2_to_str(esp_eap_ttls_phase2_types type) {
326 switch (type) {
327 case ESP_EAP_TTLS_PHASE2_PAP:
328 return "pap";
329 case ESP_EAP_TTLS_PHASE2_CHAP:
330 return "chap";
331 case ESP_EAP_TTLS_PHASE2_MSCHAP:
332 return "mschap";
333 case ESP_EAP_TTLS_PHASE2_MSCHAPV2:
334 return "mschapv2";
335 case ESP_EAP_TTLS_PHASE2_EAP:
336 return "eap";
337 default:
338 return "unknown";
339 }
340}
341#endif
342
344
346 this->wifi_pre_setup_();
347
348#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
349 // Create semaphore for high-performance mode requests
350 // Start at 0, increment on request, decrement on release
351 this->high_performance_semaphore_ = xSemaphoreCreateCounting(UINT32_MAX, 0);
352 if (this->high_performance_semaphore_ == nullptr) {
353 ESP_LOGE(TAG, "Failed semaphore");
354 }
355
356 // Store the configured power save mode as baseline
358#endif
359
360 if (this->enable_on_boot_) {
361 this->start();
362 } else {
363#ifdef USE_ESP32
364 esp_netif_init();
365#endif
367 }
368}
369
371 char mac_s[18];
372 ESP_LOGCONFIG(TAG,
373 "Starting\n"
374 " Local MAC: %s",
376 this->last_connected_ = millis();
377
378 uint32_t hash = this->has_sta() ? fnv1_hash(App.get_compilation_time_ref().c_str()) : 88491487UL;
379
381#ifdef USE_WIFI_FAST_CONNECT
383#endif
384
385 SavedWifiSettings save{};
386 if (this->pref_.load(&save)) {
387 ESP_LOGD(TAG, "Loaded settings: %s", save.ssid);
388
389 WiFiAP sta{};
390 sta.set_ssid(save.ssid);
391 sta.set_password(save.password);
392 this->set_sta(sta);
393 }
394
395 if (this->has_sta()) {
396 this->wifi_sta_pre_setup_();
397 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
398 ESP_LOGV(TAG, "Setting Output Power Option failed");
399 }
400
401#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
402 // Synchronize power_save_ with semaphore state before applying
403 if (this->high_performance_semaphore_ != nullptr) {
404 UBaseType_t semaphore_count = uxSemaphoreGetCount(this->high_performance_semaphore_);
405 if (semaphore_count > 0) {
407 this->is_high_performance_mode_ = true;
408 } else {
410 this->is_high_performance_mode_ = false;
411 }
412 }
413#endif
414 if (!this->wifi_apply_power_save_()) {
415 ESP_LOGV(TAG, "Setting Power Save Option failed");
416 }
417
419#ifdef USE_WIFI_FAST_CONNECT
420 WiFiAP params;
421 bool loaded_fast_connect = this->load_fast_connect_settings_(params);
422 // Fast connect optimization: only use when we have saved BSSID+channel data
423 // Without saved data, try first configured network or use normal flow
424 if (loaded_fast_connect) {
425 ESP_LOGI(TAG, "Starting fast_connect (saved) " LOG_SECRET("'%s'"), params.get_ssid().c_str());
426 this->start_connecting(params);
427 } else if (!this->sta_.empty() && !this->sta_[0].get_hidden()) {
428 // No saved data, but have configured networks - try first non-hidden network
429 ESP_LOGI(TAG, "Starting fast_connect (config) " LOG_SECRET("'%s'"), this->sta_[0].get_ssid().c_str());
430 this->selected_sta_index_ = 0;
431 params = this->build_params_for_current_phase_();
432 this->start_connecting(params);
433 } else {
434 // No saved data and (no networks OR first is hidden) - use normal flow
436 }
437#else
438 // Without fast_connect: go straight to scanning (or hidden mode if all networks are hidden)
440#endif
441#ifdef USE_WIFI_AP
442 } else if (this->has_ap()) {
443 this->setup_ap_config_();
444 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
445 ESP_LOGV(TAG, "Setting Output Power Option failed");
446 }
447#ifdef USE_CAPTIVE_PORTAL
449 this->wifi_sta_pre_setup_();
450 this->start_scanning();
452 }
453#endif
454#endif // USE_WIFI_AP
455 }
456#ifdef USE_IMPROV
457 if (!this->has_sta() && esp32_improv::global_improv_component != nullptr) {
458 if (this->wifi_mode_(true, {}))
460 }
461#endif
462 this->wifi_apply_hostname_();
463}
464
466 ESP_LOGW(TAG, "Restarting adapter");
467 this->wifi_mode_(false, {});
468 this->error_from_callback_ = false;
469}
470
472 this->wifi_loop_();
473 const uint32_t now = App.get_loop_component_start_time();
474
475 if (this->has_sta()) {
476 if (this->is_connected() != this->handled_connected_state_) {
477 if (this->handled_connected_state_) {
479 } else {
480 this->connect_trigger_->trigger();
481 }
483 }
484
485 switch (this->state_) {
487 this->status_set_warning(LOG_STR("waiting to reconnect"));
488 // Skip cooldown if new credentials were provided while connecting
489 if (this->skip_cooldown_next_cycle_) {
490 this->skip_cooldown_next_cycle_ = false;
492 break;
493 }
494 // Use longer cooldown when captive portal/improv is active to avoid disrupting user config
495 bool portal_active = this->is_captive_portal_active_() || this->is_esp32_improv_active_();
496 uint32_t cooldown_duration = portal_active ? WIFI_COOLDOWN_WITH_AP_ACTIVE_MS : WIFI_COOLDOWN_DURATION_MS;
497 if (now - this->action_started_ > cooldown_duration) {
498 // After cooldown we either restarted the adapter because of
499 // a failure, or something tried to connect over and over
500 // so we entered cooldown. In both cases we call
501 // check_connecting_finished to continue the state machine.
503 }
504 break;
505 }
507 this->status_set_warning(LOG_STR("scanning for networks"));
509 break;
510 }
512 this->status_set_warning(LOG_STR("associating to network"));
514 break;
515 }
516
518 if (!this->is_connected()) {
519 ESP_LOGW(TAG, "Connection lost; reconnecting");
521 // Clear error flag before reconnecting so first attempt is not seen as immediate failure
522 this->error_from_callback_ = false;
523 this->retry_connect();
524 } else {
525 this->status_clear_warning();
526 this->last_connected_ = now;
527 }
528 break;
529 }
532 break;
534 return;
535 }
536
537#ifdef USE_WIFI_AP
538 if (this->has_ap() && !this->ap_setup_) {
539 if (this->ap_timeout_ != 0 && (now - this->last_connected_ > this->ap_timeout_)) {
540 ESP_LOGI(TAG, "Starting fallback AP");
541 this->setup_ap_config_();
542#ifdef USE_CAPTIVE_PORTAL
545#endif
546 }
547 }
548#endif // USE_WIFI_AP
549
550#ifdef USE_IMPROV
552 !esp32_improv::global_improv_component->should_start()) {
553 if (now - this->last_connected_ > esp32_improv::global_improv_component->get_wifi_timeout()) {
554 if (this->wifi_mode_(true, {}))
556 }
557 }
558
559#endif
560
561 if (!this->has_ap() && this->reboot_timeout_ != 0) {
562 if (now - this->last_connected_ > this->reboot_timeout_) {
563 ESP_LOGE(TAG, "Can't connect; rebooting");
564 App.reboot();
565 }
566 }
567 }
568
569#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
570 // Check if power save mode needs to be updated based on high-performance requests
571 if (this->high_performance_semaphore_ != nullptr) {
572 // Semaphore count directly represents active requests (starts at 0, increments on request)
573 UBaseType_t semaphore_count = uxSemaphoreGetCount(this->high_performance_semaphore_);
574
575 if (semaphore_count > 0 && !this->is_high_performance_mode_) {
576 // Transition to high-performance mode (no power save)
577 ESP_LOGV(TAG, "Switching to high-performance mode (%" PRIu32 " active %s)", (uint32_t) semaphore_count,
578 semaphore_count == 1 ? "request" : "requests");
580 if (this->wifi_apply_power_save_()) {
581 this->is_high_performance_mode_ = true;
582 }
583 } else if (semaphore_count == 0 && this->is_high_performance_mode_) {
584 // Restore to configured power save mode
585 ESP_LOGV(TAG, "Restoring power save mode to configured setting");
587 if (this->wifi_apply_power_save_()) {
588 this->is_high_performance_mode_ = false;
589 }
590 }
591 }
592#endif
593}
594
596
597bool WiFiComponent::has_ap() const { return this->has_ap_; }
598bool WiFiComponent::is_ap_active() const { return this->ap_started_; }
599bool WiFiComponent::has_sta() const { return !this->sta_.empty(); }
600#ifdef USE_WIFI_11KV_SUPPORT
601void WiFiComponent::set_btm(bool btm) { this->btm_ = btm; }
602void WiFiComponent::set_rrm(bool rrm) { this->rrm_ = rrm; }
603#endif
605 if (this->has_sta())
606 return this->wifi_sta_ip_addresses();
607
608#ifdef USE_WIFI_AP
609 if (this->has_ap())
610 return {this->wifi_soft_ap_ip()};
611#endif // USE_WIFI_AP
612
613 return {};
614}
616 if (this->has_sta())
617 return this->wifi_dns_ip_(num);
618 return {};
619}
620// set_use_address() is guaranteed to be called during component setup by Python code generation,
621// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
622const char *WiFiComponent::get_use_address() const { return this->use_address_; }
623void WiFiComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
624
625#ifdef USE_WIFI_AP
627 this->wifi_mode_({}, true);
628
629 if (this->ap_setup_)
630 return;
631
632 if (this->ap_.get_ssid().empty()) {
633 std::string name = App.get_name();
634 if (name.length() > 32) {
636 // Keep first 25 chars and last 7 chars (MAC suffix), remove middle
637 name.erase(25, name.length() - 32);
638 } else {
639 name.resize(32);
640 }
641 }
642 this->ap_.set_ssid(name);
643 }
644 this->ap_setup_ = this->wifi_start_ap_(this->ap_);
645
646 auto ip_address = this->wifi_soft_ap_ip().str();
647 ESP_LOGCONFIG(TAG,
648 "Setting up AP:\n"
649 " AP SSID: '%s'\n"
650 " AP Password: '%s'\n"
651 " IP Address: %s",
652 this->ap_.get_ssid().c_str(), this->ap_.get_password().c_str(), ip_address.c_str());
653
654#ifdef USE_WIFI_MANUAL_IP
655 auto manual_ip = this->ap_.get_manual_ip();
656 if (manual_ip.has_value()) {
657 ESP_LOGCONFIG(TAG,
658 " AP Static IP: '%s'\n"
659 " AP Gateway: '%s'\n"
660 " AP Subnet: '%s'",
661 manual_ip->static_ip.str().c_str(), manual_ip->gateway.str().c_str(),
662 manual_ip->subnet.str().c_str());
663 }
664#endif
665
666 if (!this->has_sta()) {
668 }
669}
670
672 this->ap_ = ap;
673 this->has_ap_ = true;
674}
675#endif // USE_WIFI_AP
676
678 return 10.0f; // before other loop components
679}
680
681void WiFiComponent::init_sta(size_t count) { this->sta_.init(count); }
682void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); }
684 this->clear_sta();
685 this->init_sta(1);
686 this->add_sta(ap);
687 this->selected_sta_index_ = 0;
688 // When new credentials are set (e.g., from improv), skip cooldown to retry immediately
689 this->skip_cooldown_next_cycle_ = true;
690}
691
693 const WiFiAP *config = this->get_selected_sta_();
694 if (config == nullptr) {
695 ESP_LOGE(TAG, "No valid network config (selected_sta_index_=%d, sta_.size()=%zu)",
696 static_cast<int>(this->selected_sta_index_), this->sta_.size());
697 // Return empty params - caller should handle this gracefully
698 return WiFiAP();
699 }
700
701 WiFiAP params = *config;
702
703 switch (this->retry_phase_) {
705#ifdef USE_WIFI_FAST_CONNECT
707#endif
708 // Fast connect phases: use config-only (no scan results)
709 // BSSID/channel from config if user specified them, otherwise empty
710 break;
711
714 // Hidden network mode: clear BSSID/channel to trigger probe request
715 // (both explicit hidden and retry hidden use same behavior)
718 break;
719
721 // Scan-based phase: always use best scan result (index 0 - highest priority after sorting)
722 if (!this->scan_result_.empty()) {
723 apply_scan_result_to_params(params, this->scan_result_[0]);
724 }
725 break;
726
728 // Should not be building params during restart
729 break;
730 }
731
732 return params;
733}
734
736 const WiFiAP *config = this->get_selected_sta_();
737 return config ? *config : WiFiAP{};
738}
739void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
740 SavedWifiSettings save{}; // zero-initialized - all bytes set to \0, guaranteeing null termination
741 strncpy(save.ssid, ssid.c_str(), sizeof(save.ssid) - 1); // max 32 chars, byte 32 remains \0
742 strncpy(save.password, password.c_str(), sizeof(save.password) - 1); // max 64 chars, byte 64 remains \0
743 this->pref_.save(&save);
744 // ensure it's written immediately
746
747 WiFiAP sta{};
748 sta.set_ssid(ssid);
749 sta.set_password(password);
750 this->set_sta(sta);
751
752 // Trigger connection attempt (exits cooldown if needed, no-op if already connecting/connected)
753 this->connect_soon_();
754}
755
757 // Only trigger retry if we're in cooldown - if already connecting/connected, do nothing
759 ESP_LOGD(TAG, "Exiting cooldown early due to new WiFi credentials");
760 this->retry_connect();
761 }
762}
763
765 // Log connection attempt at INFO level with priority
766 char bssid_s[18];
767 int8_t priority = 0;
768
769 if (ap.get_bssid().has_value()) {
770 format_mac_addr_upper(ap.get_bssid().value().data(), bssid_s);
772 }
773
774 ESP_LOGI(TAG,
775 "Connecting to " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") " (priority %d, attempt %u/%u in phase %s)...",
776 ap.get_ssid().c_str(), ap.get_bssid().has_value() ? bssid_s : LOG_STR_LITERAL("any"), priority,
777 this->num_retried_ + 1, get_max_retries_for_phase(this->retry_phase_),
778 LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
779
780#ifdef ESPHOME_LOG_HAS_VERBOSE
781 ESP_LOGV(TAG, "Connection Params:");
782 ESP_LOGV(TAG, " SSID: '%s'", ap.get_ssid().c_str());
783 if (ap.get_bssid().has_value()) {
784 ESP_LOGV(TAG, " BSSID: %s", bssid_s);
785 } else {
786 ESP_LOGV(TAG, " BSSID: Not Set");
787 }
788
789#ifdef USE_WIFI_WPA2_EAP
790 if (ap.get_eap().has_value()) {
791 ESP_LOGV(TAG, " WPA2 Enterprise authentication configured:");
792 EAPAuth eap_config = ap.get_eap().value();
793 ESP_LOGV(TAG, " Identity: " LOG_SECRET("'%s'"), eap_config.identity.c_str());
794 ESP_LOGV(TAG, " Username: " LOG_SECRET("'%s'"), eap_config.username.c_str());
795 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), eap_config.password.c_str());
796#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
797 ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), eap_phase2_to_str(eap_config.ttls_phase_2));
798#endif
799 bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert);
800 bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert);
801 bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key);
802 ESP_LOGV(TAG, " CA Cert: %s", ca_cert_present ? "present" : "not present");
803 ESP_LOGV(TAG, " Client Cert: %s", client_cert_present ? "present" : "not present");
804 ESP_LOGV(TAG, " Client Key: %s", client_key_present ? "present" : "not present");
805 } else {
806#endif
807 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), ap.get_password().c_str());
808#ifdef USE_WIFI_WPA2_EAP
809 }
810#endif
811 if (ap.get_channel().has_value()) {
812 ESP_LOGV(TAG, " Channel: %u", *ap.get_channel());
813 } else {
814 ESP_LOGV(TAG, " Channel not set");
815 }
816#ifdef USE_WIFI_MANUAL_IP
817 if (ap.get_manual_ip().has_value()) {
818 ManualIP m = *ap.get_manual_ip();
819 ESP_LOGV(TAG, " Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s", m.static_ip.str().c_str(),
820 m.gateway.str().c_str(), m.subnet.str().c_str(), m.dns1.str().c_str(), m.dns2.str().c_str());
821 } else
822#endif
823 {
824 ESP_LOGV(TAG, " Using DHCP IP");
825 }
826 ESP_LOGV(TAG, " Hidden: %s", YESNO(ap.get_hidden()));
827#endif
828
829 if (!this->wifi_sta_connect_(ap)) {
830 ESP_LOGE(TAG, "wifi_sta_connect_ failed");
831 // Enter cooldown to allow WiFi hardware to stabilize
832 // (immediate failure suggests hardware not ready, different from connection timeout)
834 } else {
836 }
837 this->action_started_ = millis();
838}
839
840const LogString *get_signal_bars(int8_t rssi) {
841 // Check for disconnected sentinel value first
842 if (rssi == WIFI_RSSI_DISCONNECTED) {
843 // MULTIPLICATION SIGN
844 // Unicode: U+00D7, UTF-8: C3 97
845 return LOG_STR("\033[0;31m" // red
846 "\xc3\x97\xc3\x97\xc3\x97\xc3\x97"
847 "\033[0m");
848 }
849 // LOWER ONE QUARTER BLOCK
850 // Unicode: U+2582, UTF-8: E2 96 82
851 // LOWER HALF BLOCK
852 // Unicode: U+2584, UTF-8: E2 96 84
853 // LOWER THREE QUARTERS BLOCK
854 // Unicode: U+2586, UTF-8: E2 96 86
855 // FULL BLOCK
856 // Unicode: U+2588, UTF-8: E2 96 88
857 if (rssi >= -50) {
858 return LOG_STR("\033[0;32m" // green
859 "\xe2\x96\x82"
860 "\xe2\x96\x84"
861 "\xe2\x96\x86"
862 "\xe2\x96\x88"
863 "\033[0m");
864 } else if (rssi >= -65) {
865 return LOG_STR("\033[0;33m" // yellow
866 "\xe2\x96\x82"
867 "\xe2\x96\x84"
868 "\xe2\x96\x86"
869 "\033[0;37m"
870 "\xe2\x96\x88"
871 "\033[0m");
872 } else if (rssi >= -85) {
873 return LOG_STR("\033[0;33m" // yellow
874 "\xe2\x96\x82"
875 "\xe2\x96\x84"
876 "\033[0;37m"
877 "\xe2\x96\x86"
878 "\xe2\x96\x88"
879 "\033[0m");
880 } else {
881 return LOG_STR("\033[0;31m" // red
882 "\xe2\x96\x82"
883 "\033[0;37m"
884 "\xe2\x96\x84"
885 "\xe2\x96\x86"
886 "\xe2\x96\x88"
887 "\033[0m");
888 }
889}
890
892 bssid_t bssid = wifi_bssid();
893 char bssid_s[18];
894 format_mac_addr_upper(bssid.data(), bssid_s);
895
896 char mac_s[18];
897 ESP_LOGCONFIG(TAG, " Local MAC: %s", get_mac_address_pretty_into_buffer(mac_s));
898 if (this->is_disabled()) {
899 ESP_LOGCONFIG(TAG, " Disabled");
900 return;
901 }
902 for (auto &ip : wifi_sta_ip_addresses()) {
903 if (ip.is_set()) {
904 ESP_LOGCONFIG(TAG, " IP Address: %s", ip.str().c_str());
905 }
906 }
907 int8_t rssi = wifi_rssi();
908 ESP_LOGCONFIG(TAG,
909 " SSID: " LOG_SECRET("'%s'") "\n"
910 " BSSID: " LOG_SECRET("%s") "\n"
911 " Hostname: '%s'\n"
912 " Signal strength: %d dB %s\n"
913 " Channel: %" PRId32 "\n"
914 " Subnet: %s\n"
915 " Gateway: %s\n"
916 " DNS1: %s\n"
917 " DNS2: %s",
918 wifi_ssid().c_str(), bssid_s, App.get_name().c_str(), rssi, LOG_STR_ARG(get_signal_bars(rssi)),
919 get_wifi_channel(), wifi_subnet_mask_().str().c_str(), wifi_gateway_ip_().str().c_str(),
920 wifi_dns_ip_(0).str().c_str(), wifi_dns_ip_(1).str().c_str());
921#ifdef ESPHOME_LOG_HAS_VERBOSE
922 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid().has_value()) {
923 ESP_LOGV(TAG, " Priority: %d", this->get_sta_priority(*config->get_bssid()));
924 }
925#endif
926#ifdef USE_WIFI_11KV_SUPPORT
927 ESP_LOGCONFIG(TAG,
928 " BTM: %s\n"
929 " RRM: %s",
930 this->btm_ ? "enabled" : "disabled", this->rrm_ ? "enabled" : "disabled");
931#endif
932}
933
936 return;
937
938 ESP_LOGD(TAG, "Enabling");
939 this->error_from_callback_ = false;
941 this->start();
942}
943
946 return;
947
948 ESP_LOGD(TAG, "Disabling");
950 this->wifi_disconnect_();
951 this->wifi_mode_(false, false);
952}
953
955
957 this->action_started_ = millis();
958 ESP_LOGD(TAG, "Starting scan");
959 this->wifi_scan_start_(this->passive_scan_);
961}
962
996[[nodiscard]] inline static bool wifi_scan_result_is_better(const WiFiScanResult &a, const WiFiScanResult &b) {
997 // Matching networks always come before non-matching
998 if (a.get_matches() && !b.get_matches())
999 return true;
1000 if (!a.get_matches() && b.get_matches())
1001 return false;
1002
1003 // Both matching: check priority first (tracks connection failures via priority degradation)
1004 // Priority is decreased when a BSSID fails to connect, so lower priority = previously failed
1005 if (a.get_matches() && b.get_matches() && a.get_priority() != b.get_priority()) {
1006 return a.get_priority() > b.get_priority();
1007 }
1008
1009 // Use RSSI as tiebreaker (for equal-priority matching networks or all non-matching networks)
1010 return a.get_rssi() > b.get_rssi();
1011}
1012
1013// Helper function for insertion sort of WiFi scan results
1014// Using insertion sort instead of std::stable_sort saves flash memory
1015// by avoiding template instantiations (std::rotate, std::stable_sort, lambdas)
1016// IMPORTANT: This sort is stable (preserves relative order of equal elements)
1017template<typename VectorType> static void insertion_sort_scan_results(VectorType &results) {
1018 const size_t size = results.size();
1019 for (size_t i = 1; i < size; i++) {
1020 // Make a copy to avoid issues with move semantics during comparison
1021 WiFiScanResult key = results[i];
1022 int32_t j = i - 1;
1023
1024 // Move elements that are worse than key to the right
1025 // For stability, we only move if key is strictly better than results[j]
1026 while (j >= 0 && wifi_scan_result_is_better(key, results[j])) {
1027 results[j + 1] = results[j];
1028 j--;
1029 }
1030 results[j + 1] = key;
1031 }
1032}
1033
1034// Helper function to log scan results - marked noinline to prevent re-inlining into loop
1035__attribute__((noinline)) static void log_scan_result(const WiFiScanResult &res) {
1036 char bssid_s[18];
1037 auto bssid = res.get_bssid();
1038 format_mac_addr_upper(bssid.data(), bssid_s);
1039
1040 if (res.get_matches()) {
1041 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
1042 res.get_is_hidden() ? LOG_STR_LITERAL("(HIDDEN) ") : LOG_STR_LITERAL(""), bssid_s,
1043 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
1044 ESP_LOGD(TAG, " Channel: %2u, RSSI: %3d dB, Priority: %4d", res.get_channel(), res.get_rssi(), res.get_priority());
1045 } else {
1046 ESP_LOGD(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(), bssid_s,
1047 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
1048 }
1049}
1050
1052 if (!this->scan_done_) {
1053 if (millis() - this->action_started_ > WIFI_SCAN_TIMEOUT_MS) {
1054 ESP_LOGE(TAG, "Scan timeout");
1055 this->retry_connect();
1056 }
1057 return;
1058 }
1059 this->scan_done_ = false;
1060 this->did_scan_this_cycle_ = true;
1061
1062 if (this->scan_result_.empty()) {
1063 ESP_LOGW(TAG, "No networks found");
1064 this->retry_connect();
1065 return;
1066 }
1067
1068 ESP_LOGD(TAG, "Found networks:");
1069 for (auto &res : this->scan_result_) {
1070 for (auto &ap : this->sta_) {
1071 if (res.matches(ap)) {
1072 res.set_matches(true);
1073 // Cache priority lookup - do single search instead of 2 separate searches
1074 const bssid_t &bssid = res.get_bssid();
1075 if (!this->has_sta_priority(bssid)) {
1076 this->set_sta_priority(bssid, ap.get_priority());
1077 }
1078 res.set_priority(this->get_sta_priority(bssid));
1079 break;
1080 }
1081 }
1082 }
1083
1084 // Sort scan results using insertion sort for better memory efficiency
1085 insertion_sort_scan_results(this->scan_result_);
1086
1087 for (auto &res : this->scan_result_) {
1088 log_scan_result(res);
1089 }
1090
1091 // SYNCHRONIZATION POINT: Establish link between scan_result_[0] and selected_sta_index_
1092 // After sorting, scan_result_[0] contains the best network. Now find which sta_[i] config
1093 // matches that network and record it in selected_sta_index_. This keeps the two indices
1094 // synchronized so build_params_for_current_phase_() can safely use both to build connection parameters.
1095 const WiFiScanResult &scan_res = this->scan_result_[0];
1096 bool found_match = false;
1097 if (scan_res.get_matches()) {
1098 for (size_t i = 0; i < this->sta_.size(); i++) {
1099 if (scan_res.matches(this->sta_[i])) {
1100 // Safe cast: sta_.size() limited to MAX_WIFI_NETWORKS (127) in __init__.py validation
1101 // No overflow check needed - YAML validation prevents >127 networks
1102 this->selected_sta_index_ = static_cast<int8_t>(i); // Links scan_result_[0] with sta_[i]
1103 found_match = true;
1104 break;
1105 }
1106 }
1107 }
1108
1109 if (!found_match) {
1110 ESP_LOGW(TAG, "No matching network found");
1111 // No scan results matched our configured networks - transition directly to hidden mode
1112 // Don't call retry_connect() since we never attempted a connection (no BSSID to penalize)
1114 // If no hidden networks to try, skip connection attempt (will be handled on next loop)
1115 if (this->selected_sta_index_ == -1) {
1116 return;
1117 }
1118 // Now start connection attempt in hidden mode
1120 return; // scan started, wait for next loop iteration
1121 }
1122
1123 yield();
1124
1125 WiFiAP params = this->build_params_for_current_phase_();
1126 // Ensure we're in SCAN_CONNECTING phase when connecting with scan results
1127 // (needed when scan was started directly without transition_to_phase_, e.g., initial scan)
1128 this->start_connecting(params);
1129}
1130
1132 ESP_LOGCONFIG(TAG,
1133 "WiFi:\n"
1134 " Connected: %s",
1135 YESNO(this->is_connected()));
1136 this->print_connect_params_();
1137}
1138
1140 auto status = this->wifi_sta_connect_status_();
1141
1143 if (wifi_ssid().empty()) {
1144 ESP_LOGW(TAG, "Connection incomplete");
1145 this->retry_connect();
1146 return;
1147 }
1148
1149 ESP_LOGI(TAG, "Connected");
1150 // Warn if we had to retry with hidden network mode for a network that's not marked hidden
1151 // Only warn if we actually connected without scan data (SSID only), not if scan succeeded on retry
1152 if (const WiFiAP *config = this->get_selected_sta_(); this->retry_phase_ == WiFiRetryPhase::RETRY_HIDDEN &&
1153 config && !config->get_hidden() &&
1154 this->scan_result_.empty()) {
1155 ESP_LOGW(TAG, LOG_SECRET("'%s'") " should be marked hidden", config->get_ssid().c_str());
1156 }
1157 // Reset to initial phase on successful connection (don't log transition, just reset state)
1159 this->num_retried_ = 0;
1160 // Ensure next connection attempt does not inherit error state
1161 // so when WiFi disconnects later we start fresh and don't see
1162 // the first connection as a failure.
1163 this->error_from_callback_ = false;
1164
1165 this->print_connect_params_();
1166
1167 if (this->has_ap()) {
1168#ifdef USE_CAPTIVE_PORTAL
1169 if (this->is_captive_portal_active_()) {
1171 }
1172#endif
1173 ESP_LOGD(TAG, "Disabling AP");
1174 this->wifi_mode_({}, false);
1175 }
1176#ifdef USE_IMPROV
1177 if (this->is_esp32_improv_active_()) {
1179 }
1180#endif
1181
1183 this->num_retried_ = 0;
1184
1185 // Clear priority tracking if all priorities are at minimum
1187
1188#ifdef USE_WIFI_FAST_CONNECT
1190#endif
1191
1192 // Free scan results memory unless a component needs them
1193 if (!this->keep_scan_results_) {
1194 this->scan_result_.clear();
1195 this->scan_result_.shrink_to_fit();
1196 }
1197
1198 return;
1199 }
1200
1201 uint32_t now = millis();
1202 if (now - this->action_started_ > WIFI_CONNECT_TIMEOUT_MS) {
1203 ESP_LOGW(TAG, "Connection timeout, aborting connection attempt");
1204 this->wifi_disconnect_();
1205 this->retry_connect();
1206 return;
1207 }
1208
1209 if (this->error_from_callback_) {
1210 ESP_LOGW(TAG, "Connecting to network failed (callback)");
1211 this->retry_connect();
1212 return;
1213 }
1214
1216 return;
1217 }
1218
1220 ESP_LOGW(TAG, "Network no longer found");
1221 this->retry_connect();
1222 return;
1223 }
1224
1226 ESP_LOGW(TAG, "Connecting to network failed");
1227 this->retry_connect();
1228 return;
1229 }
1230
1231 ESP_LOGW(TAG, "Unknown connection status %d", (int) status);
1232 this->retry_connect();
1233}
1234
1242 switch (this->retry_phase_) {
1244#ifdef USE_WIFI_FAST_CONNECT
1246 // INITIAL_CONNECT and FAST_CONNECT_CYCLING_APS: no retries, try next AP or fall back to scan
1247 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
1248 return WiFiRetryPhase::FAST_CONNECT_CYCLING_APS; // Move to next AP
1249 }
1250#endif
1251 // Check if we should try explicit hidden networks before scanning
1252 // This handles reconnection after connection loss where first network is hidden
1253 if (!this->sta_.empty() && this->sta_[0].get_hidden()) {
1255 }
1256 // No more APs to try, fall back to scan
1258
1260 // Try all explicitly hidden networks before scanning
1261 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1262 return WiFiRetryPhase::EXPLICIT_HIDDEN; // Keep retrying same SSID
1263 }
1264
1265 // Exhausted retries on current SSID - check for more explicitly hidden networks
1266 // Stop when we reach a visible network (proceed to scanning)
1267 size_t next_index = this->selected_sta_index_ + 1;
1268 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
1269 // Found another explicitly hidden network
1271 }
1272
1273 // No more consecutive explicitly hidden networks
1274 // If ALL networks are hidden, skip scanning and go directly to restart
1275 if (this->find_first_non_hidden_index_() < 0) {
1277 }
1278 // Otherwise proceed to scanning for non-hidden networks
1280 }
1281
1283 // If scan found no networks or no matching networks, skip to hidden network mode
1284 if (this->scan_result_.empty() || !this->scan_result_[0].get_matches()) {
1286 }
1287
1288 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_BSSID) {
1289 return WiFiRetryPhase::SCAN_CONNECTING; // Keep retrying same BSSID
1290 }
1291
1292 // Exhausted retries on current BSSID (scan_result_[0])
1293 // Its priority has been decreased, so on next scan it will be sorted lower
1294 // and we'll try the next best BSSID.
1295 // Check if there are any potentially hidden networks to try
1296 if (this->find_next_hidden_sta_(-1) >= 0) {
1297 return WiFiRetryPhase::RETRY_HIDDEN; // Found hidden networks to try
1298 }
1299 // No hidden networks - always go through RESTARTING_ADAPTER phase
1300 // This ensures num_retried_ gets reset and a fresh scan is triggered
1301 // The actual adapter restart will be skipped if captive portal/improv is active
1303
1305 // If no hidden SSIDs to try (selected_sta_index_ == -1), skip directly to rescan
1306 if (this->selected_sta_index_ >= 0) {
1307 if (this->num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1308 return WiFiRetryPhase::RETRY_HIDDEN; // Keep retrying same SSID
1309 }
1310
1311 // Exhausted retries on current SSID - check if there are more potentially hidden SSIDs to try
1312 if (this->selected_sta_index_ < static_cast<int8_t>(this->sta_.size()) - 1) {
1313 // Check if find_next_hidden_sta_() would actually find another hidden SSID
1314 // as it might have been seen in the scan results and we want to skip those
1315 // otherwise we will get stuck in RETRY_HIDDEN phase
1316 if (this->find_next_hidden_sta_(this->selected_sta_index_) != -1) {
1317 // More hidden SSIDs available - stay in RETRY_HIDDEN, advance will happen in retry_connect()
1319 }
1320 }
1321 }
1322 // Exhausted all potentially hidden SSIDs - always go through RESTARTING_ADAPTER
1323 // This ensures num_retried_ gets reset and a fresh scan is triggered
1324 // The actual adapter restart will be skipped if captive portal/improv is active
1326
1328 // After restart, go back to explicit hidden if we went through it initially
1331 }
1332 // Skip scanning when captive portal/improv is active to avoid disrupting AP
1333 // Even passive scans can cause brief AP disconnections on ESP32
1334 if (this->is_captive_portal_active_() || this->is_esp32_improv_active_()) {
1336 }
1338 }
1339
1340 // Should never reach here
1342}
1343
1354 WiFiRetryPhase old_phase = this->retry_phase_;
1355
1356 // No-op if staying in same phase
1357 if (old_phase == new_phase) {
1358 return false;
1359 }
1360
1361 ESP_LOGD(TAG, "Retry phase: %s → %s", LOG_STR_ARG(retry_phase_to_log_string(old_phase)),
1362 LOG_STR_ARG(retry_phase_to_log_string(new_phase)));
1363
1364 this->retry_phase_ = new_phase;
1365 this->num_retried_ = 0; // Reset retry counter on phase change
1366
1367 // Phase-specific setup
1368 switch (new_phase) {
1369#ifdef USE_WIFI_FAST_CONNECT
1371 // Move to next configured AP - clear old scan data so new AP is tried with config only
1372 this->selected_sta_index_++;
1373 this->scan_result_.clear();
1374 break;
1375#endif
1376
1378 // Starting explicit hidden phase - reset to first network
1379 this->selected_sta_index_ = 0;
1380 break;
1381
1383 // Transitioning to scan-based connection
1384#ifdef USE_WIFI_FAST_CONNECT
1386 ESP_LOGI(TAG, "Fast connect exhausted, falling back to scan");
1387 }
1388#endif
1389 // Trigger scan if we don't have scan results OR if transitioning from phases that need fresh scan
1390 if (this->scan_result_.empty() || old_phase == WiFiRetryPhase::EXPLICIT_HIDDEN ||
1392 this->selected_sta_index_ = -1; // Will be set after scan completes
1393 this->start_scanning();
1394 return true; // Started scan, wait for completion
1395 }
1396 // Already have scan results - selected_sta_index_ should already be synchronized
1397 // (set in check_scanning_finished() when scan completed)
1398 // No need to reset it here
1399 break;
1400
1402 // Starting hidden mode - find first SSID that wasn't in scan results
1403 if (old_phase == WiFiRetryPhase::SCAN_CONNECTING) {
1404 // Keep scan results so we can skip SSIDs that were visible in the scan
1405 // Don't clear scan_result_ - we need it to know which SSIDs are NOT hidden
1406
1407 // If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
1408 // In that case, skip networks marked hidden:true (already tried)
1409 // Otherwise, include them (they haven't been tried yet)
1411
1412 if (this->selected_sta_index_ == -1) {
1413 ESP_LOGD(TAG, "All SSIDs visible or already tried, skipping hidden mode");
1414 }
1415 }
1416 break;
1417
1419 // Skip actual adapter restart if captive portal/improv is active
1420 // This allows state machine to reset num_retried_ and trigger fresh scan
1421 // without disrupting the captive portal/improv connection
1422 if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_()) {
1423 this->restart_adapter();
1424 } else {
1425 // Even when skipping full restart, disconnect to clear driver state
1426 // Without this, platforms like LibreTiny may think we're still connecting
1427 this->wifi_disconnect_();
1428 }
1429 // Clear scan flag - we're starting a new retry cycle
1430 this->did_scan_this_cycle_ = false;
1431 // Always enter cooldown after restart (or skip-restart) to allow stabilization
1432 // Use extended cooldown when AP is active to avoid constant scanning that blocks DNS
1434 this->action_started_ = millis();
1435 // Return true to indicate we should wait (go to COOLDOWN) instead of immediately connecting
1436 return true;
1437
1438 default:
1439 break;
1440 }
1441
1442 return false; // Did not start scan, can proceed with connection
1443}
1444
1449 if (this->sta_priorities_.empty()) {
1450 return;
1451 }
1452
1453 int8_t first_priority = this->sta_priorities_[0].priority;
1454
1455 // Only clear if all priorities have been decremented to the minimum value
1456 // At this point, all BSSIDs have been equally penalized and priority info is useless
1457 if (first_priority != std::numeric_limits<int8_t>::min()) {
1458 return;
1459 }
1460
1461 for (const auto &pri : this->sta_priorities_) {
1462 if (pri.priority != first_priority) {
1463 return; // Not all same, nothing to do
1464 }
1465 }
1466
1467 // All priorities are at minimum - clear the vector to save memory and reset
1468 ESP_LOGD(TAG, "Clearing BSSID priorities (all at minimum)");
1469 this->sta_priorities_.clear();
1470 this->sta_priorities_.shrink_to_fit();
1471}
1472
1492 // Determine which BSSID we tried to connect to
1493 optional<bssid_t> failed_bssid;
1494
1495 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
1496 // Scan-based phase: always use best result (index 0)
1497 failed_bssid = this->scan_result_[0].get_bssid();
1498 } else if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_bssid()) {
1499 // Config has specific BSSID (fast_connect or user-specified)
1500 failed_bssid = *config->get_bssid();
1501 }
1502
1503 if (!failed_bssid.has_value()) {
1504 return; // No BSSID to penalize
1505 }
1506
1507 // Get SSID for logging
1508 std::string ssid;
1509 if (this->retry_phase_ == WiFiRetryPhase::SCAN_CONNECTING && !this->scan_result_.empty()) {
1510 ssid = this->scan_result_[0].get_ssid();
1511 } else if (const WiFiAP *config = this->get_selected_sta_()) {
1512 ssid = config->get_ssid();
1513 }
1514
1515 // Only decrease priority on the last attempt for this phase
1516 // This prevents false positives from transient WiFi stack issues
1517 uint8_t max_retries = get_max_retries_for_phase(this->retry_phase_);
1518 bool is_last_attempt = (this->num_retried_ + 1 >= max_retries);
1519
1520 // Decrease priority only on last attempt to avoid false positives from transient failures
1521 int8_t old_priority = this->get_sta_priority(failed_bssid.value());
1522 int8_t new_priority = old_priority;
1523
1524 if (is_last_attempt) {
1525 // Decrease priority, but clamp to int8_t::min to prevent overflow
1526 new_priority =
1527 (old_priority > std::numeric_limits<int8_t>::min()) ? (old_priority - 1) : std::numeric_limits<int8_t>::min();
1528 this->set_sta_priority(failed_bssid.value(), new_priority);
1529 }
1530 char bssid_s[18];
1531 format_mac_addr_upper(failed_bssid.value().data(), bssid_s);
1532 ESP_LOGD(TAG, "Failed " LOG_SECRET("'%s'") " " LOG_SECRET("(%s)") ", priority %d → %d", ssid.c_str(), bssid_s,
1533 old_priority, new_priority);
1534
1535 // After adjusting priority, check if all priorities are now at minimum
1536 // If so, clear the vector to save memory and reset for fresh start
1538}
1539
1551 WiFiRetryPhase current_phase = this->retry_phase_;
1552
1553 // Check if we need to advance to next AP/SSID within the same phase
1554#ifdef USE_WIFI_FAST_CONNECT
1555 if (current_phase == WiFiRetryPhase::FAST_CONNECT_CYCLING_APS) {
1556 // Fast connect: always advance to next AP (no retries per AP)
1557 this->selected_sta_index_++;
1558 this->num_retried_ = 0;
1559 ESP_LOGD(TAG, "Next AP in %s", LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
1560 return;
1561 }
1562#endif
1563
1564 if (current_phase == WiFiRetryPhase::EXPLICIT_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
1565 // Explicit hidden: exhausted retries on current SSID, find next explicitly hidden network
1566 // Stop when we reach a visible network (proceed to scanning)
1567 size_t next_index = this->selected_sta_index_ + 1;
1568 if (next_index < this->sta_.size() && this->sta_[next_index].get_hidden()) {
1569 this->selected_sta_index_ = static_cast<int8_t>(next_index);
1570 this->num_retried_ = 0;
1571 ESP_LOGD(TAG, "Next explicit hidden network at index %d", static_cast<int>(next_index));
1572 return;
1573 }
1574 // No more consecutive explicit hidden networks found - fall through to trigger phase change
1575 }
1576
1577 if (current_phase == WiFiRetryPhase::RETRY_HIDDEN && this->num_retried_ + 1 >= WIFI_RETRY_COUNT_PER_SSID) {
1578 // Hidden mode: exhausted retries on current SSID, find next potentially hidden SSID
1579 // If first network is marked hidden, we went through EXPLICIT_HIDDEN phase
1580 // In that case, skip networks marked hidden:true (already tried)
1581 // Otherwise, include them (they haven't been tried yet)
1582 int8_t next_index = this->find_next_hidden_sta_(this->selected_sta_index_);
1583 if (next_index != -1) {
1584 // Found another potentially hidden SSID
1585 this->selected_sta_index_ = next_index;
1586 this->num_retried_ = 0;
1587 return;
1588 }
1589 // No more potentially hidden SSIDs - set selected_sta_index_ to -1 to trigger phase change
1590 // This ensures determine_next_phase_() will skip the RETRY_HIDDEN logic and transition out
1591 this->selected_sta_index_ = -1;
1592 // Return early - phase change will happen on next wifi_loop() iteration
1593 return;
1594 }
1595
1596 // Don't increment retry counter if we're in a scan phase with no valid targets
1597 if (this->needs_scan_results_()) {
1598 return;
1599 }
1600
1601 // Increment retry counter to try the same target again
1602 this->num_retried_++;
1603 ESP_LOGD(TAG, "Retry attempt %u/%u in phase %s", this->num_retried_ + 1,
1604 get_max_retries_for_phase(this->retry_phase_), LOG_STR_ARG(retry_phase_to_log_string(this->retry_phase_)));
1605}
1606
1609
1610 // Determine next retry phase based on current state
1611 WiFiRetryPhase current_phase = this->retry_phase_;
1612 WiFiRetryPhase next_phase = this->determine_next_phase_();
1613
1614 // Handle phase transitions (transition_to_phase_ handles same-phase no-op internally)
1615 if (this->transition_to_phase_(next_phase)) {
1616 return; // Scan started or adapter restarted (which sets its own state)
1617 }
1618
1619 if (next_phase == current_phase) {
1621 }
1622
1623 this->error_from_callback_ = false;
1624
1625 yield();
1626 // Check if we have a valid target before building params
1627 // After exhausting all networks in a phase, selected_sta_index_ may be -1
1628 // In that case, skip connection and let next wifi_loop() handle phase transition
1629 if (this->selected_sta_index_ >= 0) {
1630 WiFiAP params = this->build_params_for_current_phase_();
1631 this->start_connecting(params);
1632 }
1633}
1634
1635#ifdef USE_RP2040
1636// RP2040's mDNS library (LEAmDNS) relies on LwipIntf::stateUpCB() to restart
1637// mDNS when the network interface reconnects. However, this callback is disabled
1638// in the arduino-pico framework. As a workaround, we block component setup until
1639// WiFi is connected, ensuring mDNS.begin() is called with an active connection.
1640
1642 if (!this->has_sta() || this->state_ == WIFI_COMPONENT_STATE_DISABLED || this->ap_setup_) {
1643 return true;
1644 }
1645 return this->is_connected();
1646}
1647#endif
1648
1649void WiFiComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
1655 this->power_save_ = power_save;
1656#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1657 this->configured_power_save_ = power_save;
1658#endif
1659}
1660
1661void WiFiComponent::set_passive_scan(bool passive) { this->passive_scan_ = passive; }
1662
1664#ifdef USE_CAPTIVE_PORTAL
1666#else
1667 return false;
1668#endif
1669}
1671#ifdef USE_IMPROV
1673#else
1674 return false;
1675#endif
1676}
1677
1678#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1680 // Already configured for high performance - request satisfied
1682 return true;
1683 }
1684
1685 // Semaphore initialization failed
1686 if (this->high_performance_semaphore_ == nullptr) {
1687 return false;
1688 }
1689
1690 // Give the semaphore (non-blocking). This increments the count.
1691 return xSemaphoreGive(this->high_performance_semaphore_) == pdTRUE;
1692}
1693
1695 // Already configured for high performance - nothing to release
1697 return true;
1698 }
1699
1700 // Semaphore initialization failed
1701 if (this->high_performance_semaphore_ == nullptr) {
1702 return false;
1703 }
1704
1705 // Take the semaphore (non-blocking). This decrements the count.
1706 return xSemaphoreTake(this->high_performance_semaphore_, 0) == pdTRUE;
1707}
1708#endif // USE_ESP32 && USE_WIFI_RUNTIME_POWER_SAVE
1709
1710#ifdef USE_WIFI_FAST_CONNECT
1712 SavedWifiFastConnectSettings fast_connect_save{};
1713
1714 if (this->fast_connect_pref_.load(&fast_connect_save)) {
1715 // Validate saved AP index
1716 if (fast_connect_save.ap_index < 0 || static_cast<size_t>(fast_connect_save.ap_index) >= this->sta_.size()) {
1717 ESP_LOGW(TAG, "AP index out of bounds");
1718 return false;
1719 }
1720
1721 // Set selected index for future operations (save, retry, etc)
1722 this->selected_sta_index_ = fast_connect_save.ap_index;
1723
1724 // Copy entire config, then override with fast connect data
1725 params = this->sta_[fast_connect_save.ap_index];
1726
1727 // Override with saved BSSID/channel from fast connect (SSID/password/etc already copied from config)
1728 bssid_t bssid{};
1729 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
1730 params.set_bssid(bssid);
1731 params.set_channel(fast_connect_save.channel);
1732 // Fast connect uses specific BSSID+channel, not hidden network probe (even if config has hidden: true)
1733 params.set_hidden(false);
1734
1735 ESP_LOGD(TAG, "Loaded fast_connect settings");
1736 return true;
1737 }
1738
1739 return false;
1740}
1741
1743 bssid_t bssid = wifi_bssid();
1744 uint8_t channel = get_wifi_channel();
1745 // selected_sta_index_ is always valid here (called only after successful connection)
1746 // Fallback to 0 is defensive programming for robustness
1747 int8_t ap_index = this->selected_sta_index_ >= 0 ? this->selected_sta_index_ : 0;
1748
1749 // Skip save if settings haven't changed (compare with previously saved settings to reduce flash wear)
1750 SavedWifiFastConnectSettings previous_save{};
1751 if (this->fast_connect_pref_.load(&previous_save) && memcmp(previous_save.bssid, bssid.data(), 6) == 0 &&
1752 previous_save.channel == channel && previous_save.ap_index == ap_index) {
1753 return; // No change, nothing to save
1754 }
1755
1756 SavedWifiFastConnectSettings fast_connect_save{};
1757 memcpy(fast_connect_save.bssid, bssid.data(), 6);
1758 fast_connect_save.channel = channel;
1759 fast_connect_save.ap_index = ap_index;
1760
1761 this->fast_connect_pref_.save(&fast_connect_save);
1762
1763 ESP_LOGD(TAG, "Saved fast_connect settings");
1764}
1765#endif
1766
1767void WiFiAP::set_ssid(const std::string &ssid) { this->ssid_ = ssid; }
1768void WiFiAP::set_bssid(bssid_t bssid) { this->bssid_ = bssid; }
1769void WiFiAP::set_bssid(optional<bssid_t> bssid) { this->bssid_ = bssid; }
1770void WiFiAP::set_password(const std::string &password) { this->password_ = password; }
1771#ifdef USE_WIFI_WPA2_EAP
1772void WiFiAP::set_eap(optional<EAPAuth> eap_auth) { this->eap_ = std::move(eap_auth); }
1773#endif
1774void WiFiAP::set_channel(optional<uint8_t> channel) { this->channel_ = channel; }
1775#ifdef USE_WIFI_MANUAL_IP
1776void WiFiAP::set_manual_ip(optional<ManualIP> manual_ip) { this->manual_ip_ = manual_ip; }
1777#endif
1778void WiFiAP::set_hidden(bool hidden) { this->hidden_ = hidden; }
1779const std::string &WiFiAP::get_ssid() const { return this->ssid_; }
1780const optional<bssid_t> &WiFiAP::get_bssid() const { return this->bssid_; }
1781const std::string &WiFiAP::get_password() const { return this->password_; }
1782#ifdef USE_WIFI_WPA2_EAP
1783const optional<EAPAuth> &WiFiAP::get_eap() const { return this->eap_; }
1784#endif
1785const optional<uint8_t> &WiFiAP::get_channel() const { return this->channel_; }
1786#ifdef USE_WIFI_MANUAL_IP
1788#endif
1789bool WiFiAP::get_hidden() const { return this->hidden_; }
1790
1791WiFiScanResult::WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth,
1792 bool is_hidden)
1793 : bssid_(bssid),
1794 channel_(channel),
1795 rssi_(rssi),
1796 ssid_(std::move(ssid)),
1797 with_auth_(with_auth),
1798 is_hidden_(is_hidden) {}
1799bool WiFiScanResult::matches(const WiFiAP &config) const {
1800 if (config.get_hidden()) {
1801 // User configured a hidden network, only match actually hidden networks
1802 // don't match SSID
1803 if (!this->is_hidden_)
1804 return false;
1805 } else if (!config.get_ssid().empty()) {
1806 // check if SSID matches
1807 if (config.get_ssid() != this->ssid_)
1808 return false;
1809 } else {
1810 // network is configured without SSID - match other settings
1811 }
1812 // If BSSID configured, only match for correct BSSIDs
1813 if (config.get_bssid().has_value() && *config.get_bssid() != this->bssid_)
1814 return false;
1815
1816#ifdef USE_WIFI_WPA2_EAP
1817 // BSSID requires auth but no PSK or EAP credentials given
1818 if (this->with_auth_ && (config.get_password().empty() && !config.get_eap().has_value()))
1819 return false;
1820
1821 // BSSID does not require auth, but PSK or EAP credentials given
1822 if (!this->with_auth_ && (!config.get_password().empty() || config.get_eap().has_value()))
1823 return false;
1824#else
1825 // If PSK given, only match for networks with auth (and vice versa)
1826 if (config.get_password().empty() == this->with_auth_)
1827 return false;
1828#endif
1829
1830 // If channel configured, only match networks on that channel.
1831 if (config.get_channel().has_value() && *config.get_channel() != this->channel_) {
1832 return false;
1833 }
1834 return true;
1835}
1836bool WiFiScanResult::get_matches() const { return this->matches_; }
1837void WiFiScanResult::set_matches(bool matches) { this->matches_ = matches; }
1838const bssid_t &WiFiScanResult::get_bssid() const { return this->bssid_; }
1839const std::string &WiFiScanResult::get_ssid() const { return this->ssid_; }
1840uint8_t WiFiScanResult::get_channel() const { return this->channel_; }
1841int8_t WiFiScanResult::get_rssi() const { return this->rssi_; }
1842bool WiFiScanResult::get_with_auth() const { return this->with_auth_; }
1843bool WiFiScanResult::get_is_hidden() const { return this->is_hidden_; }
1844
1845bool WiFiScanResult::operator==(const WiFiScanResult &rhs) const { return this->bssid_ == rhs.bssid_; }
1846
1847WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1848
1849} // namespace esphome::wifi
1850#endif
uint8_t m
Definition bl0906.h:1
uint8_t status
Definition bl0942.h:8
bool is_name_add_mac_suffix_enabled() const
const std::string & get_name() const
Get the name of this Application set by pre_setup().
StringRef get_compilation_time_ref() const
Get the compilation time as StringRef (for API usage)
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
constexpr const char * c_str() const
Definition string_ref.h:69
void trigger(const Ts &...x)
Inform the parent automation that the event has triggered.
Definition automation.h:204
bool has_value() const
Definition optional.h:92
value_type const & value() const
Definition optional.h:94
const optional< bssid_t > & get_bssid() const
const std::string & get_ssid() const
void set_ssid(const std::string &ssid)
const optional< uint8_t > & get_channel() const
const optional< EAPAuth > & get_eap() const
void set_channel(optional< uint8_t > channel)
const std::string & get_password() const
void set_bssid(bssid_t bssid)
optional< uint8_t > channel_
optional< EAPAuth > eap_
optional< bssid_t > bssid_
optional< ManualIP > manual_ip_
void set_eap(optional< EAPAuth > eap_auth)
void set_password(const std::string &password)
void set_manual_ip(optional< ManualIP > manual_ip)
const optional< ManualIP > & get_manual_ip() const
void set_hidden(bool hidden)
This component is responsible for managing the ESP WiFi interface.
void add_sta(const WiFiAP &ap)
bool load_fast_connect_settings_(WiFiAP &params)
void set_ap(const WiFiAP &ap)
Setup an Access Point that should be created if no connection to a station can be made.
bool request_high_performance()
Request high-performance mode (no power saving) for improved WiFi latency.
void set_sta(const WiFiAP &ap)
bool has_sta_priority(const bssid_t &bssid)
const WiFiAP * get_selected_sta_() const
int8_t get_sta_priority(const bssid_t bssid)
void log_and_adjust_priority_for_failed_connect_()
Log failed connection and decrease BSSID priority to avoid repeated attempts.
void save_wifi_sta(const std::string &ssid, const std::string &password)
wifi_scan_vector_t< WiFiScanResult > scan_result_
WiFiPowerSaveMode configured_power_save_
void set_sta_priority(const bssid_t bssid, int8_t priority)
void loop() override
Reconnect WiFi if required.
void start_connecting(const WiFiAP &ap)
void advance_to_next_target_or_increment_retry_()
Advance to next target (AP/SSID) within current phase, or increment retry counter Called when staying...
SemaphoreHandle_t high_performance_semaphore_
network::IPAddress get_dns_address(int num)
WiFiComponent()
Construct a WiFiComponent.
std::vector< WiFiSTAPriority > sta_priorities_
void set_passive_scan(bool passive)
void set_power_save_mode(WiFiPowerSaveMode power_save)
int8_t find_next_hidden_sta_(int8_t start_index)
Find next SSID that wasn't in scan results (might be hidden) Returns index of next potentially hidden...
ESPPreferenceObject fast_connect_pref_
void clear_priorities_if_all_min_()
Clear BSSID priority tracking if all priorities are at minimum (saves memory)
WiFiRetryPhase determine_next_phase_()
Determine next retry phase based on current state and failure conditions.
network::IPAddress wifi_dns_ip_(int num)
float get_loop_priority() const override
network::IPAddresses get_ip_addresses()
float get_setup_priority() const override
WIFI setup_priority.
FixedVector< WiFiAP > sta_
int8_t find_first_non_hidden_index_() const
Find the index of the first non-hidden network Returns where EXPLICIT_HIDDEN phase would have stopped...
bool ssid_was_seen_in_scan_(const std::string &ssid) const
Check if an SSID was seen in the most recent scan results Used to skip hidden mode for SSIDs we know ...
bool needs_scan_results_() const
Check if we need valid scan results for the current phase but don't have any Returns true if the phas...
bool transition_to_phase_(WiFiRetryPhase new_phase)
Transition to a new retry phase with logging Returns true if a scan was started (caller should wait),...
optional< float > output_power_
bool release_high_performance()
Release a high-performance mode request.
const char * get_use_address() const
WiFiSTAConnectStatus wifi_sta_connect_status_()
bool went_through_explicit_hidden_phase_() const
Check if we went through EXPLICIT_HIDDEN phase (first network is marked hidden) Used in RETRY_HIDDEN ...
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
void set_reboot_timeout(uint32_t reboot_timeout)
network::IPAddresses wifi_sta_ip_addresses()
void start_initial_connection_()
Start initial connection - either scan or connect directly to hidden networks.
void setup() override
Setup WiFi interface.
void set_use_address(const char *use_address)
const std::string & get_ssid() const
const bssid_t & get_bssid() const
WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth, bool is_hidden)
bool matches(const WiFiAP &config) const
bool operator==(const WiFiScanResult &rhs) const
struct @65::@66 __attribute__
uint16_t type
uint8_t priority
CaptivePortal * global_captive_portal
ESP32ImprovComponent * global_improv_component
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:149
const char *const TAG
Definition spi.cpp:8
std::array< uint8_t, 6 > bssid_t
const LogString * get_signal_bars(int8_t rssi)
WiFiRetryPhase
Tracks the current retry strategy/phase for WiFi connection attempts.
@ RETRY_HIDDEN
Retry networks not found in scan (might be hidden)
@ RESTARTING_ADAPTER
Restarting WiFi adapter to clear stuck state.
@ INITIAL_CONNECT
Initial connection attempt (varies based on fast_connect setting)
@ EXPLICIT_HIDDEN
Explicitly hidden networks (user marked as hidden, try before scanning)
@ FAST_CONNECT_CYCLING_APS
Fast connect mode: cycling through configured APs (config-only, no scan)
@ SCAN_CONNECTING
Scan-based: connecting to best AP from scan results.
WiFiComponent * global_wifi_component
@ WIFI_COMPONENT_STATE_DISABLED
WiFi is disabled.
@ WIFI_COMPONENT_STATE_AP
WiFi is in AP-only mode and internal AP is already enabled.
@ WIFI_COMPONENT_STATE_STA_CONNECTING
WiFi is in STA(+AP) mode and currently connecting to an AP.
@ WIFI_COMPONENT_STATE_OFF
Nothing has been initialized yet.
@ WIFI_COMPONENT_STATE_STA_SCANNING
WiFi is in STA-only mode and currently scanning for APs.
@ WIFI_COMPONENT_STATE_COOLDOWN
WiFi is in cooldown mode because something went wrong, scanning will begin after a short period of ti...
@ WIFI_COMPONENT_STATE_STA_CONNECTED
WiFi is in STA(+AP) mode and successfully connected.
void format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase)
Definition helpers.h:635
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:146
void IRAM_ATTR HOT yield()
Definition core.cpp:29
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:669
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
Application App
Global storage of Application pointer - only one Application can exist.
std::string str() const
Definition ip_address.h:52
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.