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