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