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