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