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