ESPHome 2026.8.2
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 <vector>
25
26#ifdef USE_LIBRETINY
27#include <WiFi.h>
28#endif
29
30#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP)
31#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
32#include <esp_eap_client.h>
33#else
34#include <esp_wpa2.h>
35#endif
36#endif
37
38#ifdef USE_ESP8266
39#include <ESP8266WiFi.h>
40#include <ESP8266WiFiType.h>
41
42#if defined(USE_ESP8266) && USE_ARDUINO_VERSION_CODE < VERSION_CODE(2, 4, 0)
43extern "C" {
44#include <user_interface.h>
45};
46#endif
47#endif
48
49#ifdef USE_RP2
50extern "C" {
51#include "cyw43.h"
52#include "cyw43_country.h"
53#include "pico/cyw43_arch.h"
54}
55
56#include <WiFi.h>
57#endif
58
59#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
60#include <esp_wifi_types.h>
61#endif
62
63#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
64#include <freertos/FreeRTOS.h>
65#include <freertos/semphr.h>
66#endif
67
68#ifdef USE_ESP32
69// Forward declaration matching esp_netif's own typedef; avoids pulling esp_netif.h
70// into this widely-included header.
71using esp_netif_t = struct esp_netif_obj;
72#endif
73
74namespace esphome::wifi {
75
77static constexpr int8_t WIFI_RSSI_DISCONNECTED = -127;
78
80static constexpr size_t SSID_BUFFER_SIZE = 33;
81
83 char ssid[33];
84 char password[65];
85} PACKED; // NOLINT
86
88 uint8_t bssid[6];
89 uint8_t channel;
90 int8_t ap_index;
91} PACKED; // NOLINT
92
109
117
119enum class WiFiRetryPhase : uint8_t {
122#ifdef USE_WIFI_FAST_CONNECT
125#endif
134};
135
137enum class RoamingState : uint8_t {
139 IDLE,
141 SCANNING,
146};
147
149enum class RetryHiddenMode : uint8_t {
156};
157
166
167#ifdef USE_WIFI_WPA2_EAP
168struct EAPAuth {
169 std::string identity; // required for all auth types
170 std::string username;
171 std::string password;
172 const char *ca_cert; // optionally verify authentication server
173 // used for EAP-TLS
174 const char *client_cert;
175 const char *client_key;
176// used for EAP-TTLS
177#ifdef USE_ESP32
178 esp_eap_ttls_phase2_types ttls_phase_2;
179#endif
180};
181#endif // USE_WIFI_WPA2_EAP
182
183using bssid_t = std::array<uint8_t, 6>;
184
186static constexpr size_t WIFI_SCAN_RESULT_FILTERED_RESERVE = 8;
187
188// Use std::vector for RP2040 (callback-based) and ESP32 (destructive scan API)
189// Use FixedVector for ESP8266 and LibreTiny where two-pass exact allocation is possible
190#if defined(USE_RP2) || defined(USE_ESP32)
191template<typename T> using wifi_scan_vector_t = std::vector<T>;
192#else
193template<typename T> using wifi_scan_vector_t = FixedVector<T>;
194#endif
195
196// A consumer component (e.g. the captive portal) reads scan results from another
197// task; guard them with a real lock only on platforms that actually run multiple
198// threads. See ScanResultsLock below the WiFiComponent class.
199#if defined(USE_WIFI_SCAN_RESULTS_LOCK) && !defined(ESPHOME_THREAD_SINGLE)
200#define WIFI_SCAN_RESULTS_LOCK_ENABLED
201#endif
202
206 public:
207 static constexpr uint8_t MAX_LENGTH = 127;
208 static constexpr uint8_t INLINE_CAPACITY = 18; // 18 chars + null terminator fits in 19 bytes
209
210 CompactString() : length_(0), is_heap_(0) { this->storage_[0] = '\0'; }
211 CompactString(const char *str, size_t len);
212 CompactString(const CompactString &other);
213 CompactString(CompactString &&other) noexcept;
215 CompactString &operator=(CompactString &&other) noexcept;
217
218 const char *data() const { return this->is_heap_ ? this->get_heap_ptr_() : this->storage_; }
219 const char *c_str() const { return this->data(); } // Always null-terminated
220 size_t size() const { return this->length_; }
221 bool empty() const { return this->length_ == 0; }
222
224 StringRef ref() const { return StringRef(this->data(), this->size()); }
225
226 bool operator==(const CompactString &other) const;
227 bool operator!=(const CompactString &other) const { return !(*this == other); }
228 bool operator==(const StringRef &other) const;
229 bool operator!=(const StringRef &other) const { return !(*this == other); }
230 bool operator==(const char *other) const { return *this == StringRef(other); }
231 bool operator!=(const char *other) const { return !(*this == other); }
232
233 protected:
234 char *get_heap_ptr_() const {
235 char *ptr;
236 std::memcpy(&ptr, this->storage_, sizeof(ptr));
237 return ptr;
238 }
239 void set_heap_ptr_(char *ptr) { std::memcpy(this->storage_, &ptr, sizeof(ptr)); }
240
241 // Storage for string data. When is_heap_=0, contains the string directly (null-terminated).
242 // When is_heap_=1, first sizeof(char*) bytes contain pointer to heap allocation.
243 char storage_[INLINE_CAPACITY + 1]; // 19 bytes: 18 chars + null terminator
244 uint8_t length_ : 7; // String length (0-127)
245 uint8_t is_heap_ : 1; // 1 if using heap pointer, 0 if using inline storage
246 // Total size: 20 bytes (19 bytes storage + 1 byte bitfields)
247};
248
249static_assert(sizeof(CompactString) == 20, "CompactString must be exactly 20 bytes");
250// CompactString is not trivially copyable (non-trivial destructor/copy for heap case).
251// However, its layout has no self-referential pointers: storage_[] contains either inline
252// data or an external heap pointer — never a pointer to itself. This is unlike libstdc++
253// std::string SSO where _M_p points to _M_local_buf within the same object.
254// This property allows memcpy-based permutation sorting where each element ends up in
255// exactly one slot (no ownership duplication). These asserts document that layout property.
256static_assert(std::is_standard_layout<CompactString>::value, "CompactString must be standard layout");
257static_assert(!std::is_polymorphic<CompactString>::value, "CompactString must not have vtable");
258
259class WiFiAP {
260 friend class WiFiComponent;
261 friend class WiFiScanResult;
262
263 public:
264 void set_ssid(const std::string &ssid);
265 void set_ssid(const char *ssid);
266 void set_ssid(StringRef ssid) { this->ssid_ = CompactString(ssid.c_str(), ssid.size()); }
267 void set_bssid(const bssid_t &bssid);
268 void clear_bssid();
269 void set_password(const std::string &password);
270 void set_password(const char *password);
271 void set_password(StringRef password) { this->password_ = CompactString(password.c_str(), password.size()); }
272#ifdef USE_WIFI_WPA2_EAP
273 void set_eap(optional<EAPAuth> eap_auth);
274#endif // USE_WIFI_WPA2_EAP
275 void set_channel(uint8_t channel);
276 void clear_channel();
278#ifdef USE_WIFI_MANUAL_IP
279 void set_manual_ip(optional<ManualIP> manual_ip);
280#endif
281 void set_hidden(bool hidden);
282 StringRef get_ssid() const { return this->ssid_.ref(); }
283 StringRef get_password() const { return this->password_.ref(); }
284 const bssid_t &get_bssid() const;
285 bool has_bssid() const;
286#ifdef USE_WIFI_WPA2_EAP
287 const optional<EAPAuth> &get_eap() const;
288#endif // USE_WIFI_WPA2_EAP
289 uint8_t get_channel() const { return this->channel_; }
290 bool has_channel() const { return this->channel_ != 0; }
291 int8_t get_priority() const { return priority_; }
292#ifdef USE_WIFI_MANUAL_IP
293 const optional<ManualIP> &get_manual_ip() const;
294#endif
295 bool get_hidden() const;
296
297 protected:
300#ifdef USE_WIFI_WPA2_EAP
301 optional<EAPAuth> eap_;
302#endif // USE_WIFI_WPA2_EAP
303#ifdef USE_WIFI_MANUAL_IP
304 optional<ManualIP> manual_ip_;
305#endif
306 // Group small types together to minimize padding
307 bssid_t bssid_{}; // 6 bytes, all zeros = any/not set
308 uint8_t channel_{0}; // 1 byte, 0 = auto/not set
309 int8_t priority_{0}; // 1 byte
310 bool hidden_{false}; // 1 byte (+ 3 bytes end padding to 4-byte align)
311};
312
314 friend class WiFiComponent;
315
316 public:
317 WiFiScanResult(const bssid_t &bssid, const char *ssid, size_t ssid_len, uint8_t channel, int8_t rssi, bool with_auth,
318 bool is_hidden);
319
320 bool matches(const WiFiAP &config) const;
321
322 bool get_matches() const;
323 void set_matches(bool matches);
324 const bssid_t &get_bssid() const;
325 StringRef get_ssid() const { return this->ssid_.ref(); }
326 uint8_t get_channel() const;
327 int8_t get_rssi() const;
328 bool get_with_auth() const;
329 bool get_is_hidden() const;
330 int8_t get_priority() const { return priority_; }
332
333 bool operator==(const WiFiScanResult &rhs) const;
334
335 protected:
337 uint8_t channel_;
338 int8_t rssi_;
340 int8_t priority_{0};
341 bool matches_{false};
344};
345
350
356
362
363#ifdef USE_WIFI_PHY_MODE
364// Values 1-3 match ESP8266 SDK phy_mode_t (PHY_MODE_11B=1, PHY_MODE_11G=2, PHY_MODE_11N=3).
365// AUTO leaves the SDK at its default (no wifi_set_phy_mode() call).
372#endif
373
374#ifdef USE_ESP32
375struct IDFWiFiEvent;
376#endif
377
378#ifdef USE_LIBRETINY
379struct LTWiFiEvent;
380#endif
381
391 public:
392 virtual void on_ip_state(const network::IPAddresses &ips, const network::IPAddress &dns1,
393 const network::IPAddress &dns2) = 0;
394};
395
405 public:
407};
408
418 public:
419 virtual void on_wifi_connect_state(StringRef ssid, std::span<const uint8_t, 6> bssid) = 0;
420};
421
431 public:
433};
434
436class WiFiComponent final : public Component {
437 public:
440
441 void set_sta(const WiFiAP &ap);
442 // Returns a copy of the currently selected AP configuration
443 WiFiAP get_sta() const;
444 void init_sta(size_t count);
445 void add_sta(const WiFiAP &ap);
446 void clear_sta();
447
448#ifdef USE_WIFI_AP
456 void set_ap(const WiFiAP &ap);
457 WiFiAP get_ap() { return this->ap_; }
458 void set_ap_timeout(uint32_t ap_timeout) { ap_timeout_ = ap_timeout; }
459#endif // USE_WIFI_AP
460
461 void enable();
462 void disable();
463 bool is_disabled();
464 void start_scanning();
466 void start_connecting(const WiFiAP &ap);
467 // Backward compatibility overload - ignores 'two' parameter
468 void start_connecting(const WiFiAP &ap, bool /* two */) { this->start_connecting(ap); }
469
471
472 void retry_connect();
473
474 void set_reboot_timeout(uint32_t reboot_timeout);
475
476 bool is_connected() const { return this->connected_; }
477
480
483 bool is_roaming() const { return this->roaming_state_ != RoamingState::IDLE; }
484
485#ifdef USE_ESP32
489#endif
490
491 void set_power_save_mode(WiFiPowerSaveMode power_save);
492 void set_min_auth_mode(WifiMinAuthMode min_auth_mode) { min_auth_mode_ = min_auth_mode; }
493 void set_output_power(float output_power) { output_power_ = output_power; }
494#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
495 void set_band_mode(wifi_band_mode_t band_mode) { this->band_mode_ = band_mode; }
496#endif
497#ifdef USE_WIFI_PHY_MODE
498 void set_phy_mode(WiFi8266PhyMode phy_mode) { this->phy_mode_ = phy_mode; }
499#endif
500
501 void set_passive_scan(bool passive);
502
503 void save_wifi_sta(const std::string &ssid, const std::string &password);
504 void save_wifi_sta(const char *ssid, const char *password);
505 void save_wifi_sta(StringRef ssid, StringRef password) { this->save_wifi_sta(ssid.c_str(), password.c_str()); }
506
507 // ========== INTERNAL METHODS ==========
508 // (In most use cases you won't need these)
510 void setup() override;
511 void start();
512 void dump_config() override;
513 void restart_adapter();
515 float get_setup_priority() const override;
517 void loop() override;
518
519 bool has_sta() const { return !this->sta_.empty(); }
520 bool has_ap() const { return this->has_ap_; }
521 bool is_ap_active() const { return this->ap_started_; }
522
523#ifdef USE_WIFI_11KV_SUPPORT
524 void set_btm(bool btm);
525 void set_rrm(bool rrm);
526#endif
527
532 const char *get_use_address() const { return this->use_address_; }
533 void set_use_address(const char *use_address) { this->use_address_ = use_address; }
534
539
541
542 bool has_sta_priority(const bssid_t &bssid) {
543 for (auto &it : this->sta_priorities_) {
544 if (it.bssid == bssid)
545 return true;
546 }
547 return false;
548 }
549 int8_t get_sta_priority(const bssid_t bssid) {
550 for (auto &it : this->sta_priorities_) {
551 if (it.bssid == bssid)
552 return it.priority;
553 }
554 return 0;
555 }
556 void set_sta_priority(bssid_t bssid, int8_t priority);
557
559 // Remove before 2026.9.0
560 ESPDEPRECATED("Use wifi_ssid_to() instead. Removed in 2026.9.0", "2026.3.0")
561 std::string wifi_ssid();
564 const char *wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer);
566
567 int8_t wifi_rssi();
568
569 void set_enable_on_boot(bool enable_on_boot) { this->enable_on_boot_ = enable_on_boot; }
570 void set_keep_scan_results(bool keep_scan_results) { this->keep_scan_results_ = keep_scan_results; }
571 void set_post_connect_roaming(bool enabled) { this->post_connect_roaming_ = enabled; }
572
573#ifdef USE_WIFI_CONNECT_TRIGGER
575#endif
576#ifdef USE_WIFI_DISCONNECT_TRIGGER
578#endif
579
580 int32_t get_wifi_channel();
581
582#ifdef USE_WIFI_IP_STATE_LISTENERS
586 void add_ip_state_listener(WiFiIPStateListener *listener) { this->ip_state_listeners_.push_back(listener); }
587#endif // USE_WIFI_IP_STATE_LISTENERS
588#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
591 this->scan_results_listeners_.push_back(listener);
592 }
593#endif // USE_WIFI_SCAN_RESULTS_LISTENERS
594#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
599 this->connect_state_listeners_.push_back(listener);
600 }
601#endif // USE_WIFI_CONNECT_STATE_LISTENERS
602#ifdef USE_WIFI_POWER_SAVE_LISTENERS
606 void add_power_save_listener(WiFiPowerSaveListener *listener) { this->power_save_listeners_.push_back(listener); }
607#endif // USE_WIFI_POWER_SAVE_LISTENERS
608
609#ifdef USE_WIFI_RUNTIME_POWER_SAVE
625
638#endif // USE_WIFI_RUNTIME_POWER_SAVE
639
640#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
657 uint8_t current = this->roaming_suppression_count_.load(std::memory_order_relaxed);
658 // CAS loop: saturate at max instead of wrapping, so an excess of requests can't roll the
659 // counter back to zero and unintentionally re-enable roaming.
660 while (current < std::numeric_limits<uint8_t>::max() &&
661 !this->roaming_suppression_count_.compare_exchange_weak(current, current + 1, std::memory_order_relaxed)) {
662 }
663 }
664
674 uint8_t current = this->roaming_suppression_count_.load(std::memory_order_relaxed);
675 // CAS loop: decrement only if non-zero, so an unmatched release can't wrap the counter
676 // and permanently suppress roaming.
677 while (current > 0 &&
678 !this->roaming_suppression_count_.compare_exchange_weak(current, current - 1, std::memory_order_relaxed)) {
679 }
680 }
681#endif // USE_ESP32 && USE_WIFI_RUNTIME_ROAMING_SUPPRESSION
682
683 protected:
684#ifdef USE_WIFI_AP
685 void setup_ap_config_();
686#endif // USE_WIFI_AP
687
690
695 bool transition_to_phase_(WiFiRetryPhase new_phase);
698 bool needs_scan_results_() const;
704 int8_t find_first_non_hidden_index_() const;
707 bool ssid_was_seen_in_scan_(const CompactString &ssid) const;
709 bool needs_full_scan_results_() const;
712 bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const;
714 void log_discarded_scan_result_(const char *ssid, const uint8_t *bssid, int8_t rssi, uint8_t channel);
718 int8_t find_next_hidden_sta_(int8_t start_index);
730 const WiFiAP *get_selected_sta_() const {
731 if (this->selected_sta_index_ >= 0 && static_cast<size_t>(this->selected_sta_index_) < this->sta_.size()) {
732 return &this->sta_[this->selected_sta_index_];
733 }
734 return nullptr;
735 }
736
738 if (this->selected_sta_index_ < 0 || static_cast<size_t>(this->selected_sta_index_) >= this->sta_.size()) {
739 this->selected_sta_index_ = this->sta_.empty() ? -1 : 0;
740 }
741 }
742
743 bool all_networks_hidden_() const {
744 if (this->sta_.empty())
745 return false;
746 for (const auto &ap : this->sta_) {
747 if (!ap.get_hidden())
748 return false;
749 }
750 return true;
751 }
752
753 void connect_soon_();
754
755 bool wifi_loop_();
756#ifdef USE_ESP8266
758#endif
759 bool wifi_mode_(optional<bool> sta, optional<bool> ap);
760 bool wifi_sta_pre_setup_();
761 bool wifi_apply_output_power_(float output_power);
763#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
765#endif
766#ifdef USE_WIFI_PHY_MODE
768#endif
769 bool wifi_sta_ip_config_(const optional<ManualIP> &manual_ip);
771 bool wifi_sta_connect_(const WiFiAP &ap);
772 void wifi_pre_setup_();
773#ifdef USE_ESP32
774 // ESP-IDF only: defers esp_wifi_init() + netif creation (which allocate ~15-30KB of
775 // DMA-capable internal SRAM) until wifi actually needs to come up. Idempotent.
776 // Called from setup() only when enable_on_boot_=true, and from enable() on first use.
778#endif
785 bool wifi_scan_start_(bool passive);
786
787#ifdef USE_WIFI_AP
788 bool wifi_ap_ip_config_(const optional<ManualIP> &manual_ip);
789 bool wifi_start_ap_(const WiFiAP &ap);
790#endif // USE_WIFI_AP
791
792 bool wifi_disconnect_();
793
797
800
801#ifdef USE_WIFI_FAST_CONNECT
803 void save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel);
804#endif
805
806 // Post-connect roaming methods
807 void check_roaming_(uint32_t now);
810#ifdef USE_ESP32
814 void handle_driver_roam_(const bssid_t &bssid, uint8_t channel);
815#endif
816
818 bool roaming_suppressed_() const {
819#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
820 return this->roaming_suppression_count_.load(std::memory_order_relaxed) != 0;
821#else
822 return false;
823#endif
824 }
825
828
829#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
834#endif
835#ifdef USE_WIFI_IP_STATE_LISTENERS
838#endif
839#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
842#endif
843
844#ifdef USE_ESP8266
845 static void wifi_event_callback(System_Event_t *event);
846 void wifi_scan_done_callback_(void *arg, STATUS status);
847 static void s_wifi_scan_done_callback(void *arg, STATUS status);
848#endif
849
850#ifdef USE_ESP32
851 void wifi_process_event_(IDFWiFiEvent *data);
852 friend void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data);
853#endif
854
855 friend class ScanResultsLock;
856
857#ifdef USE_RP2
858 static int s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result);
859 void wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result);
860#endif
861
862#ifdef USE_LIBRETINY
863 void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info);
864 void wifi_process_event_(LTWiFiEvent *event);
866#endif
867
868 // Large/pointer-aligned members first
870 std::vector<WiFiSTAPriority> sta_priorities_;
871 // Guarded by ScanResultsLock (see below this class)
873#ifdef WIFI_SCAN_RESULTS_LOCK_ENABLED
875#endif
876#ifdef USE_WIFI_AP
878#endif
879#ifdef USE_WIFI_IP_STATE_LISTENERS
881#endif
882#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
884#endif
885#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
887#endif
888#ifdef USE_WIFI_POWER_SAVE_LISTENERS
890#endif
892#ifdef USE_WIFI_FAST_CONNECT
894#endif
895#ifdef USE_WIFI_CONNECT_TRIGGER
897#endif
898#ifdef USE_WIFI_DISCONNECT_TRIGGER
900#endif
901#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
902 SemaphoreHandle_t high_performance_semaphore_{nullptr};
903#endif
904
905 static constexpr uint8_t FIRST_5GHZ_CHANNEL = 36;
906
907 // Post-connect roaming constants
908 static constexpr uint32_t ROAMING_CHECK_INTERVAL = 5 * 60 * 1000; // 5 minutes
909 static constexpr int8_t ROAMING_MIN_IMPROVEMENT = 10; // dB
910 static constexpr int8_t ROAMING_GOOD_RSSI = -49; // Skip scan if signal is excellent
911 static constexpr uint8_t ROAMING_MAX_ATTEMPTS = 3;
912 // Grace period after roaming scan completes. If WiFi disconnects within this
913 // window (e.g., ESP8266 Beacon Timeout caused by going off-channel during scan),
914 // the disconnect is treated as roaming-related and the attempts counter is preserved.
915 static constexpr uint32_t ROAMING_SCAN_GRACE_PERIOD = 30 * 1000; // 30 seconds
916
917 // 4-byte members
918 float output_power_{NAN};
923 uint32_t roaming_scan_end_{0}; // Timestamp when last roaming scan completed
924#ifdef USE_WIFI_AP
926#endif
927
928 // 1-byte enums and integers
931#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
932 wifi_band_mode_t band_mode_{WIFI_BAND_MODE_AUTO};
933#endif
934#ifdef USE_WIFI_PHY_MODE
936#endif
939 uint8_t num_retried_{0};
940 // Index into sta_ array for the currently selected AP configuration (-1 = none selected)
941 // Used to access password, manual_ip, priority, EAP settings, and hidden flag
942 // int8_t limits to 127 APs (enforced in __init__.py via MAX_WIFI_NETWORKS)
945#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_ROAMING_SUPPRESSION)
946 // Count of active roaming-suppression requests. Incremented/decremented from any task
947 // (e.g. audio playback), read in loop(). Roaming scans are paused while non-zero.
948 // Relaxed ordering is sufficient: the count value is the only data shared across threads,
949 // so no happens-before relationship with other memory needs to be established.
950 std::atomic<uint8_t> roaming_suppression_count_{0};
951#endif
952#if USE_NETWORK_IPV6
954#endif /* USE_NETWORK_IPV6 */
956#if defined(USE_ESP8266) || defined(USE_LIBRETINY)
957 // Platform-specific STA state enum, defined in platform cpp file.
958 // On ESP8266, written from SDK system context (wifi_event_callback) —
959 // uint8_t writes are atomic on Xtensa LX106 so no synchronization is needed.
960 uint8_t sta_state_{0};
961#endif
964 bssid_t roaming_target_bssid_{}; // BSSID of the AP we're trying to roam to
965#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
967#endif
968
969 // Bools and bitfields
970 // Pending listener callbacks deferred from platform callbacks to main loop.
971 struct {
972#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
973 // Deferred until state machine reaches STA_CONNECTED so wifi.connected
974 // condition returns true in listener automations.
976#ifdef USE_ESP8266
977 // ESP8266: also defer disconnect notification to main loop
978 bool disconnect : 1;
979#endif
980#endif
981#if defined(USE_ESP8266) && defined(USE_WIFI_IP_STATE_LISTENERS)
982 bool got_ip : 1;
983#endif
984#if defined(USE_ESP8266) && defined(USE_WIFI_SCAN_RESULTS_LISTENERS)
986#endif
988 bool has_ap_{false};
989#if defined(USE_WIFI_CONNECT_TRIGGER) || defined(USE_WIFI_DISCONNECT_TRIGGER)
991#endif
992 bool scan_done_{false};
993 bool ap_setup_{false};
994 bool ap_started_{false};
995 bool passive_scan_{false};
997#ifdef USE_WIFI_11KV_SUPPORT
998 bool btm_{false};
999 bool rrm_{false};
1000#endif
1002#ifdef USE_ESP32
1003 // Tracks whether esp_wifi_init() + netif creation has happened. Allows enable()
1004 // to be called at runtime without re-allocating, and ensures the heavy init is
1005 // skipped entirely when enable_on_boot_ is false until first enable().
1007#endif
1011 false}; // Tracks if we've completed a scan after captive portal started
1013 bool connected_{false};
1014 bool post_connect_roaming_{true}; // Enabled by default
1015#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1017#endif
1018
1019#ifdef USE_ESP32
1020 // Lock-free SPSC queue for WiFi events from ESP-IDF event handler.
1021 // 17 slots = 16 usable (ring buffer reserves one slot). WiFi events are rare.
1022 // Placed at end of class to avoid padding between smaller fields.
1024#endif
1025
1026#ifdef USE_LIBRETINY
1027 // Thread-safe queue for WiFi events from LibreTiny callback thread.
1028 // LockFreeQueue on platforms with hardware atomics (RTL87xx, LN882x),
1029 // FreeRTOSQueue on platforms without (BK72xx).
1030 static constexpr uint8_t LT_EVENT_QUEUE_SIZE = 16;
1031#ifdef ESPHOME_THREAD_MULTI_ATOMICS
1032 // Ring buffer reserves one slot, so +1 for 16 usable slots
1034#else
1036#endif
1037#endif
1038
1039 private:
1040 // Stores a pointer to a string literal (static storage duration).
1041 // ONLY set from Python-generated code with string literals - never dynamic strings.
1042 const char *use_address_{nullptr};
1043};
1044
1045extern WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1046
1056 public:
1057#ifdef WIFI_SCAN_RESULTS_LOCK_ENABLED
1058 ScanResultsLock(WiFiComponent *parent) : guard_(parent->scan_result_lock_) {}
1059
1060 private:
1061 LockGuard guard_;
1062#else
1064#endif
1065};
1066
1067} // namespace esphome::wifi
1068#endif
BedjetMode mode
BedJet operating mode.
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:544
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:1969
Mutex implementation, with API based on the unavailable std::mutex.
Definition helpers.h:1930
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)
uint8_t get_channel() const
StringRef get_ssid() const
void set_ssid(const std::string &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)
ESPDEPRECATED("Use wifi_ssid_to() instead. Removed in 2026.9.0", "2026.3.0") std 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...
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.
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.
struct esphome::wifi::WiFiComponent::@193 pending_
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
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:299
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.
ESPDEPRECATED("Use LightState::gamma_correct_lut() instead. Removed in 2026.9.0.", "2026.3.0") float gamma_correct(float value
Applies gamma correction of gamma to value.
const void size_t len
Definition hal.h:64
STL namespace.
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