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