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