ESPHome  2024.12.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  if (ap.get_ssid().size() > sizeof(conf.sta.ssid)) {
141  ESP_LOGE(TAG, "SSID is too long");
142  return false;
143  }
144  if (ap.get_password().size() > sizeof(conf.sta.password)) {
145  ESP_LOGE(TAG, "password is too long");
146  return false;
147  }
148  memcpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
149  memcpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), ap.get_password().size());
150 
151  // The weakest authmode to accept in the fast scan mode
152  if (ap.get_password().empty()) {
153  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
154  } else {
155  conf.sta.threshold.authmode = WIFI_AUTH_WPA_WPA2_PSK;
156  }
157 
158 #ifdef USE_WIFI_WPA2_EAP
159  if (ap.get_eap().has_value()) {
160  conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
161  }
162 #endif
163 
164  if (ap.get_bssid().has_value()) {
165  conf.sta.bssid_set = true;
166  memcpy(conf.sta.bssid, ap.get_bssid()->data(), 6);
167  } else {
168  conf.sta.bssid_set = false;
169  }
170  if (ap.get_channel().has_value()) {
171  conf.sta.channel = *ap.get_channel();
172  conf.sta.scan_method = WIFI_FAST_SCAN;
173  } else {
174  conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
175  }
176  // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
177  // Units: AP beacon intervals. Defaults to 3 if set to 0.
178  conf.sta.listen_interval = 0;
179 
180  // Protected Management Frame
181  // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
182  conf.sta.pmf_cfg.capable = true;
183  conf.sta.pmf_cfg.required = false;
184 
185  // note, we do our own filtering
186  // The minimum rssi to accept in the fast scan mode
187  conf.sta.threshold.rssi = -127;
188 
189  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
190 
191  wifi_config_t current_conf;
192  esp_err_t err;
193  err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
194  if (err != ERR_OK) {
195  ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
196  // can continue
197  }
198 
199  if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
200  err = esp_wifi_disconnect();
201  if (err != ESP_OK) {
202  ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
203  return false;
204  }
205  }
206 
207  err = esp_wifi_set_config(WIFI_IF_STA, &conf);
208  if (err != ESP_OK) {
209  ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
210  return false;
211  }
212 
213  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
214  return false;
215  }
216 
217  // setup enterprise authentication if required
218 #ifdef USE_WIFI_WPA2_EAP
219  if (ap.get_eap().has_value()) {
220  // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
221  EAPAuth eap = ap.get_eap().value();
222  err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
223  if (err != ESP_OK) {
224  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed! %d", err);
225  }
226  int ca_cert_len = strlen(eap.ca_cert);
227  int client_cert_len = strlen(eap.client_cert);
228  int client_key_len = strlen(eap.client_key);
229  if (ca_cert_len) {
230  err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
231  if (err != ESP_OK) {
232  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed! %d", err);
233  }
234  }
235  // workout what type of EAP this is
236  // validation is not required as the config tool has already validated it
237  if (client_cert_len && client_key_len) {
238  // if we have certs, this must be EAP-TLS
239  err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
240  (uint8_t *) eap.client_key, client_key_len + 1,
241  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
242  if (err != ESP_OK) {
243  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed! %d", err);
244  }
245  } else {
246  // in the absence of certs, assume this is username/password based
247  err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
248  if (err != ESP_OK) {
249  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed! %d", err);
250  }
251  err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
252  if (err != ESP_OK) {
253  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed! %d", err);
254  }
255  }
256  err = esp_wifi_sta_wpa2_ent_enable();
257  if (err != ESP_OK) {
258  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed! %d", err);
259  }
260  }
261 #endif // USE_WIFI_WPA2_EAP
262 
263  this->wifi_apply_hostname_();
264 
265  s_sta_connecting = true;
266 
267  err = esp_wifi_connect();
268  if (err != ESP_OK) {
269  ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
270  return false;
271  }
272 
273  return true;
274 }
275 
277  // enable STA
278  if (!this->wifi_mode_(true, {}))
279  return false;
280 
281  esp_netif_dhcp_status_t dhcp_status;
282  esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
283  if (err != ESP_OK) {
284  ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
285  return false;
286  }
287 
288  if (!manual_ip.has_value()) {
289  // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
290  // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
291  // https://github.com/esphome/issues/issues/2299
292  sntp_servermode_dhcp(false);
293 
294  // No manual IP is set; use DHCP client
295  if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
296  err = esp_netif_dhcpc_start(s_sta_netif);
297  if (err != ESP_OK) {
298  ESP_LOGV(TAG, "Starting DHCP client failed! %d", err);
299  }
300  return err == ESP_OK;
301  }
302  return true;
303  }
304 
305  esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
306  info.ip = manual_ip->static_ip;
307  info.gw = manual_ip->gateway;
308  info.netmask = manual_ip->subnet;
309  err = esp_netif_dhcpc_stop(s_sta_netif);
310  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
311  ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err));
312  }
313 
314  err = esp_netif_set_ip_info(s_sta_netif, &info);
315  if (err != ESP_OK) {
316  ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err));
317  }
318 
319  esp_netif_dns_info_t dns;
320  if (manual_ip->dns1.is_set()) {
321  dns.ip = manual_ip->dns1;
322  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
323  }
324  if (manual_ip->dns2.is_set()) {
325  dns.ip = manual_ip->dns2;
326  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
327  }
328 
329  return true;
330 }
331 
333  if (!this->has_sta())
334  return {};
335  network::IPAddresses addresses;
336  esp_netif_ip_info_t ip;
337  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
338  if (err != ESP_OK) {
339  ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
340  // TODO: do something smarter
341  // return false;
342  } else {
343  addresses[0] = network::IPAddress(&ip.ip);
344  }
345 #if USE_NETWORK_IPV6
346  struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
347  uint8_t count = 0;
348  count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s);
349  assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
350  for (int i = 0; i < count; i++) {
351  addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
352  }
353 #endif /* USE_NETWORK_IPV6 */
354  return addresses;
355 }
356 
358  // setting is done in SYSTEM_EVENT_STA_START callback
359  return true;
360 }
361 const char *get_auth_mode_str(uint8_t mode) {
362  switch (mode) {
363  case WIFI_AUTH_OPEN:
364  return "OPEN";
365  case WIFI_AUTH_WEP:
366  return "WEP";
367  case WIFI_AUTH_WPA_PSK:
368  return "WPA PSK";
369  case WIFI_AUTH_WPA2_PSK:
370  return "WPA2 PSK";
371  case WIFI_AUTH_WPA_WPA2_PSK:
372  return "WPA/WPA2 PSK";
373  case WIFI_AUTH_WPA2_ENTERPRISE:
374  return "WPA2 Enterprise";
375  case WIFI_AUTH_WPA3_PSK:
376  return "WPA3 PSK";
377  case WIFI_AUTH_WPA2_WPA3_PSK:
378  return "WPA2/WPA3 PSK";
379  case WIFI_AUTH_WAPI_PSK:
380  return "WAPI PSK";
381  default:
382  return "UNKNOWN";
383  }
384 }
385 
386 using esphome_ip4_addr_t = esp_ip4_addr_t;
387 
388 std::string format_ip4_addr(const esphome_ip4_addr_t &ip) {
389  char buf[20];
390  sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
391  uint8_t(ip.addr >> 24));
392  return buf;
393 }
394 const char *get_op_mode_str(uint8_t mode) {
395  switch (mode) {
396  case WIFI_OFF:
397  return "OFF";
398  case WIFI_STA:
399  return "STA";
400  case WIFI_AP:
401  return "AP";
402  case WIFI_AP_STA:
403  return "AP+STA";
404  default:
405  return "UNKNOWN";
406  }
407 }
408 const char *get_disconnect_reason_str(uint8_t reason) {
409  switch (reason) {
410  case WIFI_REASON_AUTH_EXPIRE:
411  return "Auth Expired";
412  case WIFI_REASON_AUTH_LEAVE:
413  return "Auth Leave";
414  case WIFI_REASON_ASSOC_EXPIRE:
415  return "Association Expired";
416  case WIFI_REASON_ASSOC_TOOMANY:
417  return "Too Many Associations";
418  case WIFI_REASON_NOT_AUTHED:
419  return "Not Authenticated";
420  case WIFI_REASON_NOT_ASSOCED:
421  return "Not Associated";
422  case WIFI_REASON_ASSOC_LEAVE:
423  return "Association Leave";
424  case WIFI_REASON_ASSOC_NOT_AUTHED:
425  return "Association not Authenticated";
426  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
427  return "Disassociate Power Cap Bad";
428  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
429  return "Disassociate Supported Channel Bad";
430  case WIFI_REASON_IE_INVALID:
431  return "IE Invalid";
432  case WIFI_REASON_MIC_FAILURE:
433  return "Mic Failure";
434  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
435  return "4-Way Handshake Timeout";
436  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
437  return "Group Key Update Timeout";
438  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
439  return "IE In 4-Way Handshake Differs";
440  case WIFI_REASON_GROUP_CIPHER_INVALID:
441  return "Group Cipher Invalid";
442  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
443  return "Pairwise Cipher Invalid";
444  case WIFI_REASON_AKMP_INVALID:
445  return "AKMP Invalid";
446  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
447  return "Unsupported RSN IE version";
448  case WIFI_REASON_INVALID_RSN_IE_CAP:
449  return "Invalid RSN IE Cap";
450  case WIFI_REASON_802_1X_AUTH_FAILED:
451  return "802.1x Authentication Failed";
452  case WIFI_REASON_CIPHER_SUITE_REJECTED:
453  return "Cipher Suite Rejected";
454  case WIFI_REASON_BEACON_TIMEOUT:
455  return "Beacon Timeout";
456  case WIFI_REASON_NO_AP_FOUND:
457  return "AP Not Found";
458  case WIFI_REASON_AUTH_FAIL:
459  return "Authentication Failed";
460  case WIFI_REASON_ASSOC_FAIL:
461  return "Association Failed";
462  case WIFI_REASON_HANDSHAKE_TIMEOUT:
463  return "Handshake Failed";
464  case WIFI_REASON_CONNECTION_FAIL:
465  return "Connection Failed";
466  case WIFI_REASON_ROAMING:
467  return "Station Roaming";
468  case WIFI_REASON_UNSPECIFIED:
469  default:
470  return "Unspecified";
471  }
472 }
473 
475 
476 #define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY
477 #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE
478 #define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START
479 #define ESPHOME_EVENT_ID_WIFI_STA_STOP ARDUINO_EVENT_WIFI_STA_STOP
480 #define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED
481 #define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED
482 #define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE
483 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP
484 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6 ARDUINO_EVENT_WIFI_STA_GOT_IP6
485 #define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP ARDUINO_EVENT_WIFI_STA_LOST_IP
486 #define ESPHOME_EVENT_ID_WIFI_AP_START ARDUINO_EVENT_WIFI_AP_START
487 #define ESPHOME_EVENT_ID_WIFI_AP_STOP ARDUINO_EVENT_WIFI_AP_STOP
488 #define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED
489 #define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED ARDUINO_EVENT_WIFI_AP_STADISCONNECTED
490 #define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED
491 #define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED
492 #define ESPHOME_EVENT_ID_WIFI_AP_GOT_IP6 ARDUINO_EVENT_WIFI_AP_GOT_IP6
493 using esphome_wifi_event_id_t = arduino_event_id_t;
494 using esphome_wifi_event_info_t = arduino_event_info_t;
495 
497  switch (event) {
498  case ESPHOME_EVENT_ID_WIFI_READY: {
499  ESP_LOGV(TAG, "Event: WiFi ready");
500  break;
501  }
502  case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
503  auto it = info.wifi_scan_done;
504  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%u number=%u scan_id=%u", it.status, it.number, it.scan_id);
505 
506  this->wifi_scan_done_callback_();
507  break;
508  }
509  case ESPHOME_EVENT_ID_WIFI_STA_START: {
510  ESP_LOGV(TAG, "Event: WiFi STA start");
511  // apply hostname
512  s_sta_netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
513  esp_err_t err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
514  if (err != ERR_OK) {
515  ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
516  }
517  break;
518  }
519  case ESPHOME_EVENT_ID_WIFI_STA_STOP: {
520  ESP_LOGV(TAG, "Event: WiFi STA stop");
521  break;
522  }
523  case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
524  auto it = info.wifi_sta_connected;
525  char buf[33];
526  memcpy(buf, it.ssid, it.ssid_len);
527  buf[it.ssid_len] = '\0';
528  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
529  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
530 #if USE_NETWORK_IPV6
531  this->set_timeout(100, [] { WiFi.enableIpV6(); });
532 #endif /* USE_NETWORK_IPV6 */
533 
534  break;
535  }
536  case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
537  auto it = info.wifi_sta_disconnected;
538  char buf[33];
539  memcpy(buf, it.ssid, it.ssid_len);
540  buf[it.ssid_len] = '\0';
541  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
542  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
543  } else {
544  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
545  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
546  }
547 
548  uint8_t reason = it.reason;
549  if (reason == WIFI_REASON_AUTH_EXPIRE || reason == WIFI_REASON_BEACON_TIMEOUT ||
550  reason == WIFI_REASON_NO_AP_FOUND || reason == WIFI_REASON_ASSOC_FAIL ||
551  reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
552  err_t err = esp_wifi_disconnect();
553  if (err != ESP_OK) {
554  ESP_LOGV(TAG, "Disconnect failed: %s", esp_err_to_name(err));
555  }
556  this->error_from_callback_ = true;
557  }
558 
559  s_sta_connecting = false;
560  break;
561  }
562  case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
563  auto it = info.wifi_sta_authmode_change;
564  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
565  get_auth_mode_str(it.new_mode));
566  // Mitigate CVE-2020-12638
567  // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
568  if (it.old_mode != WIFI_AUTH_OPEN && it.new_mode == WIFI_AUTH_OPEN) {
569  ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting...");
570  // we can't call retry_connect() from this context, so disconnect immediately
571  // and notify main thread with error_from_callback_
572  err_t err = esp_wifi_disconnect();
573  if (err != ESP_OK) {
574  ESP_LOGW(TAG, "Disconnect failed: %s", esp_err_to_name(err));
575  }
576  this->error_from_callback_ = true;
577  }
578  break;
579  }
580  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP: {
581  auto it = info.got_ip.ip_info;
582  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip).c_str(),
583  format_ip4_addr(it.gw).c_str());
584  this->got_ipv4_address_ = true;
585 #if USE_NETWORK_IPV6
586  s_sta_connecting = this->num_ipv6_addresses_ < USE_NETWORK_MIN_IPV6_ADDR_COUNT;
587 #else
588  s_sta_connecting = false;
589 #endif /* USE_NETWORK_IPV6 */
590  break;
591  }
592 #if USE_NETWORK_IPV6
593  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6: {
594  auto it = info.got_ip6.ip6_info;
595  ESP_LOGV(TAG, "Got IPv6 address=" IPV6STR, IPV62STR(it.ip));
596  this->num_ipv6_addresses_++;
597  s_sta_connecting = !(this->got_ipv4_address_ & (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT));
598  break;
599  }
600 #endif /* USE_NETWORK_IPV6 */
601  case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP: {
602  ESP_LOGV(TAG, "Event: Lost IP");
603  this->got_ipv4_address_ = false;
604  break;
605  }
606  case ESPHOME_EVENT_ID_WIFI_AP_START: {
607  ESP_LOGV(TAG, "Event: WiFi AP start");
608  break;
609  }
610  case ESPHOME_EVENT_ID_WIFI_AP_STOP: {
611  ESP_LOGV(TAG, "Event: WiFi AP stop");
612  break;
613  }
614  case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
615  auto it = info.wifi_sta_connected;
616  auto &mac = it.bssid;
617  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(mac).c_str());
618  break;
619  }
620  case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
621  auto it = info.wifi_sta_disconnected;
622  auto &mac = it.bssid;
623  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(mac).c_str());
624  break;
625  }
626  case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED: {
627  ESP_LOGV(TAG, "Event: AP client assigned IP");
628  break;
629  }
630  case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
631  auto it = info.wifi_ap_probereqrecved;
632  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
633  break;
634  }
635  default:
636  break;
637  }
638 }
639 
641  auto status = WiFiClass::status();
642  if (status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST) {
644  }
645  if (status == WL_NO_SSID_AVAIL) {
647  }
648  if (s_sta_connecting) {
650  }
651  if (status == WL_CONNECTED) {
653  }
655 }
657  // enable STA
658  if (!this->wifi_mode_(true, {}))
659  return false;
660 
661  // need to use WiFi because of WiFiScanClass allocations :(
662  int16_t err = WiFi.scanNetworks(true, true, passive, 200);
663  if (err != WIFI_SCAN_RUNNING) {
664  ESP_LOGV(TAG, "WiFi.scanNetworks failed! %d", err);
665  return false;
666  }
667 
668  return true;
669 }
671  this->scan_result_.clear();
672 
673  int16_t num = WiFi.scanComplete();
674  if (num < 0)
675  return;
676 
677  this->scan_result_.reserve(static_cast<unsigned int>(num));
678  for (int i = 0; i < num; i++) {
679  String ssid = WiFi.SSID(i);
680  wifi_auth_mode_t authmode = WiFi.encryptionType(i);
681  int32_t rssi = WiFi.RSSI(i);
682  uint8_t *bssid = WiFi.BSSID(i);
683  int32_t channel = WiFi.channel(i);
684 
685  WiFiScanResult scan({bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]}, std::string(ssid.c_str()),
686  channel, rssi, authmode != WIFI_AUTH_OPEN, ssid.length() == 0);
687  this->scan_result_.push_back(scan);
688  }
689  WiFi.scanDelete();
690  this->scan_done_ = true;
691 }
692 
693 #ifdef USE_WIFI_AP
695  esp_err_t err;
696 
697  // enable AP
698  if (!this->wifi_mode_({}, true))
699  return false;
700 
701  esp_netif_ip_info_t info;
702  if (manual_ip.has_value()) {
703  info.ip = manual_ip->static_ip;
704  info.gw = manual_ip->gateway;
705  info.netmask = manual_ip->subnet;
706  } else {
707  info.ip = network::IPAddress(192, 168, 4, 1);
708  info.gw = network::IPAddress(192, 168, 4, 1);
709  info.netmask = network::IPAddress(255, 255, 255, 0);
710  }
711 
712  err = esp_netif_dhcps_stop(s_ap_netif);
713  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
714  ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
715  return false;
716  }
717 
718  err = esp_netif_set_ip_info(s_ap_netif, &info);
719  if (err != ESP_OK) {
720  ESP_LOGE(TAG, "esp_netif_set_ip_info failed! %d", err);
721  return false;
722  }
723 
724  dhcps_lease_t lease;
725  lease.enable = true;
726  network::IPAddress start_address = network::IPAddress(&info.ip);
727  start_address += 99;
728  lease.start_ip = start_address;
729  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
730  start_address += 10;
731  lease.end_ip = start_address;
732  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
733  err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
734 
735  if (err != ESP_OK) {
736  ESP_LOGE(TAG, "esp_netif_dhcps_option failed! %d", err);
737  return false;
738  }
739 
740  err = esp_netif_dhcps_start(s_ap_netif);
741 
742  if (err != ESP_OK) {
743  ESP_LOGE(TAG, "esp_netif_dhcps_start failed! %d", err);
744  return false;
745  }
746 
747  return true;
748 }
749 
751  // enable AP
752  if (!this->wifi_mode_({}, true))
753  return false;
754 
755  wifi_config_t conf;
756  memset(&conf, 0, sizeof(conf));
757  if (ap.get_ssid().size() > sizeof(conf.ap.ssid)) {
758  ESP_LOGE(TAG, "AP SSID is too long");
759  return false;
760  }
761  memcpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
762  conf.ap.channel = ap.get_channel().value_or(1);
763  conf.ap.ssid_hidden = ap.get_ssid().size();
764  conf.ap.max_connection = 5;
765  conf.ap.beacon_interval = 100;
766 
767  if (ap.get_password().empty()) {
768  conf.ap.authmode = WIFI_AUTH_OPEN;
769  *conf.ap.password = 0;
770  } else {
771  conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
772  if (ap.get_password().size() > sizeof(conf.ap.password)) {
773  ESP_LOGE(TAG, "AP password is too long");
774  return false;
775  }
776  memcpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), ap.get_password().size());
777  }
778 
779  // pairwise cipher of SoftAP, group cipher will be derived using this.
780  conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
781 
782  esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
783  if (err != ESP_OK) {
784  ESP_LOGV(TAG, "esp_wifi_set_config failed! %d", err);
785  return false;
786  }
787 
788  yield();
789 
790  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
791  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
792  return false;
793  }
794 
795  return true;
796 }
797 
799  esp_netif_ip_info_t ip;
800  esp_netif_get_ip_info(s_ap_netif, &ip);
801  return network::IPAddress(&ip.ip);
802 }
803 #endif // USE_WIFI_AP
804 
805 bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
806 
808  bssid_t bssid{};
809  uint8_t *raw_bssid = WiFi.BSSID();
810  if (raw_bssid != nullptr) {
811  for (size_t i = 0; i < bssid.size(); i++)
812  bssid[i] = raw_bssid[i];
813  }
814  return bssid;
815 }
816 std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
817 int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); }
818 int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
822 
823 } // namespace wifi
824 } // namespace esphome
825 
826 #endif // USE_ESP32_FRAMEWORK_ARDUINO
827 #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:739
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:736
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:685