9#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
10#include <esp_eap_client.h>
20#include <user_interface.h>
34#ifdef USE_CAPTIVE_PORTAL
37#ifdef USE_WEBSERVER_CAPTIVE
45#ifdef USE_IMPROV_SERIAL
49#ifdef USE_PROVISIONING
74 char *heap_data =
new char[
len + 1];
75 std::memcpy(heap_data, str,
len);
76 heap_data[
len] =
'\0';
95 std::memcpy(this->storage_, other.storage_, INLINE_CAPACITY + 1);
98 other.storage_[0] =
'\0';
102 if (
this != &other) {
116 return this->
size() == other.
size() && std::memcmp(this->
data(), other.
data(), this->size()) == 0;
119 return this->
size() == other.
size() && std::memcmp(this->
data(), other.
c_str(), this->size()) == 0;
318#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_INFO
319#ifdef USE_WIFI_PHY_MODE
323 return LOG_STR(
"11B");
325 return LOG_STR(
"11G");
327 return LOG_STR(
"11N");
328 return LOG_STR(
"Auto");
332static const LogString *retry_phase_to_log_string(
WiFiRetryPhase phase) {
334 return LOG_STR(
"INITIAL_CONNECT");
335#ifdef USE_WIFI_FAST_CONNECT
337 return LOG_STR(
"FAST_CONNECT_CYCLING");
340 return LOG_STR(
"EXPLICIT_HIDDEN");
342 return LOG_STR(
"SCAN_CONNECTING");
344 return LOG_STR(
"RETRY_HIDDEN");
346 return LOG_STR(
"RESTARTING");
347 return LOG_STR(
"UNKNOWN");
354 return !this->
sta_.empty() && this->
sta_[0].get_hidden();
360 for (
size_t i = 0; i < this->
sta_.size(); i++) {
361 if (!this->
sta_[i].get_hidden()) {
362 return static_cast<int8_t
>(i);
373static constexpr uint8_t WIFI_RETRY_COUNT_PER_BSSID = 2;
377static constexpr uint8_t WIFI_RETRY_COUNT_PER_SSID = 1;
381static constexpr uint8_t WIFI_RETRY_COUNT_PER_AP = 1;
385static constexpr uint32_t WIFI_COOLDOWN_DURATION_MS = 500;
388#ifdef USE_WIFI_AP_EXCLUSIVE
389static constexpr bool WIFI_AP_EXCLUSIVE =
true;
391static constexpr bool WIFI_AP_EXCLUSIVE =
false;
394#ifdef USE_WIFI_AP_EXCLUSIVE
399static constexpr uint32_t WIFI_AP_EXCLUSIVE_DWELL_MS = 300000;
402static constexpr uint32_t WIFI_AP_EXCLUSIVE_MAX_DWELL_MS = 3 * WIFI_AP_EXCLUSIVE_DWELL_MS;
403static constexpr uint32_t WIFI_AP_EXCLUSIVE_HANDOVER_MS = 1000;
406#if defined(USE_WIFI_AP) && (!defined(USE_WIFI_AP_WISP) || defined(USE_WIFI_AP_WISP_PORTAL))
407#define WIFI_AP_HAS_PORTAL
410#if defined(USE_WIFI_AP_PERSISTENT) && defined(WIFI_AP_HAS_PORTAL) && \
411 (defined(USE_CAPTIVE_PORTAL) || defined(USE_WEBSERVER_CAPTIVE))
412#define WIFI_AP_PORTAL_FOLLOWS_STA
414static constexpr uint32_t WIFI_PORTAL_REOPEN_DELAY_MS = 10000;
420static constexpr uint32_t WIFI_COOLDOWN_WITH_AP_ACTIVE_MS = 30000;
425static constexpr uint32_t WIFI_SCAN_TIMEOUT_MS = 31000;
435static constexpr uint32_t WIFI_CONNECT_TIMEOUT_MS = 46000;
437static constexpr uint8_t get_max_retries_for_phase(
WiFiRetryPhase phase) {
440#ifdef USE_WIFI_FAST_CONNECT
444 return WIFI_RETRY_COUNT_PER_AP;
447 return WIFI_RETRY_COUNT_PER_SSID;
450 return WIFI_RETRY_COUNT_PER_BSSID;
453 return WIFI_RETRY_COUNT_PER_SSID;
455 return WIFI_RETRY_COUNT_PER_BSSID;
459static void apply_scan_result_to_params(WiFiAP ¶ms,
const WiFiScanResult &scan) {
460 params.set_hidden(
false);
461 params.set_ssid(scan.get_ssid());
462 params.set_bssid(scan.get_bssid());
463 params.set_channel(scan.get_channel());
478 for (
const auto &conf : this->
sta_) {
479 if (conf.ssid_ == ssid && conf.get_hidden()) {
486 if (scan.ssid_ == ssid) {
500#ifdef USE_CAPTIVE_PORTAL
507#ifdef USE_IMPROV_SERIAL
526 if (ssid[0] ==
'\0') {
529 for (
const auto &sta : this->
sta_) {
531 if (sta.get_hidden()) {
535 if (sta.ssid_.empty()) {
536 if (sta.has_bssid() && std::memcmp(sta.get_bssid().data(), bssid, 6) == 0) {
542 if (sta.ssid_ == ssid) {
551 if (it.bssid == bssid) {
563#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
569 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
571 ESP_LOGV(TAG,
"- " LOG_SECRET(
"'%s'")
" " LOG_SECRET(
"(%s)")
" %ddB Ch:%u", ssid, bssid_s, rssi, channel);
595 for (
size_t i = start_index + 1; i < this->
sta_.size(); i++) {
596 const auto &sta = this->
sta_[i];
601 if (!include_explicit_hidden && sta.get_hidden()) {
603 if (first_non_hidden_idx < 0 ||
static_cast<int8_t
>(i) < first_non_hidden_idx) {
604 ESP_LOGD(TAG,
"Skipping " LOG_SECRET(
"'%s'")
" (explicit hidden, already tried)", sta.ssid_.c_str());
612 ESP_LOGD(TAG,
"Hidden candidate " LOG_SECRET(
"'%s'")
" at index %d", sta.ssid_.c_str(),
static_cast<int>(i));
613 return static_cast<int8_t
>(i);
615 ESP_LOGD(TAG,
"Skipping hidden retry for visible network " LOG_SECRET(
"'%s'"), sta.ssid_.c_str());
624 if (!this->
sta_.empty() && this->sta_[0].get_hidden()) {
625 ESP_LOGI(TAG,
"Starting with explicit hidden network (highest priority)");
635#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
636static const char *eap_phase2_to_str(esp_eap_ttls_phase2_types
type) {
638 case ESP_EAP_TTLS_PHASE2_PAP:
640 case ESP_EAP_TTLS_PHASE2_CHAP:
642 case ESP_EAP_TTLS_PHASE2_MSCHAP:
644 case ESP_EAP_TTLS_PHASE2_MSCHAPV2:
646 case ESP_EAP_TTLS_PHASE2_EAP:
657#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
662 ESP_LOGE(TAG,
"Failed semaphore");
669#if defined(USE_PROVISIONING) && (defined(USE_WIFI_DPP) || defined(WIFI_AP_HAS_PORTAL))
679#ifdef WIFI_AP_HAS_PORTAL
681#ifndef USE_WIFI_AP_PERSISTENT
683 ESP_LOGD(TAG,
"Provisioning window closed; disabling AP");
684#ifdef USE_WIFI_AP_EXCLUSIVE
712 ESP_LOGV(TAG,
"Setting Output Power Option failed");
715 ESP_LOGV(TAG,
"Setting Power Save Option failed");
720 ESP_LOGCONFIG(TAG,
"Starting");
727#ifdef USE_WIFI_FAST_CONNECT
728#ifdef USE_WIFI_FAST_CONNECT_IN_FLASH
729 const bool fast_connect_in_flash =
true;
731 const bool fast_connect_in_flash =
false;
736#ifdef USE_WIFI_LEASE_CACHE
737#ifdef USE_WIFI_LEASE_CACHE_IN_FLASH
738 const bool lease_cache_in_flash =
true;
740 const bool lease_cache_in_flash =
false;
748 ESP_LOGD(TAG,
"Loaded settings: %s", save.ssid);
752 sta.set_password(save.password);
755#ifdef USE_WIFI_LEASE_CACHE
762#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
766 if (semaphore_count > 0) {
778#ifdef USE_WIFI_FAST_CONNECT
783 if (loaded_fast_connect) {
784 ESP_LOGI(TAG,
"Starting fast_connect (saved) " LOG_SECRET(
"'%s'"), params.
ssid_.
c_str());
786 }
else if (!this->
sta_.empty() && !this->sta_[0].get_hidden()) {
788 ESP_LOGI(TAG,
"Starting fast_connect (config) " LOG_SECRET(
"'%s'"), this->
sta_[0].ssid_.c_str());
800#ifdef WIFI_AP_HAS_PORTAL
801 }
else if (this->
has_ap()) {
822 ESP_LOGW(TAG,
"Restarting adapter");
845#if defined(USE_WIFI_CONNECT_TRIGGER) || defined(USE_WIFI_DISCONNECT_TRIGGER)
847#ifdef USE_WIFI_DISCONNECT_TRIGGER
852#ifdef USE_WIFI_CONNECT_TRIGGER
867 ESP_LOGD(TAG,
"Exiting cooldown early due to new WiFi credentials");
873 uint32_t cooldown_duration = portal_active ? WIFI_COOLDOWN_WITH_AP_ACTIVE_MS : WIFI_COOLDOWN_DURATION_MS;
897 ESP_LOGW(TAG,
"Connection lost; reconnecting");
904#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
930#ifdef USE_WIFI_AP_EXCLUSIVE
945#if defined(USE_WIFI_AP) && !defined(USE_WIFI_AP_PERSISTENT)
952#ifdef USE_WIFI_AP_EXCLUSIVE
960 ESP_LOGI(TAG,
"Starting fallback AP");
961#ifdef USE_WIFI_AP_EXCLUSIVE
965#ifndef USE_WIFI_AP_EXCLUSIVE
976#ifdef WIFI_AP_PORTAL_FOLLOWS_STA
994 bool suppress =
false;
995#if defined(USE_WIFI_AP) && (defined(USE_RTL87XX) || defined(USE_LN882X))
999#elif defined(USE_WIFI_AP)
1003#ifdef USE_PROVISIONING
1013 ESP_LOGE(TAG,
"Can't connect; rebooting");
1019#ifdef USE_WIFI_AP_PERSISTENT
1023#
if defined(USE_WIFI_AP_WISP) && !defined(USE_WIFI_AP_WISP_PORTAL)
1027 ESP_LOGI(TAG,
"Starting AP");
1030#ifdef WIFI_AP_PORTAL_FOLLOWS_STA
1049#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
1057 ESP_LOGV(TAG,
"Switching to high-performance mode (%" PRIu32
" active %s)", (
uint32_t) semaphore_count,
1058 semaphore_count == 1 ? LOG_STR_LITERAL(
"request") : LOG_STR_LITERAL(
"requests"));
1065 ESP_LOGV(TAG,
"Restoring power save mode to configured setting");
1096#ifdef USE_WIFI_AP_EXCLUSIVE
1109 static constexpr size_t AP_SSID_MAX_LEN = 32;
1112 if (app_name.length() <= AP_SSID_MAX_LEN) {
1116 char ssid_buf[AP_SSID_MAX_LEN + 1];
1117 truncate_name_to(ssid_buf,
sizeof(ssid_buf), app_name.c_str(), app_name.length(),
1129#if defined(USE_WIFI_AP_EXCLUSIVE) || defined(USE_WIFI_AP_PERSISTENT)
1136 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1140 " AP Password: '%s'\n"
1142 this->
ap_.
ssid_.
c_str(), this->ap_.password_.c_str(), this->wifi_soft_ap_ip().str_to(ip_buf));
1144#ifdef USE_WIFI_MANUAL_IP
1146 if (manual_ip.has_value()) {
1147 char static_ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1148 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1149 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1151 " AP Static IP: '%s'\n"
1152 " AP Gateway: '%s'\n"
1154 manual_ip->static_ip.str_to(static_ip_buf), manual_ip->gateway.str_to(gateway_buf),
1155 manual_ip->subnet.str_to(subnet_buf));
1166#ifdef USE_WIFI_AP_EXCLUSIVE
1168 ESP_LOGI(TAG,
"Pausing AP to try the networks");
1181#ifdef USE_WIFI_AP_WISP_PORTAL
1193 ESP_LOGD(TAG,
"Disabling AP");
1218#ifdef USE_WIFI_LEASE_CACHE
1226 if (config ==
nullptr) {
1227 ESP_LOGE(TAG,
"No valid network config (selected_sta_index_=%d, sta_.size()=%zu)",
1237#ifdef USE_WIFI_FAST_CONNECT
1255 apply_scan_result_to_params(params, this->
scan_result_[0]);
1269 return config ? *config :
WiFiAP{};
1276 strncpy(save.ssid, ssid,
sizeof(save.ssid) - 1);
1277 strncpy(save.password, password,
sizeof(save.password) - 1);
1284 sta.set_password(password);
1288#ifdef USE_WIFI_AP_EXCLUSIVE
1291 this->
set_timeout(AP_HANDOVER_TIMEOUT_ID, WIFI_AP_EXCLUSIVE_HANDOVER_MS, [
this]() {
1301 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1310 "Connecting to " LOG_SECRET(
"'%s'")
" " LOG_SECRET(
"(%s)")
" (priority %d, attempt %u/%u in phase %s)...",
1314#ifdef ESPHOME_LOG_HAS_VERBOSE
1316 "Connection Params:\n"
1320 ESP_LOGV(TAG,
" BSSID: %s", bssid_s);
1322 ESP_LOGV(TAG,
" BSSID: Not Set");
1325#ifdef USE_WIFI_WPA2_EAP
1326 const auto &eap_opt = ap.
get_eap();
1327 if (eap_opt.has_value()) {
1328 const EAPAuth &eap_config = *eap_opt;
1332 " WPA2 Enterprise authentication configured:\n"
1333 " Identity: " LOG_SECRET(
"'%s'")
"\n"
1334 " Username: " LOG_SECRET(
"'%s'")
"\n"
1335 " Password: " LOG_SECRET(
"'%s'"),
1338#if defined(USE_ESP32) && defined(USE_WIFI_WPA2_EAP) && ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
1339 ESP_LOGV(TAG,
" TTLS Phase 2: " LOG_SECRET(
"'%s'"), eap_phase2_to_str(eap_config.
ttls_phase_2));
1341 bool ca_cert_present = eap_config.
ca_cert !=
nullptr && strlen(eap_config.
ca_cert);
1346 " Client Cert: %s\n"
1348 ca_cert_present ? LOG_STR_LITERAL(
"present") : LOG_STR_LITERAL(
"not present"),
1349 client_cert_present ? LOG_STR_LITERAL(
"present") : LOG_STR_LITERAL(
"not present"),
1350 client_key_present ? LOG_STR_LITERAL(
"present") : LOG_STR_LITERAL(
"not present"));
1353 ESP_LOGV(TAG,
" Password: " LOG_SECRET(
"'%s'"), ap.
password_.
c_str());
1354#ifdef USE_WIFI_WPA2_EAP
1360 ESP_LOGV(TAG,
" Channel not set");
1362#ifdef USE_WIFI_MANUAL_IP
1364 char static_ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1365 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1366 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1367 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
1368 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
1369 ESP_LOGV(TAG,
" Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s",
m->static_ip.str_to(static_ip_buf),
1370 m->gateway.str_to(gateway_buf),
m->subnet.str_to(subnet_buf),
m->dns1.str_to(dns1_buf),
1371 m->dns2.str_to(dns2_buf));
1375 ESP_LOGV(TAG,
" Using DHCP IP");
1377 ESP_LOGV(TAG,
" Hidden: %s", YESNO(ap.
get_hidden()));
1390 ESP_LOGE(TAG,
"wifi_sta_connect_ failed");
1420 return LOG_STR(
"\033[0;32m"
1426 }
else if (rssi >= -65) {
1427 return LOG_STR(
"\033[0;33m"
1434 }
else if (rssi >= -85) {
1435 return LOG_STR(
"\033[0;33m"
1443 return LOG_STR(
"\033[0;31m"
1455 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1458 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1461 ESP_LOGCONFIG(TAG,
" IP Address: %s", ip.str_to(ip_buf));
1466 char ssid_buf[SSID_BUFFER_SIZE];
1467 char subnet_buf[network::IP_ADDRESS_BUFFER_SIZE];
1468 char gateway_buf[network::IP_ADDRESS_BUFFER_SIZE];
1469 char dns1_buf[network::IP_ADDRESS_BUFFER_SIZE];
1470 char dns2_buf[network::IP_ADDRESS_BUFFER_SIZE];
1473 " SSID: " LOG_SECRET(
"'%s'")
"\n"
1474 " BSSID: " LOG_SECRET(
"%s")
"\n"
1476 " Signal strength: %d dB %s\n"
1477 " Channel: %" PRId32
"\n"
1486#ifdef ESPHOME_LOG_HAS_VERBOSE
1488 ESP_LOGV(TAG,
" Priority: %d", this->
get_sta_priority(config->get_bssid()));
1491#ifdef USE_WIFI_11KV_SUPPORT
1495 this->
btm_ ? LOG_STR_LITERAL(
"enabled") : LOG_STR_LITERAL(
"disabled"),
1496 this->
rrm_ ? LOG_STR_LITERAL(
"enabled") : LOG_STR_LITERAL(
"disabled"));
1504 ESP_LOGD(TAG,
"Enabling");
1518 ESP_LOGD(TAG,
"Disabling");
1520#ifdef USE_WIFI_LEASE_CACHE
1532#ifdef USE_WIFI_AP_PERSISTENT
1539 ESP_LOGD(TAG,
"Starting scan");
1591 return a.
get_rssi() > b.get_rssi();
1617template<
typename VectorType>
static void insertion_sort_scan_results(VectorType &results) {
1623 static_assert(!std::is_polymorphic<WiFiScanResult>::value,
"WiFiScanResult must not have vtable");
1624 static_assert(!std::is_polymorphic<CompactString>::value,
"CompactString must not have vtable");
1627 static_assert(std::is_standard_layout<WiFiScanResult>::value,
"WiFiScanResult must be standard layout");
1628 static_assert(std::is_standard_layout<CompactString>::value,
"CompactString must be standard layout");
1630 static_assert(
sizeof(WiFiScanResult) == 32,
"WiFiScanResult size changed - verify memcpy sort is still safe");
1631 static_assert(
sizeof(CompactString) == 20,
"CompactString size changed - verify memcpy sort is still safe");
1633 static_assert(
alignof(WiFiScanResult) <=
alignof(std::max_align_t),
"WiFiScanResult alignment exceeds max_align_t");
1634 const size_t size = results.size();
1635 constexpr size_t elem_size =
sizeof(WiFiScanResult);
1639 auto *memcpy_fn = &memcpy;
1640 for (
size_t i = 1; i <
size; i++) {
1641 alignas(WiFiScanResult) uint8_t key_buf[
elem_size];
1642 memcpy_fn(key_buf, &results[i],
elem_size);
1643 const auto &
key = *
reinterpret_cast<const WiFiScanResult *
>(key_buf);
1648 while (j >= 0 && wifi_scan_result_is_better(
key, results[j])) {
1649 memcpy_fn(&results[j + 1], &results[j],
elem_size);
1652 memcpy_fn(&results[j + 1], key_buf,
elem_size);
1664 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1668#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
1670 ESP_LOGI(TAG,
"- '%s' %s" LOG_SECRET(
"(%s) ")
"%s Ch:%2u %3ddB P:%d", res.
get_ssid().
c_str(),
1671 res.
get_is_hidden() ? LOG_STR_LITERAL(
"(HIDDEN) ") : LOG_STR_LITERAL(
""), bssid_s,
1674 ESP_LOGI(TAG,
"- '%s' %s" LOG_SECRET(
"(%s) ")
"%s", res.
get_ssid().
c_str(),
1675 res.
get_is_hidden() ? LOG_STR_LITERAL(
"(HIDDEN) ") : LOG_STR_LITERAL(
""), bssid_s,
1683 ESP_LOGE(TAG,
"Scan timeout");
1694 ESP_LOGW(TAG,
"No networks found");
1699 ESP_LOGD(TAG,
"Found networks:");
1703 for (
auto &ap : this->
sta_) {
1704 if (res.matches(ap)) {
1705 res.set_matches(
true);
1707 const bssid_t &bssid = res.get_bssid();
1718 insertion_sort_scan_results(this->scan_result_);
1723 if (res.get_matches()) {
1724 log_scan_result(res);
1733 bool found_match =
false;
1735 for (
size_t i = 0; i < this->
sta_.size(); i++) {
1736 if (scan_res.
matches(this->sta_[i])) {
1747 ESP_LOGW(TAG,
"No matching network found");
1770 char mac_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1777 ESP_LOGCONFIG(TAG,
" Disabled");
1782 " DPP channels: %s\n"
1783 " DPP timeout: %" PRIu32
" ms",
1786#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
1787 const char *band_mode_s;
1789 case WIFI_BAND_MODE_2G_ONLY:
1790 band_mode_s =
"2.4GHz";
1792 case WIFI_BAND_MODE_5G_ONLY:
1793 band_mode_s =
"5GHz";
1795 case WIFI_BAND_MODE_AUTO:
1797 band_mode_s =
"Auto";
1800 ESP_LOGCONFIG(TAG,
" Band Mode: %s", band_mode_s);
1802#ifdef USE_WIFI_PHY_MODE
1803 ESP_LOGCONFIG(TAG,
" PHY Mode: %s", LOG_STR_ARG(phy_mode_to_log_string(this->
phy_mode_)));
1814 char ssid_buf[SSID_BUFFER_SIZE];
1816 ESP_LOGW(TAG,
"Connection incomplete");
1821 ESP_LOGI(TAG,
"Connected");
1827 ESP_LOGW(TAG, LOG_SECRET(
"'%s'")
" should be marked hidden", config->ssid_.c_str());
1832#ifdef WIFI_AP_HAS_PORTAL
1834#ifdef USE_WIFI_AP_PERSISTENT
1844#ifdef USE_IMPROV_BLE
1864 ESP_LOGD(TAG,
"Roam successful");
1871 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
1895#ifdef USE_WIFI_FAST_CONNECT
1901#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
1907#if defined(USE_ESP8266) && defined(USE_WIFI_IP_STATE_LISTENERS) && defined(USE_WIFI_MANUAL_IP)
1919 ESP_LOGW(TAG,
"Connection timeout, aborting connection attempt");
1929 ESP_LOGW(TAG,
"Connecting to network failed (callback)");
1940 ESP_LOGW(TAG,
"Network no longer found");
1946 ESP_LOGW(TAG,
"Connecting to network failed");
1951 ESP_LOGW(TAG,
"Unknown connection status %d", (
int)
status);
1964#ifdef USE_WIFI_FAST_CONNECT
1973 if (!this->
sta_.empty() && this->sta_[0].get_hidden()) {
1981 if (this->
num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
1988 if (next_index < this->
sta_.size() && this->sta_[next_index].get_hidden()) {
2004 if (this->
scan_result_.empty() || !this->scan_result_[0].get_matches()) {
2008 if (this->
num_retried_ + 1 < WIFI_RETRY_COUNT_PER_BSSID) {
2027 if (this->
num_retried_ + 1 < WIFI_RETRY_COUNT_PER_SSID) {
2104 if (old_phase == new_phase) {
2108 ESP_LOGD(TAG,
"Retry phase: %s → %s", LOG_STR_ARG(retry_phase_to_log_string(old_phase)),
2109 LOG_STR_ARG(retry_phase_to_log_string(new_phase)));
2115 switch (new_phase) {
2116#ifdef USE_WIFI_FAST_CONNECT
2133#ifdef USE_WIFI_FAST_CONNECT
2135 ESP_LOGI(TAG,
"Fast connect exhausted, falling back to scan");
2163 ESP_LOGD(TAG,
"All SSIDs visible or already tried, skipping hidden mode");
2219 if (first_priority != std::numeric_limits<int8_t>::min()) {
2224 if (pri.priority != first_priority) {
2230 ESP_LOGD(TAG,
"Clearing BSSID priorities (all at minimum)");
2254 optional<bssid_t> failed_bssid;
2261 failed_bssid = config->get_bssid();
2264 if (!failed_bssid.has_value()) {
2269 const char *ssid =
nullptr;
2273 ssid = config->ssid_.c_str();
2278 uint8_t max_retries = get_max_retries_for_phase(this->
retry_phase_);
2279 bool is_last_attempt = (this->
num_retried_ + 1 >= max_retries);
2283 int8_t new_priority = old_priority;
2285 if (is_last_attempt) {
2288 (old_priority > std::numeric_limits<int8_t>::min()) ? (old_priority - 1) : std::numeric_limits<int8_t>::min();
2291 char bssid_s[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
2293 ESP_LOGD(TAG,
"Failed " LOG_SECRET(
"'%s'")
" " LOG_SECRET(
"(%s)")
", priority %d → %d", ssid !=
nullptr ? ssid :
"",
2294 bssid_s, old_priority, new_priority);
2315#ifdef USE_WIFI_FAST_CONNECT
2320 ESP_LOGD(TAG,
"Next AP in %s", LOG_STR_ARG(retry_phase_to_log_string(this->
retry_phase_)));
2329 if (next_index < this->
sta_.size() && this->sta_[next_index].get_hidden()) {
2332 ESP_LOGD(TAG,
"Next explicit hidden network at index %d",
static_cast<int>(next_index));
2344 if (next_index != -1) {
2364 ESP_LOGD(TAG,
"Retry attempt %u/%u in phase %s", this->
num_retried_ + 1,
2405 if (next_phase == current_phase) {
2421#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
2453#ifdef USE_CAPTIVE_PORTAL
2461#ifdef USE_WEBSERVER_CAPTIVE
2474#ifdef USE_CAPTIVE_PORTAL
2480#ifdef USE_WEBSERVER_CAPTIVE
2483#ifdef USE_WIFI_AP_WISP_PORTAL
2490#ifdef USE_CAPTIVE_PORTAL
2501#ifdef USE_CAPTIVE_PORTAL
2505#ifdef USE_WEBSERVER_CAPTIVE
2508#ifdef USE_WIFI_AP_WISP_PORTAL
2514#ifdef USE_IMPROV_BLE
2526#ifdef USE_PROVISIONING
2534#if defined(USE_ESP32) && defined(USE_WIFI_RUNTIME_POWER_SAVE)
2574#ifdef USE_WIFI_FAST_CONNECT
2580 if (fast_connect_save.ap_index < 0 ||
static_cast<size_t>(fast_connect_save.ap_index) >= this->sta_.size()) {
2581 ESP_LOGW(TAG,
"AP index out of bounds");
2589 params = this->
sta_[fast_connect_save.ap_index];
2593 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
2599 ESP_LOGD(TAG,
"Loaded fast_connect settings");
2600#if defined(USE_ESP32) && defined(SOC_WIFI_SUPPORT_5G)
2602 (this->band_mode_ == WIFI_BAND_MODE_2G_ONLY && fast_connect_save.channel >=
FIRST_5GHZ_CHANNEL)) {
2603 ESP_LOGW(TAG,
"Saved channel %u not allowed by band mode, ignoring fast_connect", fast_connect_save.channel);
2621 if (this->
fast_connect_pref_.
load(&previous_save) && memcmp(previous_save.bssid, bssid.data(), 6) == 0 &&
2622 previous_save.channel == channel && previous_save.ap_index == ap_index) {
2627 memcpy(fast_connect_save.bssid, bssid.data(), 6);
2628 fast_connect_save.channel = channel;
2629 fast_connect_save.ap_index = ap_index;
2633 ESP_LOGD(TAG,
"Saved fast_connect settings");
2637#ifdef USE_WIFI_LEASE_CACHE
2639 if (!this->
lease_cache_pref_.
load(&this->cached_lease_) || this->cached_lease_.version != SAVED_WIFI_LEASE_VERSION) {
2643 const uint8_t *ip =
reinterpret_cast<const uint8_t *
>(&this->
cached_lease_.
ip);
2644 ESP_LOGD(TAG,
"Loaded cached lease %u.%u.%u.%u (network %d, lease %us)", ip[0], ip[1], ip[2], ip[3],
2653 ESP_LOGD(TAG,
"Lease cache: cleared");
2658 bool with_auth,
bool is_hidden)
2662 ssid_(ssid, ssid_len),
2663 with_auth_(with_auth),
2664 is_hidden_(is_hidden) {}
2682#ifdef USE_WIFI_WPA2_EAP
2725#ifdef USE_WIFI_FAST_CONNECT
2744#ifdef USE_WIFI_CONNECT_STATE_LISTENERS
2748 this->
pending_.connect_state =
false;
2750 char ssid_buf[SSID_BUFFER_SIZE];
2754 listener->on_wifi_connect_state(
StringRef(ssid, strlen(ssid)), bssid);
2759 constexpr uint8_t empty_bssid[6] = {};
2761 listener->on_wifi_connect_state(
StringRef(), empty_bssid);
2766#ifdef USE_WIFI_IP_STATE_LISTENERS
2774#ifdef USE_WIFI_SCAN_RESULTS_LISTENERS
2784 ESP_LOGD(TAG,
"Roam check requested, but not able to check now");
2796 if (selected ==
nullptr || selected->
get_hidden()) {
2807 ESP_LOGD(TAG,
"Roam check skipped, signal good (%d dBm, attempt %u/%u)", rssi, this->
roaming_attempts_,
2816 ESP_LOGD(TAG,
"Roam scan failed to start");
2830 int8_t current_rssi = this->
wifi_rssi();
2832 if (current_rssi == WIFI_RSSI_DISCONNECTED) {
2837 char ssid_buf[SSID_BUFFER_SIZE];
2843 char bssid_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
2847 if (result.ssid_ != current_ssid || result.get_bssid() == current_bssid)
2850#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
2852 ESP_LOGV(TAG,
"Roam candidate %s %d dBm", bssid_buf, result.get_rssi());
2863 int8_t improvement = (best ==
nullptr) ? 0 : best->
get_rssi() - current_rssi;
2872 ESP_LOGI(TAG,
"Roaming to %s (%+d dB)", bssid_buf, improvement);
2874 WiFiAP roam_params = *selected;
2875 apply_scan_result_to_params(roam_params, *best);
2887#ifdef USE_WIFI_MANUAL_IP
2891 uint8_t b[MANUAL_IP_ENTRY_SIZE];
2893 auto ip = [&b](
size_t i) {
return network::IPAddress(b[i], b[i + 1], b[i + 2], b[i + 3]); };
2894 return ManualIP{ip(0), ip(4), ip(8), ip(12), ip(16)};
BedjetMode mode
BedJet operating mode.
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
void wake_loop_threadsafe()
Wake the main event loop from another thread or callback.
bool is_name_add_mac_suffix_enabled() const
uint32_t get_config_version_hash()
Get the config hash extended with ESPHome version.
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void status_set_warning()
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
void status_clear_warning()
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr size_type size() const
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
bool window_pending() const
void add_on_closed_callback(F &&callback)
void start_captive()
AP mode: DNS answers every name with the AP address and unknown URLs redirect to the interface.
20-byte string: 18 chars inline + null, heap for longer.
const char * data() const
CompactString & operator=(const CompactString &other)
bool operator==(const CompactString &other) const
static constexpr uint8_t INLINE_CAPACITY
const char * c_str() const
char storage_[INLINE_CAPACITY+1]
static constexpr uint8_t MAX_LENGTH
void set_heap_ptr_(char *ptr)
char * get_heap_ptr_() const
Guards WiFiComponent::scan_result_.
uint8_t get_channel() const
void set_ssid(const std::string &ssid)
const optional< EAPAuth > & get_eap() const
void set_bssid(const bssid_t &bssid)
bool has_manual_ip() const
void set_channel(uint8_t channel)
optional< ManualIP > get_manual_ip() const
void set_hidden(bool hidden)
const bssid_t & get_bssid() const
This component is responsible for managing the ESP WiFi interface.
void notify_scan_results_listeners_()
Notify scan results listeners with current scan results.
bool is_captive_portal_active_()
void clear_lease_settings_()
bool error_from_callback_
bool is_provisioning_closed_()
The provisioning window has closed, so no new provisioning surface may start.
void add_sta(const WiFiAP &ap)
bool load_fast_connect_settings_(WiFiAP ¶ms)
bool wifi_apply_power_save_()
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.
ESPPreferenceObject pref_
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...
WiFiPowerSaveMode power_save_
bool has_sta_priority(const bssid_t &bssid)
const WiFiAP * get_selected_sta_() const
WiFiSTAConnectStatus wifi_sta_connect_status_() const
uint32_t roaming_last_check_
WiFi8266PhyMode phy_mode_
int8_t get_sta_priority(const bssid_t bssid)
void set_last_connected_(uint32_t now)
void log_and_adjust_priority_for_failed_connect_()
Log failed connection and decrease BSSID priority to avoid repeated attempts.
void init_sta(size_t count)
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)
bool wifi_dpp_start_listen_()
SavedWifiLeaseSettings cached_lease_
WiFiComponentState state_
wifi_scan_vector_t< WiFiScanResult > scan_result_
void save_fast_connect_settings_(const bssid_t &bssid, uint8_t channel)
bool skip_cooldown_next_cycle_
WiFiPowerSaveMode configured_power_save_
uint32_t dpp_listen_started_
void set_sta_priority(bssid_t bssid, int8_t priority)
StaticVector< WiFiScanResultsListener *, ESPHOME_WIFI_SCAN_RESULTS_LISTENERS > scan_results_listeners_
void print_connect_params_()
void loop() override
Reconnect WiFi if required.
void notify_ip_state_listeners_()
Notify IP state listeners with current addresses.
bool is_scan_driver_filtered_() const
void start_connecting(const WiFiAP &ap)
void advance_to_next_target_or_increment_retry_()
Advance to next target (AP/SSID) within current phase, or increment retry counter Called when staying...
ESPPreferenceObject lease_cache_pref_
void check_roaming_(uint32_t now)
static constexpr uint32_t ROAMING_CHECK_INTERVAL
RoamingState roaming_state_
void check_scanning_finished()
void process_roaming_scan_()
SemaphoreHandle_t high_performance_semaphore_
bool ap_dns_known_()
Whether there is an IPv4 resolver to offer AP clients: a configured one, or the station's.
void start_cooldown_()
Wait before the next attempt; while a configurator is waited for, the wait is its listen window.
network::IPAddress get_dns_address(int num)
void pause_exclusive_ap_()
Drop the fallback AP so the networks can be tried; it comes back after ap_timeout.
void apply_ap_dns_()
Pass the station's resolvers on to AP clients when they changed.
WiFiComponent()
Construct a WiFiComponent.
wifi_band_mode_t band_mode_
void wifi_dpp_stop_listen_()
std::vector< WiFiSTAPriority > sta_priorities_
void apply_radio_settings_()
Output power and power save, wherever the radio first comes up: start() with networks,...
bssid_t roaming_target_bssid_
int8_t selected_sta_index_
static constexpr int8_t ROAMING_GOOD_RSSI
void notify_disconnect_state_listeners_()
Notify connect state listeners of disconnection.
void start_portal_scan_()
Scan alongside the AP so the portal can list networks, when there is no station to try.
bool wifi_start_ap_(const WiFiAP &ap)
StaticVector< WiFiConnectStateListener *, ESPHOME_WIFI_CONNECT_STATE_LISTENERS > connect_state_listeners_
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)
int32_t get_wifi_channel()
const char * wifi_ssid_to(std::span< char, SSID_BUFFER_SIZE > buffer)
Write SSID to buffer without heap allocation.
network::IPAddress wifi_subnet_mask_()
static constexpr uint8_t ROAMING_MAX_ATTEMPTS
network::IPAddress wifi_soft_ap_ip()
uint8_t roaming_attempts_
uint8_t ap_start_failures_
network::IPAddress wifi_gateway_ip_()
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.
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...
ESPPreferenceObject fast_connect_pref_
void clear_priorities_if_all_min_()
Clear BSSID priority tracking if all priorities are at minimum (saves memory)
bool is_ap_portal_active_()
captive_portal or the web_server AP mode is serving a user on the access point
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)
bool wifi_apply_hostname_()
bool wifi_sta_pre_setup_()
network::IPAddresses get_ip_addresses()
static constexpr int8_t ROAMING_MIN_IMPROVEMENT
bool is_provisioning_active_()
A portal, improv or DPP is waiting for credentials, so the retry machine must not disturb the radio.
void disable_ap_()
End the portals and turn the AP off.
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.
const char * dpp_channels_
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...
bool is_improv_ble_active_()
void update_connected_state_()
WiFiRetryPhase retry_phase_
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)
WiFiAP build_params_for_current_phase_()
void start_dpp_listen_(uint32_t now)
bool is_high_performance_mode_
void dump_config() override
static constexpr uint8_t FIRST_5GHZ_CHANNEL
void clear_roaming_state_()
void forget_ap_()
End the portals and forget the AP's state, before the radio takes the AP down.
bool release_high_performance()
Release a high-performance mode request.
RetryHiddenMode retry_hidden_mode_
void force_roam_check()
Force an immediate post-connect roaming check, bypassing the periodic interval and the per-connection...
bool wifi_apply_output_power_(float output_power)
bool has_completed_scan_after_captive_portal_start_
bool is_connected() const
bool wifi_sta_connect_(const WiFiAP &ap)
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)
uint32_t roaming_scan_end_
network::IPAddresses wifi_sta_ip_addresses()
void check_connecting_finished(uint32_t now)
void start_initial_connection_()
Start initial connection - either scan or connect directly to hidden networks.
bool wifi_scan_start_(bool passive)
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 ...
bool handled_connected_state_
void handle_driver_roam_(const bssid_t &bssid, uint8_t channel)
Redo post-connect bookkeeping after a driver-initiated roam (e.g.
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 setup() override
Setup WiFi interface.
void clear_all_bssid_priorities_()
Clear all BSSID priority penalties after successful connection (stale after disconnect)
bool post_connect_roaming_
void load_lease_settings_()
Trigger disconnect_trigger_
int8_t get_priority() const
uint8_t get_channel() const
WiFiScanResult(const bssid_t &bssid, const char *ssid, size_t ssid_len, uint8_t channel, int8_t rssi, bool with_auth, bool is_hidden)
const bssid_t & get_bssid() const
StringRef get_ssid() const
bool matches(const WiFiAP &config) const
bool get_is_hidden() const
bool operator==(const WiFiScanResult &rhs) const
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
CaptivePortal * global_captive_portal
ImprovBLEComponent * global_improv_component
ImprovSerialComponent * global_improv_serial_component
std::array< IPAddress, 5 > IPAddresses
ProvisioningManager * global_provisioning_manager
WebServer * global_web_server
std::array< uint8_t, 6 > bssid_t
ESPHOME_LOG_TAG(TAG, "wifi")
const LogString * get_signal_bars(int8_t rssi)
@ 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...
@ ERROR_NETWORK_NOT_FOUND
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
@ SCANNING
Scanning for better AP.
@ CONNECTING
Attempting to connect to better AP found in scan.
@ 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.
size_t truncate_name_to(char *buffer, size_t buffer_size, const char *name, size_t name_len, size_t keep_suffix_len)
Copy a name into a buffer, cutting it when it does not fit.
uint16_t uint16_t size_t elem_size
void progmem_memcpy(void *dst, const void *src, size_t len)
ESPPreferences * global_preferences
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
uint32_t IRAM_ATTR HOT millis()
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)
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
bool sync()
Commit pending writes to flash.
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.