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