ESPHome  2024.9.0
wifi_component_esp8266.cpp
Go to the documentation of this file.
1 #include "wifi_component.h"
2 #include "esphome/core/defines.h"
3 
4 #ifdef USE_WIFI
5 #ifdef USE_ESP8266
6 
7 #include <user_interface.h>
8 
9 #include <utility>
10 #include <algorithm>
11 #ifdef USE_WIFI_WPA2_EAP
12 #include <wpa2_enterprise.h>
13 #endif
14 
15 extern "C" {
16 #include "lwip/err.h"
17 #include "lwip/dns.h"
18 #include "lwip/dhcp.h"
19 #include "lwip/init.h" // LWIP_VERSION_
20 #include "lwip/apps/sntp.h"
21 #include "lwip/netif.h" // struct netif
22 #include <AddrList.h>
23 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 0, 0)
24 #include "LwipDhcpServer.h"
25 #if USE_ARDUINO_VERSION_CODE < VERSION_CODE(3, 1, 0)
26 #include <ESP8266WiFi.h>
27 #include "ESP8266WiFiAP.h"
28 #define wifi_softap_set_dhcps_lease(lease) dhcpSoftAP.set_dhcps_lease(lease)
29 #define wifi_softap_set_dhcps_lease_time(time) dhcpSoftAP.set_dhcps_lease_time(time)
30 #define wifi_softap_set_dhcps_offer_option(offer, mode) dhcpSoftAP.set_dhcps_offer_option(offer, mode)
31 #endif
32 #endif
33 }
34 
35 #include "esphome/core/helpers.h"
36 #include "esphome/core/log.h"
37 #include "esphome/core/hal.h"
38 #include "esphome/core/util.h"
40 
41 namespace esphome {
42 namespace wifi {
43 
44 static const char *const TAG = "wifi_esp8266";
45 
46 static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
47 static bool s_sta_got_ip = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
48 static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
49 static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50 static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
51 
52 bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
53  uint8_t current_mode = wifi_get_opmode();
54  bool current_sta = current_mode & 0b01;
55  bool current_ap = current_mode & 0b10;
56  bool target_sta = sta.value_or(current_sta);
57  bool target_ap = ap.value_or(current_ap);
58  if (current_sta == target_sta && current_ap == target_ap)
59  return true;
60 
61  if (target_sta && !current_sta) {
62  ESP_LOGV(TAG, "Enabling STA.");
63  } else if (!target_sta && current_sta) {
64  ESP_LOGV(TAG, "Disabling STA.");
65  // Stop DHCP client when disabling STA
66  // See https://github.com/esp8266/Arduino/pull/5703
67  wifi_station_dhcpc_stop();
68  }
69  if (target_ap && !current_ap) {
70  ESP_LOGV(TAG, "Enabling AP.");
71  } else if (!target_ap && current_ap) {
72  ESP_LOGV(TAG, "Disabling AP.");
73  }
74 
75  ETS_UART_INTR_DISABLE();
76  uint8_t mode = 0;
77  if (target_sta)
78  mode |= 0b01;
79  if (target_ap)
80  mode |= 0b10;
81  bool ret = wifi_set_opmode_current(mode);
82  ETS_UART_INTR_ENABLE();
83 
84  if (!ret) {
85  ESP_LOGW(TAG, "Setting WiFi mode failed!");
86  }
87 
88  return ret;
89 }
91  sleep_type_t power_save;
92  switch (this->power_save_) {
94  power_save = LIGHT_SLEEP_T;
95  break;
97  power_save = MODEM_SLEEP_T;
98  break;
100  default:
101  power_save = NONE_SLEEP_T;
102  break;
103  }
104  wifi_fpm_auto_sleep_set_in_null_mode(1);
105  return wifi_set_sleep_type(power_save);
106 }
107 
108 #if LWIP_VERSION_MAJOR != 1
109 /*
110  lwip v2 needs to be notified of IP changes, see also
111  https://github.com/d-a-v/Arduino/blob/0e7d21e17144cfc5f53c016191daca8723e89ee8/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L251
112  */
113 #undef netif_set_addr // need to call lwIP-v1.4 netif_set_addr()
114 extern "C" {
115 struct netif *eagle_lwip_getif(int netif_index);
116 void netif_set_addr(struct netif *netif, const ip4_addr_t *ip, const ip4_addr_t *netmask, const ip4_addr_t *gw);
117 };
118 #endif
119 
120 bool WiFiComponent::wifi_sta_ip_config_(optional<ManualIP> manual_ip) {
121  // enable STA
122  if (!this->wifi_mode_(true, {}))
123  return false;
124 
125  enum dhcp_status dhcp_status = wifi_station_dhcpc_status();
126  if (!manual_ip.has_value()) {
127  // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
128  // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
129  // https://github.com/esphome/issues/issues/2299
130  sntp_servermode_dhcp(false);
131 
132  // Use DHCP client
133  if (dhcp_status != DHCP_STARTED) {
134  bool ret = wifi_station_dhcpc_start();
135  if (!ret) {
136  ESP_LOGV(TAG, "Starting DHCP client failed!");
137  }
138  return ret;
139  }
140  return true;
141  }
142 
143  bool ret = true;
144 
145 #if LWIP_VERSION_MAJOR != 1
146  // get current->previous IP address
147  // (check below)
148  ip_info previp{};
149  wifi_get_ip_info(STATION_IF, &previp);
150 #endif
151 
152  struct ip_info info {};
153  info.ip = manual_ip->static_ip;
154  info.gw = manual_ip->gateway;
155  info.netmask = manual_ip->subnet;
156 
157  if (dhcp_status == DHCP_STARTED) {
158  bool dhcp_stop_ret = wifi_station_dhcpc_stop();
159  if (!dhcp_stop_ret) {
160  ESP_LOGV(TAG, "Stopping DHCP client failed!");
161  ret = false;
162  }
163  }
164  bool wifi_set_info_ret = wifi_set_ip_info(STATION_IF, &info);
165  if (!wifi_set_info_ret) {
166  ESP_LOGV(TAG, "Setting manual IP info failed!");
167  ret = false;
168  }
169 
170  ip_addr_t dns;
171  if (manual_ip->dns1.is_set()) {
172  dns = manual_ip->dns1;
173  dns_setserver(0, &dns);
174  }
175  if (manual_ip->dns2.is_set()) {
176  dns = manual_ip->dns2;
177  dns_setserver(1, &dns);
178  }
179 
180 #if LWIP_VERSION_MAJOR != 1
181  // trigger address change by calling lwIP-v1.4 api
182  // only when ip is already set by other mean (generally dhcp)
183  if (previp.ip.addr != 0 && previp.ip.addr != info.ip.addr) {
184  netif_set_addr(eagle_lwip_getif(STATION_IF), reinterpret_cast<const ip4_addr_t *>(&info.ip),
185  reinterpret_cast<const ip4_addr_t *>(&info.netmask), reinterpret_cast<const ip4_addr_t *>(&info.gw));
186  }
187 #endif
188  return ret;
189 }
190 
192  if (!this->has_sta())
193  return {};
194  network::IPAddresses addresses;
195  uint8_t index = 0;
196  for (auto &addr : addrList) {
197  addresses[index++] = addr.ipFromNetifNum();
198  }
199  return addresses;
200 }
202  const std::string &hostname = App.get_name();
203  bool ret = wifi_station_set_hostname(const_cast<char *>(hostname.c_str()));
204  if (!ret) {
205  ESP_LOGV(TAG, "Setting WiFi Hostname failed!");
206  }
207 
208  // inform dhcp server of hostname change using dhcp_renew()
209  for (netif *intf = netif_list; intf; intf = intf->next) {
210  // unconditionally update all known interfaces
211 #if LWIP_VERSION_MAJOR == 1
212  intf->hostname = (char *) wifi_station_get_hostname();
213 #else
214  intf->hostname = wifi_station_get_hostname();
215 #endif
216  if (netif_dhcp_data(intf) != nullptr) {
217  // renew already started DHCP leases
218  err_t lwipret = dhcp_renew(intf);
219  if (lwipret != ERR_OK) {
220  ESP_LOGW(TAG, "wifi_apply_hostname_(%s): lwIP error %d on interface %c%c (index %d)", intf->hostname,
221  (int) lwipret, intf->name[0], intf->name[1], intf->num);
222  ret = false;
223  }
224  }
225  }
226 
227  return ret;
228 }
229 
230 bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
231  // enable STA
232  if (!this->wifi_mode_(true, {}))
233  return false;
234 
235  this->wifi_disconnect_();
236 
237  struct station_config conf {};
238  memset(&conf, 0, sizeof(conf));
239  strncpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid));
240  strncpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), sizeof(conf.password));
241 
242  if (ap.get_bssid().has_value()) {
243  conf.bssid_set = 1;
244  memcpy(conf.bssid, ap.get_bssid()->data(), 6);
245  } else {
246  conf.bssid_set = 0;
247  }
248 
249 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
250  if (ap.get_password().empty()) {
251  conf.threshold.authmode = AUTH_OPEN;
252  } else {
253  // Only allow auth modes with at least WPA
254  conf.threshold.authmode = AUTH_WPA_PSK;
255  }
256  conf.threshold.rssi = -127;
257 #endif
258 
259  ETS_UART_INTR_DISABLE();
260  bool ret = wifi_station_set_config_current(&conf);
261  ETS_UART_INTR_ENABLE();
262 
263  if (!ret) {
264  ESP_LOGV(TAG, "Setting WiFi Station config failed!");
265  return false;
266  }
267 
268  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
269  return false;
270  }
271 
272  // setup enterprise authentication if required
273 #ifdef USE_WIFI_WPA2_EAP
274  if (ap.get_eap().has_value()) {
275  // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
276  EAPAuth eap = ap.get_eap().value();
277  ret = wifi_station_set_enterprise_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
278  if (ret) {
279  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed! %d", ret);
280  }
281  int ca_cert_len = strlen(eap.ca_cert);
282  int client_cert_len = strlen(eap.client_cert);
283  int client_key_len = strlen(eap.client_key);
284  if (ca_cert_len) {
285  ret = wifi_station_set_enterprise_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
286  if (ret) {
287  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed! %d", ret);
288  }
289  }
290  // workout what type of EAP this is
291  // validation is not required as the config tool has already validated it
292  if (client_cert_len && client_key_len) {
293  // if we have certs, this must be EAP-TLS
294  ret = wifi_station_set_enterprise_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
295  (uint8_t *) eap.client_key, client_key_len + 1,
296  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
297  if (ret) {
298  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed! %d", ret);
299  }
300  } else {
301  // in the absence of certs, assume this is username/password based
302  ret = wifi_station_set_enterprise_username((uint8_t *) eap.username.c_str(), eap.username.length());
303  if (ret) {
304  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed! %d", ret);
305  }
306  ret = wifi_station_set_enterprise_password((uint8_t *) eap.password.c_str(), eap.password.length());
307  if (ret) {
308  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed! %d", ret);
309  }
310  }
311  ret = wifi_station_set_wpa2_enterprise_auth(true);
312  if (ret) {
313  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed! %d", ret);
314  }
315  }
316 #endif // USE_WIFI_WPA2_EAP
317 
318  this->wifi_apply_hostname_();
319 
320  // Reset flags, do this _before_ wifi_station_connect as the callback method
321  // may be called from wifi_station_connect
322  s_sta_connecting = true;
323  s_sta_connected = false;
324  s_sta_got_ip = false;
325  s_sta_connect_error = false;
326  s_sta_connect_not_found = false;
327 
328  ETS_UART_INTR_DISABLE();
329  ret = wifi_station_connect();
330  ETS_UART_INTR_ENABLE();
331  if (!ret) {
332  ESP_LOGV(TAG, "wifi_station_connect failed!");
333  return false;
334  }
335 
336 #if USE_NETWORK_IPV6
337  bool connected = false;
338  while (!connected) {
339  uint8_t ipv6_addr_count = 0;
340  for (auto addr : addrList) {
341  ESP_LOGV(TAG, "Address %s", addr.toString().c_str());
342  if (addr.isV6()) {
343  ipv6_addr_count++;
344  }
345  }
346  delay(500); // NOLINT
347  connected = (ipv6_addr_count >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
348  }
349 #endif /* USE_NETWORK_IPV6 */
350 
351  if (ap.get_channel().has_value()) {
352  ret = wifi_set_channel(*ap.get_channel());
353  if (!ret) {
354  ESP_LOGV(TAG, "wifi_set_channel failed!");
355  return false;
356  }
357  }
358 
359  return true;
360 }
361 
362 class WiFiMockClass : public ESP8266WiFiGenericClass {
363  public:
364  static void _event_callback(void *event) { ESP8266WiFiGenericClass::_eventCallback(event); } // NOLINT
365 };
366 
367 const LogString *get_auth_mode_str(uint8_t mode) {
368  switch (mode) {
369  case AUTH_OPEN:
370  return LOG_STR("OPEN");
371  case AUTH_WEP:
372  return LOG_STR("WEP");
373  case AUTH_WPA_PSK:
374  return LOG_STR("WPA PSK");
375  case AUTH_WPA2_PSK:
376  return LOG_STR("WPA2 PSK");
377  case AUTH_WPA_WPA2_PSK:
378  return LOG_STR("WPA/WPA2 PSK");
379  default:
380  return LOG_STR("UNKNOWN");
381  }
382 }
383 #ifdef ipv4_addr
384 std::string format_ip_addr(struct ipv4_addr ip) {
385  char buf[20];
386  sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
387  uint8_t(ip.addr >> 24));
388  return buf;
389 }
390 #else
391 std::string format_ip_addr(struct ip_addr ip) {
392  char buf[20];
393  sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
394  uint8_t(ip.addr >> 24));
395  return buf;
396 }
397 #endif
398 const LogString *get_op_mode_str(uint8_t mode) {
399  switch (mode) {
400  case WIFI_OFF:
401  return LOG_STR("OFF");
402  case WIFI_STA:
403  return LOG_STR("STA");
404  case WIFI_AP:
405  return LOG_STR("AP");
406  case WIFI_AP_STA:
407  return LOG_STR("AP+STA");
408  default:
409  return LOG_STR("UNKNOWN");
410  }
411 }
412 
413 const LogString *get_disconnect_reason_str(uint8_t reason) {
414  /* If this were one big switch statement, GCC would generate a lookup table for it. However, the values of the
415  * REASON_* constants aren't continuous, and GCC will fill in the gap with the default value -- wasting 4 bytes of RAM
416  * per entry. As there's ~175 default entries, this wastes 700 bytes of RAM.
417  */
418  if (reason <= REASON_CIPHER_SUITE_REJECTED) { // This must be the last constant with a value <200
419  switch (reason) {
420  case REASON_AUTH_EXPIRE:
421  return LOG_STR("Auth Expired");
422  case REASON_AUTH_LEAVE:
423  return LOG_STR("Auth Leave");
424  case REASON_ASSOC_EXPIRE:
425  return LOG_STR("Association Expired");
426  case REASON_ASSOC_TOOMANY:
427  return LOG_STR("Too Many Associations");
428  case REASON_NOT_AUTHED:
429  return LOG_STR("Not Authenticated");
430  case REASON_NOT_ASSOCED:
431  return LOG_STR("Not Associated");
432  case REASON_ASSOC_LEAVE:
433  return LOG_STR("Association Leave");
434  case REASON_ASSOC_NOT_AUTHED:
435  return LOG_STR("Association not Authenticated");
436  case REASON_DISASSOC_PWRCAP_BAD:
437  return LOG_STR("Disassociate Power Cap Bad");
438  case REASON_DISASSOC_SUPCHAN_BAD:
439  return LOG_STR("Disassociate Supported Channel Bad");
440  case REASON_IE_INVALID:
441  return LOG_STR("IE Invalid");
442  case REASON_MIC_FAILURE:
443  return LOG_STR("Mic Failure");
444  case REASON_4WAY_HANDSHAKE_TIMEOUT:
445  return LOG_STR("4-Way Handshake Timeout");
446  case REASON_GROUP_KEY_UPDATE_TIMEOUT:
447  return LOG_STR("Group Key Update Timeout");
448  case REASON_IE_IN_4WAY_DIFFERS:
449  return LOG_STR("IE In 4-Way Handshake Differs");
450  case REASON_GROUP_CIPHER_INVALID:
451  return LOG_STR("Group Cipher Invalid");
452  case REASON_PAIRWISE_CIPHER_INVALID:
453  return LOG_STR("Pairwise Cipher Invalid");
454  case REASON_AKMP_INVALID:
455  return LOG_STR("AKMP Invalid");
456  case REASON_UNSUPP_RSN_IE_VERSION:
457  return LOG_STR("Unsupported RSN IE version");
458  case REASON_INVALID_RSN_IE_CAP:
459  return LOG_STR("Invalid RSN IE Cap");
460  case REASON_802_1X_AUTH_FAILED:
461  return LOG_STR("802.1x Authentication Failed");
462  case REASON_CIPHER_SUITE_REJECTED:
463  return LOG_STR("Cipher Suite Rejected");
464  }
465  }
466 
467  switch (reason) {
468  case REASON_BEACON_TIMEOUT:
469  return LOG_STR("Beacon Timeout");
470  case REASON_NO_AP_FOUND:
471  return LOG_STR("AP Not Found");
472  case REASON_AUTH_FAIL:
473  return LOG_STR("Authentication Failed");
474  case REASON_ASSOC_FAIL:
475  return LOG_STR("Association Failed");
476  case REASON_HANDSHAKE_TIMEOUT:
477  return LOG_STR("Handshake Failed");
478  case REASON_UNSPECIFIED:
479  default:
480  return LOG_STR("Unspecified");
481  }
482 }
483 
484 void WiFiComponent::wifi_event_callback(System_Event_t *event) {
485  switch (event->event) {
486  case EVENT_STAMODE_CONNECTED: {
487  auto it = event->event_info.connected;
488  char buf[33];
489  memcpy(buf, it.ssid, it.ssid_len);
490  buf[it.ssid_len] = '\0';
491  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=%s channel=%u", buf, format_mac_addr(it.bssid).c_str(),
492  it.channel);
493  s_sta_connected = true;
494  break;
495  }
496  case EVENT_STAMODE_DISCONNECTED: {
497  auto it = event->event_info.disconnected;
498  char buf[33];
499  memcpy(buf, it.ssid, it.ssid_len);
500  buf[it.ssid_len] = '\0';
501  if (it.reason == REASON_NO_AP_FOUND) {
502  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
503  s_sta_connect_not_found = true;
504  } else {
505  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
506  format_mac_addr(it.bssid).c_str(), LOG_STR_ARG(get_disconnect_reason_str(it.reason)));
507  s_sta_connect_error = true;
508  }
509  s_sta_connected = false;
510  s_sta_connecting = false;
511  break;
512  }
513  case EVENT_STAMODE_AUTHMODE_CHANGE: {
514  auto it = event->event_info.auth_change;
515  ESP_LOGV(TAG, "Event: Changed AuthMode old=%s new=%s", LOG_STR_ARG(get_auth_mode_str(it.old_mode)),
516  LOG_STR_ARG(get_auth_mode_str(it.new_mode)));
517  // Mitigate CVE-2020-12638
518  // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
519  if (it.old_mode != AUTH_OPEN && it.new_mode == AUTH_OPEN) {
520  ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting...");
521  // we can't call retry_connect() from this context, so disconnect immediately
522  // and notify main thread with error_from_callback_
523  wifi_station_disconnect();
525  }
526  break;
527  }
528  case EVENT_STAMODE_GOT_IP: {
529  auto it = event->event_info.got_ip;
530  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s netmask=%s", format_ip_addr(it.ip).c_str(),
531  format_ip_addr(it.gw).c_str(), format_ip_addr(it.mask).c_str());
532  s_sta_got_ip = true;
533  break;
534  }
535  case EVENT_STAMODE_DHCP_TIMEOUT: {
536  ESP_LOGW(TAG, "Event: Getting IP address timeout");
537  break;
538  }
539  case EVENT_SOFTAPMODE_STACONNECTED: {
540  auto it = event->event_info.sta_connected;
541  ESP_LOGV(TAG, "Event: AP client connected MAC=%s aid=%u", format_mac_addr(it.mac).c_str(), it.aid);
542  break;
543  }
544  case EVENT_SOFTAPMODE_STADISCONNECTED: {
545  auto it = event->event_info.sta_disconnected;
546  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s aid=%u", format_mac_addr(it.mac).c_str(), it.aid);
547  break;
548  }
549  case EVENT_SOFTAPMODE_PROBEREQRECVED: {
550  auto it = event->event_info.ap_probereqrecved;
551  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
552  break;
553  }
554 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
555  case EVENT_OPMODE_CHANGED: {
556  auto it = event->event_info.opmode_changed;
557  ESP_LOGV(TAG, "Event: Changed Mode old=%s new=%s", LOG_STR_ARG(get_op_mode_str(it.old_opmode)),
558  LOG_STR_ARG(get_op_mode_str(it.new_opmode)));
559  break;
560  }
561  case EVENT_SOFTAPMODE_DISTRIBUTE_STA_IP: {
562  auto it = event->event_info.distribute_sta_ip;
563  ESP_LOGV(TAG, "Event: AP Distribute Station IP MAC=%s IP=%s aid=%u", format_mac_addr(it.mac).c_str(),
564  format_ip_addr(it.ip).c_str(), it.aid);
565  break;
566  }
567 #endif
568  default:
569  break;
570  }
571 
572  if (event->event == EVENT_STAMODE_DISCONNECTED) {
574  }
575 
576  WiFiMockClass::_event_callback(event);
577 }
578 
579 bool WiFiComponent::wifi_apply_output_power_(float output_power) {
580  uint8_t val = static_cast<uint8_t>(output_power * 4);
581  system_phy_set_max_tpw(val);
582  return true;
583 }
585  if (!this->wifi_mode_(true, {}))
586  return false;
587 
588  bool ret1, ret2;
589  ETS_UART_INTR_DISABLE();
590  ret1 = wifi_station_set_auto_connect(0);
591  ret2 = wifi_station_set_reconnect_policy(false);
592  ETS_UART_INTR_ENABLE();
593 
594  if (!ret1 || !ret2) {
595  ESP_LOGV(TAG, "Disabling Auto-Connect failed!");
596  }
597 
598  delay(10);
599  return true;
600 }
601 
603  wifi_set_event_handler_cb(&WiFiComponent::wifi_event_callback);
604 
605  // Make sure WiFi is in clean state before anything starts
606  this->wifi_mode_(false, false);
607 }
608 
610  station_status_t status = wifi_station_get_connect_status();
611  switch (status) {
612  case STATION_GOT_IP:
614  case STATION_NO_AP_FOUND:
616  ;
617  case STATION_CONNECT_FAIL:
618  case STATION_WRONG_PASSWORD:
620  case STATION_CONNECTING:
622  case STATION_IDLE:
623  default:
625  }
626 }
627 bool WiFiComponent::wifi_scan_start_(bool passive) {
628  static bool first_scan = false;
629 
630  // enable STA
631  if (!this->wifi_mode_(true, {}))
632  return false;
633 
634  struct scan_config config {};
635  memset(&config, 0, sizeof(config));
636  config.ssid = nullptr;
637  config.bssid = nullptr;
638  config.channel = 0;
639  config.show_hidden = 1;
640 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
641  config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
642  if (first_scan) {
643  if (passive) {
644  config.scan_time.passive = 200;
645  } else {
646  config.scan_time.active.min = 100;
647  config.scan_time.active.max = 200;
648  }
649  } else {
650  if (passive) {
651  config.scan_time.passive = 500;
652  } else {
653  config.scan_time.active.min = 400;
654  config.scan_time.active.max = 500;
655  }
656  }
657 #endif
658  first_scan = false;
659  bool ret = wifi_station_scan(&config, &WiFiComponent::s_wifi_scan_done_callback);
660  if (!ret) {
661  ESP_LOGV(TAG, "wifi_station_scan failed!");
662  return false;
663  }
664 
665  return ret;
666 }
668  bool ret = true;
669  // Only call disconnect if interface is up
670  if (wifi_get_opmode() & WIFI_STA)
671  ret = wifi_station_disconnect();
672  station_config conf{};
673  memset(&conf, 0, sizeof(conf));
674  ETS_UART_INTR_DISABLE();
675  wifi_station_set_config_current(&conf);
676  ETS_UART_INTR_ENABLE();
677  return ret;
678 }
681 }
682 
684  this->scan_result_.clear();
685 
686  if (status != OK) {
687  ESP_LOGV(TAG, "Scan failed! %d", status);
688  this->retry_connect();
689  return;
690  }
691  auto *head = reinterpret_cast<bss_info *>(arg);
692  for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
693  WiFiScanResult res({it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]},
694  std::string(reinterpret_cast<char *>(it->ssid), it->ssid_len), it->channel, it->rssi,
695  it->authmode != AUTH_OPEN, it->is_hidden != 0);
696  this->scan_result_.push_back(res);
697  }
698  this->scan_done_ = true;
699 }
700 
701 #ifdef USE_WIFI_AP
703  // enable AP
704  if (!this->wifi_mode_({}, true))
705  return false;
706 
707  struct ip_info info {};
708  if (manual_ip.has_value()) {
709  info.ip = manual_ip->static_ip;
710  info.gw = manual_ip->gateway;
711  info.netmask = manual_ip->subnet;
712  } else {
713  info.ip = network::IPAddress(192, 168, 4, 1);
714  info.gw = network::IPAddress(192, 168, 4, 1);
715  info.netmask = network::IPAddress(255, 255, 255, 0);
716  }
717 
718  if (wifi_softap_dhcps_status() == DHCP_STARTED) {
719  if (!wifi_softap_dhcps_stop()) {
720  ESP_LOGW(TAG, "Stopping DHCP server failed!");
721  }
722  }
723 
724  if (!wifi_set_ip_info(SOFTAP_IF, &info)) {
725  ESP_LOGE(TAG, "Setting SoftAP info failed!");
726  return false;
727  }
728 
729 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 0, 0) && USE_ARDUINO_VERSION_CODE < VERSION_CODE(3, 1, 0)
730  dhcpSoftAP.begin(&info);
731 #endif
732 
733  struct dhcps_lease lease {};
734  lease.enable = true;
735  network::IPAddress start_address = network::IPAddress(&info.ip);
736  start_address += 99;
737  lease.start_ip = start_address;
738  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
739  start_address += 10;
740  lease.end_ip = start_address;
741  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
742  if (!wifi_softap_set_dhcps_lease(&lease)) {
743  ESP_LOGE(TAG, "Setting SoftAP DHCP lease failed!");
744  return false;
745  }
746 
747  // lease time 1440 minutes (=24 hours)
748  if (!wifi_softap_set_dhcps_lease_time(1440)) {
749  ESP_LOGE(TAG, "Setting SoftAP DHCP lease time failed!");
750  return false;
751  }
752 
753 #if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 1, 0)
754  ESP8266WiFiClass::softAPDhcpServer().setRouter(true); // send ROUTER option with netif's gateway IP
755 #else
756  uint8_t mode = 1;
757  // bit0, 1 enables router information from ESP8266 SoftAP DHCP server.
758  if (!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) {
759  ESP_LOGE(TAG, "wifi_softap_set_dhcps_offer_option failed!");
760  return false;
761  }
762 #endif
763 
764  if (!wifi_softap_dhcps_start()) {
765  ESP_LOGE(TAG, "Starting SoftAP DHCPS failed!");
766  return false;
767  }
768 
769  return true;
770 }
771 
772 bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
773  // enable AP
774  if (!this->wifi_mode_({}, true))
775  return false;
776 
777  struct softap_config conf {};
778  strncpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), sizeof(conf.ssid));
779  conf.ssid_len = static_cast<uint8>(ap.get_ssid().size());
780  conf.channel = ap.get_channel().value_or(1);
781  conf.ssid_hidden = ap.get_hidden();
782  conf.max_connection = 5;
783  conf.beacon_interval = 100;
784 
785  if (ap.get_password().empty()) {
786  conf.authmode = AUTH_OPEN;
787  *conf.password = 0;
788  } else {
789  conf.authmode = AUTH_WPA2_PSK;
790  strncpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), sizeof(conf.password));
791  }
792 
793  ETS_UART_INTR_DISABLE();
794  bool ret = wifi_softap_set_config_current(&conf);
795  ETS_UART_INTR_ENABLE();
796 
797  if (!ret) {
798  ESP_LOGV(TAG, "wifi_softap_set_config_current failed!");
799  return false;
800  }
801 
802  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
803  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
804  return false;
805  }
806 
807  return true;
808 }
809 
811  struct ip_info ip {};
812  wifi_get_ip_info(SOFTAP_IF, &ip);
813  return network::IPAddress(&ip.ip);
814 }
815 #endif // USE_WIFI_AP
816 
818  bssid_t bssid{};
819  uint8_t *raw_bssid = WiFi.BSSID();
820  if (raw_bssid != nullptr) {
821  for (size_t i = 0; i < bssid.size(); i++)
822  bssid[i] = raw_bssid[i];
823  }
824  return bssid;
825 }
826 std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
827 int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); }
828 int32_t WiFiComponent::wifi_channel_() { return WiFi.channel(); }
829 network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {(const ip_addr_t *) WiFi.subnetMask()}; }
830 network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {(const ip_addr_t *) WiFi.gatewayIP()}; }
831 network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {(const ip_addr_t *) WiFi.dnsIP(num)}; }
833 
834 } // namespace wifi
835 } // namespace esphome
836 
837 #endif
838 #endif
std::string format_ip_addr(struct ipv4_addr ip)
std::array< uint8_t, 6 > bssid_t
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)
std::string str() const
Definition: ip_address.h:122
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_
void netif_set_addr(struct netif *netif, const ip4_addr_t *ip, const ip4_addr_t *netmask, const ip4_addr_t *gw)
const char *const TAG
Definition: spi.cpp:8
struct netif * eagle_lwip_getif(int netif_index)
const optional< ManualIP > & get_manual_ip() const
in_addr ip4_addr_t
Definition: ip_address.h:23
const optional< uint8_t > & get_channel() const
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:181
Application App
Global storage of Application pointer - only one Application can exist.
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
WiFiComponent * global_wifi_component
const std::string & get_name() const
Get the name of this Application set by pre_setup().
Definition: application.h:202
std::array< IPAddress, 5 > IPAddresses
Definition: ip_address.h:141
static void s_wifi_scan_done_callback(void *arg, STATUS status)
uint8_t status
Definition: bl0942.h:74
void wifi_scan_done_callback_(void *arg, STATUS status)
const char * get_auth_mode_str(uint8_t mode)
in_addr ip_addr_t
Definition: ip_address.h:22
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
static void wifi_event_callback(System_Event_t *event)
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