ESPHome 2025.6.3
Loading...
Searching...
No Matches
wifi_component.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2#ifdef USE_WIFI
3#include <cinttypes>
4#include <map>
5
6#ifdef USE_ESP_IDF
7#if (ESP_IDF_VERSION_MAJOR >= 5 && ESP_IDF_VERSION_MINOR >= 1)
8#include <esp_eap_client.h>
9#else
10#include <esp_wpa2.h>
11#endif
12#endif
13
14#if defined(USE_ESP32) || defined(USE_ESP_IDF)
15#include <esp_wifi.h>
16#endif
17#ifdef USE_ESP8266
18#include <user_interface.h>
19#endif
20
21#include <algorithm>
22#include <utility>
23#include "lwip/dns.h"
24#include "lwip/err.h"
25
27#include "esphome/core/hal.h"
29#include "esphome/core/log.h"
30#include "esphome/core/util.h"
31
32#ifdef USE_CAPTIVE_PORTAL
34#endif
35
36#ifdef USE_IMPROV
38#endif
39
40namespace esphome {
41namespace wifi {
42
43static const char *const TAG = "wifi";
44
46
48 ESP_LOGCONFIG(TAG, "Running setup");
49 this->wifi_pre_setup_();
50 if (this->enable_on_boot_) {
51 this->start();
52 } else {
53#ifdef USE_ESP32
54 esp_netif_init();
55#endif
57 }
58}
59
61 ESP_LOGCONFIG(TAG,
62 "Starting\n"
63 " Local MAC: %s",
64 get_mac_address_pretty().c_str());
65 this->last_connected_ = millis();
66
67 uint32_t hash = this->has_sta() ? fnv1_hash(App.get_compilation_time()) : 88491487UL;
68
70 if (this->fast_connect_) {
72 }
73
74 SavedWifiSettings save{};
75 if (this->pref_.load(&save)) {
76 ESP_LOGD(TAG, "Loaded saved settings: %s", save.ssid);
77
78 WiFiAP sta{};
79 sta.set_ssid(save.ssid);
80 sta.set_password(save.password);
81 this->set_sta(sta);
82 }
83
84 if (this->has_sta()) {
85 this->wifi_sta_pre_setup_();
86 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
87 ESP_LOGV(TAG, "Setting Output Power Option failed!");
88 }
89
90 if (!this->wifi_apply_power_save_()) {
91 ESP_LOGV(TAG, "Setting Power Save Option failed!");
92 }
93
94 if (this->fast_connect_) {
95 this->selected_ap_ = this->sta_[0];
97 this->start_connecting(this->selected_ap_, false);
98 } else {
99 this->start_scanning();
100 }
101#ifdef USE_WIFI_AP
102 } else if (this->has_ap()) {
103 this->setup_ap_config_();
104 if (this->output_power_.has_value() && !this->wifi_apply_output_power_(*this->output_power_)) {
105 ESP_LOGV(TAG, "Setting Output Power Option failed!");
106 }
107#ifdef USE_CAPTIVE_PORTAL
109 this->wifi_sta_pre_setup_();
110 this->start_scanning();
112 }
113#endif
114#endif // USE_WIFI_AP
115 }
116#ifdef USE_IMPROV
117 if (!this->has_sta() && esp32_improv::global_improv_component != nullptr) {
118 if (this->wifi_mode_(true, {}))
120 }
121#endif
122 this->wifi_apply_hostname_();
123}
124
126 this->wifi_loop_();
127 const uint32_t now = App.get_loop_component_start_time();
128
129 if (this->has_sta()) {
130 if (this->is_connected() != this->handled_connected_state_) {
131 if (this->handled_connected_state_) {
133 } else {
134 this->connect_trigger_->trigger();
135 }
137 }
138
139 switch (this->state_) {
141 this->status_set_warning("waiting to reconnect");
142 if (millis() - this->action_started_ > 5000) {
143 if (this->fast_connect_ || this->retry_hidden_) {
144 this->start_connecting(this->sta_[0], false);
145 } else {
146 this->start_scanning();
147 }
148 }
149 break;
150 }
152 this->status_set_warning("scanning for networks");
154 break;
155 }
158 this->status_set_warning("associating to network");
160 break;
161 }
162
164 if (!this->is_connected()) {
165 ESP_LOGW(TAG, "Connection lost; reconnecting");
167 this->retry_connect();
168 } else {
169 this->status_clear_warning();
170 this->last_connected_ = now;
171 }
172 break;
173 }
176 break;
178 return;
179 }
180
181#ifdef USE_WIFI_AP
182 if (this->has_ap() && !this->ap_setup_) {
183 if (this->ap_timeout_ != 0 && (now - this->last_connected_ > this->ap_timeout_)) {
184 ESP_LOGI(TAG, "Starting fallback AP!");
185 this->setup_ap_config_();
186#ifdef USE_CAPTIVE_PORTAL
189#endif
190 }
191 }
192#endif // USE_WIFI_AP
193
194#ifdef USE_IMPROV
196 if (now - this->last_connected_ > esp32_improv::global_improv_component->get_wifi_timeout()) {
197 if (this->wifi_mode_(true, {}))
199 }
200 }
201
202#endif
203
204 if (!this->has_ap() && this->reboot_timeout_ != 0) {
205 if (now - this->last_connected_ > this->reboot_timeout_) {
206 ESP_LOGE(TAG, "Can't connect; rebooting");
207 App.reboot();
208 }
209 }
210 }
211}
212
214
215bool WiFiComponent::has_ap() const { return this->has_ap_; }
216bool WiFiComponent::has_sta() const { return !this->sta_.empty(); }
217void WiFiComponent::set_fast_connect(bool fast_connect) { this->fast_connect_ = fast_connect; }
218#ifdef USE_WIFI_11KV_SUPPORT
219void WiFiComponent::set_btm(bool btm) { this->btm_ = btm; }
220void WiFiComponent::set_rrm(bool rrm) { this->rrm_ = rrm; }
221#endif
223 if (this->has_sta())
224 return this->wifi_sta_ip_addresses();
225
226#ifdef USE_WIFI_AP
227 if (this->has_ap())
228 return {this->wifi_soft_ap_ip()};
229#endif // USE_WIFI_AP
230
231 return {};
232}
234 if (this->has_sta())
235 return this->wifi_dns_ip_(num);
236 return {};
237}
239 if (this->use_address_.empty()) {
240 return App.get_name() + ".local";
241 }
242 return this->use_address_;
243}
244void WiFiComponent::set_use_address(const std::string &use_address) { this->use_address_ = use_address; }
245
246#ifdef USE_WIFI_AP
248 this->wifi_mode_({}, true);
249
250 if (this->ap_setup_)
251 return;
252
253 if (this->ap_.get_ssid().empty()) {
254 std::string name = App.get_name();
255 if (name.length() > 32) {
257 name.erase(name.begin() + 25, name.end() - 7); // Remove characters between 25 and the mac address
258 } else {
259 name = name.substr(0, 32);
260 }
261 }
262 this->ap_.set_ssid(name);
263 }
264
265 ESP_LOGCONFIG(TAG, "Setting up AP");
266
267 ESP_LOGCONFIG(TAG,
268 " AP SSID: '%s'\n"
269 " AP Password: '%s'",
270 this->ap_.get_ssid().c_str(), this->ap_.get_password().c_str());
271 if (this->ap_.get_manual_ip().has_value()) {
272 auto manual = *this->ap_.get_manual_ip();
273 ESP_LOGCONFIG(TAG,
274 " AP Static IP: '%s'\n"
275 " AP Gateway: '%s'\n"
276 " AP Subnet: '%s'",
277 manual.static_ip.str().c_str(), manual.gateway.str().c_str(), manual.subnet.str().c_str());
278 }
279
280 this->ap_setup_ = this->wifi_start_ap_(this->ap_);
281 ESP_LOGCONFIG(TAG, " IP Address: %s", this->wifi_soft_ap_ip().str().c_str());
282
283 if (!this->has_sta()) {
285 }
286}
287
289 this->ap_ = ap;
290 this->has_ap_ = true;
291}
292#endif // USE_WIFI_AP
293
295 return 10.0f; // before other loop components
296}
297
298void WiFiComponent::add_sta(const WiFiAP &ap) { this->sta_.push_back(ap); }
300 this->clear_sta();
301 this->add_sta(ap);
302}
303void WiFiComponent::clear_sta() { this->sta_.clear(); }
304void WiFiComponent::save_wifi_sta(const std::string &ssid, const std::string &password) {
305 SavedWifiSettings save{};
306 snprintf(save.ssid, sizeof(save.ssid), "%s", ssid.c_str());
307 snprintf(save.password, sizeof(save.password), "%s", password.c_str());
308 this->pref_.save(&save);
309 // ensure it's written immediately
311
312 WiFiAP sta{};
313 sta.set_ssid(ssid);
314 sta.set_password(password);
315 this->set_sta(sta);
316}
317
318void WiFiComponent::start_connecting(const WiFiAP &ap, bool two) {
319 ESP_LOGI(TAG, "Connecting to '%s'", ap.get_ssid().c_str());
320#ifdef ESPHOME_LOG_HAS_VERBOSE
321 ESP_LOGV(TAG, "Connection Params:");
322 ESP_LOGV(TAG, " SSID: '%s'", ap.get_ssid().c_str());
323 if (ap.get_bssid().has_value()) {
324 bssid_t b = *ap.get_bssid();
325 ESP_LOGV(TAG, " BSSID: %02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5]);
326 } else {
327 ESP_LOGV(TAG, " BSSID: Not Set");
328 }
329
330#ifdef USE_WIFI_WPA2_EAP
331 if (ap.get_eap().has_value()) {
332 ESP_LOGV(TAG, " WPA2 Enterprise authentication configured:");
333 EAPAuth eap_config = ap.get_eap().value();
334 ESP_LOGV(TAG, " Identity: " LOG_SECRET("'%s'"), eap_config.identity.c_str());
335 ESP_LOGV(TAG, " Username: " LOG_SECRET("'%s'"), eap_config.username.c_str());
336 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), eap_config.password.c_str());
337#ifdef USE_ESP_IDF
338#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
339 std::map<esp_eap_ttls_phase2_types, std::string> phase2types = {{ESP_EAP_TTLS_PHASE2_PAP, "pap"},
340 {ESP_EAP_TTLS_PHASE2_CHAP, "chap"},
341 {ESP_EAP_TTLS_PHASE2_MSCHAP, "mschap"},
342 {ESP_EAP_TTLS_PHASE2_MSCHAPV2, "mschapv2"},
343 {ESP_EAP_TTLS_PHASE2_EAP, "eap"}};
344 ESP_LOGV(TAG, " TTLS Phase 2: " LOG_SECRET("'%s'"), phase2types[eap_config.ttls_phase_2].c_str());
345#endif
346#endif
347 bool ca_cert_present = eap_config.ca_cert != nullptr && strlen(eap_config.ca_cert);
348 bool client_cert_present = eap_config.client_cert != nullptr && strlen(eap_config.client_cert);
349 bool client_key_present = eap_config.client_key != nullptr && strlen(eap_config.client_key);
350 ESP_LOGV(TAG, " CA Cert: %s", ca_cert_present ? "present" : "not present");
351 ESP_LOGV(TAG, " Client Cert: %s", client_cert_present ? "present" : "not present");
352 ESP_LOGV(TAG, " Client Key: %s", client_key_present ? "present" : "not present");
353 } else {
354#endif
355 ESP_LOGV(TAG, " Password: " LOG_SECRET("'%s'"), ap.get_password().c_str());
356#ifdef USE_WIFI_WPA2_EAP
357 }
358#endif
359 if (ap.get_channel().has_value()) {
360 ESP_LOGV(TAG, " Channel: %u", *ap.get_channel());
361 } else {
362 ESP_LOGV(TAG, " Channel: Not Set");
363 }
364 if (ap.get_manual_ip().has_value()) {
365 ManualIP m = *ap.get_manual_ip();
366 ESP_LOGV(TAG, " Manual IP: Static IP=%s Gateway=%s Subnet=%s DNS1=%s DNS2=%s", m.static_ip.str().c_str(),
367 m.gateway.str().c_str(), m.subnet.str().c_str(), m.dns1.str().c_str(), m.dns2.str().c_str());
368 } else {
369 ESP_LOGV(TAG, " Using DHCP IP");
370 }
371 ESP_LOGV(TAG, " Hidden: %s", YESNO(ap.get_hidden()));
372#endif
373
374 if (!this->wifi_sta_connect_(ap)) {
375 ESP_LOGE(TAG, "wifi_sta_connect_ failed!");
376 this->retry_connect();
377 return;
378 }
379
380 if (!two) {
382 } else {
384 }
385 this->action_started_ = millis();
386}
387
388const LogString *get_signal_bars(int8_t rssi) {
389 // LOWER ONE QUARTER BLOCK
390 // Unicode: U+2582, UTF-8: E2 96 82
391 // LOWER HALF BLOCK
392 // Unicode: U+2584, UTF-8: E2 96 84
393 // LOWER THREE QUARTERS BLOCK
394 // Unicode: U+2586, UTF-8: E2 96 86
395 // FULL BLOCK
396 // Unicode: U+2588, UTF-8: E2 96 88
397 if (rssi >= -50) {
398 return LOG_STR("\033[0;32m" // green
399 "\xe2\x96\x82"
400 "\xe2\x96\x84"
401 "\xe2\x96\x86"
402 "\xe2\x96\x88"
403 "\033[0m");
404 } else if (rssi >= -65) {
405 return LOG_STR("\033[0;33m" // yellow
406 "\xe2\x96\x82"
407 "\xe2\x96\x84"
408 "\xe2\x96\x86"
409 "\033[0;37m"
410 "\xe2\x96\x88"
411 "\033[0m");
412 } else if (rssi >= -85) {
413 return LOG_STR("\033[0;33m" // yellow
414 "\xe2\x96\x82"
415 "\xe2\x96\x84"
416 "\033[0;37m"
417 "\xe2\x96\x86"
418 "\xe2\x96\x88"
419 "\033[0m");
420 } else {
421 return LOG_STR("\033[0;31m" // red
422 "\xe2\x96\x82"
423 "\033[0;37m"
424 "\xe2\x96\x84"
425 "\xe2\x96\x86"
426 "\xe2\x96\x88"
427 "\033[0m");
428 }
429}
430
432 bssid_t bssid = wifi_bssid();
433
434 ESP_LOGCONFIG(TAG, " Local MAC: %s", get_mac_address_pretty().c_str());
435 if (this->is_disabled()) {
436 ESP_LOGCONFIG(TAG, " Disabled");
437 return;
438 }
439 ESP_LOGCONFIG(TAG, " SSID: " LOG_SECRET("'%s'"), wifi_ssid().c_str());
440 for (auto &ip : wifi_sta_ip_addresses()) {
441 if (ip.is_set()) {
442 ESP_LOGCONFIG(TAG, " IP Address: %s", ip.str().c_str());
443 }
444 }
445 int8_t rssi = wifi_rssi();
446 ESP_LOGCONFIG(TAG,
447 " BSSID: " LOG_SECRET("%02X:%02X:%02X:%02X:%02X:%02X") "\n"
448 " Hostname: '%s'\n"
449 " Signal strength: %d dB %s",
450 bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5], App.get_name().c_str(), rssi,
451 LOG_STR_ARG(get_signal_bars(rssi)));
452 if (this->selected_ap_.get_bssid().has_value()) {
453 ESP_LOGV(TAG, " Priority: %.1f", this->get_sta_priority(*this->selected_ap_.get_bssid()));
454 }
455 ESP_LOGCONFIG(TAG,
456 " Channel: %" PRId32 "\n"
457 " Subnet: %s\n"
458 " Gateway: %s\n"
459 " DNS1: %s\n"
460 " DNS2: %s",
461 get_wifi_channel(), wifi_subnet_mask_().str().c_str(), wifi_gateway_ip_().str().c_str(),
462 wifi_dns_ip_(0).str().c_str(), wifi_dns_ip_(1).str().c_str());
463#ifdef USE_WIFI_11KV_SUPPORT
464 ESP_LOGCONFIG(TAG,
465 " BTM: %s\n"
466 " RRM: %s",
467 this->btm_ ? "enabled" : "disabled", this->rrm_ ? "enabled" : "disabled");
468#endif
469}
470
473 return;
474
475 ESP_LOGD(TAG, "Enabling");
476 this->error_from_callback_ = false;
478 this->start();
479}
480
483 return;
484
485 ESP_LOGD(TAG, "Disabling");
487 this->wifi_disconnect_();
488 this->wifi_mode_(false, false);
489}
490
492
494 this->action_started_ = millis();
495 ESP_LOGD(TAG, "Starting scan");
496 this->wifi_scan_start_(this->passive_scan_);
498}
499
501 if (!this->scan_done_) {
502 if (millis() - this->action_started_ > 30000) {
503 ESP_LOGE(TAG, "Scan timeout!");
504 this->retry_connect();
505 }
506 return;
507 }
508 this->scan_done_ = false;
509
510 ESP_LOGD(TAG, "Found networks:");
511 if (this->scan_result_.empty()) {
512 ESP_LOGD(TAG, " No network found!");
513 this->retry_connect();
514 return;
515 }
516
517 for (auto &res : this->scan_result_) {
518 for (auto &ap : this->sta_) {
519 if (res.matches(ap)) {
520 res.set_matches(true);
521 if (!this->has_sta_priority(res.get_bssid())) {
522 this->set_sta_priority(res.get_bssid(), ap.get_priority());
523 }
524 res.set_priority(this->get_sta_priority(res.get_bssid()));
525 break;
526 }
527 }
528 }
529
530 std::stable_sort(this->scan_result_.begin(), this->scan_result_.end(),
531 [](const WiFiScanResult &a, const WiFiScanResult &b) {
532 // return true if a is better than b
533 if (a.get_matches() && !b.get_matches())
534 return true;
535 if (!a.get_matches() && b.get_matches())
536 return false;
537
538 if (a.get_matches() && b.get_matches()) {
539 // if both match, check priority
540 if (a.get_priority() != b.get_priority())
541 return a.get_priority() > b.get_priority();
542 }
543
544 return a.get_rssi() > b.get_rssi();
545 });
546
547 for (auto &res : this->scan_result_) {
548 char bssid_s[18];
549 auto bssid = res.get_bssid();
550 sprintf(bssid_s, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]);
551
552 if (res.get_matches()) {
553 ESP_LOGI(TAG, "- '%s' %s" LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(),
554 res.get_is_hidden() ? "(HIDDEN) " : "", bssid_s, LOG_STR_ARG(get_signal_bars(res.get_rssi())));
555 ESP_LOGD(TAG, " Channel: %u", res.get_channel());
556 ESP_LOGD(TAG, " RSSI: %d dB", res.get_rssi());
557 } else {
558 ESP_LOGD(TAG, "- " LOG_SECRET("'%s'") " " LOG_SECRET("(%s) ") "%s", res.get_ssid().c_str(), bssid_s,
559 LOG_STR_ARG(get_signal_bars(res.get_rssi())));
560 }
561 }
562
563 if (!this->scan_result_[0].get_matches()) {
564 ESP_LOGW(TAG, "No matching network found!");
565 this->retry_connect();
566 return;
567 }
568
569 WiFiAP connect_params;
570 WiFiScanResult scan_res = this->scan_result_[0];
571 for (auto &config : this->sta_) {
572 // search for matching STA config, at least one will match (from checks before)
573 if (!scan_res.matches(config)) {
574 continue;
575 }
576
577 if (config.get_hidden()) {
578 // selected network is hidden, we use the data from the config
579 connect_params.set_hidden(true);
580 connect_params.set_ssid(config.get_ssid());
581 // don't set BSSID and channel, there might be multiple hidden networks
582 // but we can't know which one is the correct one. Rely on probe-req with just SSID.
583 } else {
584 // selected network is visible, we use the data from the scan
585 // limit the connect params to only connect to exactly this network
586 // (network selection is done during scan phase).
587 connect_params.set_hidden(false);
588 connect_params.set_ssid(scan_res.get_ssid());
589 connect_params.set_channel(scan_res.get_channel());
590 connect_params.set_bssid(scan_res.get_bssid());
591 }
592 // copy manual IP (if set)
593 connect_params.set_manual_ip(config.get_manual_ip());
594
595#ifdef USE_WIFI_WPA2_EAP
596 // copy EAP parameters (if set)
597 connect_params.set_eap(config.get_eap());
598#endif
599
600 // copy password (if set)
601 connect_params.set_password(config.get_password());
602
603 break;
604 }
605
606 yield();
607
608 this->selected_ap_ = connect_params;
609 this->start_connecting(connect_params, false);
610}
611
612void WiFiComponent::dump_config() {
613 ESP_LOGCONFIG(TAG, "WiFi:");
614 this->print_connect_params_();
615}
616
617void WiFiComponent::check_connecting_finished() {
618 auto status = this->wifi_sta_connect_status_();
619
620 if (status == WiFiSTAConnectStatus::CONNECTED) {
621 if (wifi_ssid().empty()) {
622 ESP_LOGW(TAG, "Incomplete connection.");
623 this->retry_connect();
624 return;
625 }
626
627 // We won't retry hidden networks unless a reconnect fails more than three times again
628 this->retry_hidden_ = false;
629
630 ESP_LOGI(TAG, "Connected");
631 this->print_connect_params_();
632
633 if (this->has_ap()) {
634#ifdef USE_CAPTIVE_PORTAL
635 if (this->is_captive_portal_active_()) {
637 }
638#endif
639 ESP_LOGD(TAG, "Disabling AP");
640 this->wifi_mode_({}, false);
641 }
642#ifdef USE_IMPROV
643 if (this->is_esp32_improv_active_()) {
645 }
646#endif
647
649 this->num_retried_ = 0;
650
651 if (this->fast_connect_) {
652 this->save_fast_connect_settings_();
653 }
654
655 return;
656 }
657
658 uint32_t now = millis();
659 if (now - this->action_started_ > 30000) {
660 ESP_LOGW(TAG, "Connection timeout");
661 this->retry_connect();
662 return;
663 }
664
665 if (this->error_from_callback_) {
666 ESP_LOGW(TAG, "Error while connecting to network.");
667 this->retry_connect();
668 return;
669 }
670
671 if (status == WiFiSTAConnectStatus::CONNECTING) {
672 return;
673 }
674
675 if (status == WiFiSTAConnectStatus::ERROR_NETWORK_NOT_FOUND) {
676 ESP_LOGW(TAG, "Network no longer found");
677 this->retry_connect();
678 return;
679 }
680
681 if (status == WiFiSTAConnectStatus::ERROR_CONNECT_FAILED) {
682 ESP_LOGW(TAG, "Connection failed. Check credentials");
683 this->retry_connect();
684 return;
685 }
686
687 ESP_LOGW(TAG, "Unknown connection status %d", (int) status);
688 this->retry_connect();
689}
690
691void WiFiComponent::retry_connect() {
692 if (this->selected_ap_.get_bssid()) {
693 auto bssid = *this->selected_ap_.get_bssid();
694 float priority = this->get_sta_priority(bssid);
695 this->set_sta_priority(bssid, priority - 1.0f);
696 }
697
698 delay(10);
699 if (!this->is_captive_portal_active_() && !this->is_esp32_improv_active_() &&
700 (this->num_retried_ > 3 || this->error_from_callback_)) {
701 if (this->num_retried_ > 5) {
702 // If retry failed for more than 5 times, let's restart STA
703 ESP_LOGW(TAG, "Restarting WiFi adapter");
704 this->wifi_mode_(false, {});
705 delay(100); // NOLINT
706 this->num_retried_ = 0;
707 this->retry_hidden_ = false;
708 } else {
709 // Try hidden networks after 3 failed retries
710 ESP_LOGD(TAG, "Retrying with hidden networks");
711 this->retry_hidden_ = true;
712 this->num_retried_++;
713 }
714 } else {
715 this->num_retried_++;
716 }
717 this->error_from_callback_ = false;
718 if (this->state_ == WIFI_COMPONENT_STATE_STA_CONNECTING) {
719 yield();
721 this->start_connecting(this->selected_ap_, true);
722 return;
723 }
724
725 this->state_ = WIFI_COMPONENT_STATE_COOLDOWN;
726 this->action_started_ = millis();
727}
728
729bool WiFiComponent::can_proceed() {
730 if (!this->has_sta() || this->state_ == WIFI_COMPONENT_STATE_DISABLED || this->ap_setup_) {
731 return true;
732 }
733 return this->is_connected();
734}
735void WiFiComponent::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
736bool WiFiComponent::is_connected() {
737 return this->state_ == WIFI_COMPONENT_STATE_STA_CONNECTED &&
738 this->wifi_sta_connect_status_() == WiFiSTAConnectStatus::CONNECTED && !this->error_from_callback_;
739}
740void WiFiComponent::set_power_save_mode(WiFiPowerSaveMode power_save) { this->power_save_ = power_save; }
741
742void WiFiComponent::set_passive_scan(bool passive) { this->passive_scan_ = passive; }
743
744std::string WiFiComponent::format_mac_addr(const uint8_t *mac) {
745 char buf[20];
746 sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
747 return buf;
748}
749bool WiFiComponent::is_captive_portal_active_() {
750#ifdef USE_CAPTIVE_PORTAL
752#else
753 return false;
754#endif
755}
756bool WiFiComponent::is_esp32_improv_active_() {
757#ifdef USE_IMPROV
759#else
760 return false;
761#endif
762}
763
764void WiFiComponent::load_fast_connect_settings_() {
765 SavedWifiFastConnectSettings fast_connect_save{};
766
767 if (this->fast_connect_pref_.load(&fast_connect_save)) {
768 bssid_t bssid{};
769 std::copy(fast_connect_save.bssid, fast_connect_save.bssid + 6, bssid.begin());
770 this->selected_ap_.set_bssid(bssid);
771 this->selected_ap_.set_channel(fast_connect_save.channel);
772
773 ESP_LOGD(TAG, "Loaded saved fast_connect wifi settings");
774 }
775}
776
777void WiFiComponent::save_fast_connect_settings_() {
778 bssid_t bssid = wifi_bssid();
779 uint8_t channel = get_wifi_channel();
780
781 if (bssid != this->selected_ap_.get_bssid() || channel != this->selected_ap_.get_channel()) {
782 SavedWifiFastConnectSettings fast_connect_save{};
783
784 memcpy(fast_connect_save.bssid, bssid.data(), 6);
785 fast_connect_save.channel = channel;
786
787 this->fast_connect_pref_.save(&fast_connect_save);
788
789 ESP_LOGD(TAG, "Saved fast_connect wifi settings");
790 }
791}
792
793void WiFiAP::set_ssid(const std::string &ssid) { this->ssid_ = ssid; }
794void WiFiAP::set_bssid(bssid_t bssid) { this->bssid_ = bssid; }
795void WiFiAP::set_bssid(optional<bssid_t> bssid) { this->bssid_ = bssid; }
796void WiFiAP::set_password(const std::string &password) { this->password_ = password; }
797#ifdef USE_WIFI_WPA2_EAP
798void WiFiAP::set_eap(optional<EAPAuth> eap_auth) { this->eap_ = std::move(eap_auth); }
799#endif
800void WiFiAP::set_channel(optional<uint8_t> channel) { this->channel_ = channel; }
801void WiFiAP::set_manual_ip(optional<ManualIP> manual_ip) { this->manual_ip_ = manual_ip; }
802void WiFiAP::set_hidden(bool hidden) { this->hidden_ = hidden; }
803const std::string &WiFiAP::get_ssid() const { return this->ssid_; }
804const optional<bssid_t> &WiFiAP::get_bssid() const { return this->bssid_; }
805const std::string &WiFiAP::get_password() const { return this->password_; }
806#ifdef USE_WIFI_WPA2_EAP
807const optional<EAPAuth> &WiFiAP::get_eap() const { return this->eap_; }
808#endif
809const optional<uint8_t> &WiFiAP::get_channel() const { return this->channel_; }
810const optional<ManualIP> &WiFiAP::get_manual_ip() const { return this->manual_ip_; }
811bool WiFiAP::get_hidden() const { return this->hidden_; }
812
813WiFiScanResult::WiFiScanResult(const bssid_t &bssid, std::string ssid, uint8_t channel, int8_t rssi, bool with_auth,
814 bool is_hidden)
815 : bssid_(bssid),
816 ssid_(std::move(ssid)),
817 channel_(channel),
818 rssi_(rssi),
819 with_auth_(with_auth),
820 is_hidden_(is_hidden) {}
821bool WiFiScanResult::matches(const WiFiAP &config) {
822 if (config.get_hidden()) {
823 // User configured a hidden network, only match actually hidden networks
824 // don't match SSID
825 if (!this->is_hidden_)
826 return false;
827 } else if (!config.get_ssid().empty()) {
828 // check if SSID matches
829 if (config.get_ssid() != this->ssid_)
830 return false;
831 } else {
832 // network is configured without SSID - match other settings
833 }
834 // If BSSID configured, only match for correct BSSIDs
835 if (config.get_bssid().has_value() && *config.get_bssid() != this->bssid_)
836 return false;
837
838#ifdef USE_WIFI_WPA2_EAP
839 // BSSID requires auth but no PSK or EAP credentials given
840 if (this->with_auth_ && (config.get_password().empty() && !config.get_eap().has_value()))
841 return false;
842
843 // BSSID does not require auth, but PSK or EAP credentials given
844 if (!this->with_auth_ && (!config.get_password().empty() || config.get_eap().has_value()))
845 return false;
846#else
847 // If PSK given, only match for networks with auth (and vice versa)
848 if (config.get_password().empty() == this->with_auth_)
849 return false;
850#endif
851
852 // If channel configured, only match networks on that channel.
853 if (config.get_channel().has_value() && *config.get_channel() != this->channel_) {
854 return false;
855 }
856 return true;
857}
858bool WiFiScanResult::get_matches() const { return this->matches_; }
859void WiFiScanResult::set_matches(bool matches) { this->matches_ = matches; }
860const bssid_t &WiFiScanResult::get_bssid() const { return this->bssid_; }
861const std::string &WiFiScanResult::get_ssid() const { return this->ssid_; }
862uint8_t WiFiScanResult::get_channel() const { return this->channel_; }
863int8_t WiFiScanResult::get_rssi() const { return this->rssi_; }
864bool WiFiScanResult::get_with_auth() const { return this->with_auth_; }
865bool WiFiScanResult::get_is_hidden() const { return this->is_hidden_; }
866
867bool WiFiScanResult::operator==(const WiFiScanResult &rhs) const { return this->bssid_ == rhs.bssid_; }
868
869WiFiComponent *global_wifi_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
870
871} // namespace wifi
872} // namespace esphome
873#endif
uint8_t m
Definition bl0906.h:1
uint8_t status
Definition bl0942.h:8
std::string get_compilation_time() const
bool is_name_add_mac_suffix_enabled() const
const std::string & get_name() const
Get the name of this Application set by pre_setup().
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(const char *message="unspecified")
void status_clear_warning()
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition automation.h:96
bool has_value() const
Definition optional.h:87
const optional< bssid_t > & get_bssid() const
const std::string & get_ssid() const
void set_ssid(const std::string &ssid)
const optional< uint8_t > & get_channel() const
const optional< EAPAuth > & get_eap() const
const std::string & get_password() const
const optional< ManualIP > & get_manual_ip() const
This component is responsible for managing the ESP WiFi interface.
void add_sta(const WiFiAP &ap)
void set_ap(const WiFiAP &ap)
Setup an Access Point that should be created if no connection to a station can be made.
void set_sta(const WiFiAP &ap)
bool has_sta_priority(const bssid_t &bssid)
std::string get_use_address() const
void save_wifi_sta(const std::string &ssid, const std::string &password)
void loop() override
Reconnect WiFi if required.
float get_sta_priority(const bssid_t bssid)
network::IPAddress get_dns_address(int num)
WiFiComponent()
Construct a WiFiComponent.
std::vector< WiFiScanResult > scan_result_
void start_connecting(const WiFiAP &ap, bool two)
void set_use_address(const std::string &use_address)
ESPPreferenceObject fast_connect_pref_
float get_loop_priority() const override
network::IPAddresses get_ip_addresses()
std::vector< WiFiAP > sta_
float get_setup_priority() const override
WIFI setup_priority.
optional< float > output_power_
void set_sta_priority(const bssid_t bssid, float priority)
void set_fast_connect(bool fast_connect)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
void setup() override
Setup WiFi interface.
const std::string & get_ssid() const
const bssid_t & get_bssid() const
bool matches(const WiFiAP &config)
bool operator==(const WiFiScanResult &rhs) const
uint8_t priority
CaptivePortal * global_captive_portal
ESP32ImprovComponent * global_improv_component
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:143
std::array< uint8_t, 6 > bssid_t
const LogString * get_signal_bars(int8_t rssi)
@ 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_STA_CONNECTING_2
WiFi is in STA(+AP) mode and currently connecting to an AP a second time.
@ 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.
WiFiComponent * global_wifi_component
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
uint32_t fnv1_hash(const std::string &str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:186
ESPPreferences * global_preferences
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition helpers.cpp:732
void IRAM_ATTR HOT yield()
Definition core.cpp:27
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
Application App
Global storage of Application pointer - only one Application can exist.
esp_eap_ttls_phase2_types ttls_phase_2
Struct for setting static IPs in WiFiComponent.