ESPHome 2025.5.0
Loading...
Searching...
No Matches
wifi_component_esp_idf.cpp
Go to the documentation of this file.
1#include "wifi_component.h"
2
3#ifdef USE_WIFI
4#ifdef USE_ESP_IDF
5
6#include <esp_event.h>
7#include <esp_netif.h>
8#include <esp_system.h>
9#include <esp_wifi.h>
10#include <esp_wifi_types.h>
11#include <freertos/FreeRTOS.h>
12#include <freertos/event_groups.h>
13#include <freertos/task.h>
14
15#include <algorithm>
16#include <cinttypes>
17#include <utility>
18#ifdef USE_WIFI_WPA2_EAP
19#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
20#include <esp_eap_client.h>
21#else
22#include <esp_wpa2.h>
23#endif
24#endif
25
26#ifdef USE_WIFI_AP
27#include "dhcpserver/dhcpserver.h"
28#endif // USE_WIFI_AP
29
30#include "lwip/apps/sntp.h"
31#include "lwip/dns.h"
32#include "lwip/err.h"
33
35#include "esphome/core/hal.h"
37#include "esphome/core/log.h"
38#include "esphome/core/util.h"
39
40namespace esphome {
41namespace wifi {
42
43static const char *const TAG = "wifi_esp32";
44
45static EventGroupHandle_t s_wifi_event_group; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
46static QueueHandle_t s_event_queue; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
47static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
48#ifdef USE_WIFI_AP
49static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50#endif // USE_WIFI_AP
51static bool s_sta_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
52static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
53static bool s_ap_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
54static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
55static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
56static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
57static bool s_wifi_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
58
59struct IDFWiFiEvent {
60 esp_event_base_t event_base;
61 int32_t event_id;
62 union {
63 wifi_event_sta_scan_done_t sta_scan_done;
64 wifi_event_sta_connected_t sta_connected;
65 wifi_event_sta_disconnected_t sta_disconnected;
66 wifi_event_sta_authmode_change_t sta_authmode_change;
67 wifi_event_ap_staconnected_t ap_staconnected;
68 wifi_event_ap_stadisconnected_t ap_stadisconnected;
69 wifi_event_ap_probe_req_rx_t ap_probe_req_rx;
70 wifi_event_bss_rssi_low_t bss_rssi_low;
71 ip_event_got_ip_t ip_got_ip;
72#if USE_NETWORK_IPV6
73 ip_event_got_ip6_t ip_got_ip6;
74#endif /* USE_NETWORK_IPV6 */
75 ip_event_ap_staipassigned_t ip_ap_staipassigned;
76 } data;
77};
78
79// general design: event handler translates events and pushes them to a queue,
80// events get processed in the main loop
81void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
82 IDFWiFiEvent event;
83 memset(&event, 0, sizeof(IDFWiFiEvent));
84 event.event_base = event_base;
85 event.event_id = event_id;
86 if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { // NOLINT(bugprone-branch-clone)
87 // no data
88 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_STOP) { // NOLINT(bugprone-branch-clone)
89 // no data
90 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
91 memcpy(&event.data.sta_authmode_change, event_data, sizeof(wifi_event_sta_authmode_change_t));
92 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) {
93 memcpy(&event.data.sta_connected, event_data, sizeof(wifi_event_sta_connected_t));
94 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
95 memcpy(&event.data.sta_disconnected, event_data, sizeof(wifi_event_sta_disconnected_t));
96 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
97 memcpy(&event.data.ip_got_ip, event_data, sizeof(ip_event_got_ip_t));
98#if USE_NETWORK_IPV6
99 } else if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
100 memcpy(&event.data.ip_got_ip6, event_data, sizeof(ip_event_got_ip6_t));
101#endif
102 } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) { // NOLINT(bugprone-branch-clone)
103 // no data
104 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
105 memcpy(&event.data.sta_scan_done, event_data, sizeof(wifi_event_sta_scan_done_t));
106 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) { // NOLINT(bugprone-branch-clone)
107 // no data
108 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STOP) { // NOLINT(bugprone-branch-clone)
109 // no data
110 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
111 memcpy(&event.data.ap_probe_req_rx, event_data, sizeof(wifi_event_ap_probe_req_rx_t));
112 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
113 memcpy(&event.data.ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t));
114 } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
115 memcpy(&event.data.ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t));
116 } else if (event_base == IP_EVENT && event_id == IP_EVENT_AP_STAIPASSIGNED) {
117 memcpy(&event.data.ip_ap_staipassigned, event_data, sizeof(ip_event_ap_staipassigned_t));
118 } else {
119 // did not match any event, don't send anything
120 return;
121 }
122
123 // copy to heap to keep queue object small
124 auto *to_send = new IDFWiFiEvent; // NOLINT(cppcoreguidelines-owning-memory)
125 memcpy(to_send, &event, sizeof(IDFWiFiEvent));
126 // don't block, we may miss events but the core can handle that
127 if (xQueueSend(s_event_queue, &to_send, 0L) != pdPASS) {
128 delete to_send; // NOLINT(cppcoreguidelines-owning-memory)
129 }
130}
131
133 uint8_t mac[6];
136 set_mac_address(mac);
137 }
138 esp_err_t err = esp_netif_init();
139 if (err != ERR_OK) {
140 ESP_LOGE(TAG, "esp_netif_init failed: %s", esp_err_to_name(err));
141 return;
142 }
143 s_wifi_event_group = xEventGroupCreate();
144 if (s_wifi_event_group == nullptr) {
145 ESP_LOGE(TAG, "xEventGroupCreate failed");
146 return;
147 }
148 // NOLINTNEXTLINE(bugprone-sizeof-expression)
149 s_event_queue = xQueueCreate(64, sizeof(IDFWiFiEvent *));
150 if (s_event_queue == nullptr) {
151 ESP_LOGE(TAG, "xQueueCreate failed");
152 return;
153 }
154 err = esp_event_loop_create_default();
155 if (err != ERR_OK) {
156 ESP_LOGE(TAG, "esp_event_loop_create_default failed: %s", esp_err_to_name(err));
157 return;
158 }
159 esp_event_handler_instance_t instance_wifi_id, instance_ip_id;
160 err = esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_wifi_id);
161 if (err != ERR_OK) {
162 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
163 return;
164 }
165 err = esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, &event_handler, nullptr, &instance_ip_id);
166 if (err != ERR_OK) {
167 ESP_LOGE(TAG, "esp_event_handler_instance_register failed: %s", esp_err_to_name(err));
168 return;
169 }
170
171 s_sta_netif = esp_netif_create_default_wifi_sta();
172
173#ifdef USE_WIFI_AP
174 s_ap_netif = esp_netif_create_default_wifi_ap();
175#endif // USE_WIFI_AP
176
177 wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
178 // cfg.nvs_enable = false;
179 err = esp_wifi_init(&cfg);
180 if (err != ERR_OK) {
181 ESP_LOGE(TAG, "esp_wifi_init failed: %s", esp_err_to_name(err));
182 return;
183 }
184 err = esp_wifi_set_storage(WIFI_STORAGE_RAM);
185 if (err != ERR_OK) {
186 ESP_LOGE(TAG, "esp_wifi_set_storage failed: %s", esp_err_to_name(err));
187 return;
188 }
189}
190
191bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
192 esp_err_t err;
193 wifi_mode_t current_mode = WIFI_MODE_NULL;
194 if (s_wifi_started) {
195 err = esp_wifi_get_mode(&current_mode);
196 if (err != ERR_OK) {
197 ESP_LOGW(TAG, "esp_wifi_get_mode failed: %s", esp_err_to_name(err));
198 return false;
199 }
200 }
201 bool current_sta = current_mode == WIFI_MODE_STA || current_mode == WIFI_MODE_APSTA;
202 bool current_ap = current_mode == WIFI_MODE_AP || current_mode == WIFI_MODE_APSTA;
203
204 bool set_sta = sta.value_or(current_sta);
205 bool set_ap = ap.value_or(current_ap);
206
207 wifi_mode_t set_mode;
208 if (set_sta && set_ap) {
209 set_mode = WIFI_MODE_APSTA;
210 } else if (set_sta && !set_ap) {
211 set_mode = WIFI_MODE_STA;
212 } else if (!set_sta && set_ap) {
213 set_mode = WIFI_MODE_AP;
214 } else {
215 set_mode = WIFI_MODE_NULL;
216 }
217
218 if (current_mode == set_mode)
219 return true;
220
221 if (set_sta && !current_sta) {
222 ESP_LOGV(TAG, "Enabling STA.");
223 } else if (!set_sta && current_sta) {
224 ESP_LOGV(TAG, "Disabling STA.");
225 }
226 if (set_ap && !current_ap) {
227 ESP_LOGV(TAG, "Enabling AP.");
228 } else if (!set_ap && current_ap) {
229 ESP_LOGV(TAG, "Disabling AP.");
230 }
231
232 if (set_mode == WIFI_MODE_NULL && s_wifi_started) {
233 err = esp_wifi_stop();
234 if (err != ESP_OK) {
235 ESP_LOGV(TAG, "esp_wifi_stop failed: %s", esp_err_to_name(err));
236 return false;
237 }
238 s_wifi_started = false;
239 return true;
240 }
241
242 err = esp_wifi_set_mode(set_mode);
243 if (err != ERR_OK) {
244 ESP_LOGW(TAG, "esp_wifi_set_mode failed: %s", esp_err_to_name(err));
245 return false;
246 }
247
248 if (set_mode != WIFI_MODE_NULL && !s_wifi_started) {
249 err = esp_wifi_start();
250 if (err != ESP_OK) {
251 ESP_LOGV(TAG, "esp_wifi_start failed: %s", esp_err_to_name(err));
252 return false;
253 }
254 s_wifi_started = true;
255 }
256
257 return true;
258}
259
260bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
261
262bool WiFiComponent::wifi_apply_output_power_(float output_power) {
263 int8_t val = static_cast<int8_t>(output_power * 4);
264 return esp_wifi_set_max_tx_power(val) == ESP_OK;
265}
266
268 wifi_ps_type_t power_save;
269 switch (this->power_save_) {
271 power_save = WIFI_PS_MIN_MODEM;
272 break;
274 power_save = WIFI_PS_MAX_MODEM;
275 break;
277 default:
278 power_save = WIFI_PS_NONE;
279 break;
280 }
281 return esp_wifi_set_ps(power_save) == ESP_OK;
282}
283
284bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
285 // enable STA
286 if (!this->wifi_mode_(true, {}))
287 return false;
288
289 // https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/network/esp_wifi.html#_CPPv417wifi_sta_config_t
290 wifi_config_t conf;
291 memset(&conf, 0, sizeof(conf));
292 if (ap.get_ssid().size() > sizeof(conf.sta.ssid)) {
293 ESP_LOGE(TAG, "SSID is too long");
294 return false;
295 }
296 if (ap.get_password().size() > sizeof(conf.sta.password)) {
297 ESP_LOGE(TAG, "password is too long");
298 return false;
299 }
300 memcpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
301 memcpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), ap.get_password().size());
302
303 // The weakest authmode to accept in the fast scan mode
304 if (ap.get_password().empty()) {
305 conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
306 } else {
307 conf.sta.threshold.authmode = WIFI_AUTH_WPA_WPA2_PSK;
308 }
309
310#ifdef USE_WIFI_WPA2_EAP
311 if (ap.get_eap().has_value()) {
312 conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
313 }
314#endif
315
316#ifdef USE_WIFI_11KV_SUPPORT
317 conf.sta.btm_enabled = this->btm_;
318 conf.sta.rm_enabled = this->rrm_;
319#endif
320
321 if (ap.get_bssid().has_value()) {
322 conf.sta.bssid_set = true;
323 memcpy(conf.sta.bssid, ap.get_bssid()->data(), 6);
324 } else {
325 conf.sta.bssid_set = false;
326 }
327 if (ap.get_channel().has_value()) {
328 conf.sta.channel = *ap.get_channel();
329 conf.sta.scan_method = WIFI_FAST_SCAN;
330 } else {
331 conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
332 }
333 // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
334 // Units: AP beacon intervals. Defaults to 3 if set to 0.
335 conf.sta.listen_interval = 0;
336
337 // Protected Management Frame
338 // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
339 conf.sta.pmf_cfg.capable = true;
340 conf.sta.pmf_cfg.required = false;
341
342 // note, we do our own filtering
343 // The minimum rssi to accept in the fast scan mode
344 conf.sta.threshold.rssi = -127;
345
346 conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
347
348 wifi_config_t current_conf;
349 esp_err_t err;
350 err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
351 if (err != ERR_OK) {
352 ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
353 // can continue
354 }
355
356 if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
357 err = esp_wifi_disconnect();
358 if (err != ESP_OK) {
359 ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
360 return false;
361 }
362 }
363
364 err = esp_wifi_set_config(WIFI_IF_STA, &conf);
365 if (err != ESP_OK) {
366 ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
367 return false;
368 }
369
370 if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
371 return false;
372 }
373
374 // setup enterprise authentication if required
375#ifdef USE_WIFI_WPA2_EAP
376 if (ap.get_eap().has_value()) {
377 // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
378 EAPAuth eap = ap.get_eap().value();
379#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
380 err = esp_eap_client_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
381#else
382 err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
383#endif
384 if (err != ESP_OK) {
385 ESP_LOGV(TAG, "set_identity failed %d", err);
386 }
387 int ca_cert_len = strlen(eap.ca_cert);
388 int client_cert_len = strlen(eap.client_cert);
389 int client_key_len = strlen(eap.client_key);
390 if (ca_cert_len) {
391#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
392 err = esp_eap_client_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
393#else
394 err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
395#endif
396 if (err != ESP_OK) {
397 ESP_LOGV(TAG, "set_ca_cert failed %d", err);
398 }
399 }
400 // workout what type of EAP this is
401 // validation is not required as the config tool has already validated it
402 if (client_cert_len && client_key_len) {
403 // if we have certs, this must be EAP-TLS
404#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
405 err = esp_eap_client_set_certificate_and_key((uint8_t *) eap.client_cert, client_cert_len + 1,
406 (uint8_t *) eap.client_key, client_key_len + 1,
407 (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
408#else
409 err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
410 (uint8_t *) eap.client_key, client_key_len + 1,
411 (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
412#endif
413 if (err != ESP_OK) {
414 ESP_LOGV(TAG, "set_cert_key failed %d", err);
415 }
416 } else {
417 // in the absence of certs, assume this is username/password based
418#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
419 err = esp_eap_client_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
420#else
421 err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
422#endif
423 if (err != ESP_OK) {
424 ESP_LOGV(TAG, "set_username failed %d", err);
425 }
426#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
427 err = esp_eap_client_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
428#else
429 err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
430#endif
431 if (err != ESP_OK) {
432 ESP_LOGV(TAG, "set_password failed %d", err);
433 }
434 // set TTLS Phase 2, defaults to MSCHAPV2
435#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
436 err = esp_eap_client_set_ttls_phase2_method(eap.ttls_phase_2);
437#else
438 err = esp_wifi_sta_wpa2_ent_set_ttls_phase2_method(eap.ttls_phase_2);
439#endif
440 if (err != ESP_OK) {
441 ESP_LOGV(TAG, "set_ttls_phase2_method failed %d", err);
442 }
443 }
444#if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
445 err = esp_wifi_sta_enterprise_enable();
446#else
447 err = esp_wifi_sta_wpa2_ent_enable();
448#endif
449 if (err != ESP_OK) {
450 ESP_LOGV(TAG, "enterprise_enable failed %d", err);
451 }
452 }
453#endif // USE_WIFI_WPA2_EAP
454
455 // Reset flags, do this _before_ wifi_station_connect as the callback method
456 // may be called from wifi_station_connect
457 s_sta_connecting = true;
458 s_sta_connected = false;
459 s_sta_connect_error = false;
460 s_sta_connect_not_found = false;
461
462 err = esp_wifi_connect();
463 if (err != ESP_OK) {
464 ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
465 return false;
466 }
467
468 return true;
469}
470
471bool WiFiComponent::wifi_sta_ip_config_(optional<ManualIP> manual_ip) {
472 // enable STA
473 if (!this->wifi_mode_(true, {}))
474 return false;
475
476 esp_netif_dhcp_status_t dhcp_status;
477 esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
478 if (err != ESP_OK) {
479 ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
480 return false;
481 }
482
483 if (!manual_ip.has_value()) {
484 // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
485 // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
486 // https://github.com/esphome/issues/issues/2299
487 sntp_servermode_dhcp(false);
488
489 // No manual IP is set; use DHCP client
490 if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
491 err = esp_netif_dhcpc_start(s_sta_netif);
492 if (err != ESP_OK) {
493 ESP_LOGV(TAG, "Starting DHCP client failed! %d", err);
494 }
495 return err == ESP_OK;
496 }
497 return true;
498 }
499
500 esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
501 info.ip = manual_ip->static_ip;
502 info.gw = manual_ip->gateway;
503 info.netmask = manual_ip->subnet;
504 err = esp_netif_dhcpc_stop(s_sta_netif);
505 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
506 ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err));
507 }
508
509 err = esp_netif_set_ip_info(s_sta_netif, &info);
510 if (err != ESP_OK) {
511 ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err));
512 }
513
514 esp_netif_dns_info_t dns;
515 if (manual_ip->dns1.is_set()) {
516 dns.ip = manual_ip->dns1;
517 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
518 }
519 if (manual_ip->dns2.is_set()) {
520 dns.ip = manual_ip->dns2;
521 esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
522 }
523
524 return true;
525}
526
528 if (!this->has_sta())
529 return {};
530 network::IPAddresses addresses;
531 esp_netif_ip_info_t ip;
532 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
533 if (err != ESP_OK) {
534 ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
535 // TODO: do something smarter
536 // return false;
537 } else {
538 addresses[0] = network::IPAddress(&ip.ip);
539 }
540#if USE_NETWORK_IPV6
541 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
542 uint8_t count = 0;
543 count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s);
544 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
545 for (int i = 0; i < count; i++) {
546 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
547 }
548#endif /* USE_NETWORK_IPV6 */
549 return addresses;
550}
551
553 // setting is done in SYSTEM_EVENT_STA_START callback
554 return true;
555}
556const char *get_auth_mode_str(uint8_t mode) {
557 switch (mode) {
558 case WIFI_AUTH_OPEN:
559 return "OPEN";
560 case WIFI_AUTH_WEP:
561 return "WEP";
562 case WIFI_AUTH_WPA_PSK:
563 return "WPA PSK";
564 case WIFI_AUTH_WPA2_PSK:
565 return "WPA2 PSK";
566 case WIFI_AUTH_WPA_WPA2_PSK:
567 return "WPA/WPA2 PSK";
568 case WIFI_AUTH_WPA2_ENTERPRISE:
569 return "WPA2 Enterprise";
570 case WIFI_AUTH_WPA3_PSK:
571 return "WPA3 PSK";
572 case WIFI_AUTH_WPA2_WPA3_PSK:
573 return "WPA2/WPA3 PSK";
574 case WIFI_AUTH_WAPI_PSK:
575 return "WAPI PSK";
576 default:
577 return "UNKNOWN";
578 }
579}
580
581std::string format_ip4_addr(const esp_ip4_addr_t &ip) { return str_snprintf(IPSTR, 15, IP2STR(&ip)); }
582#if LWIP_IPV6
583std::string format_ip6_addr(const esp_ip6_addr_t &ip) { return str_snprintf(IPV6STR, 39, IPV62STR(ip)); }
584#endif /* LWIP_IPV6 */
585const char *get_disconnect_reason_str(uint8_t reason) {
586 switch (reason) {
587 case WIFI_REASON_AUTH_EXPIRE:
588 return "Auth Expired";
589 case WIFI_REASON_AUTH_LEAVE:
590 return "Auth Leave";
591 case WIFI_REASON_ASSOC_EXPIRE:
592 return "Association Expired";
593 case WIFI_REASON_ASSOC_TOOMANY:
594 return "Too Many Associations";
595 case WIFI_REASON_NOT_AUTHED:
596 return "Not Authenticated";
597 case WIFI_REASON_NOT_ASSOCED:
598 return "Not Associated";
599 case WIFI_REASON_ASSOC_LEAVE:
600 return "Association Leave";
601 case WIFI_REASON_ASSOC_NOT_AUTHED:
602 return "Association not Authenticated";
603 case WIFI_REASON_DISASSOC_PWRCAP_BAD:
604 return "Disassociate Power Cap Bad";
605 case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
606 return "Disassociate Supported Channel Bad";
607 case WIFI_REASON_IE_INVALID:
608 return "IE Invalid";
609 case WIFI_REASON_MIC_FAILURE:
610 return "Mic Failure";
611 case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
612 return "4-Way Handshake Timeout";
613 case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
614 return "Group Key Update Timeout";
615 case WIFI_REASON_IE_IN_4WAY_DIFFERS:
616 return "IE In 4-Way Handshake Differs";
617 case WIFI_REASON_GROUP_CIPHER_INVALID:
618 return "Group Cipher Invalid";
619 case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
620 return "Pairwise Cipher Invalid";
621 case WIFI_REASON_AKMP_INVALID:
622 return "AKMP Invalid";
623 case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
624 return "Unsupported RSN IE version";
625 case WIFI_REASON_INVALID_RSN_IE_CAP:
626 return "Invalid RSN IE Cap";
627 case WIFI_REASON_802_1X_AUTH_FAILED:
628 return "802.1x Authentication Failed";
629 case WIFI_REASON_CIPHER_SUITE_REJECTED:
630 return "Cipher Suite Rejected";
631 case WIFI_REASON_BEACON_TIMEOUT:
632 return "Beacon Timeout";
633 case WIFI_REASON_NO_AP_FOUND:
634 return "AP Not Found";
635 case WIFI_REASON_AUTH_FAIL:
636 return "Authentication Failed";
637 case WIFI_REASON_ASSOC_FAIL:
638 return "Association Failed";
639 case WIFI_REASON_HANDSHAKE_TIMEOUT:
640 return "Handshake Failed";
641 case WIFI_REASON_CONNECTION_FAIL:
642 return "Connection Failed";
643 case WIFI_REASON_ROAMING:
644 return "Station Roaming";
645 case WIFI_REASON_UNSPECIFIED:
646 default:
647 return "Unspecified";
648 }
649}
650
652 while (true) {
653 IDFWiFiEvent *data;
654 if (xQueueReceive(s_event_queue, &data, 0L) != pdTRUE) {
655 // no event ready
656 break;
657 }
658
659 // process event
661
662 delete data; // NOLINT(cppcoreguidelines-owning-memory)
663 }
664}
665void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
666 esp_err_t err;
667 if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
668 ESP_LOGV(TAG, "Event: WiFi STA start");
669 // apply hostname
670 err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
671 if (err != ERR_OK) {
672 ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
673 }
674
675 s_sta_started = true;
676 // re-apply power save mode
678
679 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
680 ESP_LOGV(TAG, "Event: WiFi STA stop");
681 s_sta_started = false;
682
683 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
684 const auto &it = data->data.sta_authmode_change;
685 ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
686 get_auth_mode_str(it.new_mode));
687
688 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
689 const auto &it = data->data.sta_connected;
690 char buf[33];
691 assert(it.ssid_len <= 32);
692 memcpy(buf, it.ssid, it.ssid_len);
693 buf[it.ssid_len] = '\0';
694 ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
695 format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
696 s_sta_connected = true;
697
698 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
699 const auto &it = data->data.sta_disconnected;
700 char buf[33];
701 assert(it.ssid_len <= 32);
702 memcpy(buf, it.ssid, it.ssid_len);
703 buf[it.ssid_len] = '\0';
704 if (it.reason == WIFI_REASON_NO_AP_FOUND) {
705 ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
706 s_sta_connect_not_found = true;
707 } else if (it.reason == WIFI_REASON_ROAMING) {
708 ESP_LOGI(TAG, "Event: Disconnected ssid='%s' reason='Station Roaming'", buf);
709 return;
710 } else {
711 ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
712 format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
713 s_sta_connect_error = true;
714 }
715 s_sta_connected = false;
716 s_sta_connecting = false;
718
719 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
720 const auto &it = data->data.ip_got_ip;
721#if USE_NETWORK_IPV6
722 esp_netif_create_ip6_linklocal(s_sta_netif);
723#endif /* USE_NETWORK_IPV6 */
724 ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip_info.ip).c_str(),
725 format_ip4_addr(it.ip_info.gw).c_str());
726 this->got_ipv4_address_ = true;
727
728#if USE_NETWORK_IPV6
729 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
730 const auto &it = data->data.ip_got_ip6;
731 ESP_LOGV(TAG, "Event: Got IPv6 address=%s", format_ip6_addr(it.ip6_info.ip).c_str());
732 this->num_ipv6_addresses_++;
733#endif /* USE_NETWORK_IPV6 */
734
735 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
736 ESP_LOGV(TAG, "Event: Lost IP");
737 this->got_ipv4_address_ = false;
738
739 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
740 const auto &it = data->data.sta_scan_done;
741 ESP_LOGV(TAG, "Event: WiFi Scan Done status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
742
743 scan_result_.clear();
744 this->scan_done_ = true;
745 if (it.status != 0) {
746 // scan error
747 return;
748 }
749
750 if (it.number == 0) {
751 // no results
752 return;
753 }
754
755 uint16_t number = it.number;
756 std::vector<wifi_ap_record_t> records(number);
757 err = esp_wifi_scan_get_ap_records(&number, records.data());
758 if (err != ESP_OK) {
759 ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
760 return;
761 }
762 records.resize(number);
763
764 scan_result_.reserve(number);
765 for (int i = 0; i < number; i++) {
766 auto &record = records[i];
767 bssid_t bssid;
768 std::copy(record.bssid, record.bssid + 6, bssid.begin());
769 std::string ssid(reinterpret_cast<const char *>(record.ssid));
770 WiFiScanResult result(bssid, ssid, record.primary, record.rssi, record.authmode != WIFI_AUTH_OPEN, ssid.empty());
771 scan_result_.push_back(result);
772 }
773
774 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
775 ESP_LOGV(TAG, "Event: WiFi AP start");
776 s_ap_started = true;
777
778 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
779 ESP_LOGV(TAG, "Event: WiFi AP stop");
780 s_ap_started = false;
781
782 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
783 const auto &it = data->data.ap_probe_req_rx;
784 ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
785
786 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
787 const auto &it = data->data.ap_staconnected;
788 ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(it.mac).c_str());
789
790 } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
791 const auto &it = data->data.ap_stadisconnected;
792 ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(it.mac).c_str());
793
794 } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
795 const auto &it = data->data.ip_ap_staipassigned;
796 ESP_LOGV(TAG, "Event: AP client assigned IP %s", format_ip4_addr(it.ip).c_str());
797 }
798}
799
801 if (s_sta_connected && this->got_ipv4_address_) {
802#if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
803 if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
805 }
806#else
808#endif /* USE_NETWORK_IPV6 */
809 }
810 if (s_sta_connect_error) {
812 }
813 if (s_sta_connect_not_found) {
815 }
816 if (s_sta_connecting) {
818 }
820}
821bool WiFiComponent::wifi_scan_start_(bool passive) {
822 // enable STA
823 if (!this->wifi_mode_(true, {}))
824 return false;
825
826 wifi_scan_config_t config{};
827 config.ssid = nullptr;
828 config.bssid = nullptr;
829 config.channel = 0;
830 config.show_hidden = true;
831 config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
832 if (passive) {
833 config.scan_time.passive = 300;
834 } else {
835 config.scan_time.active.min = 100;
836 config.scan_time.active.max = 300;
837 }
838
839 esp_err_t err = esp_wifi_scan_start(&config, false);
840 if (err != ESP_OK) {
841 ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
842 return false;
843 }
844
845 this->scan_done_ = false;
846 return true;
847}
848
849#ifdef USE_WIFI_AP
850bool WiFiComponent::wifi_ap_ip_config_(optional<ManualIP> manual_ip) {
851 esp_err_t err;
852
853 // enable AP
854 if (!this->wifi_mode_({}, true))
855 return false;
856
857 esp_netif_ip_info_t info;
858 if (manual_ip.has_value()) {
859 info.ip = manual_ip->static_ip;
860 info.gw = manual_ip->gateway;
861 info.netmask = manual_ip->subnet;
862 } else {
863 info.ip = network::IPAddress(192, 168, 4, 1);
864 info.gw = network::IPAddress(192, 168, 4, 1);
865 info.netmask = network::IPAddress(255, 255, 255, 0);
866 }
867
868 err = esp_netif_dhcps_stop(s_ap_netif);
869 if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
870 ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
871 return false;
872 }
873
874 err = esp_netif_set_ip_info(s_ap_netif, &info);
875 if (err != ESP_OK) {
876 ESP_LOGE(TAG, "esp_netif_set_ip_info failed! %d", err);
877 return false;
878 }
879
880 dhcps_lease_t lease;
881 lease.enable = true;
882 network::IPAddress start_address = network::IPAddress(&info.ip);
883 start_address += 99;
884 lease.start_ip = start_address;
885 ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
886 start_address += 10;
887 lease.end_ip = start_address;
888 ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
889 err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
890
891 if (err != ESP_OK) {
892 ESP_LOGE(TAG, "esp_netif_dhcps_option failed! %d", err);
893 return false;
894 }
895
896 err = esp_netif_dhcps_start(s_ap_netif);
897
898 if (err != ESP_OK) {
899 ESP_LOGE(TAG, "esp_netif_dhcps_start failed! %d", err);
900 return false;
901 }
902
903 return true;
904}
905
906bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
907 // enable AP
908 if (!this->wifi_mode_({}, true))
909 return false;
910
911 wifi_config_t conf;
912 memset(&conf, 0, sizeof(conf));
913 if (ap.get_ssid().size() > sizeof(conf.ap.ssid)) {
914 ESP_LOGE(TAG, "AP SSID is too long");
915 return false;
916 }
917 memcpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), ap.get_ssid().size());
918 conf.ap.channel = ap.get_channel().value_or(1);
919 conf.ap.ssid_hidden = ap.get_ssid().size();
920 conf.ap.max_connection = 5;
921 conf.ap.beacon_interval = 100;
922
923 if (ap.get_password().empty()) {
924 conf.ap.authmode = WIFI_AUTH_OPEN;
925 *conf.ap.password = 0;
926 } else {
927 conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
928 if (ap.get_password().size() > sizeof(conf.ap.password)) {
929 ESP_LOGE(TAG, "AP password is too long");
930 return false;
931 }
932 memcpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), ap.get_password().size());
933 }
934
935 // pairwise cipher of SoftAP, group cipher will be derived using this.
936 conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
937
938 esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
939 if (err != ESP_OK) {
940 ESP_LOGE(TAG, "esp_wifi_set_config failed! %d", err);
941 return false;
942 }
943
944 if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
945 ESP_LOGE(TAG, "wifi_ap_ip_config_ failed!");
946 return false;
947 }
948
949 return true;
950}
951
952network::IPAddress WiFiComponent::wifi_soft_ap_ip() {
953 esp_netif_ip_info_t ip;
954 esp_netif_get_ip_info(s_ap_netif, &ip);
955 return network::IPAddress(&ip.ip);
956}
957#endif // USE_WIFI_AP
958
959bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
960
962 bssid_t bssid{};
963 wifi_ap_record_t info;
964 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
965 if (err != ESP_OK) {
966 ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
967 return bssid;
968 }
969 std::copy(info.bssid, info.bssid + 6, bssid.begin());
970 return bssid;
971}
972std::string WiFiComponent::wifi_ssid() {
973 wifi_ap_record_t info{};
974 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
975 if (err != ESP_OK) {
976 ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
977 return "";
978 }
979 auto *ssid_s = reinterpret_cast<const char *>(info.ssid);
980 size_t len = strnlen(ssid_s, sizeof(info.ssid));
981 return {ssid_s, len};
982}
984 wifi_ap_record_t info;
985 esp_err_t err = esp_wifi_sta_get_ap_info(&info);
986 if (err != ESP_OK) {
987 ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
988 return 0;
989 }
990 return info.rssi;
991}
993 uint8_t primary;
994 wifi_second_chan_t second;
995 esp_err_t err = esp_wifi_get_channel(&primary, &second);
996 if (err != ESP_OK) {
997 ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
998 return 0;
999 }
1000 return primary;
1001}
1002network::IPAddress WiFiComponent::wifi_subnet_mask_() {
1003 esp_netif_ip_info_t ip;
1004 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1005 if (err != ESP_OK) {
1006 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1007 return {};
1008 }
1009 return network::IPAddress(&ip.netmask);
1010}
1011network::IPAddress WiFiComponent::wifi_gateway_ip_() {
1012 esp_netif_ip_info_t ip;
1013 esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
1014 if (err != ESP_OK) {
1015 ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1016 return {};
1017 }
1018 return network::IPAddress(&ip.gw);
1019}
1020network::IPAddress WiFiComponent::wifi_dns_ip_(int num) {
1021 const ip_addr_t *dns_ip = dns_getserver(num);
1022 return network::IPAddress(dns_ip);
1023}
1024
1025} // namespace wifi
1026} // namespace esphome
1027
1028#endif // USE_ESP_IDF
1029#endif
BedjetMode mode
BedJet operating mode.
const std::string & get_name() const
Get the name of this Application set by pre_setup().
void set_ap(const WiFiAP &ap)
Setup an Access Point that should be created if no connection to a station can be made.
void set_sta(const WiFiAP &ap)
bool wifi_sta_ip_config_(optional< ManualIP > manual_ip)
std::vector< WiFiScanResult > scan_result_
void wifi_process_event_(IDFWiFiEvent *data)
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
static std::string format_mac_addr(const uint8_t mac[6])
bool wifi_apply_output_power_(float output_power)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
uint8_t second
in_addr ip_addr_t
Definition ip_address.h:22
mopeka_std_values val[4]
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:143
const char *const TAG
Definition spi.cpp:8
std::string format_ip6_addr(const esp_ip6_addr_t &ip)
std::array< uint8_t, 6 > bssid_t
const char * get_auth_mode_str(uint8_t mode)
const char * get_disconnect_reason_str(uint8_t reason)
void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
std::string format_ip4_addr(const esphome_ip4_addr_t &ip)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:301
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition helpers.cpp:742
std::string str_snprintf(const char *fmt, size_t len,...)
Definition helpers.cpp:309
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition helpers.cpp:739
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
Definition helpers.cpp:688
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t event_id
Definition tt21100.cpp:3