ESPHome 2025.11.0b4
Loading...
Searching...
No Matches
wifi_component_esp8266.cpp
Go to the documentation of this file.
1#include "wifi_component.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
15extern "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
36#include "esphome/core/hal.h"
38#include "esphome/core/log.h"
39#include "esphome/core/util.h"
40
41namespace esphome {
42namespace wifi {
43
44static const char *const TAG = "wifi_esp8266";
45
46static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
47static bool s_sta_got_ip = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
48static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
49static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
51
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, "Set 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()
114extern "C" {
115struct netif *eagle_lwip_getif(int netif_index);
116void 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
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, "Set 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, "Set 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
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 if (ap.get_ssid().size() > sizeof(conf.ssid)) {
240 ESP_LOGE(TAG, "SSID too long");
241 return false;
242 }
243 if (ap.get_password().size() > sizeof(conf.password)) {
244 ESP_LOGE(TAG, "Password too long");
245 return false;
246 }
247 memcpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
248 memcpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), ap.get_password().size());
249
250 if (ap.get_bssid().has_value()) {
251 conf.bssid_set = 1;
252 memcpy(conf.bssid, ap.get_bssid()->data(), 6);
253 } else {
254 conf.bssid_set = 0;
255 }
256
257#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
258 if (ap.get_password().empty()) {
259 conf.threshold.authmode = AUTH_OPEN;
260 } else {
261 // Set threshold based on configured minimum auth mode
262 // Note: ESP8266 doesn't support WPA3
263 switch (this->min_auth_mode_) {
265 conf.threshold.authmode = AUTH_WPA_PSK;
266 break;
268 case WIFI_MIN_AUTH_MODE_WPA3: // Fall back to WPA2 for ESP8266
269 conf.threshold.authmode = AUTH_WPA2_PSK;
270 break;
271 }
272 }
273 conf.threshold.rssi = -127;
274#endif
275
276 ETS_UART_INTR_DISABLE();
277 bool ret = wifi_station_set_config_current(&conf);
278 ETS_UART_INTR_ENABLE();
279
280 if (!ret) {
281 ESP_LOGV(TAG, "Set Station config failed");
282 return false;
283 }
284
285#ifdef USE_WIFI_MANUAL_IP
286 if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
287 return false;
288 }
289#else
290 if (!this->wifi_sta_ip_config_({})) {
291 return false;
292 }
293#endif
294
295 // setup enterprise authentication if required
296#ifdef USE_WIFI_WPA2_EAP
297 if (ap.get_eap().has_value()) {
298 // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
299 EAPAuth eap = ap.get_eap().value();
300 ret = wifi_station_set_enterprise_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
301 if (ret) {
302 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed: %d", ret);
303 }
304 int ca_cert_len = strlen(eap.ca_cert);
305 int client_cert_len = strlen(eap.client_cert);
306 int client_key_len = strlen(eap.client_key);
307 if (ca_cert_len) {
308 ret = wifi_station_set_enterprise_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
309 if (ret) {
310 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed: %d", ret);
311 }
312 }
313 // workout what type of EAP this is
314 // validation is not required as the config tool has already validated it
315 if (client_cert_len && client_key_len) {
316 // if we have certs, this must be EAP-TLS
317 ret = wifi_station_set_enterprise_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
318 (uint8_t *) eap.client_key, client_key_len + 1,
319 (uint8_t *) eap.password.c_str(), eap.password.length());
320 if (ret) {
321 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed: %d", ret);
322 }
323 } else {
324 // in the absence of certs, assume this is username/password based
325 ret = wifi_station_set_enterprise_username((uint8_t *) eap.username.c_str(), eap.username.length());
326 if (ret) {
327 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed: %d", ret);
328 }
329 ret = wifi_station_set_enterprise_password((uint8_t *) eap.password.c_str(), eap.password.length());
330 if (ret) {
331 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed: %d", ret);
332 }
333 }
334 ret = wifi_station_set_wpa2_enterprise_auth(true);
335 if (ret) {
336 ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed: %d", ret);
337 }
338 }
339#endif // USE_WIFI_WPA2_EAP
340
341 this->wifi_apply_hostname_();
342
343 // Reset flags, do this _before_ wifi_station_connect as the callback method
344 // may be called from wifi_station_connect
345 s_sta_connecting = true;
346 s_sta_connected = false;
347 s_sta_got_ip = false;
348 s_sta_connect_error = false;
349 s_sta_connect_not_found = false;
350
351 ETS_UART_INTR_DISABLE();
352 ret = wifi_station_connect();
353 ETS_UART_INTR_ENABLE();
354 if (!ret) {
355 ESP_LOGV(TAG, "wifi_station_connect failed");
356 return false;
357 }
358
359#if USE_NETWORK_IPV6
360 bool connected = false;
361 while (!connected) {
362 uint8_t ipv6_addr_count = 0;
363 for (auto addr : addrList) {
364 ESP_LOGV(TAG, "Address %s", addr.toString().c_str());
365 if (addr.isV6()) {
366 ipv6_addr_count++;
367 }
368 }
369 delay(500); // NOLINT
370 connected = (ipv6_addr_count >= USE_NETWORK_MIN_IPV6_ADDR_COUNT);
371 }
372#endif /* USE_NETWORK_IPV6 */
373
374 if (ap.get_channel().has_value()) {
375 ret = wifi_set_channel(*ap.get_channel());
376 if (!ret) {
377 ESP_LOGV(TAG, "wifi_set_channel failed");
378 return false;
379 }
380 }
381
382 return true;
383}
384
385class WiFiMockClass : public ESP8266WiFiGenericClass {
386 public:
387 static void _event_callback(void *event) { ESP8266WiFiGenericClass::_eventCallback(event); } // NOLINT
388};
389
390const LogString *get_auth_mode_str(uint8_t mode) {
391 switch (mode) {
392 case AUTH_OPEN:
393 return LOG_STR("OPEN");
394 case AUTH_WEP:
395 return LOG_STR("WEP");
396 case AUTH_WPA_PSK:
397 return LOG_STR("WPA PSK");
398 case AUTH_WPA2_PSK:
399 return LOG_STR("WPA2 PSK");
400 case AUTH_WPA_WPA2_PSK:
401 return LOG_STR("WPA/WPA2 PSK");
402 default:
403 return LOG_STR("UNKNOWN");
404 }
405}
406#ifdef ipv4_addr
407std::string format_ip_addr(struct ipv4_addr ip) {
408 char buf[20];
409 sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
410 uint8_t(ip.addr >> 24));
411 return buf;
412}
413#else
414std::string format_ip_addr(struct ip_addr ip) {
415 char buf[20];
416 sprintf(buf, "%u.%u.%u.%u", uint8_t(ip.addr >> 0), uint8_t(ip.addr >> 8), uint8_t(ip.addr >> 16),
417 uint8_t(ip.addr >> 24));
418 return buf;
419}
420#endif
421const LogString *get_op_mode_str(uint8_t mode) {
422 switch (mode) {
423 case WIFI_OFF:
424 return LOG_STR("OFF");
425 case WIFI_STA:
426 return LOG_STR("STA");
427 case WIFI_AP:
428 return LOG_STR("AP");
429 case WIFI_AP_STA:
430 return LOG_STR("AP+STA");
431 default:
432 return LOG_STR("UNKNOWN");
433 }
434}
435
436const LogString *get_disconnect_reason_str(uint8_t reason) {
437 /* If this were one big switch statement, GCC would generate a lookup table for it. However, the values of the
438 * REASON_* constants aren't continuous, and GCC will fill in the gap with the default value -- wasting 4 bytes of RAM
439 * per entry. As there's ~175 default entries, this wastes 700 bytes of RAM.
440 */
441 if (reason <= REASON_CIPHER_SUITE_REJECTED) { // This must be the last constant with a value <200
442 switch (reason) {
443 case REASON_AUTH_EXPIRE:
444 return LOG_STR("Auth Expired");
445 case REASON_AUTH_LEAVE:
446 return LOG_STR("Auth Leave");
447 case REASON_ASSOC_EXPIRE:
448 return LOG_STR("Association Expired");
449 case REASON_ASSOC_TOOMANY:
450 return LOG_STR("Too Many Associations");
451 case REASON_NOT_AUTHED:
452 return LOG_STR("Not Authenticated");
453 case REASON_NOT_ASSOCED:
454 return LOG_STR("Not Associated");
455 case REASON_ASSOC_LEAVE:
456 return LOG_STR("Association Leave");
457 case REASON_ASSOC_NOT_AUTHED:
458 return LOG_STR("Association not Authenticated");
459 case REASON_DISASSOC_PWRCAP_BAD:
460 return LOG_STR("Disassociate Power Cap Bad");
461 case REASON_DISASSOC_SUPCHAN_BAD:
462 return LOG_STR("Disassociate Supported Channel Bad");
463 case REASON_IE_INVALID:
464 return LOG_STR("IE Invalid");
465 case REASON_MIC_FAILURE:
466 return LOG_STR("Mic Failure");
467 case REASON_4WAY_HANDSHAKE_TIMEOUT:
468 return LOG_STR("4-Way Handshake Timeout");
469 case REASON_GROUP_KEY_UPDATE_TIMEOUT:
470 return LOG_STR("Group Key Update Timeout");
471 case REASON_IE_IN_4WAY_DIFFERS:
472 return LOG_STR("IE In 4-Way Handshake Differs");
473 case REASON_GROUP_CIPHER_INVALID:
474 return LOG_STR("Group Cipher Invalid");
475 case REASON_PAIRWISE_CIPHER_INVALID:
476 return LOG_STR("Pairwise Cipher Invalid");
477 case REASON_AKMP_INVALID:
478 return LOG_STR("AKMP Invalid");
479 case REASON_UNSUPP_RSN_IE_VERSION:
480 return LOG_STR("Unsupported RSN IE version");
481 case REASON_INVALID_RSN_IE_CAP:
482 return LOG_STR("Invalid RSN IE Cap");
483 case REASON_802_1X_AUTH_FAILED:
484 return LOG_STR("802.1x Authentication Failed");
485 case REASON_CIPHER_SUITE_REJECTED:
486 return LOG_STR("Cipher Suite Rejected");
487 }
488 }
489
490 switch (reason) {
491 case REASON_BEACON_TIMEOUT:
492 return LOG_STR("Beacon Timeout");
493 case REASON_NO_AP_FOUND:
494 return LOG_STR("AP Not Found");
495 case REASON_AUTH_FAIL:
496 return LOG_STR("Authentication Failed");
497 case REASON_ASSOC_FAIL:
498 return LOG_STR("Association Failed");
499 case REASON_HANDSHAKE_TIMEOUT:
500 return LOG_STR("Handshake Failed");
501 case REASON_UNSPECIFIED:
502 default:
503 return LOG_STR("Unspecified");
504 }
505}
506
507void WiFiComponent::wifi_event_callback(System_Event_t *event) {
508 switch (event->event) {
509 case EVENT_STAMODE_CONNECTED: {
510 auto it = event->event_info.connected;
511 char buf[33];
512 memcpy(buf, it.ssid, it.ssid_len);
513 buf[it.ssid_len] = '\0';
514 ESP_LOGV(TAG, "Connected ssid='%s' bssid=%s channel=%u", buf, format_mac_address_pretty(it.bssid).c_str(),
515 it.channel);
516 s_sta_connected = true;
517 break;
518 }
519 case EVENT_STAMODE_DISCONNECTED: {
520 auto it = event->event_info.disconnected;
521 char buf[33];
522 memcpy(buf, it.ssid, it.ssid_len);
523 buf[it.ssid_len] = '\0';
524 if (it.reason == REASON_NO_AP_FOUND) {
525 ESP_LOGW(TAG, "Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
526 s_sta_connect_not_found = true;
527 } else {
528 ESP_LOGW(TAG, "Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
529 format_mac_address_pretty(it.bssid).c_str(), LOG_STR_ARG(get_disconnect_reason_str(it.reason)));
530 s_sta_connect_error = true;
531 }
532 s_sta_connected = false;
533 s_sta_connecting = false;
534 break;
535 }
536 case EVENT_STAMODE_AUTHMODE_CHANGE: {
537 auto it = event->event_info.auth_change;
538 ESP_LOGV(TAG, "Changed Authmode old=%s new=%s", LOG_STR_ARG(get_auth_mode_str(it.old_mode)),
539 LOG_STR_ARG(get_auth_mode_str(it.new_mode)));
540 // Mitigate CVE-2020-12638
541 // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
542 if (it.old_mode != AUTH_OPEN && it.new_mode == AUTH_OPEN) {
543 ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting");
544 // we can't call retry_connect() from this context, so disconnect immediately
545 // and notify main thread with error_from_callback_
546 wifi_station_disconnect();
548 }
549 break;
550 }
551 case EVENT_STAMODE_GOT_IP: {
552 auto it = event->event_info.got_ip;
553 ESP_LOGV(TAG, "static_ip=%s gateway=%s netmask=%s", format_ip_addr(it.ip).c_str(), format_ip_addr(it.gw).c_str(),
554 format_ip_addr(it.mask).c_str());
555 s_sta_got_ip = true;
556 break;
557 }
558 case EVENT_STAMODE_DHCP_TIMEOUT: {
559 ESP_LOGW(TAG, "DHCP request timeout");
560 break;
561 }
562 case EVENT_SOFTAPMODE_STACONNECTED: {
563 auto it = event->event_info.sta_connected;
564 ESP_LOGV(TAG, "AP client connected MAC=%s aid=%u", format_mac_address_pretty(it.mac).c_str(), it.aid);
565 break;
566 }
567 case EVENT_SOFTAPMODE_STADISCONNECTED: {
568 auto it = event->event_info.sta_disconnected;
569 ESP_LOGV(TAG, "AP client disconnected MAC=%s aid=%u", format_mac_address_pretty(it.mac).c_str(), it.aid);
570 break;
571 }
572 case EVENT_SOFTAPMODE_PROBEREQRECVED: {
573 auto it = event->event_info.ap_probereqrecved;
574 ESP_LOGVV(TAG, "AP receive Probe Request MAC=%s RSSI=%d", format_mac_address_pretty(it.mac).c_str(), it.rssi);
575 break;
576 }
577#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
578 case EVENT_OPMODE_CHANGED: {
579 auto it = event->event_info.opmode_changed;
580 ESP_LOGV(TAG, "Changed Mode old=%s new=%s", LOG_STR_ARG(get_op_mode_str(it.old_opmode)),
581 LOG_STR_ARG(get_op_mode_str(it.new_opmode)));
582 break;
583 }
584 case EVENT_SOFTAPMODE_DISTRIBUTE_STA_IP: {
585 auto it = event->event_info.distribute_sta_ip;
586 ESP_LOGV(TAG, "AP Distribute Station IP MAC=%s IP=%s aid=%u", format_mac_address_pretty(it.mac).c_str(),
587 format_ip_addr(it.ip).c_str(), it.aid);
588 break;
589 }
590#endif
591 default:
592 break;
593 }
594
595 if (event->event == EVENT_STAMODE_DISCONNECTED) {
597 }
598
599 WiFiMockClass::_event_callback(event);
600}
601
603 uint8_t val = static_cast<uint8_t>(output_power * 4);
604 system_phy_set_max_tpw(val);
605 return true;
606}
608 if (!this->wifi_mode_(true, {}))
609 return false;
610
611 bool ret1, ret2;
612 ETS_UART_INTR_DISABLE();
613 ret1 = wifi_station_set_auto_connect(0);
614 ret2 = wifi_station_set_reconnect_policy(false);
615 ETS_UART_INTR_ENABLE();
616
617 if (!ret1 || !ret2) {
618 ESP_LOGV(TAG, "Disabling Auto-Connect failed");
619 }
620
621 delay(10);
622 return true;
623}
624
626 wifi_set_event_handler_cb(&WiFiComponent::wifi_event_callback);
627
628 // Make sure WiFi is in clean state before anything starts
629 this->wifi_mode_(false, false);
630}
631
633 station_status_t status = wifi_station_get_connect_status();
634 switch (status) {
635 case STATION_GOT_IP:
637 case STATION_NO_AP_FOUND:
639 ;
640 case STATION_CONNECT_FAIL:
641 case STATION_WRONG_PASSWORD:
643 case STATION_CONNECTING:
645 case STATION_IDLE:
646 default:
648 }
649}
651 static bool first_scan = false;
652
653 // enable STA
654 if (!this->wifi_mode_(true, {}))
655 return false;
656
657 struct scan_config config {};
658 memset(&config, 0, sizeof(config));
659 config.ssid = nullptr;
660 config.bssid = nullptr;
661 config.channel = 0;
662 config.show_hidden = 1;
663#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(2, 4, 0)
664 config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
665 if (first_scan) {
666 if (passive) {
667 config.scan_time.passive = 200;
668 } else {
669 config.scan_time.active.min = 100;
670 config.scan_time.active.max = 200;
671 }
672 } else {
673 if (passive) {
674 config.scan_time.passive = 500;
675 } else {
676 config.scan_time.active.min = 400;
677 config.scan_time.active.max = 500;
678 }
679 }
680#endif
681 first_scan = false;
682 bool ret = wifi_station_scan(&config, &WiFiComponent::s_wifi_scan_done_callback);
683 if (!ret) {
684 ESP_LOGV(TAG, "wifi_station_scan failed");
685 return false;
686 }
687
688 return ret;
689}
691 bool ret = true;
692 // Only call disconnect if interface is up
693 if (wifi_get_opmode() & WIFI_STA)
694 ret = wifi_station_disconnect();
695 station_config conf{};
696 memset(&conf, 0, sizeof(conf));
697 ETS_UART_INTR_DISABLE();
698 wifi_station_set_config_current(&conf);
699 ETS_UART_INTR_ENABLE();
700 return ret;
701}
705
706void WiFiComponent::wifi_scan_done_callback_(void *arg, STATUS status) {
707 this->scan_result_.clear();
708
709 if (status != OK) {
710 ESP_LOGV(TAG, "Scan failed: %d", status);
711 this->retry_connect();
712 return;
713 }
714
715 // Count the number of results first
716 auto *head = reinterpret_cast<bss_info *>(arg);
717 size_t count = 0;
718 for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
719 count++;
720 }
721
722 this->scan_result_.init(count);
723 for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
724 this->scan_result_.emplace_back(
725 bssid_t{it->bssid[0], it->bssid[1], it->bssid[2], it->bssid[3], it->bssid[4], it->bssid[5]},
726 std::string(reinterpret_cast<char *>(it->ssid), it->ssid_len), it->channel, it->rssi, it->authmode != AUTH_OPEN,
727 it->is_hidden != 0);
728 }
729 this->scan_done_ = true;
730}
731
732#ifdef USE_WIFI_AP
734 // enable AP
735 if (!this->wifi_mode_({}, true))
736 return false;
737
738 struct ip_info info {};
739 if (manual_ip.has_value()) {
740 info.ip = manual_ip->static_ip;
741 info.gw = manual_ip->gateway;
742 info.netmask = manual_ip->subnet;
743 } else {
744 info.ip = network::IPAddress(192, 168, 4, 1);
745 info.gw = network::IPAddress(192, 168, 4, 1);
746 info.netmask = network::IPAddress(255, 255, 255, 0);
747 }
748
749 if (wifi_softap_dhcps_status() == DHCP_STARTED) {
750 if (!wifi_softap_dhcps_stop()) {
751 ESP_LOGW(TAG, "Stopping DHCP server failed");
752 }
753 }
754
755 if (!wifi_set_ip_info(SOFTAP_IF, &info)) {
756 ESP_LOGE(TAG, "Set SoftAP info failed");
757 return false;
758 }
759
760#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 0, 0) && USE_ARDUINO_VERSION_CODE < VERSION_CODE(3, 1, 0)
761 dhcpSoftAP.begin(&info);
762#endif
763
764 struct dhcps_lease lease {};
765 lease.enable = true;
766 network::IPAddress start_address = network::IPAddress(&info.ip);
767 start_address += 99;
768 lease.start_ip = start_address;
769 ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
770 start_address += 10;
771 lease.end_ip = start_address;
772 ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
773 if (!wifi_softap_set_dhcps_lease(&lease)) {
774 ESP_LOGE(TAG, "Set SoftAP DHCP lease failed");
775 return false;
776 }
777
778 // lease time 1440 minutes (=24 hours)
779 if (!wifi_softap_set_dhcps_lease_time(1440)) {
780 ESP_LOGE(TAG, "Set SoftAP DHCP lease time failed");
781 return false;
782 }
783
784#if USE_ARDUINO_VERSION_CODE >= VERSION_CODE(3, 1, 0)
785 ESP8266WiFiClass::softAPDhcpServer().setRouter(true); // send ROUTER option with netif's gateway IP
786#else
787 uint8_t mode = 1;
788 // bit0, 1 enables router information from ESP8266 SoftAP DHCP server.
789 if (!wifi_softap_set_dhcps_offer_option(OFFER_ROUTER, &mode)) {
790 ESP_LOGE(TAG, "wifi_softap_set_dhcps_offer_option failed");
791 return false;
792 }
793#endif
794
795 if (!wifi_softap_dhcps_start()) {
796 ESP_LOGE(TAG, "Starting SoftAP DHCPS failed");
797 return false;
798 }
799
800 return true;
801}
802
804 // enable AP
805 if (!this->wifi_mode_({}, true))
806 return false;
807
808 struct softap_config conf {};
809 if (ap.get_ssid().size() > sizeof(conf.ssid)) {
810 ESP_LOGE(TAG, "AP SSID too long");
811 return false;
812 }
813 memcpy(reinterpret_cast<char *>(conf.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
814 conf.ssid_len = static_cast<uint8>(ap.get_ssid().size());
815 conf.channel = ap.get_channel().value_or(1);
816 conf.ssid_hidden = ap.get_hidden();
817 conf.max_connection = 5;
818 conf.beacon_interval = 100;
819
820 if (ap.get_password().empty()) {
821 conf.authmode = AUTH_OPEN;
822 *conf.password = 0;
823 } else {
824 conf.authmode = AUTH_WPA2_PSK;
825 if (ap.get_password().size() > sizeof(conf.password)) {
826 ESP_LOGE(TAG, "AP password too long");
827 return false;
828 }
829 memcpy(reinterpret_cast<char *>(conf.password), ap.get_password().c_str(), ap.get_password().size());
830 }
831
832 ETS_UART_INTR_DISABLE();
833 bool ret = wifi_softap_set_config_current(&conf);
834 ETS_UART_INTR_ENABLE();
835
836 if (!ret) {
837 ESP_LOGV(TAG, "wifi_softap_set_config_current failed");
838 return false;
839 }
840
841#ifdef USE_WIFI_MANUAL_IP
842 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
843 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
844 return false;
845 }
846#else
847 if (!this->wifi_ap_ip_config_({})) {
848 ESP_LOGV(TAG, "wifi_ap_ip_config_ failed");
849 return false;
850 }
851#endif
852
853 return true;
854}
855
857 struct ip_info ip {};
858 wifi_get_ip_info(SOFTAP_IF, &ip);
859 return network::IPAddress(&ip.ip);
860}
861#endif // USE_WIFI_AP
862
864 bssid_t bssid{};
865 uint8_t *raw_bssid = WiFi.BSSID();
866 if (raw_bssid != nullptr) {
867 for (size_t i = 0; i < bssid.size(); i++)
868 bssid[i] = raw_bssid[i];
869 }
870 return bssid;
871}
872std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
873int8_t WiFiComponent::wifi_rssi() { return WiFi.status() == WL_CONNECTED ? WiFi.RSSI() : WIFI_RSSI_DISCONNECTED; }
874int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
875network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {(const ip_addr_t *) WiFi.subnetMask()}; }
876network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {(const ip_addr_t *) WiFi.gatewayIP()}; }
877network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {(const ip_addr_t *) WiFi.dnsIP(num)}; }
879
880} // namespace wifi
881} // namespace esphome
882
883#endif
884#endif
BedjetMode mode
BedJet operating mode.
uint8_t status
Definition bl0942.h:8
const std::string & get_name() const
Get the name of this Application set by pre_setup().
bool has_value() const
Definition optional.h:92
value_type value_or(U const &v) const
Definition optional.h:98
const optional< bssid_t > & get_bssid() const
const std::string & get_ssid() const
const optional< uint8_t > & get_channel() const
const optional< EAPAuth > & get_eap() const
const std::string & get_password() const
const optional< ManualIP > & get_manual_ip() const
void wifi_scan_done_callback_(void *arg, STATUS status)
wifi_scan_vector_t< WiFiScanResult > scan_result_
bool wifi_sta_ip_config_(optional< ManualIP > manual_ip)
static void wifi_event_callback(System_Event_t *event)
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
static void s_wifi_scan_done_callback(void *arg, STATUS status)
network::IPAddress wifi_dns_ip_(int num)
bool wifi_apply_output_power_(float output_power)
WiFiSTAConnectStatus wifi_sta_connect_status_()
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
network::IPAddresses wifi_sta_ip_addresses()
uint32_t ip_addr
in_addr ip_addr_t
Definition ip_address.h:22
in_addr ip4_addr_t
Definition ip_address.h:23
mopeka_std_values val[4]
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:144
const char *const TAG
Definition spi.cpp:8
std::array< uint8_t, 6 > bssid_t
const LogString * get_auth_mode_str(uint8_t mode)
const LogString * get_disconnect_reason_str(uint8_t reason)
struct netif * eagle_lwip_getif(int netif_index)
std::string format_ip_addr(struct ipv4_addr ip)
void netif_set_addr(struct netif *netif, const ip4_addr_t *ip, const ip4_addr_t *netmask, const ip4_addr_t *gw)
WiFiComponent * global_wifi_component
const LogString * get_op_mode_str(uint8_t mode)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string format_mac_address_pretty(const uint8_t *mac)
Definition helpers.cpp:282
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:31
Application App
Global storage of Application pointer - only one Application can exist.
std::string str() const
Definition ip_address.h:52