ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
wifi_component_libretiny.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2
3#ifdef USE_WIFI
4#ifdef USE_LIBRETINY
5
6#include <cinttypes>
7#include <utility>
8#include <algorithm>
9#include "lwip/ip_addr.h"
10#include "lwip/err.h"
11#include "lwip/dns.h"
12
13#ifdef USE_BK72XX
14extern "C" {
15// BDK 3.0.78 (required for BK7238) redeclares wifi_event_sta_disconnected_t,
16// which LibreTiny's Arduino WiFi API already defines. ESPHome doesn't use the
17// BDK version, so rename it across this include to avoid the collision.
18#define wifi_event_sta_disconnected_t bdk_wifi_event_sta_disconnected_t
19#include <wlan_ui_pub.h>
20#undef wifi_event_sta_disconnected_t
21}
22#endif
23
24#ifdef USE_RTL87XX
25extern "C" {
26#include <wifi_conf.h>
27#include <wifi_structures.h>
28#include <wifi_util.h>
29}
30#endif
31
32#ifdef USE_LN882X
33#include <WiFiPrivate.h>
34#undef DATA // clashes with setup_priority::DATA
35// LibreTiny 1.13's LN882H reconnect() gives the SDK a NULL bssid; pass on the requested one. Remove once it passes
36// info.bssid. Safe without a BSSID: begin() frees sta.bssid (resetNetworkInfo), so it stays NULL.
37// NOLINTBEGIN(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
38// Names are mandated by the --wrap linker mechanism.
39extern "C" int __real_wifi_sta_connect(wifi_sta_connect_t *connect, wifi_scan_cfg_t *scan_cfg);
40extern "C" int __wrap_wifi_sta_connect(wifi_sta_connect_t *connect, wifi_scan_cfg_t *scan_cfg) {
41 if (connect->bssid == nullptr)
42 connect->bssid = static_cast<WiFiData *>(WiFi.data)->sta.bssid;
43 return __real_wifi_sta_connect(connect, scan_cfg);
44}
45// NOLINTEND(bugprone-reserved-identifier,cert-dcl37-c,cert-dcl51-cpp,readability-identifier-naming)
46#endif
47
49#include "esphome/core/hal.h"
51#include "esphome/core/log.h"
53#include "esphome/core/util.h"
54
55namespace esphome::wifi {
56
57ESPHOME_LOG_TAG(TAG, "wifi_lt");
58
59#ifdef USE_RTL87XX
60// rtw_connect_error_flag_t, in order, as wifi_get_last_error() returns it
61PROGMEM_STRING_TABLE(JoinErrorStrings, "none", "network not found", "connect failed",
62 "handshake failed (wrong password?)", "4-way handshake timeout", "DHCP failed", "auth failed",
63 "assoc failed", "deauthenticated", "unknown");
64#endif
65
66// Thread-safe event handling for LibreTiny WiFi
67//
68// LibreTiny's WiFi.onEvent() callback runs in the WiFi driver's thread context,
69// not the main ESPHome loop. Without synchronization, modifying shared state
70// (like connection status flags) from the callback causes race conditions:
71// - The main loop may never see state changes (values cached in registers)
72// - State changes may be visible in inconsistent order
73//
74// Solution: Queue events in the callback and process them in the main loop.
75// This is the same approach used by ESP32 IDF's wifi_process_event_().
76// All state modifications happen in the main loop context, eliminating races.
77//
78// On platforms with hardware atomics (RTL87xx, LN882x): LockFreeQueue (SPSC ring buffer)
79// On platforms without (BK72xx): FreeRTOSQueue (xQueue wrapper with critical sections)
80
81// Event structure for queued WiFi events - contains a copy of event data
82// to avoid lifetime issues with the original event data from the callback
83struct LTWiFiEvent {
84 arduino_event_id_t event_id;
85 union {
86 struct {
87 uint8_t ssid[33];
88 uint8_t ssid_len;
89 uint8_t bssid[6];
90 uint8_t channel;
91 uint8_t authmode;
92 } sta_connected;
93 struct {
94 uint8_t ssid[33];
95 uint8_t ssid_len;
96 uint8_t bssid[6];
97 uint8_t reason;
98 } sta_disconnected;
99 struct {
100 uint8_t old_mode;
101 uint8_t new_mode;
102 } sta_authmode_change;
103 struct {
104 uint32_t status;
105 uint8_t number;
106 uint8_t scan_id;
107 } scan_done;
108 struct {
109 uint8_t mac[MAC_ADDRESS_SIZE];
110 int rssi;
111 } ap_probe_req;
112 } data;
113};
114
115// Connection state machine - only modified from main loop after queue processing
116enum class LTWiFiSTAState : uint8_t {
117 IDLE, // Not connecting
118 CONNECTING, // Connection in progress
119 CONNECTED, // Successfully connected with IP
120 ERROR_NOT_FOUND, // AP not found (probe failed)
121 ERROR_FAILED, // Connection failed (auth, timeout, etc.)
122};
123
124// Count of ignored disconnect events during connection - too many indicates real failure
125static uint8_t s_ignored_disconnect_count = 0; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
126// Threshold for ignored disconnect events before treating as connection failure
127// LibreTiny sends spurious "Association Leave" events, but more than this many
128// indicates the connection is failing repeatedly. Value of 3 balances fast failure
129// detection with tolerance for occasional spurious events on successful connections.
130static constexpr uint8_t IGNORED_DISCONNECT_THRESHOLD = 3;
131
132bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
133 uint8_t current_mode = WiFi.getMode();
134 bool current_sta = current_mode & 0b01;
135 bool current_ap = current_mode & 0b10;
136 bool enable_sta = sta.value_or(current_sta);
137 bool enable_ap = ap.value_or(current_ap);
138 if (current_sta == enable_sta && current_ap == enable_ap)
139 return true;
140
141 if (enable_sta && !current_sta) {
142 ESP_LOGV(TAG, "Enabling STA");
143 // Fresh STA stack: skip the pre-attempt teardown again.
144 this->lt_first_connect_attempt_ = true;
145 } else if (!enable_sta && current_sta) {
146 ESP_LOGV(TAG, "Disabling STA");
147 }
148 if (enable_ap && !current_ap) {
149 ESP_LOGV(TAG, "Enabling AP");
150 } else if (!enable_ap && current_ap) {
151 ESP_LOGV(TAG, "Disabling AP");
152 }
153
154 uint8_t mode = 0;
155 if (enable_sta)
156 mode |= 0b01;
157 if (enable_ap)
158 mode |= 0b10;
159 bool ret = WiFi.mode(static_cast<wifi_mode_t>(mode));
160
161 if (!ret) {
162 ESP_LOGW(TAG, "Setting mode failed");
163 return false;
164 }
165
166 this->ap_started_ = enable_ap;
167
168 return ret;
169}
170bool WiFiComponent::wifi_apply_output_power_(float output_power) {
171 int8_t val = static_cast<int8_t>(output_power * 4);
172 return WiFi.setTxPower(val);
173}
175 if (!this->wifi_mode_(true, {}))
176 return false;
177
178 WiFi.setAutoReconnect(false);
179 delay(10);
180 return true;
181}
183 bool success = WiFi.setSleep(this->power_save_ != WIFI_POWER_SAVE_NONE);
184#ifdef USE_WIFI_POWER_SAVE_LISTENERS
185 if (success) {
186 for (auto *listener : this->power_save_listeners_) {
187 listener->on_wifi_power_save(this->power_save_);
188 }
189 }
190#endif
191 return success;
192}
193bool WiFiComponent::wifi_sta_ip_config_(const optional<ManualIP> &manual_ip) {
194 // enable STA
195 if (!this->wifi_mode_(true, {}))
196 return false;
197
198 if (!manual_ip.has_value()) {
199 return true;
200 }
201
202 WiFi.config(manual_ip->static_ip, manual_ip->gateway, manual_ip->subnet, manual_ip->dns1, manual_ip->dns2);
203
204 return true;
205}
206
208 if (!this->has_sta())
209 return {};
210 network::IPAddresses addresses;
211 addresses[0] = WiFi.localIP();
212#if USE_NETWORK_IPV6
213 int i = 1;
214 auto v6_addresses = WiFi.allLocalIPv6();
215 for (auto address : v6_addresses) {
216 addresses[i++] = network::IPAddress(address.toString().c_str());
217 }
218#endif /* USE_NETWORK_IPV6 */
219 return addresses;
220}
221
223 // setting is done in SYSTEM_EVENT_STA_START callback too
224 WiFi.setHostname(App.get_name().c_str());
225 return true;
226}
227bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
228 // enable STA
229 if (!this->wifi_mode_(true, {}))
230 return false;
231
232 // Tear down any live session so begin() re-fires its events; skipped on the
233 // first attempt after STA-up (nothing to tear down, and BK7231N on the older
234 // Beken SDK did not come back from it). The flag is per-attempt and armed
235 // only for a live session: an idle disconnect may emit no event, and a stale
236 // flag would swallow this attempt's first real failure.
237 this->lt_teardown_event_pending_ = false;
238 if (!this->lt_first_connect_attempt_) {
239 const bool was_live = WiFi.status() == WL_CONNECTED;
240 if (WiFi.disconnect()) {
241 this->lt_teardown_event_pending_ = was_live;
242 } else {
243 ESP_LOGD(TAG, "Pre-connect teardown returned false");
244 }
245 }
246 this->lt_first_connect_attempt_ = false;
247
248#ifdef USE_WIFI_MANUAL_IP
249 if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
250 return false;
251 }
252#else
253 if (!this->wifi_sta_ip_config_({})) {
254 return false;
255 }
256#endif
257
258 this->wifi_apply_hostname_();
259
260 // Reset state machine and disconnect counter before connecting
261 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::CONNECTING);
262 s_ignored_disconnect_count = 0;
263
264 uint8_t channel = ap.get_channel(); // 0 = auto
265#ifdef USE_RTL87XX
266 // Given a channel and a BSSID, LibreTiny narrows the driver's scan list to the channel for the join, then leaves it
267 // disabled, so the next scan finds nothing. Narrow it here and pass no channel (LibreTiny ignores a channel without
268 // a BSSID); the join's own scan restores the full list when it ends. The placeholder SSID starts that scan, as
269 // LibreTiny's does; narrowed before it, the scan can miss the beacon.
270 if (channel != 0 && ap.has_bssid()) {
271 wext_set_ssid(WLAN0_NAME, reinterpret_cast<const uint8_t *>("-"), 1);
272 uint8_t pscan_config = PSCAN_ENABLE | PSCAN_FAST_SURVEY;
273 wifi_set_pscan_chan(&channel, &pscan_config, 1);
274 }
275 channel = 0;
276#endif
277 WiFiStatus status;
278 {
279 // The driver blocks until the join has started, or finished on Realtek
280 UnavoidableBlockingScope scope;
281 status = WiFi.begin(ap.ssid_.c_str(), ap.password_.empty() ? NULL : ap.password_.c_str(), channel,
282 ap.has_bssid() ? ap.get_bssid().data() : NULL);
283 }
284 if (status != WL_CONNECTED) {
285#ifdef USE_RTL87XX
286 ESP_LOGW(TAG, "WiFi.begin failed: %d (%s)", status,
287 LOG_STR_ARG(JoinErrorStrings::get_log_str(wifi_get_last_error(), JoinErrorStrings::LAST_INDEX)));
288#else
289 ESP_LOGW(TAG, "WiFi.begin failed: %d", status);
290#endif
291 // Without this reset the state machine stays at CONNECTING and each retry
292 // stalls for the full connect timeout (46 s).
293 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::ERROR_FAILED);
294 return false;
295 }
296
297 return true;
298}
299const char *get_auth_mode_str(uint8_t mode) {
300 switch (mode) {
301 case WIFI_AUTH_OPEN:
302 return "OPEN";
303 case WIFI_AUTH_WEP:
304 return "WEP";
305 case WIFI_AUTH_WPA_PSK:
306 return "WPA PSK";
307 case WIFI_AUTH_WPA2_PSK:
308 return "WPA2 PSK";
309 case WIFI_AUTH_WPA_WPA2_PSK:
310 return "WPA/WPA2 PSK";
311 default:
312 return "UNKNOWN";
313 }
314}
315
316const char *get_op_mode_str(uint8_t mode) {
317 switch (mode) {
318 case WIFI_OFF:
319 return "OFF";
320 case WIFI_STA:
321 return "STA";
322 case WIFI_AP:
323 return "AP";
324 case WIFI_AP_STA:
325 return "AP+STA";
326 default:
327 return "UNKNOWN";
328 }
329}
330const char *get_disconnect_reason_str(uint8_t reason) {
331 switch (reason) {
332 case WIFI_REASON_AUTH_EXPIRE:
333 return "Auth Expired";
334 case WIFI_REASON_AUTH_LEAVE:
335 return "Auth Leave";
336 case WIFI_REASON_ASSOC_EXPIRE:
337 return "Association Expired";
338 case WIFI_REASON_ASSOC_TOOMANY:
339 return "Too Many Associations";
340 case WIFI_REASON_NOT_AUTHED:
341 return "Not Authenticated";
342 case WIFI_REASON_NOT_ASSOCED:
343 return "Not Associated";
344 case WIFI_REASON_ASSOC_LEAVE:
345 return "Association Leave";
346 case WIFI_REASON_ASSOC_NOT_AUTHED:
347 return "Association not Authenticated";
348 case WIFI_REASON_DISASSOC_PWRCAP_BAD:
349 return "Disassociate Power Cap Bad";
350 case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
351 return "Disassociate Supported Channel Bad";
352 case WIFI_REASON_IE_INVALID:
353 return "IE Invalid";
354 case WIFI_REASON_MIC_FAILURE:
355 return "Mic Failure";
356 case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
357 return "4-Way Handshake Timeout";
358 case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
359 return "Group Key Update Timeout";
360 case WIFI_REASON_IE_IN_4WAY_DIFFERS:
361 return "IE In 4-Way Handshake Differs";
362 case WIFI_REASON_GROUP_CIPHER_INVALID:
363 return "Group Cipher Invalid";
364 case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
365 return "Pairwise Cipher Invalid";
366 case WIFI_REASON_AKMP_INVALID:
367 return "AKMP Invalid";
368 case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
369 return "Unsupported RSN IE version";
370 case WIFI_REASON_INVALID_RSN_IE_CAP:
371 return "Invalid RSN IE Cap";
372 case WIFI_REASON_802_1X_AUTH_FAILED:
373 return "802.1x Authentication Failed";
374 case WIFI_REASON_CIPHER_SUITE_REJECTED:
375 return "Cipher Suite Rejected";
376 case WIFI_REASON_BEACON_TIMEOUT:
377 return "Beacon Timeout";
378 case WIFI_REASON_NO_AP_FOUND:
379 return "AP Not Found";
380 case WIFI_REASON_AUTH_FAIL:
381 return "Authentication Failed";
382 case WIFI_REASON_ASSOC_FAIL:
383 return "Association Failed";
384 case WIFI_REASON_HANDSHAKE_TIMEOUT:
385 return "Handshake Failed";
386 case WIFI_REASON_CONNECTION_FAIL:
387 return "Connection Failed";
388 case WIFI_REASON_UNSPECIFIED:
389 default:
390 return "Unspecified";
391 }
392}
393
394#define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY
395#define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE
396#define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START
397#define ESPHOME_EVENT_ID_WIFI_STA_STOP ARDUINO_EVENT_WIFI_STA_STOP
398#define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED
399#define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED
400#define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE
401#define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP
402#define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6 ARDUINO_EVENT_WIFI_STA_GOT_IP6
403#define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP ARDUINO_EVENT_WIFI_STA_LOST_IP
404#define ESPHOME_EVENT_ID_WIFI_AP_START ARDUINO_EVENT_WIFI_AP_START
405#define ESPHOME_EVENT_ID_WIFI_AP_STOP ARDUINO_EVENT_WIFI_AP_STOP
406#define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED
407#define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED ARDUINO_EVENT_WIFI_AP_STADISCONNECTED
408#define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED
409#define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED
410#define ESPHOME_EVENT_ID_WIFI_AP_GOT_IP6 ARDUINO_EVENT_WIFI_AP_GOT_IP6
411using esphome_wifi_event_id_t = arduino_event_id_t;
412using esphome_wifi_event_info_t = arduino_event_info_t;
413
414// Event callback - runs in WiFi driver thread context
415// Only queues events for processing in main loop, no logging or state changes here
417 // Allocate on heap and fill directly to avoid extra memcpy
418 auto *to_send = new LTWiFiEvent{}; // NOLINT(cppcoreguidelines-owning-memory)
419 to_send->event_id = event;
420
421 // Copy event-specific data
422 switch (event) {
423 case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
424 auto &it = info.wifi_sta_connected;
425 to_send->data.sta_connected.ssid_len = it.ssid_len;
426 memcpy(to_send->data.sta_connected.ssid, it.ssid,
427 std::min(static_cast<size_t>(it.ssid_len), sizeof(to_send->data.sta_connected.ssid) - 1));
428 memcpy(to_send->data.sta_connected.bssid, it.bssid, 6);
429 to_send->data.sta_connected.channel = it.channel;
430 to_send->data.sta_connected.authmode = it.authmode;
431 break;
432 }
433 case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
434 auto &it = info.wifi_sta_disconnected;
435 to_send->data.sta_disconnected.ssid_len = it.ssid_len;
436 memcpy(to_send->data.sta_disconnected.ssid, it.ssid,
437 std::min(static_cast<size_t>(it.ssid_len), sizeof(to_send->data.sta_disconnected.ssid) - 1));
438 memcpy(to_send->data.sta_disconnected.bssid, it.bssid, 6);
439 to_send->data.sta_disconnected.reason = it.reason;
440 break;
441 }
442 case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
443 auto &it = info.wifi_sta_authmode_change;
444 to_send->data.sta_authmode_change.old_mode = it.old_mode;
445 to_send->data.sta_authmode_change.new_mode = it.new_mode;
446 break;
447 }
448 case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
449 auto &it = info.wifi_scan_done;
450 to_send->data.scan_done.status = it.status;
451 to_send->data.scan_done.number = it.number;
452 to_send->data.scan_done.scan_id = it.scan_id;
453 break;
454 }
455 case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
456 auto &it = info.wifi_ap_probereqrecved;
457 memcpy(to_send->data.ap_probe_req.mac, it.mac, MAC_ADDRESS_SIZE);
458 to_send->data.ap_probe_req.rssi = it.rssi;
459 break;
460 }
461 case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
462 auto &it = info.wifi_sta_connected;
463 memcpy(to_send->data.sta_connected.bssid, it.bssid, 6);
464 break;
465 }
466 case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
467 auto &it = info.wifi_sta_disconnected;
468 memcpy(to_send->data.sta_disconnected.bssid, it.bssid, 6);
469 break;
470 }
471 case ESPHOME_EVENT_ID_WIFI_READY:
472 case ESPHOME_EVENT_ID_WIFI_STA_START:
473 case ESPHOME_EVENT_ID_WIFI_STA_STOP:
474 case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP:
475 case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6:
476 case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP:
477 case ESPHOME_EVENT_ID_WIFI_AP_START:
478 case ESPHOME_EVENT_ID_WIFI_AP_STOP:
479 case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED:
480 // No additional data needed
481 break;
482 default:
483 // Unknown event, don't queue
484 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
485 return;
486 }
487
488 // Queue event (don't block if queue is full)
489 if (!this->event_queue_.push(to_send)) {
490 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
491 }
492}
493
494// Process a single event from the queue - runs in main loop context.
495// Listener notifications must be deferred until after the state machine transitions
496// (in check_connecting_finished) so that conditions like wifi.connected return
497// correct values in automations.
498void WiFiComponent::wifi_process_event_(LTWiFiEvent *event) {
499 switch (event->event_id) {
500 case ESPHOME_EVENT_ID_WIFI_READY: {
501 ESP_LOGV(TAG, "Ready");
502 break;
503 }
504 case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
505 auto &it = event->data.scan_done;
506 ESP_LOGV(TAG, "Scan done: status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
507#ifdef USE_RTL87XX
508 // The driver also reports the scan inside each join; taking that one would clear the results the
509 // retry phases are working from, so only a scan this component started counts
511 break;
512#endif
514 break;
515 }
516 case ESPHOME_EVENT_ID_WIFI_STA_START: {
517 ESP_LOGV(TAG, "STA start");
518 WiFi.setHostname(App.get_name().c_str());
519 break;
520 }
521 case ESPHOME_EVENT_ID_WIFI_STA_STOP: {
522 ESP_LOGV(TAG, "STA stop");
523 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::IDLE);
524 break;
525 }
526 case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
527 // Processed in queue order, so a teardown event still ahead of this
528 // CONNECTED was already consumed; a leftover flag is stale.
529 this->lt_teardown_event_pending_ = false;
530 auto &it = event->data.sta_connected;
531 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
532 format_mac_addr_upper(it.bssid, bssid_buf);
533 ESP_LOGV(TAG, "Connected ssid='%.*s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", it.ssid_len,
534 (const char *) it.ssid, bssid_buf, it.channel, get_auth_mode_str(it.authmode));
535 // Note: We don't set CONNECTED state here yet - wait for GOT_IP
536 // This matches ESP32 IDF behavior where s_sta_connected is set but
537 // wifi_sta_connect_status_() also checks got_ipv4_address_
538#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
539 // Defer listener notification until state machine reaches STA_CONNECTED
540 // This ensures wifi.connected condition returns true in listener automations
541 this->pending_.connect_state = true;
542#endif
543 // For static IP configurations, GOT_IP event may not fire, so set connected state here
544#ifdef USE_WIFI_MANUAL_IP
545 if (const WiFiAP *config = this->get_selected_sta_(); config && config->has_manual_ip()) {
546 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::CONNECTED);
547#ifdef USE_WIFI_IP_STATE_LISTENERS
549#endif
550 }
551#endif
552 break;
553 }
554 case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
555 auto &it = event->data.sta_disconnected;
556
557 // Consume the disconnect our own teardown queued, without spending an
558 // ignore slot. Ungated on SSID and state: the flag is armed only for this
559 // attempt's teardown of a live session.
560 if (this->lt_teardown_event_pending_ && it.reason != WIFI_REASON_NO_AP_FOUND) {
561 this->lt_teardown_event_pending_ = false;
562 break;
563 }
564
565 // LibreTiny can send spurious disconnect events with empty ssid/bssid during connection.
566 // These are typically "Association Leave" events that don't indicate actual failures:
567 // [W][wifi_lt]: Disconnected ssid='' bssid=00:00:00:00:00:00 reason='Association Leave'
568 // [W][wifi_lt]: Disconnected ssid='' bssid=00:00:00:00:00:00 reason='Association Leave'
569 // [V][wifi_lt]: Connected ssid='WIFI' bssid=... channel=3, authmode=WPA2 PSK
570 // Without this check, the spurious events would transition state to ERROR_FAILED,
571 // causing wifi_sta_connect_status_() to return an error. The main loop would then
572 // call retry_connect(), aborting a connection that may succeed moments later.
573 // Only ignore benign reasons - real failures like NO_AP_FOUND should still be processed.
574 // However, if we get too many of these events (IGNORED_DISCONNECT_THRESHOLD), treat it
575 // as a real connection failure to avoid waiting the full timeout for a failing connection.
576 if (it.ssid_len == 0 && this->sta_state_ == static_cast<uint8_t>(LTWiFiSTAState::CONNECTING) &&
577 it.reason != WIFI_REASON_NO_AP_FOUND) {
578 s_ignored_disconnect_count++;
579 if (s_ignored_disconnect_count >= IGNORED_DISCONNECT_THRESHOLD) {
580 ESP_LOGW(TAG, "Too many disconnect events (%u) while connecting, treating as failure (reason=%s)",
581 s_ignored_disconnect_count, get_disconnect_reason_str(it.reason));
582 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::ERROR_FAILED);
583 WiFi.disconnect();
584 this->error_from_callback_ = true;
585 // Don't break - fall through to notify listeners
586 } else {
587 ESP_LOGV(TAG, "Ignoring disconnect event with empty ssid while connecting (reason=%s, count=%u)",
588 get_disconnect_reason_str(it.reason), s_ignored_disconnect_count);
589 break;
590 }
591 }
592
593 if (it.reason == WIFI_REASON_NO_AP_FOUND) {
594 ESP_LOGW(TAG, "Disconnected ssid='%.*s' reason='Probe Request Unsuccessful'", it.ssid_len,
595 (const char *) it.ssid);
596 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::ERROR_NOT_FOUND);
597 } else {
598 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
599 format_mac_addr_upper(it.bssid, bssid_s);
600 ESP_LOGW(TAG, "Disconnected ssid='%.*s' bssid=" LOG_SECRET("%s") " reason='%s'", it.ssid_len,
601 (const char *) it.ssid, bssid_s, get_disconnect_reason_str(it.reason));
602 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::ERROR_FAILED);
603 }
604
605 uint8_t reason = it.reason;
606 if (reason == WIFI_REASON_AUTH_EXPIRE || reason == WIFI_REASON_BEACON_TIMEOUT ||
607 reason == WIFI_REASON_NO_AP_FOUND || reason == WIFI_REASON_ASSOC_FAIL ||
608 reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
609 WiFi.disconnect();
610 this->error_from_callback_ = true;
611 }
612
613 // Refresh is_connected() cache; sta_state_/error_from_callback_ make it false.
615#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
617#endif
618 break;
619 }
620 case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
621 auto &it = event->data.sta_authmode_change;
622 ESP_LOGV(TAG, "Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode), get_auth_mode_str(it.new_mode));
623 // Mitigate CVE-2020-12638
624 // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
625 if (it.old_mode != WIFI_AUTH_OPEN && it.new_mode == WIFI_AUTH_OPEN) {
626 ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting");
627 WiFi.disconnect();
628 this->error_from_callback_ = true;
629 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::ERROR_FAILED);
630 }
631 break;
632 }
633 case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP: {
634 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE], gw_buf[network::IP_ADDRESS_BUFFER_SIZE];
635 ESP_LOGV(TAG, "static_ip=%s gateway=%s", network::IPAddress(WiFi.localIP()).str_to(ip_buf),
636 network::IPAddress(WiFi.gatewayIP()).str_to(gw_buf));
637 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::CONNECTED);
638#ifdef USE_WIFI_IP_STATE_LISTENERS
640#endif
641 break;
642 }
643 case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6: {
644 ESP_LOGV(TAG, "Got IPv6");
645#ifdef USE_WIFI_IP_STATE_LISTENERS
647#endif
648 break;
649 }
650 case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP: {
651 ESP_LOGV(TAG, "Lost IP");
652 // Don't change state to IDLE - let the disconnect event handle that
653 break;
654 }
655 case ESPHOME_EVENT_ID_WIFI_AP_START: {
656 ESP_LOGV(TAG, "AP start");
657 break;
658 }
659 case ESPHOME_EVENT_ID_WIFI_AP_STOP: {
660 ESP_LOGV(TAG, "AP stop");
661 break;
662 }
663 case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
664#ifdef USE_WIFI_AP
665 this->ap_clients_++;
666#endif
667#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
668 auto &it = event->data.sta_connected;
669 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
670 format_mac_addr_upper(it.bssid, mac_buf);
671 ESP_LOGV(TAG, "AP client connected MAC=%s", mac_buf);
672#endif
673 break;
674 }
675 case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
676#ifdef USE_WIFI_AP
677 if (this->ap_clients_ > 0)
678 this->ap_clients_--;
679#endif
680#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
681 auto &it = event->data.sta_disconnected;
682 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
683 format_mac_addr_upper(it.bssid, mac_buf);
684 ESP_LOGV(TAG, "AP client disconnected MAC=%s", mac_buf);
685#endif
686 break;
687 }
688 case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED: {
689 ESP_LOGV(TAG, "AP client assigned IP");
690 break;
691 }
692 case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
693#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
694 auto &it = event->data.ap_probe_req;
695 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
696 format_mac_addr_upper(it.mac, mac_buf);
697 ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", mac_buf, it.rssi);
698#endif
699 break;
700 }
701 default:
702 break;
703 }
704}
706 WiFi.onEvent(
707 [this](arduino_event_id_t event, arduino_event_info_t info) { this->wifi_event_callback_(event, info); });
708 // Make sure WiFi is in clean state before anything starts
709 this->wifi_mode_(false, false);
710}
712 // Use state machine instead of querying WiFi.status() directly
713 // State is updated in main loop from queued events, ensuring thread safety
714 switch (static_cast<LTWiFiSTAState>(this->sta_state_)) {
724 default:
726 }
727}
728bool WiFiComponent::wifi_scan_start_(bool passive) {
729 // enable STA
730 if (!this->wifi_mode_(true, {}))
731 return false;
732
733 // Reset scan_done_ before starting new scan to prevent stale flag from previous scan
734 // (e.g., roaming scan completed just before unexpected disconnect)
735 this->scan_done_ = false;
736
737 // need to use WiFi because of WiFiScanClass allocations :(
738 int16_t err = WiFi.scanNetworks(true, true, passive, 200);
739 if (err != WIFI_SCAN_RUNNING) {
740 ESP_LOGV(TAG, "WiFi.scanNetworks failed: %d", err);
741 return false;
742 }
743
744 return true;
745}
747 int16_t num = WiFi.scanComplete();
748 bool needs_full = this->needs_full_scan_results_();
749 {
750 // Mutate in place under the lock; blocking a portal request is fine and
751 // avoids scratch buffers
752 ScanResultsLock lock(this);
753 this->scan_result_.clear();
754 this->scan_done_ = true;
755
756 if (num < 0)
757 return;
758
759 // Access scan results directly via WiFi.scan struct to avoid Arduino String allocations
760 // WiFi.scan is public in LibreTiny for WiFiEvents & WiFiScan static handlers
761 auto *scan = WiFi.scan;
762
763 // First pass: count matching networks
764 size_t count = 0;
765 for (int i = 0; i < num; i++) {
766 const char *ssid_cstr = scan->ap[i].ssid;
767 if (needs_full || this->matches_configured_network_(ssid_cstr, scan->ap[i].bssid.addr)) {
768 count++;
769 }
770 }
771
772 if (!this->scan_result_.try_init(count)) {
773 ESP_LOGW(TAG, "No memory for %zu scan results", count);
774 WiFi.scanDelete();
775 return;
776 }
777
778 // Second pass: store matching networks
779 for (int i = 0; i < num; i++) {
780 const char *ssid_cstr = scan->ap[i].ssid;
781 auto &ap = scan->ap[i];
782 const WiFiAP *config = this->find_configured_network_(ssid_cstr, ap.bssid.addr);
783 if (needs_full || config != nullptr) {
784#ifdef USE_RTL87XX
785 // LibreTiny maps the low byte of the driver's security type as an encryption type, so WEP comes out OPEN
786 // and open, WPA/WPA2 mixed and PMF networks all come out INVALID. For INVALID, follow the configured network.
787 bool with_auth = true;
788 if (ap.auth == WIFI_AUTH_INVALID && config != nullptr) {
789#ifdef USE_WIFI_WPA2_EAP
790 with_auth = !config->password_.empty() || config->get_eap().has_value();
791#else
792 with_auth = !config->password_.empty();
793#endif
794 }
795#else
796 const bool with_auth = ap.auth != WIFI_AUTH_OPEN;
797#endif
798 this->scan_result_.emplace_back(bssid_t{ap.bssid.addr[0], ap.bssid.addr[1], ap.bssid.addr[2], ap.bssid.addr[3],
799 ap.bssid.addr[4], ap.bssid.addr[5]},
800 ssid_cstr, strlen(ssid_cstr), ap.channel, ap.rssi, with_auth,
801 ssid_cstr[0] == '\0');
802 } else {
803 this->log_discarded_scan_result_(ssid_cstr, ap.bssid.addr, ap.rssi, ap.channel);
804 }
805 }
806 }
807
808 ESP_LOGV(TAG, "Scan complete: %d found, %zu stored%s", num, this->scan_result_.size(),
809 needs_full ? "" : " (filtered)");
810 WiFi.scanDelete();
811#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
813#endif
814}
815
816#ifdef USE_WIFI_AP
817bool WiFiComponent::wifi_ap_ip_config_(const optional<ManualIP> &manual_ip) {
818 // enable AP
819 if (!this->wifi_mode_({}, true))
820 return false;
821
822 if (manual_ip.has_value()) {
823 return WiFi.softAPConfig(manual_ip->static_ip, manual_ip->gateway, manual_ip->subnet);
824 } else {
825 return WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));
826 }
827}
828
829bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
830 // enable AP
831 if (!this->wifi_mode_({}, true))
832 return false;
833
834#ifdef USE_WIFI_MANUAL_IP
835 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
836 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
837 return false;
838 }
839#else
840 if (!this->wifi_ap_ip_config_({})) {
841 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
842 return false;
843 }
844#endif
845
846 yield();
847
848#ifdef USE_LN882X
849 // LibreTiny's LN882H softAP() points ap.bssid at a static array and frees it
850 // on the next call, tripping FreeRTOS's configASSERT until the watchdog
851 // resets the chip. Clear it so that a second AP start frees nothing.
852 static_cast<WiFiData *>(WiFi.data)->ap.bssid = nullptr;
853#endif
854
855 return WiFi.softAP(ap.ssid_.c_str(), ap.password_.empty() ? NULL : ap.password_.c_str(),
856 ap.has_channel() ? ap.get_channel() : 1, ap.get_hidden());
857}
858
859network::IPAddress WiFiComponent::wifi_soft_ap_ip() { return {WiFi.softAPIP()}; }
860#endif // USE_WIFI_AP
861
862#ifdef USE_LN882X
864 // Leave the AP so it no longer holds the association when we come back.
865 if (WiFi.status() != WL_CONNECTED) // associated, even before DHCP has finished
866 return;
867 ESP_LOGD(TAG, "Disconnecting before powerdown");
868 wifi_sta_disconnect(); // not WiFi.disconnect(): it frees the SSID its event handlers read
869 delay(100); // NOLINT: once per reboot or deep sleep, lets the deauth go out
870}
871#endif
872
873#ifdef USE_BK72XX
875 // Leave the AP so it no longer holds the association when we come back.
876 // Beken reports WL_CONNECTED only once it has an IP; joining or associated is WL_SCAN_COMPLETED
877 const WiFiStatus status = WiFi.status();
878 if (status != WL_CONNECTED && status != WL_SCAN_COMPLETED)
879 return;
880 ESP_LOGD(TAG, "Disconnecting before powerdown");
881 wlan_sta_disconnect(); // not WiFi.disconnect(): it only reports a lost link and sends no deauth
882 delay(100); // NOLINT: once per reboot or deep sleep, lets the deauth go out
883}
884#endif
885
887 // Reset state first so disconnect events aren't ignored
888 // and wifi_sta_connect_status_() returns IDLE instead of CONNECTING
889 this->sta_state_ = static_cast<uint8_t>(LTWiFiSTAState::IDLE);
890 return WiFi.disconnect();
891}
892
894 bssid_t bssid{};
895 uint8_t *raw_bssid = WiFi.BSSID();
896 if (raw_bssid != nullptr) {
897 for (size_t i = 0; i < bssid.size(); i++)
898 bssid[i] = raw_bssid[i];
899 }
900 return bssid;
901}
902const char *WiFiComponent::wifi_ssid_to(std::span<char, SSID_BUFFER_SIZE> buffer) {
903#ifdef USE_BK72XX
904 LinkStatusTypeDef link_status{};
905 bk_wlan_get_link_status(&link_status);
906 size_t len = strnlen(reinterpret_cast<const char *>(link_status.ssid), SSID_BUFFER_SIZE - 1);
907 memcpy(buffer.data(), link_status.ssid, len);
908#elif defined(USE_RTL87XX)
909 rtw_wifi_setting_t setting{};
910 wifi_get_setting("wlan0", &setting);
911 size_t len = strnlen(reinterpret_cast<const char *>(setting.ssid), SSID_BUFFER_SIZE - 1);
912 memcpy(buffer.data(), setting.ssid, len);
913#else
914 // LN882X: wifi_get_sta_conn_info() provides direct pointer access
915 String ssid = WiFi.SSID();
916 size_t len = std::min(static_cast<size_t>(ssid.length()), SSID_BUFFER_SIZE - 1);
917 memcpy(buffer.data(), ssid.c_str(), len);
918#endif
919 buffer[len] = '\0';
920 return buffer.data();
921}
922int8_t WiFiComponent::wifi_rssi() { return WiFi.status() == WL_CONNECTED ? WiFi.RSSI() : WIFI_RSSI_DISCONNECTED; }
923int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
924network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {WiFi.subnetMask()}; }
925network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {WiFi.gatewayIP()}; }
926network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {WiFi.dnsIP(num)}; }
928 // Use pop() directly instead of empty() — avoids redundant synchronization.
929 // LockFreeQueue: pop() costs 1 memw vs empty()'s 2 memw on Xtensa.
930 // FreeRTOSQueue: pop() is 1 critical section vs empty() + pop() = 2.
931 LTWiFiEvent *event = this->event_queue_.pop();
932 if (event == nullptr)
933 return false;
934
935 do {
936 wifi_process_event_(event);
937 delete event; // NOLINT(cppcoreguidelines-owning-memory)
938 } while ((event = this->event_queue_.pop()) != nullptr);
939
940 // Drops only occur when the queue is full, and only this loop drains it,
941 // so if pop() returned nullptr above we can skip this check.
942 uint16_t dropped = this->event_queue_.get_and_reset_dropped_count();
943 if (dropped > 0) {
944 // A dropped station event cannot be made up for: the BK72xx core has no station query
945 ESP_LOGW(TAG, "Dropped %" PRIu16 " WiFi events due to buffer overflow", dropped);
946 }
947 return true;
948}
949
950} // namespace esphome::wifi
951#endif // USE_LIBRETINY
952#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().
uint16_t get_and_reset_dropped_count()
bool push(T *element)
constexpr const char * c_str() const
Definition string_ref.h:78
Guards WiFiComponent::scan_result_.
const optional< EAPAuth > & get_eap() 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 notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
bool wifi_sta_ip_config_(const optional< ManualIP > &manual_ip)
void wifi_process_event_(IDFWiFiEvent *data)
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.
void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info)
bool is_roaming_scan_active() const
True while a post-connect roaming scan holds the radio off-channel.
network::IPAddress wifi_dns_ip_(int num)
bool matches_configured_network_(const char *ssid, const uint8_t *bssid) const
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)
LockFreeQueue< IDFWiFiEvent, 17 > event_queue_
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::@199 pending_
const WiFiAP * find_configured_network_(const char *ssid, const uint8_t *bssid) const
The configured network a scan result belongs to, or nullptr (for scan result filtering) Matches by SS...
void yield(void)
unsigned count
Definition gif.cpp:51
uint32_t buffer
Definition gif.cpp:50
int ret
mopeka_std_values val[3]
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:368
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
ESPHOME_LOG_TAG(TAG, "wifi")
arduino_event_info_t esphome_wifi_event_info_t
const LogString * get_disconnect_reason_str(uint8_t reason)
arduino_event_id_t esphome_wifi_event_id_t
PROGMEM_STRING_TABLE(AuthModeStrings, "OPEN", "WEP", "WPA PSK", "WPA2 PSK", "WPA/WPA2 PSK", "UNKNOWN")
const LogString * get_op_mode_str(uint8_t mode)
@ 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
void HOT delay(uint32_t ms)
Definition hal.cpp:85
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
Definition helpers.h:1754
static void uint32_t
char * str_to(char *buf) const
Definition ip_address.h:152
SemaphoreHandle_t lock
int __real_wifi_sta_connect(wifi_sta_connect_t *connect, wifi_scan_cfg_t *scan_cfg)
int __wrap_wifi_sta_connect(wifi_sta_connect_t *connect, wifi_scan_cfg_t *scan_cfg)