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