ESPHome  2023.3.1
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 advertises 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  err = esp_wifi_sta_wpa2_ent_enable();
270  if (err != ESP_OK) {
271  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed! %d", err);
272  }
273  }
274 #endif // USE_WIFI_WPA2_EAP
275 
276  this->wifi_apply_hostname_();
277 
278  s_sta_connecting = true;
279 
280  err = esp_wifi_connect();
281  if (err != ESP_OK) {
282  ESP_LOGW(TAG, "esp_wifi_connect failed! %d", err);
283  return false;
284  }
285 
286  return true;
287 }
288 const char *get_auth_mode_str(uint8_t mode) {
289  switch (mode) {
290  case WIFI_AUTH_OPEN:
291  return "OPEN";
292  case WIFI_AUTH_WEP:
293  return "WEP";
294  case WIFI_AUTH_WPA_PSK:
295  return "WPA PSK";
296  case WIFI_AUTH_WPA2_PSK:
297  return "WPA2 PSK";
298  case WIFI_AUTH_WPA_WPA2_PSK:
299  return "WPA/WPA2 PSK";
300  case WIFI_AUTH_WPA2_ENTERPRISE:
301  return "WPA2 Enterprise";
302  default:
303  return "UNKNOWN";
304  }
305 }
306 
307 #if ESP_IDF_VERSION_MAJOR >= 4
308 using esphome_ip4_addr_t = esp_ip4_addr_t;
309 #else
310 using esphome_ip4_addr_t = ip4_addr_t;
311 #endif
312 
313 std::string format_ip4_addr(const esphome_ip4_addr_t &ip) {
314  char buf[20];
315  sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
316  uint8_t(ip.addr >> 24));
317  return buf;
318 }
319 const char *get_op_mode_str(uint8_t mode) {
320  switch (mode) {
321  case WIFI_OFF:
322  return "OFF";
323  case WIFI_STA:
324  return "STA";
325  case WIFI_AP:
326  return "AP";
327  case WIFI_AP_STA:
328  return "AP+STA";
329  default:
330  return "UNKNOWN";
331  }
332 }
333 const char *get_disconnect_reason_str(uint8_t reason) {
334  switch (reason) {
335  case WIFI_REASON_AUTH_EXPIRE:
336  return "Auth Expired";
337  case WIFI_REASON_AUTH_LEAVE:
338  return "Auth Leave";
339  case WIFI_REASON_ASSOC_EXPIRE:
340  return "Association Expired";
341  case WIFI_REASON_ASSOC_TOOMANY:
342  return "Too Many Associations";
343  case WIFI_REASON_NOT_AUTHED:
344  return "Not Authenticated";
345  case WIFI_REASON_NOT_ASSOCED:
346  return "Not Associated";
347  case WIFI_REASON_ASSOC_LEAVE:
348  return "Association Leave";
349  case WIFI_REASON_ASSOC_NOT_AUTHED:
350  return "Association not Authenticated";
351  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
352  return "Disassociate Power Cap Bad";
353  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
354  return "Disassociate Supported Channel Bad";
355  case WIFI_REASON_IE_INVALID:
356  return "IE Invalid";
357  case WIFI_REASON_MIC_FAILURE:
358  return "Mic Failure";
359  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
360  return "4-Way Handshake Timeout";
361  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
362  return "Group Key Update Timeout";
363  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
364  return "IE In 4-Way Handshake Differs";
365  case WIFI_REASON_GROUP_CIPHER_INVALID:
366  return "Group Cipher Invalid";
367  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
368  return "Pairwise Cipher Invalid";
369  case WIFI_REASON_AKMP_INVALID:
370  return "AKMP Invalid";
371  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
372  return "Unsupported RSN IE version";
373  case WIFI_REASON_INVALID_RSN_IE_CAP:
374  return "Invalid RSN IE Cap";
375  case WIFI_REASON_802_1X_AUTH_FAILED:
376  return "802.1x Authentication Failed";
377  case WIFI_REASON_CIPHER_SUITE_REJECTED:
378  return "Cipher Suite Rejected";
379  case WIFI_REASON_BEACON_TIMEOUT:
380  return "Beacon Timeout";
381  case WIFI_REASON_NO_AP_FOUND:
382  return "AP Not Found";
383  case WIFI_REASON_AUTH_FAIL:
384  return "Authentication Failed";
385  case WIFI_REASON_ASSOC_FAIL:
386  return "Association Failed";
387  case WIFI_REASON_HANDSHAKE_TIMEOUT:
388  return "Handshake Failed";
389  case WIFI_REASON_CONNECTION_FAIL:
390  return "Connection Failed";
391  case WIFI_REASON_UNSPECIFIED:
392  default:
393  return "Unspecified";
394  }
395 }
396 
397 #if ESP_IDF_VERSION_MAJOR >= 4
398 
399 #define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY
400 #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE
401 #define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START
402 #define ESPHOME_EVENT_ID_WIFI_STA_STOP ARDUINO_EVENT_WIFI_STA_STOP
403 #define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED
404 #define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED
405 #define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE
406 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP
407 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6 ARDUINO_EVENT_WIFI_STA_GOT_IP6
408 #define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP ARDUINO_EVENT_WIFI_STA_LOST_IP
409 #define ESPHOME_EVENT_ID_WIFI_AP_START ARDUINO_EVENT_WIFI_AP_START
410 #define ESPHOME_EVENT_ID_WIFI_AP_STOP ARDUINO_EVENT_WIFI_AP_STOP
411 #define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED
412 #define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED ARDUINO_EVENT_WIFI_AP_STADISCONNECTED
413 #define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED
414 #define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED
415 #define ESPHOME_EVENT_ID_WIFI_AP_GOT_IP6 ARDUINO_EVENT_WIFI_AP_GOT_IP6
416 using esphome_wifi_event_id_t = arduino_event_id_t;
417 using esphome_wifi_event_info_t = arduino_event_info_t;
418 
419 #else // ESP_IDF_VERSION_MAJOR >= 4
420 
421 #define ESPHOME_EVENT_ID_WIFI_READY SYSTEM_EVENT_WIFI_READY
422 #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE
423 #define ESPHOME_EVENT_ID_WIFI_STA_START SYSTEM_EVENT_STA_START
424 #define ESPHOME_EVENT_ID_WIFI_STA_STOP SYSTEM_EVENT_STA_STOP
425 #define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED SYSTEM_EVENT_STA_CONNECTED
426 #define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED
427 #define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE SYSTEM_EVENT_STA_AUTHMODE_CHANGE
428 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP SYSTEM_EVENT_STA_GOT_IP
429 #define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP SYSTEM_EVENT_STA_LOST_IP
430 #define ESPHOME_EVENT_ID_WIFI_AP_START SYSTEM_EVENT_AP_START
431 #define ESPHOME_EVENT_ID_WIFI_AP_STOP SYSTEM_EVENT_AP_STOP
432 #define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED SYSTEM_EVENT_AP_STACONNECTED
433 #define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED SYSTEM_EVENT_AP_STADISCONNECTED
434 #define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED SYSTEM_EVENT_AP_STAIPASSIGNED
435 #define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED SYSTEM_EVENT_AP_PROBEREQRECVED
436 using esphome_wifi_event_id_t = system_event_id_t;
437 using esphome_wifi_event_info_t = system_event_info_t;
438 
439 #endif // !(ESP_IDF_VERSION_MAJOR >= 4)
440 
442  switch (event) {
443  case ESPHOME_EVENT_ID_WIFI_READY: {
444  ESP_LOGV(TAG, "Event: WiFi ready");
445  break;
446  }
447  case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
448 #if ESP_IDF_VERSION_MAJOR >= 4
449  auto it = info.wifi_scan_done;
450 #else
451  auto it = info.scan_done;
452 #endif
453  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%u number=%u scan_id=%u", it.status, it.number, it.scan_id);
454 
455  this->wifi_scan_done_callback_();
456  break;
457  }
458  case ESPHOME_EVENT_ID_WIFI_STA_START: {
459  ESP_LOGV(TAG, "Event: WiFi STA start");
460  tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, App.get_name().c_str());
461  break;
462  }
463  case ESPHOME_EVENT_ID_WIFI_STA_STOP: {
464  ESP_LOGV(TAG, "Event: WiFi STA stop");
465  break;
466  }
467  case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
468 #if ESP_IDF_VERSION_MAJOR >= 4
469  auto it = info.wifi_sta_connected;
470 #else
471  auto it = info.connected;
472 #endif
473  char buf[33];
474  memcpy(buf, it.ssid, it.ssid_len);
475  buf[it.ssid_len] = '\0';
476  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
477  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
478 
479  break;
480  }
481  case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
482 #if ESP_IDF_VERSION_MAJOR >= 4
483  auto it = info.wifi_sta_disconnected;
484 #else
485  auto it = info.disconnected;
486 #endif
487  char buf[33];
488  memcpy(buf, it.ssid, it.ssid_len);
489  buf[it.ssid_len] = '\0';
490  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
491  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
492  } else {
493  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
494  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
495  }
496 
497  uint8_t reason = it.reason;
498  if (reason == WIFI_REASON_AUTH_EXPIRE || reason == WIFI_REASON_BEACON_TIMEOUT ||
499  reason == WIFI_REASON_NO_AP_FOUND || reason == WIFI_REASON_ASSOC_FAIL ||
500  reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
501  err_t err = esp_wifi_disconnect();
502  if (err != ESP_OK) {
503  ESP_LOGV(TAG, "Disconnect failed: %s", esp_err_to_name(err));
504  }
505  this->error_from_callback_ = true;
506  }
507 
508  s_sta_connecting = false;
509  break;
510  }
511  case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
512 #if ESP_IDF_VERSION_MAJOR >= 4
513  auto it = info.wifi_sta_authmode_change;
514 #else
515  auto it = info.auth_change;
516 #endif
517  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
518  get_auth_mode_str(it.new_mode));
519  // Mitigate CVE-2020-12638
520  // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
521  if (it.old_mode != WIFI_AUTH_OPEN && it.new_mode == WIFI_AUTH_OPEN) {
522  ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting...");
523  // we can't call retry_connect() from this context, so disconnect immediately
524  // and notify main thread with error_from_callback_
525  err_t err = esp_wifi_disconnect();
526  if (err != ESP_OK) {
527  ESP_LOGW(TAG, "Disconnect failed: %s", esp_err_to_name(err));
528  }
529  this->error_from_callback_ = true;
530  }
531  break;
532  }
533  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP: {
534  auto it = info.got_ip.ip_info;
535  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip).c_str(),
536  format_ip4_addr(it.gw).c_str());
537  s_sta_connecting = false;
538  break;
539  }
540  case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP: {
541  ESP_LOGV(TAG, "Event: Lost IP");
542  break;
543  }
544  case ESPHOME_EVENT_ID_WIFI_AP_START: {
545  ESP_LOGV(TAG, "Event: WiFi AP start");
546  break;
547  }
548  case ESPHOME_EVENT_ID_WIFI_AP_STOP: {
549  ESP_LOGV(TAG, "Event: WiFi AP stop");
550  break;
551  }
552  case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
553 #if ESP_IDF_VERSION_MAJOR >= 4
554  auto it = info.wifi_sta_connected;
555  auto &mac = it.bssid;
556 #else
557  auto it = info.sta_connected;
558  auto &mac = it.mac;
559 #endif
560  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(mac).c_str());
561  break;
562  }
563  case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
564 #if ESP_IDF_VERSION_MAJOR >= 4
565  auto it = info.wifi_sta_disconnected;
566  auto &mac = it.bssid;
567 #else
568  auto it = info.sta_disconnected;
569  auto &mac = it.mac;
570 #endif
571  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(mac).c_str());
572  break;
573  }
574  case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED: {
575  ESP_LOGV(TAG, "Event: AP client assigned IP");
576  break;
577  }
578  case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
579 #if ESP_IDF_VERSION_MAJOR >= 4
580  auto it = info.wifi_ap_probereqrecved;
581 #else
582  auto it = info.ap_probereqrecved;
583 #endif
584  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
585  break;
586  }
587  default:
588  break;
589  }
590 }
592  auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2);
593  WiFi.onEvent(f);
594  WiFi.persistent(false);
595  // Make sure WiFi is in clean state before anything starts
596  this->wifi_mode_(false, false);
597 }
599  auto status = WiFiClass::status();
600  if (status == WL_CONNECTED) {
602  } else if (status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST) {
604  } else if (status == WL_NO_SSID_AVAIL) {
606  } else if (s_sta_connecting) {
608  }
610 }
612  // enable STA
613  if (!this->wifi_mode_(true, {}))
614  return false;
615 
616  // need to use WiFi because of WiFiScanClass allocations :(
617  int16_t err = WiFi.scanNetworks(true, true, false, 200);
618  if (err != WIFI_SCAN_RUNNING) {
619  ESP_LOGV(TAG, "WiFi.scanNetworks failed! %d", err);
620  return false;
621  }
622 
623  return true;
624 }
626  this->scan_result_.clear();
627 
628  int16_t num = WiFi.scanComplete();
629  if (num < 0)
630  return;
631 
632  this->scan_result_.reserve(static_cast<unsigned int>(num));
633  for (int i = 0; i < num; i++) {
634  String ssid = WiFi.SSID(i);
635  wifi_auth_mode_t authmode = WiFi.encryptionType(i);
636  int32_t rssi = WiFi.RSSI(i);
637  uint8_t *bssid = WiFi.BSSID(i);
638  int32_t channel = WiFi.channel(i);
639 
640  WiFiScanResult scan({bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]}, std::string(ssid.c_str()),
641  channel, rssi, authmode != WIFI_AUTH_OPEN, ssid.length() == 0);
642  this->scan_result_.push_back(scan);
643  }
644  WiFi.scanDelete();
645  this->scan_done_ = true;
646 }
648  esp_err_t err;
649 
650  // enable AP
651  if (!this->wifi_mode_({}, true))
652  return false;
653 
654  tcpip_adapter_ip_info_t info;
655  memset(&info, 0, sizeof(info));
656  if (manual_ip.has_value()) {
657  info.ip.addr = static_cast<uint32_t>(manual_ip->static_ip);
658  info.gw.addr = static_cast<uint32_t>(manual_ip->gateway);
659  info.netmask.addr = static_cast<uint32_t>(manual_ip->subnet);
660  } else {
661  info.ip.addr = static_cast<uint32_t>(network::IPAddress(192, 168, 4, 1));
662  info.gw.addr = static_cast<uint32_t>(network::IPAddress(192, 168, 4, 1));
663  info.netmask.addr = static_cast<uint32_t>(network::IPAddress(255, 255, 255, 0));
664  }
665  tcpip_adapter_dhcp_status_t dhcp_status;
666  tcpip_adapter_dhcps_get_status(TCPIP_ADAPTER_IF_AP, &dhcp_status);
667  err = tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP);
668  if (err != ESP_OK) {
669  ESP_LOGV(TAG, "tcpip_adapter_dhcps_stop failed! %d", err);
670  return false;
671  }
672 
673  err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info);
674  if (err != ESP_OK) {
675  ESP_LOGV(TAG, "tcpip_adapter_set_ip_info failed! %d", err);
676  return false;
677  }
678 
679  dhcps_lease_t lease;
680  lease.enable = true;
681  network::IPAddress start_address = info.ip.addr;
682  start_address[3] += 99;
683  lease.start_ip.addr = static_cast<uint32_t>(start_address);
684  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
685  start_address[3] += 100;
686  lease.end_ip.addr = static_cast<uint32_t>(start_address);
687  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
688  err = tcpip_adapter_dhcps_option(TCPIP_ADAPTER_OP_SET, TCPIP_ADAPTER_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
689 
690  if (err != ESP_OK) {
691  ESP_LOGV(TAG, "tcpip_adapter_dhcps_option failed! %d", err);
692  return false;
693  }
694 
695  err = tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP);
696 
697  if (err != ESP_OK) {
698  ESP_LOGV(TAG, "tcpip_adapter_dhcps_start failed! %d", err);
699  return false;
700  }
701 
702  return true;
703 }
705  // enable AP
706  if (!this->wifi_mode_({}, true))
707  return false;
708 
709  wifi_config_t conf;
710  memset(&conf, 0, sizeof(conf));
711  strncpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid));
712  conf.ap.channel = ap.get_channel().value_or(1);
713  conf.ap.ssid_hidden = ap.get_ssid().size();
714  conf.ap.max_connection = 5;
715  conf.ap.beacon_interval = 100;
716 
717  if (ap.get_password().empty()) {
718  conf.ap.authmode = WIFI_AUTH_OPEN;
719  *conf.ap.password = 0;
720  } else {
721  conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
722  strncpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.ssid));
723  }
724 
725 #if ESP_IDF_VERSION_MAJOR >= 4
726  // pairwise cipher of SoftAP, group cipher will be derived using this.
727  conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
728 #endif
729 
730  esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
731  if (err != ESP_OK) {
732  ESP_LOGV(TAG, "esp_wifi_set_config failed! %d", err);
733  return false;
734  }
735 
736  yield();
737 
738  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
739  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
740  return false;
741  }
742 
743  return true;
744 }
746  tcpip_adapter_ip_info_t ip;
747  tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip);
748  return {ip.ip.addr};
749 }
750 bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
751 
753  bssid_t bssid{};
754  uint8_t *raw_bssid = WiFi.BSSID();
755  if (raw_bssid != nullptr) {
756  for (size_t i = 0; i < bssid.size(); i++)
757  bssid[i] = raw_bssid[i];
758  }
759  return bssid;
760 }
761 std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
762 int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); }
763 int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); }
764 network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {WiFi.subnetMask()}; }
765 network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {WiFi.gatewayIP()}; }
766 network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {WiFi.dnsIP(num)}; }
768 
769 } // namespace wifi
770 } // namespace esphome
771 
772 #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:25
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:27