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