ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
wifi_component_pico_w.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2
3#ifdef USE_WIFI
4#ifdef USE_RP2
5
6#include <cassert>
7
8#include "lwip/dns.h"
9#include "lwip/err.h"
10#include "lwip/netif.h"
11#include <AddrList.h>
12
14#include "esphome/core/hal.h"
16#include "esphome/core/log.h"
17#include "esphome/core/util.h"
18
19namespace esphome::wifi {
20
21ESPHOME_LOG_TAG(TAG, "wifi_pico_w");
22
23// Check if STA is fully connected (WiFi joined + has IP address).
24// Do NOT use WiFi.status() or WiFi.connected() for this — in AP-only mode they
25// unconditionally return true regardless of STA state, causing false positives
26// when the fallback AP is active.
27static bool wifi_sta_connected() {
28 int link = cyw43_wifi_link_status(&cyw43_state, CYW43_ITF_STA);
29 IPAddress local = WiFi.localIP();
30 if (link == CYW43_LINK_JOIN && local.isSet()) {
31 // Verify the IP is a real STA IP, not the AP's IP leaking through
32 IPAddress ap_ip = WiFi.softAPIP();
33 if (local == ap_ip) {
34 ESP_LOGV(TAG, "wifi_sta_connected: localIP %s matches AP IP, ignoring", local.toString().c_str());
35 return false;
36 }
37 return true;
38 }
39 return false;
40}
41
42// Track previous state for detecting changes
43static bool s_sta_was_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
44static bool s_sta_had_ip = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
45static size_t s_scan_result_count = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
46
47bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
48 if (sta.has_value()) {
49 if (sta.value()) {
50 cyw43_wifi_set_up(&cyw43_state, CYW43_ITF_STA, true, CYW43_COUNTRY_WORLDWIDE);
51 } else {
52 // Leave the STA network so the radio is free for scanning.
53 // Use cyw43_wifi_leave directly to avoid corrupting Arduino framework state.
54 cyw43_wifi_leave(&cyw43_state, CYW43_ITF_STA);
55 }
56 }
57
58 if (ap.has_value()) {
59 if (ap.value()) {
60 cyw43_wifi_set_up(&cyw43_state, CYW43_ITF_AP, true, CYW43_COUNTRY_WORLDWIDE);
61 } else {
62#ifdef USE_WIFI_AP
63 // Takes down the Arduino AP interface and its DHCP server; a later beginAP() is refused
64 // while they are still up
65 WiFi.disconnectAP();
66#endif
67 cyw43_wifi_set_up(&cyw43_state, CYW43_ITF_AP, false, CYW43_COUNTRY_WORLDWIDE);
68 }
69 this->ap_started_ = ap.value();
70 }
71 return true;
72}
73
75 uint32_t pm;
76 switch (this->power_save_) {
78 pm = CYW43_PERFORMANCE_PM;
79 break;
81 pm = CYW43_DEFAULT_PM;
82 break;
84 pm = CYW43_AGGRESSIVE_PM;
85 break;
86 }
87 int ret = cyw43_wifi_pm(&cyw43_state, pm);
88 bool success = ret == 0;
89#ifdef USE_WIFI_POWER_SAVE_LISTENERS
90 if (success) {
91 for (auto *listener : this->power_save_listeners_) {
92 listener->on_wifi_power_save(this->power_save_);
93 }
94 }
95#endif
96 return success;
97}
98
99// TODO: The driver doesn't seem to have an API for this
100bool WiFiComponent::wifi_apply_output_power_(float output_power) { return true; }
101
102bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
103#ifdef USE_WIFI_MANUAL_IP
104 if (!this->wifi_sta_ip_config_(ap.get_manual_ip()))
105 return false;
106#else
107 if (!this->wifi_sta_ip_config_({}))
108 return false;
109#endif
110
111 // Use beginNoBlock to avoid WiFi.begin()'s additional 2x timeout wait loop on top of
112 // CYW43::begin()'s internal blocking join. CYW43::begin() blocks for up to 10 seconds
113 // (default timeout) to complete the join - this is required because the LwipIntfDev netif
114 // setup depends on begin() succeeding. beginNoBlock() skips the outer wait loop, saving
115 // up to 20 additional seconds of blocking per attempt.
116 auto ret = WiFi.beginNoBlock(ap.ssid_.c_str(), ap.password_.c_str());
117 return ret != WL_IDLE_STATUS;
118}
119
120bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
121
122bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
123 if (!manual_ip.has_value()) {
124 return true;
125 }
126
127 IPAddress ip_address = manual_ip->static_ip;
128 IPAddress gateway = manual_ip->gateway;
129 IPAddress subnet = manual_ip->subnet;
130
131 IPAddress dns = manual_ip->dns1;
132
133 WiFi.config(ip_address, dns, gateway, subnet);
134 return true;
135}
136
138 WiFi.setHostname(App.get_name().c_str());
139 return true;
140}
141const char *get_auth_mode_str(uint8_t mode) {
142 // TODO:
143 return "UNKNOWN";
144}
145const char *get_disconnect_reason_str(uint8_t reason) {
146 // TODO:
147 return "UNKNOWN";
148}
149
151 // Use cyw43_wifi_link_status instead of cyw43_tcpip_link_status because the Arduino
152 // framework's __wrap_cyw43_cb_tcpip_init is a no-op — the SDK's internal netif
153 // (cyw43_state.netif[]) is never initialized. cyw43_tcpip_link_status checks that netif's
154 // flags and would only fall through to cyw43_wifi_link_status when the flags aren't set.
155 // Using cyw43_wifi_link_status directly gives us the actual WiFi radio join state.
156 int status = cyw43_wifi_link_status(&cyw43_state, CYW43_ITF_STA);
157 switch (status) {
158 case CYW43_LINK_JOIN:
159 // WiFi joined, check if STA has an IP address via wifi_sta_connected()
160 if (wifi_sta_connected()) {
162 }
164 case CYW43_LINK_FAIL:
165 case CYW43_LINK_BADAUTH:
167 case CYW43_LINK_NONET:
169 default:
171 }
172}
173
174int WiFiComponent::s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result) {
176 return 0;
177}
178
179void WiFiComponent::wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result) {
180 s_scan_result_count++;
181
182 // CYW43 scan results have ssid as a 32-byte buffer that is NOT null-terminated.
183 // Use ssid_len to create a properly terminated copy for string operations.
184 uint8_t len = std::min(result->ssid_len, static_cast<uint8_t>(sizeof(result->ssid)));
185 char ssid_buf[33]; // 32 max + null terminator
186 memcpy(ssid_buf, result->ssid, len);
187 ssid_buf[len] = '\0';
188
189 // Skip networks that don't match any configured network (unless full results needed)
190 if (!this->needs_full_scan_results_() && !this->matches_configured_network_(ssid_buf, result->bssid)) {
191 this->log_discarded_scan_result_(ssid_buf, result->bssid, result->rssi, result->channel);
192 return;
193 }
194
195 bssid_t bssid;
196 std::copy(result->bssid, result->bssid + 6, bssid.begin());
197 WiFiScanResult res(bssid, ssid_buf, len, result->channel, result->rssi, result->auth_mode != CYW43_AUTH_OPEN,
198 len == 0);
199 // Compiles to nothing here; kept so every scan_result_ mutation holds the lock
200 ScanResultsLock lock(this);
201 if (std::find(this->scan_result_.begin(), this->scan_result_.end(), res) == this->scan_result_.end()) {
202 this->scan_result_.push_back(res);
203 }
204}
205
206bool WiFiComponent::wifi_scan_start_(bool passive) {
207 // Compiles to nothing here; kept so every scan_result_ mutation holds the lock
208 ScanResultsLock lock(this);
209 this->scan_result_.clear();
210 this->scan_done_ = false;
211 s_scan_result_count = 0;
212 cyw43_wifi_scan_options_t scan_options = {0};
213 scan_options.scan_type = passive ? 1 : 0;
214 int err = cyw43_wifi_scan(&cyw43_state, &scan_options, nullptr, &s_wifi_scan_result);
215 if (err) {
216 ESP_LOGV(TAG, "cyw43_wifi_scan failed");
217 }
218 return err == 0;
219}
220
221#ifdef USE_WIFI_AP
222bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
223 // AP IP is configured by WiFi.beginAP() internally using defaults (192.168.4.1).
224 // Manual AP IP has never worked on RP2040 — WiFi.config() configures the STA
225 // interface, not the AP. This is now rejected at config validation time.
226 return true;
227}
228
229bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
230 if (!this->wifi_mode_({}, true))
231 return false;
232#ifdef USE_WIFI_MANUAL_IP
233 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
234 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
235 return false;
236 }
237#else
238 if (!this->wifi_ap_ip_config_({})) {
239 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
240 return false;
241 }
242#endif
243
244 // Pass nullptr for empty password — CYW43 uses the password pointer (not length)
245 // to choose between OPEN and WPA2 auth mode.
246 const char *ap_password = ap.password_.empty() ? nullptr : ap.password_.c_str();
247 if (WiFi.beginAP(ap.ssid_.c_str(), ap_password, ap.has_channel() ? ap.get_channel() : 1) != WL_CONNECTED) {
248 ESP_LOGW(TAG, "beginAP failed");
249 return false;
250 }
251
252 return true;
253}
254
255network::IPAddress WiFiComponent::wifi_soft_ap_ip() { return {(const ip_addr_t *) WiFi.softAPIP()}; }
256
257#endif // USE_WIFI_AP
258
260 // Use cyw43_wifi_leave() directly instead of WiFi.disconnect().
261 // WiFi.disconnect() sets _wifiHWInitted=false in the Arduino framework. beginAP()
262 // uses _wifiHWInitted to determine AP+STA vs AP-only mode — with it false,
263 // beginAP() enters AP-only mode (IP 192.168.42.1) instead of AP_STA mode
264 // (IP 192.168.4.1). In AP-only mode, _beginInternal() redirects all subsequent
265 // STA connect attempts to beginAP(), creating an infinite loop.
266 cyw43_wifi_leave(&cyw43_state, CYW43_ITF_STA);
267 return true;
268}
269
271 bssid_t bssid{};
272 uint8_t raw_bssid[6];
273 WiFi.BSSID(raw_bssid);
274 for (size_t i = 0; i < bssid.size(); i++)
275 bssid[i] = raw_bssid[i];
276 return bssid;
277}
278const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
279 // TODO: Find direct CYW43 API to avoid Arduino String allocation
280 String ssid = WiFi.SSID();
281 size_t len = std::min(static_cast<size_t>(ssid.length()), SSID_BUFFER_SIZE - 1);
282 memcpy(buffer.data(), ssid.c_str(), len);
283 buffer[len] = '\0';
284 return buffer.data();
285}
286int8_t WiFiComponent::wifi_rssi() { return this->is_connected_() ? WiFi.RSSI() : WIFI_RSSI_DISCONNECTED; }
287int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
288
290 network::IPAddresses addresses;
291 uint8_t index = 0;
292 // Filter out AP interface addresses — addrList includes all lwIP netifs.
293 // The AP netif IP lingers even after the AP radio is disabled.
294 IPAddress ap_ip = WiFi.softAPIP();
295 for (const auto &addr : addrList) {
296 IPAddress ip(addr.ipFromNetifNum());
297 if (ip == ap_ip) {
298 continue;
299 }
300 assert(index < addresses.size());
301 addresses[index++] = ip;
302 }
303 return addresses;
304}
305network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {(const ip_addr_t *) WiFi.subnetMask()}; }
306network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {(const ip_addr_t *) WiFi.gatewayIP()}; }
307network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
308 const ip_addr_t *dns_ip = dns_getserver(num);
309 return network::IPAddress(dns_ip);
310}
311
312// Pico W uses polling for connection state detection.
313// Connect state listener notifications are deferred until after the state machine
314// transitions (in check_connecting_finished) so that conditions like wifi.connected
315// return correct values in automations.
317 // Handle scan completion
318 if (this->state_ == WIFI_COMPONENT_STATE_STA_SCANNING && !cyw43_wifi_scan_active(&cyw43_state)) {
319 this->scan_done_ = true;
320 bool needs_full = this->needs_full_scan_results_();
321 ESP_LOGV(TAG, "Scan complete: %zu found, %zu stored%s", s_scan_result_count, this->scan_result_.size(),
322 needs_full ? "" : " (filtered)");
323#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
325#endif
326 }
327
328 // Poll for connection state changes
329 // The arduino-pico WiFi library doesn't have event callbacks like ESP8266/ESP32,
330 // so we need to poll the link status to detect state changes.
331 bool is_connected = wifi_sta_connected();
332
333 // Detect connection state change
334 if (is_connected && !s_sta_was_connected) {
335 // Just connected
336 s_sta_was_connected = true;
337 ESP_LOGV(TAG, "Connected");
338#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
339 // Defer listener notification until state machine reaches STA_CONNECTED
340 // This ensures wifi.connected condition returns true in listener automations
341 this->pending_.connect_state = true;
342#endif
343 // For static IP configurations, notify IP listeners immediately as the IP is already configured
344#if defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
345 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_manual_ip().has_value()) {
346 s_sta_had_ip = true;
348 }
349#endif
350 } else if (!is_connected && s_sta_was_connected) {
351 // Just disconnected
352 s_sta_was_connected = false;
353 s_sta_had_ip = false;
354 ESP_LOGV(TAG, "Disconnected");
355 // Refresh is_connected() cache; driver link status reports disconnected.
357#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
359#endif
360 }
361
362 // Detect IP address changes (only when connected)
363 if (is_connected) {
364 // Check for any IP address (IPv4 or IPv6). The iterator comparison
365 // operators take non-const references, so the temporaries need names.
366 auto addr_it = addrList.begin();
367 auto addr_end = addrList.end();
368 bool has_ip = addr_it != addr_end;
369
370 if (has_ip && !s_sta_had_ip) {
371 // Just got IP address
372 s_sta_had_ip = true;
373 ESP_LOGV(TAG, "Got IP address");
374#ifdef USE_WIFI_IP_STATE_LISTENERS
376#endif
377 }
378 }
379 return true;
380}
381
383
384} // namespace esphome::wifi
385
386#ifdef USE_WIFI_AP
387// Firmware event ids the driver header leaves out
388static constexpr uint32_t AP_STATION_ASSOC_IND = 8;
389
390// The driver hands every firmware event to cyw43_cb_process_async_event and ignores the AP station
391// ones, so they are counted here before it sees them. Runs in the driver's context. Verified with
392// arduino-pico 6.1.1 on a Pico 2W: a join gives AUTH_IND then ASSOC_IND, a leave gives DISASSOC_IND.
393// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
394// Names are mandated by the --wrap linker mechanism.
395extern "C" void __real_cyw43_cb_process_async_event(void *cb_data, const cyw43_async_event_t *ev);
396extern "C" void __wrap_cyw43_cb_process_async_event(void *cb_data, const cyw43_async_event_t *ev) {
397 if (ev->interface == CYW43_ITF_AP) {
398 switch (ev->event_type) {
399 case AP_STATION_ASSOC_IND:
400 // A refused association carries its status here and has no leave event to balance it. A
401 // reassociation comes from a station that is already counted, whether or not its leave was seen.
402 if (ev->status == CYW43_STATUS_SUCCESS)
404 break;
405 case CYW43_EV_DISASSOC_IND:
406 case CYW43_EV_DEAUTH_IND:
407 if (esphome::wifi::global_wifi_component->ap_clients_ > 0)
409 break;
410 }
411 }
413}
414// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
415#endif // USE_WIFI_AP
416#endif
417#endif
BedjetMode mode
BedJet operating mode.
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
constexpr const char * c_str() const
Definition string_ref.h:78
Guards WiFiComponent::scan_result_.
const optional< ManualIP > & get_manual_ip() const
void notify_scan_results_listeners_()
Notify scan results listeners with current scan results.
const WiFiAP * get_selected_sta_() const
WiFiSTAConnectStatus wifi_sta_connect_status_() const
wifi_scan_vector_t< WiFiScanResult > scan_result_
void wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result)
void notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
bool wifi_sta_ip_config_(const optional< ManualIP > &manual_ip)
static int s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result)
void notify_disconnect_state_listeners_()
Notify connect state listeners of disconnection.
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.
network::IPAddress wifi_dns_ip_(int num)
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_
bool wifi_ap_ip_config_(const optional< ManualIP > &manual_ip)
bool needs_full_scan_results_() const
Check if full scan results are needed (captive portal active, improv, listeners)
StaticVector< WiFiPowerSaveListener *, ESPHOME_WIFI_POWER_SAVE_LISTENERS > power_save_listeners_
bool wifi_apply_output_power_(float output_power)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
network::IPAddresses wifi_sta_ip_addresses()
uint32_t buffer
Definition gif.cpp:50
int ret
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:369
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
ESPHOME_LOG_TAG(TAG, "wifi")
const LogString * get_disconnect_reason_str(uint8_t reason)
WiFiComponent * global_wifi_component
@ WIFI_COMPONENT_STATE_STA_SCANNING
WiFi is in STA-only mode and currently scanning for APs.
const void size_t len
Definition hal.h:68
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
SemaphoreHandle_t lock
void __wrap_cyw43_cb_process_async_event(void *cb_data, const cyw43_async_event_t *ev)
void __real_cyw43_cb_process_async_event(void *cb_data, const cyw43_async_event_t *ev)