ESPHome  2024.10.2
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"
36 #include "esphome/core/helpers.h"
37 #include "esphome/core/log.h"
38 #include "esphome/core/util.h"
39 
40 namespace esphome {
41 namespace wifi {
42 
43 static const char *const TAG = "wifi_esp32";
44 
45 static EventGroupHandle_t s_wifi_event_group; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
46 static QueueHandle_t s_event_queue; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
47 static esp_netif_t *s_sta_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
48 #ifdef USE_WIFI_AP
49 static esp_netif_t *s_ap_netif = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
50 #endif // USE_WIFI_AP
51 static bool s_sta_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
52 static bool s_sta_connected = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
53 static bool s_ap_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
54 static bool s_sta_connect_not_found = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
55 static bool s_sta_connect_error = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
56 static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
57 static bool s_wifi_started = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
58 
59 struct 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
81 void 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];
134  if (has_custom_mac_address()) {
135  get_mac_address_raw(mac);
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 
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 
260 bool WiFiComponent::wifi_sta_pre_setup_() { return this->wifi_mode_(true, {}); }
261 
262 bool 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 
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  strncpy(reinterpret_cast<char *>(conf.sta.ssid), ap.get_ssid().c_str(), sizeof(conf.sta.ssid));
293  strncpy(reinterpret_cast<char *>(conf.sta.password), ap.get_password().c_str(), sizeof(conf.sta.password));
294 
295  // The weakest authmode to accept in the fast scan mode
296  if (ap.get_password().empty()) {
297  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
298  } else {
299  conf.sta.threshold.authmode = WIFI_AUTH_WPA_WPA2_PSK;
300  }
301 
302 #ifdef USE_WIFI_WPA2_EAP
303  if (ap.get_eap().has_value()) {
304  conf.sta.threshold.authmode = WIFI_AUTH_WPA2_ENTERPRISE;
305  }
306 #endif
307 
308 #ifdef USE_WIFI_11KV_SUPPORT
309  conf.sta.btm_enabled = this->btm_;
310  conf.sta.rm_enabled = this->rrm_;
311 #endif
312 
313  if (ap.get_bssid().has_value()) {
314  conf.sta.bssid_set = true;
315  memcpy(conf.sta.bssid, ap.get_bssid()->data(), 6);
316  } else {
317  conf.sta.bssid_set = false;
318  }
319  if (ap.get_channel().has_value()) {
320  conf.sta.channel = *ap.get_channel();
321  conf.sta.scan_method = WIFI_FAST_SCAN;
322  } else {
323  conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
324  }
325  // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
326  // Units: AP beacon intervals. Defaults to 3 if set to 0.
327  conf.sta.listen_interval = 0;
328 
329  // Protected Management Frame
330  // Device will prefer to connect in PMF mode if other device also advertises PMF capability.
331  conf.sta.pmf_cfg.capable = true;
332  conf.sta.pmf_cfg.required = false;
333 
334  // note, we do our own filtering
335  // The minimum rssi to accept in the fast scan mode
336  conf.sta.threshold.rssi = -127;
337 
338  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
339 
340  wifi_config_t current_conf;
341  esp_err_t err;
342  err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
343  if (err != ERR_OK) {
344  ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
345  // can continue
346  }
347 
348  if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) { // NOLINT
349  err = esp_wifi_disconnect();
350  if (err != ESP_OK) {
351  ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
352  return false;
353  }
354  }
355 
356  err = esp_wifi_set_config(WIFI_IF_STA, &conf);
357  if (err != ESP_OK) {
358  ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
359  return false;
360  }
361 
362  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
363  return false;
364  }
365 
366  // setup enterprise authentication if required
367 #ifdef USE_WIFI_WPA2_EAP
368  if (ap.get_eap().has_value()) {
369  // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
370  EAPAuth eap = ap.get_eap().value();
371 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
372  err = esp_eap_client_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
373 #else
374  err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
375 #endif
376  if (err != ESP_OK) {
377  ESP_LOGV(TAG, "set_identity failed %d", err);
378  }
379  int ca_cert_len = strlen(eap.ca_cert);
380  int client_cert_len = strlen(eap.client_cert);
381  int client_key_len = strlen(eap.client_key);
382  if (ca_cert_len) {
383 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
384  err = esp_eap_client_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
385 #else
386  err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
387 #endif
388  if (err != ESP_OK) {
389  ESP_LOGV(TAG, "set_ca_cert failed %d", err);
390  }
391  }
392  // workout what type of EAP this is
393  // validation is not required as the config tool has already validated it
394  if (client_cert_len && client_key_len) {
395  // if we have certs, this must be EAP-TLS
396 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
397  err = esp_eap_client_set_certificate_and_key((uint8_t *) eap.client_cert, client_cert_len + 1,
398  (uint8_t *) eap.client_key, client_key_len + 1,
399  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
400 #else
401  err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
402  (uint8_t *) eap.client_key, client_key_len + 1,
403  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
404 #endif
405  if (err != ESP_OK) {
406  ESP_LOGV(TAG, "set_cert_key failed %d", err);
407  }
408  } else {
409  // in the absence of certs, assume this is username/password based
410 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
411  err = esp_eap_client_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
412 #else
413  err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
414 #endif
415  if (err != ESP_OK) {
416  ESP_LOGV(TAG, "set_username failed %d", err);
417  }
418 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
419  err = esp_eap_client_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
420 #else
421  err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
422 #endif
423  if (err != ESP_OK) {
424  ESP_LOGV(TAG, "set_password failed %d", err);
425  }
426  // set TTLS Phase 2, defaults to MSCHAPV2
427 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
428  err = esp_eap_client_set_ttls_phase2_method(eap.ttls_phase_2);
429 #else
430  err = esp_wifi_sta_wpa2_ent_set_ttls_phase2_method(eap.ttls_phase_2);
431 #endif
432  if (err != ESP_OK) {
433  ESP_LOGV(TAG, "set_ttls_phase2_method failed %d", err);
434  }
435  }
436 #if (ESP_IDF_VERSION_MAJOR >= 5) && (ESP_IDF_VERSION_MINOR >= 1)
437  err = esp_wifi_sta_enterprise_enable();
438 #else
439  err = esp_wifi_sta_wpa2_ent_enable();
440 #endif
441  if (err != ESP_OK) {
442  ESP_LOGV(TAG, "enterprise_enable failed %d", err);
443  }
444  }
445 #endif // USE_WIFI_WPA2_EAP
446 
447  // Reset flags, do this _before_ wifi_station_connect as the callback method
448  // may be called from wifi_station_connect
449  s_sta_connecting = true;
450  s_sta_connected = false;
451  s_sta_connect_error = false;
452  s_sta_connect_not_found = false;
453 
454  err = esp_wifi_connect();
455  if (err != ESP_OK) {
456  ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
457  return false;
458  }
459 
460  return true;
461 }
462 
464  // enable STA
465  if (!this->wifi_mode_(true, {}))
466  return false;
467 
468  esp_netif_dhcp_status_t dhcp_status;
469  esp_err_t err = esp_netif_dhcpc_get_status(s_sta_netif, &dhcp_status);
470  if (err != ESP_OK) {
471  ESP_LOGV(TAG, "esp_netif_dhcpc_get_status failed: %s", esp_err_to_name(err));
472  return false;
473  }
474 
475  if (!manual_ip.has_value()) {
476  // lwIP starts the SNTP client if it gets an SNTP server from DHCP. We don't need the time, and more importantly,
477  // the built-in SNTP client has a memory leak in certain situations. Disable this feature.
478  // https://github.com/esphome/issues/issues/2299
479  sntp_servermode_dhcp(false);
480 
481  // No manual IP is set; use DHCP client
482  if (dhcp_status != ESP_NETIF_DHCP_STARTED) {
483  err = esp_netif_dhcpc_start(s_sta_netif);
484  if (err != ESP_OK) {
485  ESP_LOGV(TAG, "Starting DHCP client failed! %d", err);
486  }
487  return err == ESP_OK;
488  }
489  return true;
490  }
491 
492  esp_netif_ip_info_t info; // struct of ip4_addr_t with ip, netmask, gw
493  info.ip = manual_ip->static_ip;
494  info.gw = manual_ip->gateway;
495  info.netmask = manual_ip->subnet;
496  err = esp_netif_dhcpc_stop(s_sta_netif);
497  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
498  ESP_LOGV(TAG, "Stopping DHCP client failed! %s", esp_err_to_name(err));
499  }
500 
501  err = esp_netif_set_ip_info(s_sta_netif, &info);
502  if (err != ESP_OK) {
503  ESP_LOGV(TAG, "Setting manual IP info failed! %s", esp_err_to_name(err));
504  }
505 
506  esp_netif_dns_info_t dns;
507  if (manual_ip->dns1.is_set()) {
508  dns.ip = manual_ip->dns1;
509  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
510  }
511  if (manual_ip->dns2.is_set()) {
512  dns.ip = manual_ip->dns2;
513  esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_BACKUP, &dns);
514  }
515 
516  return true;
517 }
518 
520  if (!this->has_sta())
521  return {};
522  network::IPAddresses addresses;
523  esp_netif_ip_info_t ip;
524  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
525  if (err != ESP_OK) {
526  ESP_LOGV(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
527  // TODO: do something smarter
528  // return false;
529  } else {
530  addresses[0] = network::IPAddress(&ip.ip);
531  }
532 #if USE_NETWORK_IPV6
533  struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
534  uint8_t count = 0;
535  count = esp_netif_get_all_ip6(s_sta_netif, if_ip6s);
536  assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
537  for (int i = 0; i < count; i++) {
538  addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
539  }
540 #endif /* USE_NETWORK_IPV6 */
541  return addresses;
542 }
543 
545  // setting is done in SYSTEM_EVENT_STA_START callback
546  return true;
547 }
548 const char *get_auth_mode_str(uint8_t mode) {
549  switch (mode) {
550  case WIFI_AUTH_OPEN:
551  return "OPEN";
552  case WIFI_AUTH_WEP:
553  return "WEP";
554  case WIFI_AUTH_WPA_PSK:
555  return "WPA PSK";
556  case WIFI_AUTH_WPA2_PSK:
557  return "WPA2 PSK";
558  case WIFI_AUTH_WPA_WPA2_PSK:
559  return "WPA/WPA2 PSK";
560  case WIFI_AUTH_WPA2_ENTERPRISE:
561  return "WPA2 Enterprise";
562  case WIFI_AUTH_WPA3_PSK:
563  return "WPA3 PSK";
564  case WIFI_AUTH_WPA2_WPA3_PSK:
565  return "WPA2/WPA3 PSK";
566  case WIFI_AUTH_WAPI_PSK:
567  return "WAPI PSK";
568  default:
569  return "UNKNOWN";
570  }
571 }
572 
573 std::string format_ip4_addr(const esp_ip4_addr_t &ip) { return str_snprintf(IPSTR, 15, IP2STR(&ip)); }
574 #if LWIP_IPV6
575 std::string format_ip6_addr(const esp_ip6_addr_t &ip) { return str_snprintf(IPV6STR, 39, IPV62STR(ip)); }
576 #endif /* LWIP_IPV6 */
577 const char *get_disconnect_reason_str(uint8_t reason) {
578  switch (reason) {
579  case WIFI_REASON_AUTH_EXPIRE:
580  return "Auth Expired";
581  case WIFI_REASON_AUTH_LEAVE:
582  return "Auth Leave";
583  case WIFI_REASON_ASSOC_EXPIRE:
584  return "Association Expired";
585  case WIFI_REASON_ASSOC_TOOMANY:
586  return "Too Many Associations";
587  case WIFI_REASON_NOT_AUTHED:
588  return "Not Authenticated";
589  case WIFI_REASON_NOT_ASSOCED:
590  return "Not Associated";
591  case WIFI_REASON_ASSOC_LEAVE:
592  return "Association Leave";
593  case WIFI_REASON_ASSOC_NOT_AUTHED:
594  return "Association not Authenticated";
595  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
596  return "Disassociate Power Cap Bad";
597  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
598  return "Disassociate Supported Channel Bad";
599  case WIFI_REASON_IE_INVALID:
600  return "IE Invalid";
601  case WIFI_REASON_MIC_FAILURE:
602  return "Mic Failure";
603  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
604  return "4-Way Handshake Timeout";
605  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
606  return "Group Key Update Timeout";
607  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
608  return "IE In 4-Way Handshake Differs";
609  case WIFI_REASON_GROUP_CIPHER_INVALID:
610  return "Group Cipher Invalid";
611  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
612  return "Pairwise Cipher Invalid";
613  case WIFI_REASON_AKMP_INVALID:
614  return "AKMP Invalid";
615  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
616  return "Unsupported RSN IE version";
617  case WIFI_REASON_INVALID_RSN_IE_CAP:
618  return "Invalid RSN IE Cap";
619  case WIFI_REASON_802_1X_AUTH_FAILED:
620  return "802.1x Authentication Failed";
621  case WIFI_REASON_CIPHER_SUITE_REJECTED:
622  return "Cipher Suite Rejected";
623  case WIFI_REASON_BEACON_TIMEOUT:
624  return "Beacon Timeout";
625  case WIFI_REASON_NO_AP_FOUND:
626  return "AP Not Found";
627  case WIFI_REASON_AUTH_FAIL:
628  return "Authentication Failed";
629  case WIFI_REASON_ASSOC_FAIL:
630  return "Association Failed";
631  case WIFI_REASON_HANDSHAKE_TIMEOUT:
632  return "Handshake Failed";
633  case WIFI_REASON_CONNECTION_FAIL:
634  return "Connection Failed";
635  case WIFI_REASON_ROAMING:
636  return "Station Roaming";
637  case WIFI_REASON_UNSPECIFIED:
638  default:
639  return "Unspecified";
640  }
641 }
642 
644  while (true) {
645  IDFWiFiEvent *data;
646  if (xQueueReceive(s_event_queue, &data, 0L) != pdTRUE) {
647  // no event ready
648  break;
649  }
650 
651  // process event
652  wifi_process_event_(data);
653 
654  delete data; // NOLINT(cppcoreguidelines-owning-memory)
655  }
656 }
657 void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
658  esp_err_t err;
659  if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
660  ESP_LOGV(TAG, "Event: WiFi STA start");
661  // apply hostname
662  err = esp_netif_set_hostname(s_sta_netif, App.get_name().c_str());
663  if (err != ERR_OK) {
664  ESP_LOGW(TAG, "esp_netif_set_hostname failed: %s", esp_err_to_name(err));
665  }
666 
667  s_sta_started = true;
668  // re-apply power save mode
669  wifi_apply_power_save_();
670 
671  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
672  ESP_LOGV(TAG, "Event: WiFi STA stop");
673  s_sta_started = false;
674 
675  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
676  const auto &it = data->data.sta_authmode_change;
677  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
678  get_auth_mode_str(it.new_mode));
679 
680  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
681  const auto &it = data->data.sta_connected;
682  char buf[33];
683  assert(it.ssid_len <= 32);
684  memcpy(buf, it.ssid, it.ssid_len);
685  buf[it.ssid_len] = '\0';
686  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
687  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
688  s_sta_connected = true;
689 
690  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
691  const auto &it = data->data.sta_disconnected;
692  char buf[33];
693  assert(it.ssid_len <= 32);
694  memcpy(buf, it.ssid, it.ssid_len);
695  buf[it.ssid_len] = '\0';
696  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
697  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
698  s_sta_connect_not_found = true;
699  } else if (it.reason == WIFI_REASON_ROAMING) {
700  ESP_LOGI(TAG, "Event: Disconnected ssid='%s' reason='Station Roaming'", buf);
701  return;
702  } else {
703  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
704  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
705  s_sta_connect_error = true;
706  }
707  s_sta_connected = false;
708  s_sta_connecting = false;
709  error_from_callback_ = true;
710 
711  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
712  const auto &it = data->data.ip_got_ip;
713 #if USE_NETWORK_IPV6
714  esp_netif_create_ip6_linklocal(s_sta_netif);
715 #endif /* USE_NETWORK_IPV6 */
716  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip_info.ip).c_str(),
717  format_ip4_addr(it.ip_info.gw).c_str());
718  this->got_ipv4_address_ = true;
719 
720 #if USE_NETWORK_IPV6
721  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
722  const auto &it = data->data.ip_got_ip6;
723  ESP_LOGV(TAG, "Event: Got IPv6 address=%s", format_ip6_addr(it.ip6_info.ip).c_str());
724  this->num_ipv6_addresses_++;
725 #endif /* USE_NETWORK_IPV6 */
726 
727  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
728  ESP_LOGV(TAG, "Event: Lost IP");
729  this->got_ipv4_address_ = false;
730 
731  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
732  const auto &it = data->data.sta_scan_done;
733  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%" PRIu32 " number=%u scan_id=%u", it.status, it.number, it.scan_id);
734 
735  scan_result_.clear();
736  this->scan_done_ = true;
737  if (it.status != 0) {
738  // scan error
739  return;
740  }
741 
742  if (it.number == 0) {
743  // no results
744  return;
745  }
746 
747  uint16_t number = it.number;
748  std::vector<wifi_ap_record_t> records(number);
749  err = esp_wifi_scan_get_ap_records(&number, records.data());
750  if (err != ESP_OK) {
751  ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
752  return;
753  }
754  records.resize(number);
755 
756  scan_result_.reserve(number);
757  for (int i = 0; i < number; i++) {
758  auto &record = records[i];
759  bssid_t bssid;
760  std::copy(record.bssid, record.bssid + 6, bssid.begin());
761  std::string ssid(reinterpret_cast<const char *>(record.ssid));
762  WiFiScanResult result(bssid, ssid, record.primary, record.rssi, record.authmode != WIFI_AUTH_OPEN, ssid.empty());
763  scan_result_.push_back(result);
764  }
765 
766  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
767  ESP_LOGV(TAG, "Event: WiFi AP start");
768  s_ap_started = true;
769 
770  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
771  ESP_LOGV(TAG, "Event: WiFi AP stop");
772  s_ap_started = false;
773 
774  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
775  const auto &it = data->data.ap_probe_req_rx;
776  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
777 
778  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
779  const auto &it = data->data.ap_staconnected;
780  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(it.mac).c_str());
781 
782  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
783  const auto &it = data->data.ap_stadisconnected;
784  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(it.mac).c_str());
785 
786  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
787  const auto &it = data->data.ip_ap_staipassigned;
788  ESP_LOGV(TAG, "Event: AP client assigned IP %s", format_ip4_addr(it.ip).c_str());
789  }
790 }
791 
793  if (s_sta_connected && this->got_ipv4_address_) {
794 #if USE_NETWORK_IPV6 && (USE_NETWORK_MIN_IPV6_ADDR_COUNT > 0)
795  if (this->num_ipv6_addresses_ >= USE_NETWORK_MIN_IPV6_ADDR_COUNT) {
797  }
798 #else
800 #endif /* USE_NETWORK_IPV6 */
801  }
802  if (s_sta_connect_error) {
804  }
805  if (s_sta_connect_not_found) {
807  }
808  if (s_sta_connecting) {
810  }
812 }
813 bool WiFiComponent::wifi_scan_start_(bool passive) {
814  // enable STA
815  if (!this->wifi_mode_(true, {}))
816  return false;
817 
818  wifi_scan_config_t config{};
819  config.ssid = nullptr;
820  config.bssid = nullptr;
821  config.channel = 0;
822  config.show_hidden = true;
823  config.scan_type = passive ? WIFI_SCAN_TYPE_PASSIVE : WIFI_SCAN_TYPE_ACTIVE;
824  if (passive) {
825  config.scan_time.passive = 300;
826  } else {
827  config.scan_time.active.min = 100;
828  config.scan_time.active.max = 300;
829  }
830 
831  esp_err_t err = esp_wifi_scan_start(&config, false);
832  if (err != ESP_OK) {
833  ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
834  return false;
835  }
836 
837  this->scan_done_ = false;
838  return true;
839 }
840 
841 #ifdef USE_WIFI_AP
843  esp_err_t err;
844 
845  // enable AP
846  if (!this->wifi_mode_({}, true))
847  return false;
848 
849  esp_netif_ip_info_t info;
850  if (manual_ip.has_value()) {
851  info.ip = manual_ip->static_ip;
852  info.gw = manual_ip->gateway;
853  info.netmask = manual_ip->subnet;
854  } else {
855  info.ip = network::IPAddress(192, 168, 4, 1);
856  info.gw = network::IPAddress(192, 168, 4, 1);
857  info.netmask = network::IPAddress(255, 255, 255, 0);
858  }
859 
860  err = esp_netif_dhcps_stop(s_ap_netif);
861  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
862  ESP_LOGE(TAG, "esp_netif_dhcps_stop failed: %s", esp_err_to_name(err));
863  return false;
864  }
865 
866  err = esp_netif_set_ip_info(s_ap_netif, &info);
867  if (err != ESP_OK) {
868  ESP_LOGE(TAG, "esp_netif_set_ip_info failed! %d", err);
869  return false;
870  }
871 
872  dhcps_lease_t lease;
873  lease.enable = true;
874  network::IPAddress start_address = network::IPAddress(&info.ip);
875  start_address += 99;
876  lease.start_ip = start_address;
877  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
878  start_address += 10;
879  lease.end_ip = start_address;
880  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
881  err = esp_netif_dhcps_option(s_ap_netif, ESP_NETIF_OP_SET, ESP_NETIF_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
882 
883  if (err != ESP_OK) {
884  ESP_LOGE(TAG, "esp_netif_dhcps_option failed! %d", err);
885  return false;
886  }
887 
888  err = esp_netif_dhcps_start(s_ap_netif);
889 
890  if (err != ESP_OK) {
891  ESP_LOGE(TAG, "esp_netif_dhcps_start failed! %d", err);
892  return false;
893  }
894 
895  return true;
896 }
897 
898 bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
899  // enable AP
900  if (!this->wifi_mode_({}, true))
901  return false;
902 
903  wifi_config_t conf;
904  memset(&conf, 0, sizeof(conf));
905  strncpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid));
906  conf.ap.channel = ap.get_channel().value_or(1);
907  conf.ap.ssid_hidden = ap.get_ssid().size();
908  conf.ap.max_connection = 5;
909  conf.ap.beacon_interval = 100;
910 
911  if (ap.get_password().empty()) {
912  conf.ap.authmode = WIFI_AUTH_OPEN;
913  *conf.ap.password = 0;
914  } else {
915  conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
916  strncpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password));
917  }
918 
919  // pairwise cipher of SoftAP, group cipher will be derived using this.
920  conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
921 
922  esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
923  if (err != ESP_OK) {
924  ESP_LOGE(TAG, "esp_wifi_set_config failed! %d", err);
925  return false;
926  }
927 
928  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
929  ESP_LOGE(TAG, "wifi_ap_ip_config_ failed!");
930  return false;
931  }
932 
933  return true;
934 }
935 
937  esp_netif_ip_info_t ip;
938  esp_netif_get_ip_info(s_ap_netif, &ip);
939  return network::IPAddress(&ip.ip);
940 }
941 #endif // USE_WIFI_AP
942 
943 bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
944 
946  bssid_t bssid{};
947  wifi_ap_record_t info;
948  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
949  if (err != ESP_OK) {
950  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
951  return bssid;
952  }
953  std::copy(info.bssid, info.bssid + 6, bssid.begin());
954  return bssid;
955 }
956 std::string WiFiComponent::wifi_ssid() {
957  wifi_ap_record_t info{};
958  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
959  if (err != ESP_OK) {
960  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
961  return "";
962  }
963  auto *ssid_s = reinterpret_cast<const char *>(info.ssid);
964  size_t len = strnlen(ssid_s, sizeof(info.ssid));
965  return {ssid_s, len};
966 }
967 int8_t WiFiComponent::wifi_rssi() {
968  wifi_ap_record_t info;
969  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
970  if (err != ESP_OK) {
971  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
972  return 0;
973  }
974  return info.rssi;
975 }
977  uint8_t primary;
978  wifi_second_chan_t second;
979  esp_err_t err = esp_wifi_get_channel(&primary, &second);
980  if (err != ESP_OK) {
981  ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
982  return 0;
983  }
984  return primary;
985 }
987  esp_netif_ip_info_t ip;
988  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
989  if (err != ESP_OK) {
990  ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
991  return {};
992  }
993  return network::IPAddress(&ip.netmask);
994 }
996  esp_netif_ip_info_t ip;
997  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
998  if (err != ESP_OK) {
999  ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
1000  return {};
1001  }
1002  return network::IPAddress(&ip.gw);
1003 }
1005  const ip_addr_t *dns_ip = dns_getserver(num);
1006  return network::IPAddress(dns_ip);
1007 }
1008 
1009 } // namespace wifi
1010 } // namespace esphome
1011 
1012 #endif // USE_ESP_IDF
1013 #endif
std::array< uint8_t, 6 > bssid_t
bool has_custom_mac_address()
Check if a custom MAC address is set (ESP32 & variants)
Definition: helpers.cpp:707
const optional< EAPAuth > & get_eap() const
const std::string & get_password() const
network::IPAddress wifi_dns_ip_(int num)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
const optional< bssid_t > & get_bssid() const
std::string str() const
Definition: ip_address.h:122
bool wifi_apply_output_power_(float output_power)
bool wifi_sta_ip_config_(optional< ManualIP > manual_ip)
void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
mopeka_std_values val[4]
bool has_value() const
Definition: optional.h:87
std::string format_ip6_addr(const esp_ip6_addr_t &ip)
const char *const TAG
Definition: spi.cpp:8
void wifi_process_event_(IDFWiFiEvent *data)
const optional< ManualIP > & get_manual_ip() const
const optional< uint8_t > & get_channel() const
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:183
esp_eap_ttls_phase2_types ttls_phase_2
uint8_t second
Application App
Global storage of Application pointer - only one Application can exist.
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
void set_mac_address(uint8_t *mac)
Set the MAC address to use from the provided byte array (6 bytes).
Definition: helpers.cpp:704
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
const char * get_auth_mode_str(uint8_t mode)
std::string size_t len
Definition: helpers.h:292
in_addr ip_addr_t
Definition: ip_address.h:22
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
std::string format_ip4_addr(const esphome_ip4_addr_t &ip)
const std::string & get_ssid() const
uint8_t event_id
Definition: tt21100.cpp:15
const char * get_disconnect_reason_str(uint8_t reason)
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:296
value_type value_or(U const &v) const
Definition: optional.h:93
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:660