ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
wifi_component.h
Go to the documentation of this file.
1#pragma once
2
4#ifdef USE_WIFI
9#ifdef USE_ESP32
11#endif
12#if defined(USE_LIBRETINY) && defined(ESPHOME_THREAD_MULTI_ATOMICS)
14#elif defined(USE_LIBRETINY) && defined(ESPHOME_THREAD_MULTI_NO_ATOMICS)
16#endif
18
19#include <atomic>
20#include <limits>
21#include <span>
22#include <string>
23#include <type_traits>
24#include <utility>
25#include <vector>
26
27#ifdef USE_LIBRETINY
28#include <WiFi.h>
29#endif
30
31#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP)
32#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
33#include <esp_eap_client.h>
34#else
35#include <esp_wpa2.h>
36#endif
37#endif
38
39#ifdef USE_ESP8266
40#include <ESP8266WiFi.h>
41#include <ESP8266WiFiType.h>
42
43#endif
44
45#ifdef USE_RP2
46extern "C" {
47#include "cyw43.h"
48#include "cyw43_country.h"
49#include "pico/cyw43_arch.h"
50}
51
52#include <WiFi.h>
53#endif
54
55#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
56#include <esp_wifi_types.h>
57#endif
58
59#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
60#include <freertos/FreeRTOS.h>
61#include <freertos/semphr.h>
62#endif
63
64#ifdef USE_ESP32
65// Forward declaration matching esp_netif's own typedef; avoids pulling esp_netif.h
66// into this widely-included header.
67using esp_netif_t = struct esp_netif_obj;
68#endif
69
70namespace esphome::wifi {
71
73static constexpr int8_t WIFI_RSSI_DISCONNECTED = -127;
74
76static constexpr size_t SSID_BUFFER_SIZE = 33;
77
79 char ssid[33];
80 char password[65];
81} PACKED; // NOLINT
82
84 uint8_t bssid[6];
85 uint8_t channel;
86 int8_t ap_index;
87} PACKED; // NOLINT
88
105
113
115enum class WiFiRetryPhase : uint8_t {
118#ifdef USE_WIFI_FAST_CONNECT
121#endif
130};
131
133enum class RoamingState : uint8_t {
135 IDLE,
137 SCANNING,
142};
143
145enum class RetryHiddenMode : uint8_t {
152};
153
162
163#ifdef USE_WIFI_WPA2_EAP
164struct EAPAuth {
165 std::string identity; // required for all auth types
166 std::string username;
167 std::string password;
168 const char *ca_cert; // optionally verify authentication server
169 // used for EAP-TLS
170 const char *client_cert;
171 const char *client_key;
172// used for EAP-TTLS
173#ifdef USE_ESP32
174 esp_eap_ttls_phase2_types ttls_phase_2;
175#endif
176};
177#endif // USE_WIFI_WPA2_EAP
178
179using bssid_t = std::array<uint8_t, 6>;
180
182static constexpr size_t WIFI_SCAN_RESULT_FILTERED_RESERVE = 8;
183
184// Use std::vector for RP2040 (callback-based) and ESP32 (destructive scan API)
185// Use FixedVector for ESP8266 and LibreTiny where two-pass exact allocation is possible
186#if defined(USE_RP2) || defined(USE_ESP32)
187template<typename T> using wifi_scan_vector_t = std::vector<T>;
188#else
189template<typename T> using wifi_scan_vector_t = FixedVector<T>;
190#endif
191
192// A consumer component (e.g. the captive portal) reads scan results from another
193// task; guard them with a real lock only on platforms that actually run multiple
194// threads. See ScanResultsLock below the WiFiComponent class.
195#if defined(USE_WIFI_SCAN_RESULTS_LOCK) && !defined(ESPHOME_THREAD_SINGLE)
196#define WIFI_SCAN_RESULTS_LOCK_ENABLED
197#endif
198
202 public:
203 static constexpr uint8_t MAX_LENGTH = 127;
204 static constexpr uint8_t INLINE_CAPACITY = 18; // 18 chars + null terminator fits in 19 bytes
205
206 CompactString() : length_(0), is_heap_(0) { this->storage_[0] = '\0'; }
207 CompactString(const char *str, size_t len);
208 CompactString(const CompactString &other);
209 CompactString(CompactString &&other) noexcept;
211 CompactString &operator=(CompactString &&other) noexcept;
213
214 const char *data() const { return this->is_heap_ ? this->get_heap_ptr_() : this->storage_; }
215 const char *c_str() const { return this->data(); } // Always null-terminated
216 size_t size() const { return this->length_; }
217 bool empty() const { return this->length_ == 0; }
218
220 StringRef ref() const { return StringRef(this->data(), this->size()); }
221
222 bool operator==(const CompactString &other) const;
223 bool operator!=(const CompactString &other) const { return !(*this == other); }
224 bool operator==(const StringRef &other) const;
225 bool operator!=(const StringRef &other) const { return !(*this == other); }
226 bool operator==(const char *other) const { return *this == StringRef(other); }
227 bool operator!=(const char *other) const { return !(*this == other); }
228
229 protected:
230 char *get_heap_ptr_() const {
231 char *ptr;
232 std::memcpy(&ptr, this->storage_, sizeof(ptr));
233 return ptr;
234 }
235 void set_heap_ptr_(char *ptr) { std::memcpy(this->storage_, &ptr, sizeof(ptr)); }
236
237 // Storage for string data. When is_heap_=0, contains the string directly (null-terminated).
238 // When is_heap_=1, first sizeof(char*) bytes contain pointer to heap allocation.
239 char storage_[INLINE_CAPACITY + 1]; // 19 bytes: 18 chars + null terminator
240 uint8_t length_ : 7; // String length (0-127)
241 uint8_t is_heap_ : 1; // 1 if using heap pointer, 0 if using inline storage
242 // Total size: 20 bytes (19 bytes storage + 1 byte bitfields)
243};
244
245static_assert(sizeof(CompactString) == 20, "CompactString must be exactly 20 bytes");
246// CompactString is not trivially copyable (non-trivial destructor/copy for heap case).
247// However, its layout has no self-referential pointers: storage_[] contains either inline
248// data or an external heap pointer — never a pointer to itself. This is unlike libstdc++
249// std::string SSO where _M_p points to _M_local_buf within the same object.
250// This property allows memcpy-based permutation sorting where each element ends up in
251// exactly one slot (no ownership duplication). These asserts document that layout property.
252static_assert(std::is_standard_layout<CompactString>::value, "CompactString must be standard layout");
253static_assert(!std::is_polymorphic<CompactString>::value, "CompactString must not have vtable");
254
255class WiFiAP {
256 friend class WiFiComponent;
257 friend class WiFiScanResult;
258
259 public:
260 void set_ssid(const std::string &ssid) { this->ssid_ = CompactString(ssid.c_str(), ssid.size()); }
261 void set_ssid(const char *ssid) { this->set_ssid(StringRef(ssid)); }
262 void set_ssid(StringRef ssid) { this->ssid_ = CompactString(ssid.c_str(), ssid.size()); }
263 void set_bssid(const bssid_t &bssid) { this->bssid_ = bssid; }
264 void clear_bssid() { this->bssid_ = {}; }
265 void set_password(const std::string &password) { this->password_ = CompactString(password.c_str(), password.size()); }
266 void set_password(const char *password) { this->set_password(StringRef(password)); }
267 void set_password(StringRef password) { this->password_ = CompactString(password.c_str(), password.size()); }
268#ifdef USE_WIFI_WPA2_EAP
269 void set_eap(optional<EAPAuth> eap_auth) { this->eap_ = std::move(eap_auth); }
270#endif // USE_WIFI_WPA2_EAP
271 void set_channel(uint8_t channel) { this->channel_ = channel; }
272 void clear_channel() { this->channel_ = 0; }
274#ifdef USE_WIFI_MANUAL_IP
275 void set_manual_ip(optional<ManualIP> manual_ip) { this->manual_ip_ = manual_ip; }
276#endif
277 void set_hidden(bool hidden) { this->hidden_ = hidden; }
278 StringRef get_ssid() const { return this->ssid_.ref(); }
279 StringRef get_password() const { return this->password_.ref(); }
280 const bssid_t &get_bssid() const { return this->bssid_; }
281 bool has_bssid() const { return this->bssid_ != bssid_t{}; }
282#ifdef USE_WIFI_WPA2_EAP
283 const optional<EAPAuth> &get_eap() const { return this->eap_; }
284#endif // USE_WIFI_WPA2_EAP
285 uint8_t get_channel() const { return this->channel_; }
286 bool has_channel() const { return this->channel_ != 0; }
287 int8_t get_priority() const { return priority_; }
288#ifdef USE_WIFI_MANUAL_IP
289 const optional<ManualIP> &get_manual_ip() const { return this->manual_ip_; }
290#endif
291 bool get_hidden() const { return this->hidden_; }
292
293 protected:
296#ifdef USE_WIFI_WPA2_EAP
297 optional<EAPAuth> eap_;
298#endif // USE_WIFI_WPA2_EAP
299#ifdef USE_WIFI_MANUAL_IP
300 optional<ManualIP> manual_ip_;
301#endif
302 // Group small types together to minimize padding
303 bssid_t bssid_{}; // 6 bytes, all zeros = any/not set
304 uint8_t channel_{0}; // 1 byte, 0 = auto/not set
305 int8_t priority_{0}; // 1 byte
306 bool hidden_{false}; // 1 byte (+ 3 bytes end padding to 4-byte align)
307};
308
310 friend class WiFiComponent;
311
312 public:
313 WiFiScanResult(const bssid_t &bssid, const char *ssid, size_t ssid_len, uint8_t channel, int8_t rssi, bool with_auth,
314 bool is_hidden);
315
316 bool matches(const WiFiAP &config) const;
317
318 bool get_matches() const { return this->matches_; }
319 void set_matches(bool matches) { this->matches_ = matches; }
320 const bssid_t &get_bssid() const { return this->bssid_; }
321 StringRef get_ssid() const { return this->ssid_.ref(); }
322 uint8_t get_channel() const { return this->channel_; }
323 int8_t get_rssi() const { return this->rssi_; }
324 bool get_with_auth() const { return this->with_auth_; }
325 bool get_is_hidden() const { return this->is_hidden_; }
326 bool ssid_equals(const WiFiScanResult &other) const { return this->ssid_ == other.ssid_; }
327 int8_t get_priority() const { return priority_; }
329
330 bool operator==(const WiFiScanResult &rhs) const;
331
332 protected:
334 uint8_t channel_;
335 int8_t rssi_;
337 int8_t priority_{0};
338 bool matches_{false};
341};
342
347
353
359
360#ifdef USE_WIFI_PHY_MODE
361// Values 1-3 match ESP8266 SDK phy_mode_t (PHY_MODE_11B=1, PHY_MODE_11G=2, PHY_MODE_11N=3).
362// AUTO leaves the SDK at its default (no wifi_set_phy_mode() call).
369#endif
370
371#ifdef USE_ESP32
372struct IDFWiFiEvent;
373#endif
374
375#ifdef USE_LIBRETINY
376struct LTWiFiEvent;
377#endif
378
388 public:
389 virtual void on_ip_state(const network::IPAddresses &ips, const network::IPAddress &dns1,
390 const network::IPAddress &dns2) = 0;
391};
392
402 public:
404};
405
415 public:
416 virtual void on_wifi_connect_state(StringRef ssid, std::span<const uint8_t, 6> bssid) = 0;
417};
418
428 public:
430};
431
433class WiFiComponent final : public Component {
434 public:
437
438 void set_sta(const WiFiAP &ap);
439 // Returns a copy of the currently selected AP configuration
440 WiFiAP get_sta() const;
441 // init_sta/add_sta kept out of line: inlining them into the generated setup() grows flash
442 void init_sta(size_t count);
443 void add_sta(const WiFiAP &ap);
444 void clear_sta();
445
446#ifdef USE_WIFI_AP
454 void set_ap(const WiFiAP &ap);
455 WiFiAP get_ap() { return this->ap_; }
456 void set_ap_timeout(uint32_t ap_timeout) { ap_timeout_ = ap_timeout; }
457#endif // USE_WIFI_AP
458
459 void enable();
460 void disable();
462 void start_scanning();
464 void start_connecting(const WiFiAP &ap);
465 // Backward compatibility overload - ignores 'two' parameter
466 void start_connecting(const WiFiAP &ap, bool /* two */) { this->start_connecting(ap); }
467
469
470 void retry_connect();
471
472 void set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
473
474 bool is_connected() const { return this->connected_; }
475
478
481 bool is_roaming() const { return this->roaming_state_ != RoamingState::IDLE; }
482
483#ifdef USE_ESP32
487#endif
488
489 void set_power_save_mode(WiFiPowerSaveMode power_save);
490 void set_min_auth_mode(WifiMinAuthMode min_auth_mode) { min_auth_mode_ = min_auth_mode; }
491 void set_output_power(float output_power) { output_power_ = output_power; }
492#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
493 void set_band_mode(wifi_band_mode_t band_mode) { this->band_mode_ = band_mode; }
494#endif
495#ifdef USE_WIFI_PHY_MODE
496 void set_phy_mode(WiFi8266PhyMode phy_mode) { this->phy_mode_ = phy_mode; }
497#endif
498
499 void set_passive_scan(bool passive) { this->passive_scan_ = passive; }
500
501 void save_wifi_sta(const std::string &ssid, const std::string &password);
502 void save_wifi_sta(const char *ssid, const char *password);
503 void save_wifi_sta(StringRef ssid, StringRef password) { this->save_wifi_sta(ssid.c_str(), password.c_str()); }
504
505 // ========== INTERNAL METHODS ==========
506 // (In most use cases you won't need these)
508 void setup() override;
509 void start();
510 void dump_config() override;
511 void restart_adapter();
513 float get_setup_priority() const override { return setup_priority::WIFI; }
515 void loop() override;
516
517 bool has_sta() const { return !this->sta_.empty(); }
518 bool has_ap() const { return this->has_ap_; }
519 bool is_ap_active() const { return this->ap_started_; }
520
521#ifdef USE_WIFI_11KV_SUPPORT
522 void set_btm(bool btm) { this->btm_ = btm; }
523 void set_rrm(bool rrm) { this->rrm_ = rrm; }
524#endif
525
530 const char *get_use_address() const { return this->use_address_; }
531 void set_use_address(const char *use_address) { this->use_address_ = use_address; }
532
537
539
540 bool has_sta_priority(const bssid_t &bssid) {
541 for (auto &it : this->sta_priorities_) {
542 if (it.bssid == bssid)
543 return true;
544 }
545 return false;
546 }
547 int8_t get_sta_priority(const bssid_t bssid) {
548 for (auto &it : this->sta_priorities_) {
549 if (it.bssid == bssid)
550 return it.priority;
551 }
552 return 0;
553 }
554 void set_sta_priority(bssid_t bssid, int8_t priority);
555
559 const char *wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer);
561
562 int8_t wifi_rssi();
563
564 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
565 void set_keep_scan_results(bool keep_scan_results) { this->keep_scan_results_ = keep_scan_results; }
566 void set_post_connect_roaming(bool enabled) { this->post_connect_roaming_ = enabled; }
567
572 void force_roam_check();
573
574#ifdef USE_WIFI_CONNECT_TRIGGER
576#endif
577#ifdef USE_WIFI_DISCONNECT_TRIGGER
579#endif
580
581 int32_t get_wifi_channel();
582
583#ifdef USE_WIFI_IP_STATE_LISTENERS
587 void add_ip_state_listener(WiFiIPStateListener *listener) { this->ip_state_listeners_.push_back(listener); }
588#endif // USE_WIFI_IP_STATE_LISTENERS
589#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
592 this->scan_results_listeners_.push_back(listener);
593 }
594#endif // USE_WIFI_SCAN_RESULTS_LISTENERS
595#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
600 this->connect_state_listeners_.push_back(listener);
601 }
602#endif // USE_WIFI_CONNECT_STATE_LISTENERS
603#ifdef USE_WIFI_POWER_SAVE_LISTENERS
607 void add_power_save_listener(WiFiPowerSaveListener *listener) { this->power_save_listeners_.push_back(listener); }
608#endif // USE_WIFI_POWER_SAVE_LISTENERS
609
610#ifdef USE_WIFI_RUNTIME_POWER_SAVE
626
639#endif // USE_WIFI_RUNTIME_POWER_SAVE
640
641#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
658 uint8_t current = this->roaming_suppression_count_.load(std::memory_order_relaxed);
659 // CAS loop: saturate at max instead of wrapping, so an excess of requests can't roll the
660 // counter back to zero and unintentionally re-enable roaming.
661 while (current < std::numeric_limits<uint8_t>::max() &&
662 !this->roaming_suppression_count_.compare_exchange_weak(current, current + 1, std::memory_order_relaxed)) {
663 }
664 }
665
675 uint8_t current = this->roaming_suppression_count_.load(std::memory_order_relaxed);
676 // CAS loop: decrement only if non-zero, so an unmatched release can't wrap the counter
677 // and permanently suppress roaming.
678 while (current > 0 &&
679 !this->roaming_suppression_count_.compare_exchange_weak(current, current - 1, std::memory_order_relaxed)) {
680 }
681 }
682#endif // USE_ESP32 && USE_WIFI_RUNTIME_ROAMING_SUPPRESSION
683
684 protected:
685#ifdef USE_WIFI_AP
686 void setup_ap_config_();
687#endif // USE_WIFI_AP
688
691
696 bool transition_to_phase_(WiFiRetryPhase new_phase);
699 bool needs_scan_results_() const;
705 int8_t find_first_non_hidden_index_() const;
708 bool ssid_was_seen_in_scan_(const CompactString &ssid) const;
710 bool needs_full_scan_results_() const;
713 bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const;
715 void log_discarded_scan_result_(const char *ssid, const uint8_t *bssid, int8_t rssi, uint8_t channel);
719 int8_t find_next_hidden_sta_(int8_t start_index);
731 const WiFiAP *get_selected_sta_() const {
732 if (this->selected_sta_index_ >= 0 && static_cast<size_t>(this->selected_sta_index_) < this->sta_.size()) {
733 return &this->sta_[this->selected_sta_index_];
734 }
735 return nullptr;
736 }
737
739 if (this->selected_sta_index_ < 0 || static_cast<size_t>(this->selected_sta_index_) >= this->sta_.size()) {
740 this->selected_sta_index_ = this->sta_.empty() ? -1 : 0;
741 }
742 }
743
744 bool all_networks_hidden_() const {
745 if (this->sta_.empty())
746 return false;
747 for (const auto &ap : this->sta_) {
748 if (!ap.get_hidden())
749 return false;
750 }
751 return true;
752 }
753
754 void connect_soon_();
755
756 bool wifi_loop_();
757#ifdef USE_ESP8266
759#endif
760 bool wifi_mode_(optional<bool> sta, optional<bool> ap);
761 bool wifi_sta_pre_setup_();
762 bool wifi_apply_output_power_(float output_power);
764#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
766#endif
767#ifdef USE_WIFI_PHY_MODE
769#endif
770 bool wifi_sta_ip_config_(const optional<ManualIP> &manual_ip);
772 bool wifi_sta_connect_(const WiFiAP &ap);
773 void wifi_pre_setup_();
774#ifdef USE_ESP32
775 // ESP-IDF only: defers esp_wifi_init() + netif creation (which allocate ~15-30KB of
776 // DMA-capable internal SRAM) until wifi actually needs to come up. Idempotent.
777 // Called from setup() only when enable_on_boot_=true, and from enable() on first use.
779#endif
786 bool wifi_scan_start_(bool passive);
787
788#ifdef USE_WIFI_AP
789 bool wifi_ap_ip_config_(const optional<ManualIP> &manual_ip);
790 bool wifi_start_ap_(const WiFiAP &ap);
791#endif // USE_WIFI_AP
792
793 bool wifi_disconnect_();
794
798
801
802#ifdef USE_WIFI_FAST_CONNECT
804 void save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel);
805#endif
806
807 // Post-connect roaming methods
808 void check_roaming_(uint32_t now);
811#ifdef USE_ESP32
815 void handle_driver_roam_(const bssid_t &bssid, uint8_t channel);
816#endif
817
819 bool roaming_suppressed_() const {
820#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
821 return this->roaming_suppression_count_.load(std::memory_order_relaxed) != 0;
822#else
823 return false;
824#endif
825 }
826
829
830#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
835#endif
836#ifdef USE_WIFI_IP_STATE_LISTENERS
839#endif
840#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
843#endif
844
845#ifdef USE_ESP8266
846 static void wifi_event_callback(System_Event_t *event);
847 void wifi_scan_done_callback_(void *arg, STATUS status);
848 static void s_wifi_scan_done_callback(void *arg, STATUS status);
849#endif
850
851#ifdef USE_ESP32
852 void wifi_process_event_(IDFWiFiEvent *data);
853 friend void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
854#endif
855
856 friend class ScanResultsLock;
857
858#ifdef USE_RP2
859 static int s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result);
860 void wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result);
861#endif
862
863#ifdef USE_LIBRETINY
864 void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info);
865 void wifi_process_event_(LTWiFiEvent *event);
867#endif
868
869 // Large/pointer-aligned members first
871 std::vector<WiFiSTAPriority> sta_priorities_;
872 // Guarded by ScanResultsLock (see below this class)
874#ifdef WIFI_SCAN_RESULTS_LOCK_ENABLED
876#endif
877#ifdef USE_WIFI_AP
879#endif
880#ifdef USE_WIFI_IP_STATE_LISTENERS
882#endif
883#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
885#endif
886#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
888#endif
889#ifdef USE_WIFI_POWER_SAVE_LISTENERS
891#endif
893#ifdef USE_WIFI_FAST_CONNECT
895#endif
896#ifdef USE_WIFI_CONNECT_TRIGGER
898#endif
899#ifdef USE_WIFI_DISCONNECT_TRIGGER
901#endif
902#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
903 SemaphoreHandle_t high_performance_semaphore_{nullptr};
904#endif
905
906 static constexpr uint8_t FIRST_5GHZ_CHANNEL = 36;
907
908 // Post-connect roaming constants
909 static constexpr uint32_t ROAMING_CHECK_INTERVAL = 5 * 60 * 1000; // 5 minutes
910 static constexpr int8_t ROAMING_MIN_IMPROVEMENT = 10; // dB
911 static constexpr int8_t ROAMING_GOOD_RSSI = -49; // Skip scan if signal is excellent
912 static constexpr uint8_t ROAMING_MAX_ATTEMPTS = 3;
913 // Grace period after roaming scan completes. If WiFi disconnects within this
914 // window (e.g., ESP8266 Beacon Timeout caused by going off-channel during scan),
915 // the disconnect is treated as roaming-related and the attempts counter is preserved.
916 static constexpr uint32_t ROAMING_SCAN_GRACE_PERIOD = 30 * 1000; // 30 seconds
917
918 // 4-byte members
919 float output_power_{NAN};
924 uint32_t roaming_scan_end_{0}; // Timestamp when last roaming scan completed
925#ifdef USE_WIFI_AP
927#endif
928
929 // 1-byte enums and integers
932#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
933 wifi_band_mode_t band_mode_{WIFI_BAND_MODE_AUTO};
934#endif
935#ifdef USE_WIFI_PHY_MODE
937#endif
940 uint8_t num_retried_{0};
941 // Index into sta_ array for the currently selected AP configuration (-1 = none selected)
942 // Used to access password, manual_ip, priority, EAP settings, and hidden flag
943 // int8_t limits to 127 APs (enforced in __init__.py via MAX_WIFI_NETWORKS)
946#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
947 // Count of active roaming-suppression requests. Incremented/decremented from any task
948 // (e.g. audio playback), read in loop(). Roaming scans are paused while non-zero.
949 // Relaxed ordering is sufficient: the count value is the only data shared across threads,
950 // so no happens-before relationship with other memory needs to be established.
951 std::atomic<uint8_t> roaming_suppression_count_{0};
952#endif
953#if USE_NETWORK_IPV6
955#endif /* USE_NETWORK_IPV6 */
957#if defined(USE_ESP8266) || defined(USE_LIBRETINY)
958 // Platform-specific STA state enum, defined in platform cpp file.
959 // On ESP8266, written from SDK system context (wifi_event_callback) —
960 // uint8_t writes are atomic on Xtensa LX106 so no synchronization is needed.
961 uint8_t sta_state_{0};
962#endif
963#ifdef USE_LIBRETINY
964 // First attempt since STA-up (re-armed on every STA off->on); the
965 // pre-attempt teardown is skipped then.
967 // A self-inflicted disconnect from that teardown is pending; it must not
968 // consume an ignored-disconnect slot.
970#endif
973 bssid_t roaming_target_bssid_{}; // BSSID of the AP we're trying to roam to
974#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
976#endif
977
978 // Bools and bitfields
979 // Pending listener callbacks deferred from platform callbacks to main loop.
980 struct {
981#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
982 // Deferred until state machine reaches STA_CONNECTED so wifi.connected
983 // condition returns true in listener automations.
985#ifdef USE_ESP8266
986 // ESP8266: also defer disconnect notification to main loop
987 bool disconnect : 1;
988#endif
989#endif
990#if defined(USE_ESP8266) && defined(USE_WIFI_IP_STATE_LISTENERS)
991 bool got_ip : 1;
992#endif
993#if defined(USE_ESP8266) && defined(USE_WIFI_SCAN_RESULTS_LISTENERS)
995#endif
997 bool has_ap_{false};
998#if defined(USE_WIFI_CONNECT_TRIGGER) || defined(USE_WIFI_DISCONNECT_TRIGGER)
1000#endif
1001 bool scan_done_{false};
1002 bool ap_setup_{false};
1003 bool ap_started_{false};
1004 bool passive_scan_{false};
1006#ifdef USE_WIFI_11KV_SUPPORT
1007 bool btm_{false};
1008 bool rrm_{false};
1009#endif
1011#ifdef USE_ESP32
1012 // Tracks whether esp_wifi_init() + netif creation has happened. Allows enable()
1013 // to be called at runtime without re-allocating, and ensures the heavy init is
1014 // skipped entirely when enable_on_boot_ is false until first enable().
1016#endif
1020 false}; // Tracks if we've completed a scan after captive portal started
1022 bool connected_{false};
1023 bool post_connect_roaming_{true}; // Enabled by default
1024#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1026#endif
1027
1028#ifdef USE_ESP32
1029 // Lock-free SPSC queue for WiFi events from ESP-IDF event handler.
1030 // 17 slots = 16 usable (ring buffer reserves one slot). WiFi events are rare.
1031 // Placed at end of class to avoid padding between smaller fields.
1033#endif
1034
1035#ifdef USE_LIBRETINY
1036 // Thread-safe queue for WiFi events from LibreTiny callback thread.
1037 // LockFreeQueue on platforms with hardware atomics (RTL87xx, LN882x),
1038 // FreeRTOSQueue on platforms without (BK72xx).
1039 static constexpr uint8_t LT_EVENT_QUEUE_SIZE = 16;
1040#ifdef ESPHOME_THREAD_MULTI_ATOMICS
1041 // Ring buffer reserves one slot, so +1 for 16 usable slots
1043#else
1045#endif
1046#endif
1047
1048 private:
1049 // Stores a pointer to a string literal (static storage duration).
1050 // ONLY set from Python-generated code with string literals - never dynamic strings.
1051 const char *use_address_{nullptr};
1052};
1053
1054extern WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1055
1065 public:
1066#ifdef WIFI_SCAN_RESULTS_LOCK_ENABLED
1067 ScanResultsLock(WiFiComponent *parent) : guard_(parent->scan_result_lock_) {}
1068
1069 private:
1070 LockGuard guard_;
1071#else
1073#endif
1074};
1075
1076} // namespace esphome::wifi
1077#endif
BedjetMode mode
BedJet operating mode.
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:545
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1972
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1933
Minimal static vector - saves memory by avoiding std::vector overhead.
Definition helpers.h:227
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
constexpr const char * c_str() const
Definition string_ref.h:73
constexpr size_type size() const
Definition string_ref.h:74
20-byte string: 18 chars inline + null, heap for longer.
const char * data() const
StringRef ref() const
Return a StringRef view of this string (zero-copy)
bool operator!=(const CompactString &other) const
CompactString & operator=(const CompactString &other)
bool operator==(const CompactString &other) const
static constexpr uint8_t INLINE_CAPACITY
bool operator==(const char *other) const
bool operator!=(const StringRef &other) const
const char * c_str() const
char storage_[INLINE_CAPACITY+1]
static constexpr uint8_t MAX_LENGTH
bool operator!=(const char *other) const
Guards WiFiComponent::scan_result_.
ScanResultsLock(WiFiComponent *parent)
void set_password(const char *password)
uint8_t get_channel() const
StringRef get_ssid() const
void set_ssid(const std::string &ssid)
void set_ssid(const char *ssid)
const optional< EAPAuth > & get_eap() const
void set_ssid(StringRef ssid)
void set_bssid(const bssid_t &bssid)
void set_channel(uint8_t channel)
optional< EAPAuth > eap_
StringRef get_password() const
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
int8_t get_priority() const
void set_hidden(bool hidden)
const bssid_t & get_bssid() const
void set_priority(int8_t priority)
void set_password(StringRef password)
This component is responsible for managing the ESP WiFi interface.
void notify_scan_results_listeners_()
Notify scan results listeners with current scan results.
void add_sta(const WiFiAP &ap)
bool load_fast_connect_settings_(WiFiAP &params)
void add_connect_state_listener(WiFiConnectStateListener *listener)
Add a listener for WiFi connection state changes.
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
void set_band_mode(wifi_band_mode_t band_mode)
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)
void notify_connect_state_listeners_()
Notify connect state listeners (called after state machine reaches STA_CONNECTED)
wifi_scan_vector_t< WiFiScanResult > scan_result_
void save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel)
WiFiPowerSaveMode configured_power_save_
void wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result)
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)
std::atomic< uint8_t > roaming_suppression_count_
void set_enable_on_boot(bool enable_on_boot)
void advance_to_next_target_or_increment_retry_()
Advance to next target (AP/SSID) within current phase, or increment retry counter Called when staying...
void add_power_save_listener(WiFiPowerSaveListener *listener)
Add a listener for WiFi power save mode changes.
bool wifi_sta_ip_config_(const optional< ManualIP > &manual_ip)
static constexpr uint32_t ROAMING_CHECK_INTERVAL
esp_netif_t * get_esp_netif_sta()
esp_netif handle of the station interface, used by network for default-route arbitration.
bool is_roaming() const
True while a post-connect roam is in progress (scanning off-channel, reassociating,...
static int s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result)
SemaphoreHandle_t high_performance_semaphore_
network::IPAddress get_dns_address(int num)
static void wifi_event_callback(System_Event_t *event)
WiFiComponent()
Construct a WiFiComponent.
void wifi_process_event_(IDFWiFiEvent *data)
std::vector< WiFiSTAPriority > sta_priorities_
FreeRTOSQueue< LTWiFiEvent, LT_EVENT_QUEUE_SIZE > event_queue_
static constexpr int8_t ROAMING_GOOD_RSSI
void notify_disconnect_state_listeners_()
Notify connect state listeners of disconnection.
void set_min_auth_mode(WifiMinAuthMode min_auth_mode)
friend void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
StaticVector< WiFiConnectStateListener *, ESPHOME_WIFI_CONNECT_STATE_LISTENERS > connect_state_listeners_
void release_roaming_suppression()
Release a roaming suppression request.
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.
void start_connecting(const WiFiAP &ap, bool)
static constexpr uint8_t ROAMING_MAX_ATTEMPTS
void set_passive_scan(bool passive)
void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info)
static void s_wifi_scan_done_callback(void *arg, STATUS status)
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.
LockFreeQueue< LTWiFiEvent, LT_EVENT_QUEUE_SIZE+1 > event_queue_
void set_phy_mode(WiFi8266PhyMode phy_mode)
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...
void add_ip_state_listener(WiFiIPStateListener *listener)
Add a listener for IP state changes.
ESPPreferenceObject fast_connect_pref_
void clear_priorities_if_all_min_()
Clear BSSID priority tracking if all priorities are at minimum (saves memory)
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
static constexpr uint8_t LT_EVENT_QUEUE_SIZE
bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const
Check if network matches any configured network (for scan result filtering) Matches by SSID when conf...
struct esphome::wifi::WiFiComponent::@194 pending_
float get_setup_priority() const override
WIFI setup_priority.
void set_output_power(float output_power)
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.
void request_roaming_suppression()
Request that post-connect roaming scans be suppressed.
bool wifi_ap_ip_config_(const optional< ManualIP > &manual_ip)
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...
void add_scan_results_listener(WiFiScanResultsListener *listener)
Add a listener for WiFi scan results.
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)
static constexpr uint8_t FIRST_5GHZ_CHANNEL
LockFreeQueue< IDFWiFiEvent, 17 > event_queue_
void set_ap_timeout(uint32_t ap_timeout)
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...
StaticVector< WiFiPowerSaveListener *, ESPHOME_WIFI_POWER_SAVE_LISTENERS > power_save_listeners_
bool wifi_apply_output_power_(float output_power)
void set_post_connect_roaming(bool enabled)
const char * get_use_address() const
Returns nullptr when no explicit use_address is configured and the address is derived at runtime from...
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 check_connecting_finished(uint32_t now)
void set_keep_scan_results(bool keep_scan_results)
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 save_wifi_sta(StringRef ssid, StringRef password)
void handle_driver_roam_(const bssid_t &bssid, uint8_t channel)
Redo post-connect bookkeeping after a driver-initiated roam (e.g.
void setup() override
Setup WiFi interface.
void clear_all_bssid_priorities_()
Clear all BSSID priority penalties after successful connection (stale after disconnect)
void set_use_address(const char *use_address)
const wifi_scan_vector_t< WiFiScanResult > & get_scan_result() const
Main-loop callers may read this directly.
Listener interface for WiFi connection state changes.
virtual void on_wifi_connect_state(StringRef ssid, std::span< const uint8_t, 6 > bssid)=0
Listener interface for WiFi IP state changes.
virtual void on_ip_state(const network::IPAddresses &ips, const network::IPAddress &dns1, const network::IPAddress &dns2)=0
Listener interface for WiFi power save mode changes.
virtual void on_wifi_power_save(WiFiPowerSaveMode mode)=0
bool ssid_equals(const WiFiScanResult &other) const
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
void set_priority(int8_t priority)
bool operator==(const WiFiScanResult &rhs) const
Listener interface for WiFi scan results.
virtual void on_wifi_scan_results(const wifi_scan_vector_t< WiFiScanResult > &results)=0
uint8_t priority
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:301
constexpr float WIFI
Definition component.h:50
std::array< uint8_t, 6 > bssid_t
RetryHiddenMode
Controls how RETRY_HIDDEN phase selects networks to try.
@ 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...
std::vector< T > wifi_scan_vector_t
struct esphome::wifi::SavedWifiSettings PACKED
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
RoamingState
Tracks post-connect roaming state machine.
@ SCANNING
Scanning for better AP.
@ 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.
const void size_t len
Definition hal.h:64
struct esp_netif_obj esp_netif_t
static void uint32_t
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.
network::IPAddress static_ip
network::IPAddress dns1
The first DNS server. 0.0.0.0 for default.
network::IPAddress gateway
network::IPAddress dns2
The second DNS server. 0.0.0.0 for default.
network::IPAddress subnet
uint8_t event_id
Definition tt21100.cpp:3