ESPHome  2024.10.2
wifi_component_esp32_arduino.cpp
Go to the documentation of this file.
1 #include "wifi_component.h"
2 
3 #ifdef USE_WIFI
4 #ifdef USE_ESP32_FRAMEWORK_ARDUINO
5 
6 #include <esp_netif.h>
7 #include <esp_wifi.h>
8 
9 #include <algorithm>
10 #include <utility>
11 #ifdef USE_WIFI_WPA2_EAP
12 #include <esp_wpa2.h>
13 #endif
14 #include "lwip/apps/sntp.h"
15 #include "lwip/dns.h"
16 #include "lwip/err.h"
17 
19 #include "esphome/core/hal.h"
20 #include "esphome/core/helpers.h"
21 #include "esphome/core/log.h"
22 #include "esphome/core/util.h"
23 
24 namespace esphome {
25 namespace wifi {
26 
27 static const char *const TAG = "wifi_esp32";
28 
29 static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
30 #ifdef USE_WIFI_AP
31 static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
32 #endif // USE_WIFI_AP
33 
34 static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
35 
37  uint8_t mac[6];
38  if (has_custom_mac_address()) {
40  set_mac_address(mac);
41  }
42  auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2);
43  WiFi.onEvent(f);
44  WiFi.persistent(false);
45  // Make sure WiFi is in clean state before anything starts
46  this->wifi_mode_(false, false);
47 }
48 
50  wifi_mode_t current_mode = WiFiClass::getMode();
51  bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA;
52  bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA;
53 
54  bool set_sta = sta.value_or(current_sta);
55  bool set_ap = ap.value_or(current_ap);
56 
57  wifi_mode_t set_mode;
58  if (set_sta && set_ap) {
59  set_mode = WIFI_MODE_APSTA;
60  } else if (set_sta && !set_ap) {
61  set_mode = WIFI_MODE_STA;
62  } else if (!set_sta && set_ap) {
63  set_mode = WIFI_MODE_AP;
64  } else {
65  set_mode = WIFI_MODE_NULL;
66  }
67 
68  if (current_mode == set_mode)
69  return true;
70 
71  if (set_sta && !current_sta) {
72  ESP_LOGV(TAG, "Enabling STA.");
73  } else if (!set_sta && current_sta) {
74  ESP_LOGV(TAG, "Disabling STA.");
75  }
76  if (set_ap && !current_ap) {
77  ESP_LOGV(TAG, "Enabling AP.");
78  } else if (!set_ap && current_ap) {
79  ESP_LOGV(TAG, "Disabling AP.");
80  }
81 
82  bool ret = WiFiClass::mode(set_mode);
83 
84  if (!ret) {
85  ESP_LOGW(TAG, "Setting WiFi mode failed!");
86  return false;
87  }
88 
89  // WiFiClass::mode above calls esp_netif_create_default_wifi_sta() and
90  // esp_netif_create_default_wifi_ap(), which creates the interfaces.
91  // s_sta_netif handle is set during ESPHOME_EVENT_ID_WIFI_STA_START event
92 
93 #ifdef USE_WIFI_AP
94  if (set_ap)
95  s_ap_netif = esp_netif_get_handle_from_ifkey("WIFI_AP_DEF");
96 #endif
97 
98  return ret;
99 }
100 
102  if (!this->wifi_mode_(true, {}))
103  return false;
104 
105  WiFi.setAutoReconnect(false);
106  delay(10);
107  return true;
108 }
109 
110 bool WiFiComponent::wifi_apply_output_power_(float output_power) {
111  int8_t val = static_cast<int8_t>(output_power * 4);
112  return esp_wifi_set_max_tx_power(val) == ESP_OK;
113 }
114 
116  wifi_ps_type_t power_save;
117  switch (this->power_save_) {
119  power_save = WIFI_PS_MIN_MODEM;
120  break;
122  power_save = WIFI_PS_MAX_MODEM;
123  break;
125  default:
126  power_save = WIFI_PS_NONE;
127  break;
128  }
129  return esp_wifi_set_ps(power_save) == ESP_OK;
130 }
131 
133  // enable STA
134  if (!this->wifi_mode_(true, {}))
135  return false;
136 
137  // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
138  wifi_config_t conf;
139  memset(&conf, 0, sizeof(conf));
140  strncpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid));
141  strncpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password));
142 
143  // The weakest authmode to accept in the fast scan mode
144  if (ap.get_password().empty()) {
145  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
146  } else {
147  conf.sta.threshold.authmode = WIFI_AUTH_WPA_WPA2_PSK;
148  }
149 
150 #ifdef USE_WIFI_WPA2_EAP
151  if (ap.get_eap().has_value()) {
152  conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
153  }
154 #endif
155 
156  if (ap.get_bssid().has_value()) {
157  conf.sta.bssid_set = true;
158  memcpy(conf.sta.bssid, ap.get_bssid()->data(), 6);
159  } else {
160  conf.sta.bssid_set = false;
161  }
162  if (ap.get_channel().has_value()) {
163  conf.sta.channel = *ap.get_channel();
164  conf.sta.scan_method = WIFI_FAST_SCAN;
165  } else {
166  conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
167  }
168  // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
169  // Units: AP beacon intervals. Defaults to 3 if set to 0.
170  conf.sta.listen_interval = 0;
171 
172  // Protected Management Frame
173  // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
174  conf.sta.pmf_cfg.capable = true;
175  conf.sta.pmf_cfg.required = false;
176 
177  // note, we do our own filtering
178  // The minimum rssi to accept in the fast scan mode
179  conf.sta.threshold.rssi = -127;
180 
181  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
182 
183  wifi_config_t current_conf;
184  esp_err_t err;
185  err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
186  if (err != ERR_OK) {
187  ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
188  // can continue
189  }
190 
191  if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
192  err = esp_wifi_disconnect();
193  if (err != ESP_OK) {
194  ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
195  return false;
196  }
197  }
198 
199  err = esp_wifi_set_config(WIFI_IF_STA, &conf);
200  if (err != ESP_OK) {
201  ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
202  return false;
203  }
204 
205  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
206  return false;
207  }
208 
209  // setup enterprise authentication if required
210 #ifdef USE_WIFI_WPA2_EAP
211  if (ap.get_eap().has_value()) {
212  // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
213  EAPAuth eap = ap.get_eap().value();
214  err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
215  if (err != ESP_OK) {
216  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed! %d", err);
217  }
218  int ca_cert_len = strlen(eap.ca_cert);
219  int client_cert_len = strlen(eap.client_cert);
220  int client_key_len = strlen(eap.client_key);
221  if (ca_cert_len) {
222  err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
223  if (err != ESP_OK) {
224  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed! %d", err);
225  }
226  }
227  // workout what type of EAP this is
228  // validation is not required as the config tool has already validated it
229  if (client_cert_len && client_key_len) {
230  // if we have certs, this must be EAP-TLS
231  err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
232  (uint8_t *) eap.client_key, client_key_len + 1,
233  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
234  if (err != ESP_OK) {
235  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed! %d", err);
236  }
237  } else {
238  // in the absence of certs, assume this is username/password based
239  err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
240  if (err != ESP_OK) {
241  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed! %d", err);
242  }
243  err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
244  if (err != ESP_OK) {
245  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed! %d", err);
246  }
247  }
248  err = esp_wifi_sta_wpa2_ent_enable();
249  if (err != ESP_OK) {
250  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed! %d", err);
251  }
252  }
253 #endif // USE_WIFI_WPA2_EAP
254 
255  this->wifi_apply_hostname_();
256 
257  s_sta_connecting = true;
258 
259  err = esp_wifi_connect();
260  if (err != ESP_OK) {
261  ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
262  return false;
263  }
264 
265  return true;
266 }
267 
269  // enable STA
270  if (!this->wifi_mode_(true, {}))
271  return false;
272 
273  esp_netif_dhcp_status_t dhcp_status;
274  esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
275  if (err != ESP_OK) {
276  ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
277  return false;
278  }
279 
280  if (!manual_ip.has_value()) {
281  // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
282  // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
283  // https://github.com/esphome/issues/issues/2299
284  sntp_servermode_dhcp(false);
285 
286  // No manual IP is set; use DHCP client
287  if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
288  err = esp_netif_dhcpc_start(s_sta_netif);
289  if (err != ESP_OK) {
290  ESP_LOGV(TAG, "Starting DHCP client failed! %d", err);
291  }
292  return err == ESP_OK;
293  }
294  return true;
295  }
296 
297  esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
298  info.ip = manual_ip->static_ip;
299  info.gw = manual_ip->gateway;
300  info.netmask = manual_ip->subnet;
301  err = esp_netif_dhcpc_stop(s_sta_netif);
302  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
303  ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err));
304  }
305 
306  err = esp_netif_set_ip_info(s_sta_netif, &info);
307  if (err != ESP_OK) {
308  ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err));
309  }
310 
311  esp_netif_dns_info_t dns;
312  if (manual_ip->dns1.is_set()) {
313  dns.ip = manual_ip->dns1;
314  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
315  }
316  if (manual_ip->dns2.is_set()) {
317  dns.ip = manual_ip->dns2;
318  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
319  }
320 
321  return true;
322 }
323 
325  if (!this->has_sta())
326  return {};
327  network::IPAddresses addresses;
328  esp_netif_ip_info_t ip;
329  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
330  if (err != ESP_OK) {
331  ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
332  // TODO: do something smarter
333  // return false;
334  } else {
335  addresses[0] = network::IPAddress(&ip.ip);
336  }
337 #if USE_NETWORK_IPV6
338  struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
339  uint8_t count = 0;
340  count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s);
341  assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
342  for (int i = 0; i < count; i++) {
343  addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
344  }
345 #endif /* USE_NETWORK_IPV6 */
346  return addresses;
347 }
348 
350  // setting is done in SYSTEM_EVENT_STA_START callback
351  return true;
352 }
353 const char *get_auth_mode_str(uint8_t mode) {
354  switch (mode) {
355  case WIFI_AUTH_OPEN:
356  return "OPEN";
357  case WIFI_AUTH_WEP:
358  return "WEP";
359  case WIFI_AUTH_WPA_PSK:
360  return "WPA PSK";
361  case WIFI_AUTH_WPA2_PSK:
362  return "WPA2 PSK";
363  case WIFI_AUTH_WPA_WPA2_PSK:
364  return "WPA/WPA2 PSK";
365  case WIFI_AUTH_WPA2_ENTERPRISE:
366  return "WPA2 Enterprise";
367  case WIFI_AUTH_WPA3_PSK:
368  return "WPA3 PSK";
369  case WIFI_AUTH_WPA2_WPA3_PSK:
370  return "WPA2/WPA3 PSK";
371  case WIFI_AUTH_WAPI_PSK:
372  return "WAPI PSK";
373  default:
374  return "UNKNOWN";
375  }
376 }
377 
378 using esphome_ip4_addr_t = esp_ip4_addr_t;
379 
380 std::string format_ip4_addr(const esphome_ip4_addr_t &ip) {
381  char buf[20];
382  sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
383  uint8_t(ip.addr >> 24));
384  return buf;
385 }
386 const char *get_op_mode_str(uint8_t mode) {
387  switch (mode) {
388  case WIFI_OFF:
389  return "OFF";
390  case WIFI_STA:
391  return "STA";
392  case WIFI_AP:
393  return "AP";
394  case WIFI_AP_STA:
395  return "AP+STA";
396  default:
397  return "UNKNOWN";
398  }
399 }
400 const char *get_disconnect_reason_str(uint8_t reason) {
401  switch (reason) {
402  case WIFI_REASON_AUTH_EXPIRE:
403  return "Auth Expired";
404  case WIFI_REASON_AUTH_LEAVE:
405  return "Auth Leave";
406  case WIFI_REASON_ASSOC_EXPIRE:
407  return "Association Expired";
408  case WIFI_REASON_ASSOC_TOOMANY:
409  return "Too Many Associations";
410  case WIFI_REASON_NOT_AUTHED:
411  return "Not Authenticated";
412  case WIFI_REASON_NOT_ASSOCED:
413  return "Not Associated";
414  case WIFI_REASON_ASSOC_LEAVE:
415  return "Association Leave";
416  case WIFI_REASON_ASSOC_NOT_AUTHED:
417  return "Association not Authenticated";
418  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
419  return "Disassociate Power Cap Bad";
420  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
421  return "Disassociate Supported Channel Bad";
422  case WIFI_REASON_IE_INVALID:
423  return "IE Invalid";
424  case WIFI_REASON_MIC_FAILURE:
425  return "Mic Failure";
426  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
427  return "4-Way Handshake Timeout";
428  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
429  return "Group Key Update Timeout";
430  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
431  return "IE In 4-Way Handshake Differs";
432  case WIFI_REASON_GROUP_CIPHER_INVALID:
433  return "Group Cipher Invalid";
434  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
435  return "Pairwise Cipher Invalid";
436  case WIFI_REASON_AKMP_INVALID:
437  return "AKMP Invalid";
438  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
439  return "Unsupported RSN IE version";
440  case WIFI_REASON_INVALID_RSN_IE_CAP:
441  return "Invalid RSN IE Cap";
442  case WIFI_REASON_802_1X_AUTH_FAILED:
443  return "802.1x Authentication Failed";
444  case WIFI_REASON_CIPHER_SUITE_REJECTED:
445  return "Cipher Suite Rejected";
446  case WIFI_REASON_BEACON_TIMEOUT:
447  return "Beacon Timeout";
448  case WIFI_REASON_NO_AP_FOUND:
449  return "AP Not Found";
450  case WIFI_REASON_AUTH_FAIL:
451  return "Authentication Failed";
452  case WIFI_REASON_ASSOC_FAIL:
453  return "Association Failed";
454  case WIFI_REASON_HANDSHAKE_TIMEOUT:
455  return "Handshake Failed";
456  case WIFI_REASON_CONNECTION_FAIL:
457  return "Connection Failed";
458  case WIFI_REASON_ROAMING:
459  return "Station Roaming";
460  case WIFI_REASON_UNSPECIFIED:
461  default:
462  return "Unspecified";
463  }
464 }
465 
467 
468 #define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY
469 #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE
470 #define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START
471 #define ESPHOME_EVENT_ID_WIFI_STA_STOP ARDUINO_EVENT_WIFI_STA_STOP
472 #define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED
473 #define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED
474 #define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE
475 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP
476 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6 ARDUINO_EVENT_WIFI_STA_GOT_IP6
477 #define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP ARDUINO_EVENT_WIFI_STA_LOST_IP
478 #define ESPHOME_EVENT_ID_WIFI_AP_START ARDUINO_EVENT_WIFI_AP_START
479 #define ESPHOME_EVENT_ID_WIFI_AP_STOP ARDUINO_EVENT_WIFI_AP_STOP
480 #define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED
481 #define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED ARDUINO_EVENT_WIFI_AP_STADISCONNECTED
482 #define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED
483 #define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED
484 #define ESPHOME_EVENT_ID_WIFI_AP_GOT_IP6 ARDUINO_EVENT_WIFI_AP_GOT_IP6
485 using esphome_wifi_event_id_t = arduino_event_id_t;
486 using esphome_wifi_event_info_t = arduino_event_info_t;
487 
489  switch (event) {
490  case ESPHOME_EVENT_ID_WIFI_READY: {
491  ESP_LOGV(TAG, "Event: WiFi ready");
492  break;
493  }
494  case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
495  auto it = info.wifi_scan_done;
496  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%u number=%u scan_id=%u", it.status, it.number, it.scan_id);
497 
498  this->wifi_scan_done_callback_();
499  break;
500  }
501  case ESPHOME_EVENT_ID_WIFI_STA_START: {
502  ESP_LOGV(TAG, "Event: WiFi STA start");
503  // apply hostname
504  s_sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
505  esp_err_t err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
506  if (err != ERR_OK) {
507  ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
508  }
509  break;
510  }
511  case ESPHOME_EVENT_ID_WIFI_STA_STOP: {
512  ESP_LOGV(TAG, "Event: WiFi STA stop");
513  break;
514  }
515  case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
516  auto it = info.wifi_sta_connected;
517  char buf[33];
518  memcpy(buf, it.ssid, it.ssid_len);
519  buf[it.ssid_len] = '\0';
520  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
521  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
522 #if USE_NETWORK_IPV6
523  this->set_timeout(100, [] { WiFi.enableIpV6(); });
524 #endif /* USE_NETWORK_IPV6 */
525 
526  break;
527  }
528  case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
529  auto it = info.wifi_sta_disconnected;
530  char buf[33];
531  memcpy(buf, it.ssid, it.ssid_len);
532  buf[it.ssid_len] = '\0';
533  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
534  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
535  } else {
536  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
537  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
538  }
539 
540  uint8_t reason = it.reason;
541  if (reason == WIFI_REASON_AUTH_EXPIRE || reason == WIFI_REASON_BEACON_TIMEOUT ||
542  reason == WIFI_REASON_NO_AP_FOUND || reason == WIFI_REASON_ASSOC_FAIL ||
543  reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
544  err_t err = esp_wifi_disconnect();
545  if (err != ESP_OK) {
546  ESP_LOGV(TAG, "Disconnect failed: %s", esp_err_to_name(err));
547  }
548  this->error_from_callback_ = true;
549  }
550 
551  s_sta_connecting = false;
552  break;
553  }
554  case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
555  auto it = info.wifi_sta_authmode_change;
556  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
557  get_auth_mode_str(it.new_mode));
558  // Mitigate CVE-2020-12638
559  // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
560  if (it.old_mode != WIFI_AUTH_OPEN && it.new_mode == WIFI_AUTH_OPEN) {
561  ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting...");
562  // we can't call retry_connect() from this context, so disconnect immediately
563  // and notify main thread with error_from_callback_
564  err_t err = esp_wifi_disconnect();
565  if (err != ESP_OK) {
566  ESP_LOGW(TAG, "Disconnect failed: %s", esp_err_to_name(err));
567  }
568  this->error_from_callback_ = true;
569  }
570  break;
571  }
572  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP: {
573  auto it = info.got_ip.ip_info;
574  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip).c_str(),
575  format_ip4_addr(it.gw).c_str());
576  this->got_ipv4_address_ = true;
577 #if USE_NETWORK_IPV6
578  s_sta_connecting = this->num_ipv6_addresses_ < USE_NETWORK_MIN_IPV6_ADDR_COUNT;
579 #else
580  s_sta_connecting = false;
581 #endif /* USE_NETWORK_IPV6 */
582  break;
583  }
584 #if USE_NETWORK_IPV6
585  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6: {
586  auto it = info.got_ip6.ip6_info;
587  ESP_LOGV(TAG, "Got IPv6 address=" IPV6STR, IPV62STR(it.ip));
588  this->num_ipv6_addresses_++;
589  s_sta_connecting = !(this->got_ipv4_address_ & (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT));
590  break;
591  }
592 #endif /* USE_NETWORK_IPV6 */
593  case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP: {
594  ESP_LOGV(TAG, "Event: Lost IP");
595  this->got_ipv4_address_ = false;
596  break;
597  }
598  case ESPHOME_EVENT_ID_WIFI_AP_START: {
599  ESP_LOGV(TAG, "Event: WiFi AP start");
600  break;
601  }
602  case ESPHOME_EVENT_ID_WIFI_AP_STOP: {
603  ESP_LOGV(TAG, "Event: WiFi AP stop");
604  break;
605  }
606  case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
607  auto it = info.wifi_sta_connected;
608  auto &mac = it.bssid;
609  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(mac).c_str());
610  break;
611  }
612  case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
613  auto it = info.wifi_sta_disconnected;
614  auto &mac = it.bssid;
615  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(mac).c_str());
616  break;
617  }
618  case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED: {
619  ESP_LOGV(TAG, "Event: AP client assigned IP");
620  break;
621  }
622  case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
623  auto it = info.wifi_ap_probereqrecved;
624  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
625  break;
626  }
627  default:
628  break;
629  }
630 }
631 
633  auto status = WiFiClass::status();
634  if (status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST) {
636  }
637  if (status == WL_NO_SSID_AVAIL) {
639  }
640  if (s_sta_connecting) {
642  }
643  if (status == WL_CONNECTED) {
645  }
647 }
649  // enable STA
650  if (!this->wifi_mode_(true, {}))
651  return false;
652 
653  // need to use WiFi because of WiFiScanClass allocations :(
654  int16_t err = WiFi.scanNetworks(true, true, passive, 200);
655  if (err != WIFI_SCAN_RUNNING) {
656  ESP_LOGV(TAG, "WiFi.scanNetworks failed! %d", err);
657  return false;
658  }
659 
660  return true;
661 }
663  this->scan_result_.clear();
664 
665  int16_t num = WiFi.scanComplete();
666  if (num < 0)
667  return;
668 
669  this->scan_result_.reserve(static_cast<unsigned int>(num));
670  for (int i = 0; i < num; i++) {
671  String ssid = WiFi.SSID(i);
672  wifi_auth_mode_t authmode = WiFi.encryptionType(i);
673  int32_t rssi = WiFi.RSSI(i);
674  uint8_t *bssid = WiFi.BSSID(i);
675  int32_t channel = WiFi.channel(i);
676 
677  WiFiScanResult scan({bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]}, std::string(ssid.c_str()),
678  channel, rssi, authmode != WIFI_AUTH_OPEN, ssid.length() == 0);
679  this->scan_result_.push_back(scan);
680  }
681  WiFi.scanDelete();
682  this->scan_done_ = true;
683 }
684 
685 #ifdef USE_WIFI_AP
687  esp_err_t err;
688 
689  // enable AP
690  if (!this->wifi_mode_({}, true))
691  return false;
692 
693  esp_netif_ip_info_t info;
694  if (manual_ip.has_value()) {
695  info.ip = manual_ip->static_ip;
696  info.gw = manual_ip->gateway;
697  info.netmask = manual_ip->subnet;
698  } else {
699  info.ip = network::IPAddress(192, 168, 4, 1);
700  info.gw = network::IPAddress(192, 168, 4, 1);
701  info.netmask = network::IPAddress(255, 255, 255, 0);
702  }
703 
704  err = esp_netif_dhcps_stop(s_ap_netif);
705  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
706  ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
707  return false;
708  }
709 
710  err = esp_netif_set_ip_info(s_ap_netif, &info);
711  if (err != ESP_OK) {
712  ESP_LOGE(TAG, "esp_netif_set_ip_info failed! %d", err);
713  return false;
714  }
715 
716  dhcps_lease_t lease;
717  lease.enable = true;
718  network::IPAddress start_address = network::IPAddress(&info.ip);
719  start_address += 99;
720  lease.start_ip = start_address;
721  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
722  start_address += 10;
723  lease.end_ip = start_address;
724  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
725  err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
726 
727  if (err != ESP_OK) {
728  ESP_LOGE(TAG, "esp_netif_dhcps_option failed! %d", err);
729  return false;
730  }
731 
732  err = esp_netif_dhcps_start(s_ap_netif);
733 
734  if (err != ESP_OK) {
735  ESP_LOGE(TAG, "esp_netif_dhcps_start failed! %d", err);
736  return false;
737  }
738 
739  return true;
740 }
741 
743  // enable AP
744  if (!this->wifi_mode_({}, true))
745  return false;
746 
747  wifi_config_t conf;
748  memset(&conf, 0, sizeof(conf));
749  strncpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid));
750  conf.ap.channel = ap.get_channel().value_or(1);
751  conf.ap.ssid_hidden = ap.get_ssid().size();
752  conf.ap.max_connection = 5;
753  conf.ap.beacon_interval = 100;
754 
755  if (ap.get_password().empty()) {
756  conf.ap.authmode = WIFI_AUTH_OPEN;
757  *conf.ap.password = 0;
758  } else {
759  conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
760  strncpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password));
761  }
762 
763  // pairwise cipher of SoftAP, group cipher will be derived using this.
764  conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
765 
766  esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
767  if (err != ESP_OK) {
768  ESP_LOGV(TAG, "esp_wifi_set_config failed! %d", err);
769  return false;
770  }
771 
772  yield();
773 
774  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
775  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
776  return false;
777  }
778 
779  return true;
780 }
781 
783  esp_netif_ip_info_t ip;
784  esp_netif_get_ip_info(s_ap_netif, &ip);
785  return network::IPAddress(&ip.ip);
786 }
787 #endif // USE_WIFI_AP
788 
789 bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
790 
792  bssid_t bssid{};
793  uint8_t *raw_bssid = WiFi.BSSID();
794  if (raw_bssid != nullptr) {
795  for (size_t i = 0; i < bssid.size(); i++)
796  bssid[i] = raw_bssid[i];
797  }
798  return bssid;
799 }
800 std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
801 int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); }
802 int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); }
806 
807 } // namespace wifi
808 } // namespace esphome
809 
810 #endif // USE_ESP32_FRAMEWORK_ARDUINO
811 #endif
std::array< uint8_t, 6 > bssid_t
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition: helpers.cpp:707
const optional< EAPAuth > & get_eap() const
static std::string format_mac_addr(const uint8_t mac[6])
const std::string & get_password() const
WiFiPowerSaveMode power_save_
network::IPAddress wifi_dns_ip_(int num)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
const optional< bssid_t > & get_bssid() const
std::string str() const
Definition: ip_address.h:122
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
Definition: component.cpp:69
bool wifi_apply_output_power_(float output_power)
bool wifi_sta_ip_config_(optional< ManualIP > manual_ip)
mopeka_std_values val[4]
bool has_value() const
Definition: optional.h:87
void set_ap(const WiFiAP &ap)
Setup an Access Point that should be created if no connection to a station can be made...
const char * get_op_mode_str(uint8_t mode)
std::vector< WiFiScanResult > scan_result_
const char *const TAG
Definition: spi.cpp:8
const optional< ManualIP > & get_manual_ip() const
const optional< uint8_t > & get_channel() const
arduino_event_id_t esphome_wifi_event_id_t
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:183
Application App
Global storage of Application pointer - only one Application can exist.
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition: helpers.cpp:704
const std::string & get_name() const
Get the name of this Application set by pre_setup().
Definition: application.h:202
std::array< IPAddress, 5 > IPAddresses
Definition: ip_address.h:141
void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info)
arduino_event_info_t esphome_wifi_event_info_t
uint8_t status
Definition: bl0942.h:74
const char * get_auth_mode_str(uint8_t mode)
void IRAM_ATTR HOT yield()
Definition: core.cpp:24
void set_sta(const WiFiAP &ap)
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
std::string format_ip4_addr(const esphome_ip4_addr_t &ip)
const std::string & get_ssid() const
const char * get_disconnect_reason_str(uint8_t reason)
value_type value_or(U const &v) const
Definition: optional.h:93
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition: helpers.cpp:660