ESPHome 2026.8.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
21static const char *const 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 cyw43_wifi_set_up(&cyw43_state, CYW43_ITF_AP, false, CYW43_COUNTRY_WORLDWIDE);
63 }
64 this->ap_started_ = ap.value();
65 }
66 return true;
67}
68
70 uint32_t pm;
71 switch (this->power_save_) {
73 pm = CYW43_PERFORMANCE_PM;
74 break;
76 pm = CYW43_DEFAULT_PM;
77 break;
79 pm = CYW43_AGGRESSIVE_PM;
80 break;
81 }
82 int ret = cyw43_wifi_pm(&cyw43_state, pm);
83 bool success = ret == 0;
84#ifdef USE_WIFI_POWER_SAVE_LISTENERS
85 if (success) {
86 for (auto *listener : this->power_save_listeners_) {
87 listener->on_wifi_power_save(this->power_save_);
88 }
89 }
90#endif
91 return success;
92}
93
94// TODO: The driver doesn't seem to have an API for this
95bool WiFiComponent::wifi_apply_output_power_(float output_power) { return true; }
96
97bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
98#ifdef USE_WIFI_MANUAL_IP
99 if (!this->wifi_sta_ip_config_(ap.get_manual_ip()))
100 return false;
101#else
102 if (!this->wifi_sta_ip_config_({}))
103 return false;
104#endif
105
106 // Use beginNoBlock to avoid WiFi.begin()'s additional 2x timeout wait loop on top of
107 // CYW43::begin()'s internal blocking join. CYW43::begin() blocks for up to 10 seconds
108 // (default timeout) to complete the join - this is required because the LwipIntfDev netif
109 // setup depends on begin() succeeding. beginNoBlock() skips the outer wait loop, saving
110 // up to 20 additional seconds of blocking per attempt.
111 auto ret = WiFi.beginNoBlock(ap.ssid_.c_str(), ap.password_.c_str());
112 return ret != WL_IDLE_STATUS;
113}
114
115bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
116
117bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
118 if (!manual_ip.has_value()) {
119 return true;
120 }
121
122 IPAddress ip_address = manual_ip->static_ip;
123 IPAddress gateway = manual_ip->gateway;
124 IPAddress subnet = manual_ip->subnet;
125
126 IPAddress dns = manual_ip->dns1;
127
128 WiFi.config(ip_address, dns, gateway, subnet);
129 return true;
130}
131
133 WiFi.setHostname(App.get_name().c_str());
134 return true;
135}
136const char *get_auth_mode_str(uint8_t mode) {
137 // TODO:
138 return "UNKNOWN";
139}
140const char *get_disconnect_reason_str(uint8_t reason) {
141 // TODO:
142 return "UNKNOWN";
143}
144
146 // Use cyw43_wifi_link_status instead of cyw43_tcpip_link_status because the Arduino
147 // framework's __wrap_cyw43_cb_tcpip_init is a no-op — the SDK's internal netif
148 // (cyw43_state.netif[]) is never initialized. cyw43_tcpip_link_status checks that netif's
149 // flags and would only fall through to cyw43_wifi_link_status when the flags aren't set.
150 // Using cyw43_wifi_link_status directly gives us the actual WiFi radio join state.
151 int status = cyw43_wifi_link_status(&cyw43_state, CYW43_ITF_STA);
152 switch (status) {
153 case CYW43_LINK_JOIN:
154 // WiFi joined, check if STA has an IP address via wifi_sta_connected()
155 if (wifi_sta_connected()) {
157 }
159 case CYW43_LINK_FAIL:
160 case CYW43_LINK_BADAUTH:
162 case CYW43_LINK_NONET:
164 }
166}
167
168int WiFiComponent::s_wifi_scan_result(void *env, const cyw43_ev_scan_result_t *result) {
170 return 0;
171}
172
173void WiFiComponent::wifi_scan_result_(void *env, const cyw43_ev_scan_result_t *result) {
174 s_scan_result_count++;
175
176 // CYW43 scan results have ssid as a 32-byte buffer that is NOT null-terminated.
177 // Use ssid_len to create a properly terminated copy for string operations.
178 uint8_t len = std::min(result->ssid_len, static_cast<uint8_t>(sizeof(result->ssid)));
179 char ssid_buf[33]; // 32 max + null terminator
180 memcpy(ssid_buf, result->ssid, len);
181 ssid_buf[len] = '\0';
182
183 // Skip networks that don't match any configured network (unless full results needed)
184 if (!this->needs_full_scan_results_() && !this->matches_configured_network_(ssid_buf, result->bssid)) {
185 this->log_discarded_scan_result_(ssid_buf, result->bssid, result->rssi, result->channel);
186 return;
187 }
188
189 bssid_t bssid;
190 std::copy(result->bssid, result->bssid + 6, bssid.begin());
191 WiFiScanResult res(bssid, ssid_buf, len, result->channel, result->rssi, result->auth_mode != CYW43_AUTH_OPEN,
192 len == 0);
193 if (std::find(this->scan_result_.begin(), this->scan_result_.end(), res) == this->scan_result_.end()) {
194 this->scan_result_.push_back(res);
195 }
196}
197
198bool WiFiComponent::wifi_scan_start_(bool passive) {
199 this->scan_result_.clear();
200 this->scan_done_ = false;
201 s_scan_result_count = 0;
202 cyw43_wifi_scan_options_t scan_options = {0};
203 scan_options.scan_type = passive ? 1 : 0;
204 int err = cyw43_wifi_scan(&cyw43_state, &scan_options, nullptr, &s_wifi_scan_result);
205 if (err) {
206 ESP_LOGV(TAG, "cyw43_wifi_scan failed");
207 }
208 return err == 0;
209}
210
211#ifdef USE_WIFI_AP
212bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
213 // AP IP is configured by WiFi.beginAP() internally using defaults (192.168.4.1).
214 // Manual AP IP has never worked on RP2040 — WiFi.config() configures the STA
215 // interface, not the AP. This is now rejected at config validation time.
216 return true;
217}
218
219bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
220 if (!this->wifi_mode_({}, true))
221 return false;
222#ifdef USE_WIFI_MANUAL_IP
223 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
224 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
225 return false;
226 }
227#else
228 if (!this->wifi_ap_ip_config_({})) {
229 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
230 return false;
231 }
232#endif
233
234 // Pass nullptr for empty password — CYW43 uses the password pointer (not length)
235 // to choose between OPEN and WPA2 auth mode.
236 const char *ap_password = ap.password_.empty() ? nullptr : ap.password_.c_str();
237 WiFi.beginAP(ap.ssid_.c_str(), ap_password, ap.has_channel() ? ap.get_channel() : 1);
238
239 return true;
240}
241
242network::IPAddress WiFiComponent::wifi_soft_ap_ip() { return {(const ip_addr_t *) WiFi.softAPIP()}; }
243#endif // USE_WIFI_AP
244
246 // Use cyw43_wifi_leave() directly instead of WiFi.disconnect().
247 // WiFi.disconnect() sets _wifiHWInitted=false in the Arduino framework. beginAP()
248 // uses _wifiHWInitted to determine AP+STA vs AP-only mode — with it false,
249 // beginAP() enters AP-only mode (IP 192.168.42.1) instead of AP_STA mode
250 // (IP 192.168.4.1). In AP-only mode, _beginInternal() redirects all subsequent
251 // STA connect attempts to beginAP(), creating an infinite loop.
252 cyw43_wifi_leave(&cyw43_state, CYW43_ITF_STA);
253 return true;
254}
255
257 bssid_t bssid{};
258 uint8_t raw_bssid[6];
259 WiFi.BSSID(raw_bssid);
260 for (size_t i = 0; i < bssid.size(); i++)
261 bssid[i] = raw_bssid[i];
262 return bssid;
263}
264std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
265const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
266 // TODO: Find direct CYW43 API to avoid Arduino String allocation
267 String ssid = WiFi.SSID();
268 size_t len = std::min(static_cast<size_t>(ssid.length()), SSID_BUFFER_SIZE - 1);
269 memcpy(buffer.data(), ssid.c_str(), len);
270 buffer[len] = '\0';
271 return buffer.data();
272}
273int8_t WiFiComponent::wifi_rssi() { return this->is_connected_() ? WiFi.RSSI() : WIFI_RSSI_DISCONNECTED; }
274int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
275
277 network::IPAddresses addresses;
278 uint8_t index = 0;
279 // Filter out AP interface addresses — addrList includes all lwIP netifs.
280 // The AP netif IP lingers even after the AP radio is disabled.
281 IPAddress ap_ip = WiFi.softAPIP();
282 for (const auto &addr : addrList) {
283 IPAddress ip(addr.ipFromNetifNum());
284 if (ip == ap_ip) {
285 continue;
286 }
287 assert(index < addresses.size());
288 addresses[index++] = ip;
289 }
290 return addresses;
291}
292network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {(const ip_addr_t *) WiFi.subnetMask()}; }
293network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {(const ip_addr_t *) WiFi.gatewayIP()}; }
294network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
295 const ip_addr_t *dns_ip = dns_getserver(num);
296 return network::IPAddress(dns_ip);
297}
298
299// Pico W uses polling for connection state detection.
300// Connect state listener notifications are deferred until after the state machine
301// transitions (in check_connecting_finished) so that conditions like wifi.connected
302// return correct values in automations.
304 // Handle scan completion
305 if (this->state_ == WIFI_COMPONENT_STATE_STA_SCANNING && !cyw43_wifi_scan_active(&cyw43_state)) {
306 this->scan_done_ = true;
307 bool needs_full = this->needs_full_scan_results_();
308 ESP_LOGV(TAG, "Scan complete: %zu found, %zu stored%s", s_scan_result_count, this->scan_result_.size(),
309 needs_full ? "" : " (filtered)");
310#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
312#endif
313 }
314
315 // Poll for connection state changes
316 // The arduino-pico WiFi library doesn't have event callbacks like ESP8266/ESP32,
317 // so we need to poll the link status to detect state changes.
318 bool is_connected = wifi_sta_connected();
319
320 // Detect connection state change
321 if (is_connected && !s_sta_was_connected) {
322 // Just connected
323 s_sta_was_connected = true;
324 ESP_LOGV(TAG, "Connected");
325#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
326 // Defer listener notification until state machine reaches STA_CONNECTED
327 // This ensures wifi.connected condition returns true in listener automations
328 this->pending_.connect_state = true;
329#endif
330 // For static IP configurations, notify IP listeners immediately as the IP is already configured
331#if defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
332 if (const WiFiAP *config = this->get_selected_sta_(); config && config->get_manual_ip().has_value()) {
333 s_sta_had_ip = true;
335 }
336#endif
337 } else if (!is_connected && s_sta_was_connected) {
338 // Just disconnected
339 s_sta_was_connected = false;
340 s_sta_had_ip = false;
341 ESP_LOGV(TAG, "Disconnected");
342 // Refresh is_connected() cache; driver link status reports disconnected.
344#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
346#endif
347 }
348
349 // Detect IP address changes (only when connected)
350 if (is_connected) {
351 // Check for any IP address (IPv4 or IPv6). The iterator comparison
352 // operators take non-const references, so the temporaries need names.
353 auto addr_it = addrList.begin();
354 auto addr_end = addrList.end();
355 bool has_ip = addr_it != addr_end;
356
357 if (has_ip && !s_sta_had_ip) {
358 // Just got IP address
359 s_sta_had_ip = true;
360 ESP_LOGV(TAG, "Got IP address");
361#ifdef USE_WIFI_IP_STATE_LISTENERS
363#endif
364 }
365 }
366 return true;
367}
368
370
371} // namespace esphome::wifi
372#endif
373#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:73
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)
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.
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...
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()
struct esphome::wifi::WiFiComponent::@193 pending_
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:299
const char *const TAG
Definition spi.cpp:7
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
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:64
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t