ESPHome  2022.6.3
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  if (ap.get_bssid().has_value()) {
289  conf.sta.bssid_set = true;
290  memcpy(conf.sta.bssid, ap.get_bssid()->data(), 6);
291  } else {
292  conf.sta.bssid_set = false;
293  }
294  if (ap.get_channel().has_value()) {
295  conf.sta.channel = *ap.get_channel();
296  conf.sta.scan_method = WIFI_FAST_SCAN;
297  } else {
298  conf.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
299  }
300  // Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set.
301  // Units: AP beacon intervals. Defaults to 3 if set to 0.
302  conf.sta.listen_interval = 0;
303 
304 #if ESP_IDF_VERSION_MAJOR >= 4
305  // Protected Management Frame
306  // Device will prefer to connect in PMF mode if other device also advertizes PMF capability.
307  conf.sta.pmf_cfg.capable = true;
308  conf.sta.pmf_cfg.required = false;
309 #endif
310 
311  // note, we do our own filtering
312  // The minimum rssi to accept in the fast scan mode
313  conf.sta.threshold.rssi = -127;
314 
315  conf.sta.threshold.authmode = WIFI_AUTH_OPEN;
316 
317  wifi_config_t current_conf;
318  esp_err_t err;
319  err = esp_wifi_get_config(WIFI_IF_STA, &current_conf);
320  if (err != ERR_OK) {
321  ESP_LOGW(TAG, "esp_wifi_get_config failed: %s", esp_err_to_name(err));
322  // can continue
323  }
324 
325  if (memcmp(&current_conf, &conf, sizeof(wifi_config_t)) != 0) {
326  err = esp_wifi_disconnect();
327  if (err != ESP_OK) {
328  ESP_LOGV(TAG, "esp_wifi_disconnect failed: %s", esp_err_to_name(err));
329  return false;
330  }
331  }
332 
333  err = esp_wifi_set_config(WIFI_IF_STA, &conf);
334  if (err != ESP_OK) {
335  ESP_LOGV(TAG, "esp_wifi_set_config failed: %s", esp_err_to_name(err));
336  return false;
337  }
338 
339  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
340  return false;
341  }
342 
343  // setup enterprise authentication if required
344 #ifdef USE_WIFI_WPA2_EAP
345  if (ap.get_eap().has_value()) {
346  // note: all certificates and keys have to be null terminated. Lengths are appended by +1 to include \0.
347  EAPAuth eap = ap.get_eap().value();
348  err = esp_wifi_sta_wpa2_ent_set_identity((uint8_t *) eap.identity.c_str(), eap.identity.length());
349  if (err != ESP_OK) {
350  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_identity failed! %d", err);
351  }
352  int ca_cert_len = strlen(eap.ca_cert);
353  int client_cert_len = strlen(eap.client_cert);
354  int client_key_len = strlen(eap.client_key);
355  if (ca_cert_len) {
356  err = esp_wifi_sta_wpa2_ent_set_ca_cert((uint8_t *) eap.ca_cert, ca_cert_len + 1);
357  if (err != ESP_OK) {
358  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_ca_cert failed! %d", err);
359  }
360  }
361  // workout what type of EAP this is
362  // validation is not required as the config tool has already validated it
363  if (client_cert_len && client_key_len) {
364  // if we have certs, this must be EAP-TLS
365  err = esp_wifi_sta_wpa2_ent_set_cert_key((uint8_t *) eap.client_cert, client_cert_len + 1,
366  (uint8_t *) eap.client_key, client_key_len + 1,
367  (uint8_t *) eap.password.c_str(), strlen(eap.password.c_str()));
368  if (err != ESP_OK) {
369  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_cert_key failed! %d", err);
370  }
371  } else {
372  // in the absence of certs, assume this is username/password based
373  err = esp_wifi_sta_wpa2_ent_set_username((uint8_t *) eap.username.c_str(), eap.username.length());
374  if (err != ESP_OK) {
375  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_username failed! %d", err);
376  }
377  err = esp_wifi_sta_wpa2_ent_set_password((uint8_t *) eap.password.c_str(), eap.password.length());
378  if (err != ESP_OK) {
379  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_set_password failed! %d", err);
380  }
381  }
382  err = esp_wifi_sta_wpa2_ent_enable();
383  if (err != ESP_OK) {
384  ESP_LOGV(TAG, "esp_wifi_sta_wpa2_ent_enable failed! %d", err);
385  }
386  }
387 #endif // USE_WIFI_WPA2_EAP
388 
389  // Reset flags, do this _before_ wifi_station_connect as the callback method
390  // may be called from wifi_station_connect
391  s_sta_connecting = true;
392  s_sta_connected = false;
393  s_sta_got_ip = false;
394  s_sta_connect_error = false;
395  s_sta_connect_not_found = false;
396 
397  err = esp_wifi_connect();
398  if (err != ESP_OK) {
399  ESP_LOGW(TAG, "esp_wifi_connect failed: %s", esp_err_to_name(err));
400  return false;
401  }
402 
403  return true;
404 }
405 
407  // enable STA
408  if (!this->wifi_mode_(true, {}))
409  return false;
410 
411  tcpip_adapter_dhcp_status_t dhcp_status;
412  esp_err_t err = tcpip_adapter_dhcpc_get_status(TCPIP_ADAPTER_IF_STA, &dhcp_status);
413  if (err != ESP_OK) {
414  ESP_LOGV(TAG, "tcpip_adapter_dhcpc_get_status failed: %s", esp_err_to_name(err));
415  return false;
416  }
417 
418  if (!manual_ip.has_value()) {
419  // Use DHCP client
420  if (dhcp_status != TCPIP_ADAPTER_DHCP_STARTED) {
421  err = tcpip_adapter_dhcpc_start(TCPIP_ADAPTER_IF_STA);
422  if (err != ESP_OK) {
423  ESP_LOGV(TAG, "Starting DHCP client failed! %d", err);
424  }
425  return err == ESP_OK;
426  }
427  return true;
428  }
429 
430  tcpip_adapter_ip_info_t info;
431  memset(&info, 0, sizeof(info));
432  info.ip.addr = static_cast<uint32_t>(manual_ip->static_ip);
433  info.gw.addr = static_cast<uint32_t>(manual_ip->gateway);
434  info.netmask.addr = static_cast<uint32_t>(manual_ip->subnet);
435 
436  err = tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA);
437  if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
438  ESP_LOGV(TAG, "tcpip_adapter_dhcpc_stop failed: %s", esp_err_to_name(err));
439  return false;
440  }
441 
442  err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_STA, &info);
443  if (err != ESP_OK) {
444  ESP_LOGV(TAG, "tcpip_adapter_set_ip_info failed: %s", esp_err_to_name(err));
445  return false;
446  }
447 
448  ip_addr_t dns;
449  dns.type = IPADDR_TYPE_V4;
450  if (uint32_t(manual_ip->dns1) != 0) {
451  dns.u_addr.ip4.addr = static_cast<uint32_t>(manual_ip->dns1);
452  dns_setserver(0, &dns);
453  }
454  if (uint32_t(manual_ip->dns2) != 0) {
455  dns.u_addr.ip4.addr = static_cast<uint32_t>(manual_ip->dns2);
456  dns_setserver(1, &dns);
457  }
458 
459  return true;
460 }
461 
463  if (!this->has_sta())
464  return {};
465  tcpip_adapter_ip_info_t ip;
466  esp_err_t err = tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_STA, &ip);
467  if (err != ESP_OK) {
468  ESP_LOGV(TAG, "tcpip_adapter_get_ip_info failed: %s", esp_err_to_name(err));
469  return false;
470  }
471  return {ip.ip.addr};
472 }
473 
475  // setting is done in SYSTEM_EVENT_STA_START callback
476  return true;
477 }
478 const char *get_auth_mode_str(uint8_t mode) {
479  switch (mode) {
480  case WIFI_AUTH_OPEN:
481  return "OPEN";
482  case WIFI_AUTH_WEP:
483  return "WEP";
484  case WIFI_AUTH_WPA_PSK:
485  return "WPA PSK";
486  case WIFI_AUTH_WPA2_PSK:
487  return "WPA2 PSK";
488  case WIFI_AUTH_WPA_WPA2_PSK:
489  return "WPA/WPA2 PSK";
490  case WIFI_AUTH_WPA2_ENTERPRISE:
491  return "WPA2 Enterprise";
492  case WIFI_AUTH_WPA3_PSK:
493  return "WPA3 PSK";
494  case WIFI_AUTH_WPA2_WPA3_PSK:
495  return "WPA2/WPA3 PSK";
496  case WIFI_AUTH_WAPI_PSK:
497  return "WAPI PSK";
498  default:
499  return "UNKNOWN";
500  }
501 }
502 
503 std::string format_ip4_addr(const esp_ip4_addr_t &ip) { return str_snprintf(IPSTR, 15, IP2STR(&ip)); }
504 std::string format_ip6_addr(const esp_ip6_addr_t &ip) { return str_snprintf(IPV6STR, 39, IPV62STR(ip)); }
505 const char *get_disconnect_reason_str(uint8_t reason) {
506  switch (reason) {
507  case WIFI_REASON_AUTH_EXPIRE:
508  return "Auth Expired";
509  case WIFI_REASON_AUTH_LEAVE:
510  return "Auth Leave";
511  case WIFI_REASON_ASSOC_EXPIRE:
512  return "Association Expired";
513  case WIFI_REASON_ASSOC_TOOMANY:
514  return "Too Many Associations";
515  case WIFI_REASON_NOT_AUTHED:
516  return "Not Authenticated";
517  case WIFI_REASON_NOT_ASSOCED:
518  return "Not Associated";
519  case WIFI_REASON_ASSOC_LEAVE:
520  return "Association Leave";
521  case WIFI_REASON_ASSOC_NOT_AUTHED:
522  return "Association not Authenticated";
523  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
524  return "Disassociate Power Cap Bad";
525  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
526  return "Disassociate Supported Channel Bad";
527  case WIFI_REASON_IE_INVALID:
528  return "IE Invalid";
529  case WIFI_REASON_MIC_FAILURE:
530  return "Mic Failure";
531  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
532  return "4-Way Handshake Timeout";
533  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
534  return "Group Key Update Timeout";
535  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
536  return "IE In 4-Way Handshake Differs";
537  case WIFI_REASON_GROUP_CIPHER_INVALID:
538  return "Group Cipher Invalid";
539  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
540  return "Pairwise Cipher Invalid";
541  case WIFI_REASON_AKMP_INVALID:
542  return "AKMP Invalid";
543  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
544  return "Unsupported RSN IE version";
545  case WIFI_REASON_INVALID_RSN_IE_CAP:
546  return "Invalid RSN IE Cap";
547  case WIFI_REASON_802_1X_AUTH_FAILED:
548  return "802.1x Authentication Failed";
549  case WIFI_REASON_CIPHER_SUITE_REJECTED:
550  return "Cipher Suite Rejected";
551  case WIFI_REASON_BEACON_TIMEOUT:
552  return "Beacon Timeout";
553  case WIFI_REASON_NO_AP_FOUND:
554  return "AP Not Found";
555  case WIFI_REASON_AUTH_FAIL:
556  return "Authentication Failed";
557  case WIFI_REASON_ASSOC_FAIL:
558  return "Association Failed";
559  case WIFI_REASON_HANDSHAKE_TIMEOUT:
560  return "Handshake Failed";
561  case WIFI_REASON_CONNECTION_FAIL:
562  return "Connection Failed";
563  case WIFI_REASON_UNSPECIFIED:
564  default:
565  return "Unspecified";
566  }
567 }
568 
570  while (true) {
571  IDFWiFiEvent *data;
572  if (xQueueReceive(s_event_queue, &data, 0L) != pdTRUE) {
573  // no event ready
574  break;
575  }
576 
577  // process event
578  wifi_process_event_(data);
579 
580  delete data; // NOLINT(cppcoreguidelines-owning-memory)
581  }
582 }
583 void WiFiComponent::wifi_process_event_(IDFWiFiEvent *data) {
584  esp_err_t err;
585  if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_START) {
586  ESP_LOGV(TAG, "Event: WiFi STA start");
587  // apply hostname
588  err = tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA, App.get_name().c_str());
589  if (err != ERR_OK) {
590  ESP_LOGW(TAG, "tcpip_adapter_set_hostname failed: %s", esp_err_to_name(err));
591  }
592 
593  s_sta_started = true;
594  // re-apply power save mode
595  wifi_apply_power_save_();
596 
597  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_STOP) {
598  ESP_LOGV(TAG, "Event: WiFi STA stop");
599  s_sta_started = false;
600 
601  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
602  const auto &it = data->data.sta_authmode_change;
603  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
604  get_auth_mode_str(it.new_mode));
605 
606  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_CONNECTED) {
607  const auto &it = data->data.sta_connected;
608  char buf[33];
609  assert(it.ssid_len <= 32);
610  memcpy(buf, it.ssid, it.ssid_len);
611  buf[it.ssid_len] = '\0';
612  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
613  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
614  s_sta_connected = true;
615 
616  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_STA_DISCONNECTED) {
617  const auto &it = data->data.sta_disconnected;
618  char buf[33];
619  assert(it.ssid_len <= 32);
620  memcpy(buf, it.ssid, it.ssid_len);
621  buf[it.ssid_len] = '\0';
622  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
623  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
624  s_sta_connect_not_found = true;
625 
626  } else {
627  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
628  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
629  s_sta_connect_error = true;
630  }
631  s_sta_connected = false;
632  s_sta_connecting = false;
633  error_from_callback_ = true;
634 
635  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_GOT_IP) {
636  const auto &it = data->data.ip_got_ip;
637 #ifdef LWIP_IPV6_AUTOCONFIG
638  tcpip_adapter_create_ip6_linklocal(TCPIP_ADAPTER_IF_STA);
639 #endif
640  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(it.ip_info.ip).c_str(),
641  format_ip4_addr(it.ip_info.gw).c_str());
642  s_sta_got_ip = true;
643 
644  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_GOT_IP6) {
645  const auto &it = data->data.ip_got_ip6;
646  ESP_LOGV(TAG, "Event: Got IPv6 address=%s", format_ip6_addr(it.ip6_info.ip).c_str());
647 
648  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_STA_LOST_IP) {
649  ESP_LOGV(TAG, "Event: Lost IP");
650  s_sta_got_ip = false;
651 
652  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_SCAN_DONE) {
653  const auto &it = data->data.sta_scan_done;
654  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%u number=%u scan_id=%u", it.status, it.number, it.scan_id);
655 
656  scan_result_.clear();
657  this->scan_done_ = true;
658  if (it.status != 0) {
659  // scan error
660  return;
661  }
662 
663  uint16_t number = it.number;
664  std::vector<wifi_ap_record_t> records(number);
665  err = esp_wifi_scan_get_ap_records(&number, records.data());
666  if (err != ESP_OK) {
667  ESP_LOGW(TAG, "esp_wifi_scan_get_ap_records failed: %s", esp_err_to_name(err));
668  return;
669  }
670  records.resize(number);
671 
672  scan_result_.reserve(number);
673  for (int i = 0; i < number; i++) {
674  auto &record = records[i];
675  bssid_t bssid;
676  std::copy(record.bssid, record.bssid + 6, bssid.begin());
677  std::string ssid(reinterpret_cast<const char *>(record.ssid));
678  WiFiScanResult result(bssid, ssid, record.primary, record.rssi, record.authmode != WIFI_AUTH_OPEN, ssid.empty());
679  scan_result_.push_back(result);
680  }
681 
682  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_START) {
683  ESP_LOGV(TAG, "Event: WiFi AP start");
684  s_ap_started = true;
685 
686  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STOP) {
687  ESP_LOGV(TAG, "Event: WiFi AP stop");
688  s_ap_started = false;
689 
690  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
691  const auto &it = data->data.ap_probe_req_rx;
692  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
693 
694  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STACONNECTED) {
695  const auto &it = data->data.ap_staconnected;
696  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(it.mac).c_str());
697 
698  } else if (data->event_base == WIFI_EVENT && data->event_id == WIFI_EVENT_AP_STADISCONNECTED) {
699  const auto &it = data->data.ap_stadisconnected;
700  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(it.mac).c_str());
701 
702  } else if (data->event_base == IP_EVENT && data->event_id == IP_EVENT_AP_STAIPASSIGNED) {
703  const auto &it = data->data.ip_ap_staipassigned;
704  ESP_LOGV(TAG, "Event: AP client assigned IP %s", format_ip4_addr(it.ip).c_str());
705  }
706 }
707 
709  if (s_sta_connected && s_sta_got_ip) {
711  }
712  if (s_sta_connect_error) {
714  }
715  if (s_sta_connect_not_found) {
717  }
718  if (s_sta_connecting) {
720  }
722 }
724  // enable STA
725  if (!this->wifi_mode_(true, {}))
726  return false;
727 
728  wifi_scan_config_t config{};
729  config.ssid = nullptr;
730  config.bssid = nullptr;
731  config.channel = 0;
732  config.show_hidden = true;
733  config.scan_type = WIFI_SCAN_TYPE_ACTIVE;
734  config.scan_time.active.min = 100;
735  config.scan_time.active.max = 300;
736 
737  esp_err_t err = esp_wifi_scan_start(&config, false);
738  if (err != ESP_OK) {
739  ESP_LOGV(TAG, "esp_wifi_scan_start failed: %s", esp_err_to_name(err));
740  return false;
741  }
742 
743  scan_done_ = false;
744  return true;
745 }
747  esp_err_t err;
748 
749  // enable AP
750  if (!this->wifi_mode_({}, true))
751  return false;
752 
753  tcpip_adapter_ip_info_t info;
754  memset(&info, 0, sizeof(info));
755  if (manual_ip.has_value()) {
756  info.ip.addr = static_cast<uint32_t>(manual_ip->static_ip);
757  info.gw.addr = static_cast<uint32_t>(manual_ip->gateway);
758  info.netmask.addr = static_cast<uint32_t>(manual_ip->subnet);
759  } else {
760  info.ip.addr = static_cast<uint32_t>(network::IPAddress(192, 168, 4, 1));
761  info.gw.addr = static_cast<uint32_t>(network::IPAddress(192, 168, 4, 1));
762  info.netmask.addr = static_cast<uint32_t>(network::IPAddress(255, 255, 255, 0));
763  }
764  tcpip_adapter_dhcp_status_t dhcp_status;
765  tcpip_adapter_dhcps_get_status(TCPIP_ADAPTER_IF_AP, &dhcp_status);
766  err = tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP);
767  if (err != ESP_OK) {
768  ESP_LOGV(TAG, "tcpip_adapter_dhcps_stop failed! %d", err);
769  return false;
770  }
771 
772  err = tcpip_adapter_set_ip_info(TCPIP_ADAPTER_IF_AP, &info);
773  if (err != ESP_OK) {
774  ESP_LOGV(TAG, "tcpip_adapter_set_ip_info failed! %d", err);
775  return false;
776  }
777 
778  dhcps_lease_t lease;
779  lease.enable = true;
780  network::IPAddress start_address = info.ip.addr;
781  start_address[3] += 99;
782  lease.start_ip.addr = static_cast<uint32_t>(start_address);
783  ESP_LOGV(TAG, "DHCP server IP lease start: %s", start_address.str().c_str());
784  start_address[3] += 100;
785  lease.end_ip.addr = static_cast<uint32_t>(start_address);
786  ESP_LOGV(TAG, "DHCP server IP lease end: %s", start_address.str().c_str());
787  err = tcpip_adapter_dhcps_option(TCPIP_ADAPTER_OP_SET, TCPIP_ADAPTER_REQUESTED_IP_ADDRESS, &lease, sizeof(lease));
788 
789  if (err != ESP_OK) {
790  ESP_LOGV(TAG, "tcpip_adapter_dhcps_option failed! %d", err);
791  return false;
792  }
793 
794  err = tcpip_adapter_dhcps_start(TCPIP_ADAPTER_IF_AP);
795 
796  if (err != ESP_OK) {
797  ESP_LOGV(TAG, "tcpip_adapter_dhcps_start failed! %d", err);
798  return false;
799  }
800 
801  return true;
802 }
803 bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
804  // enable AP
805  if (!this->wifi_mode_({}, true))
806  return false;
807 
808  wifi_config_t conf;
809  memset(&conf, 0, sizeof(conf));
810  strncpy(reinterpret_cast<char *>(conf.ap.ssid), ap.get_ssid().c_str(), sizeof(conf.ap.ssid));
811  conf.ap.channel = ap.get_channel().value_or(1);
812  conf.ap.ssid_hidden = ap.get_ssid().size();
813  conf.ap.max_connection = 5;
814  conf.ap.beacon_interval = 100;
815 
816  if (ap.get_password().empty()) {
817  conf.ap.authmode = WIFI_AUTH_OPEN;
818  *conf.ap.password = 0;
819  } else {
820  conf.ap.authmode = WIFI_AUTH_WPA2_PSK;
821  strncpy(reinterpret_cast<char *>(conf.ap.password), ap.get_password().c_str(), sizeof(conf.ap.password));
822  }
823 
824 #if ESP_IDF_VERSION_MAJOR >= 4
825  // pairwise cipher of SoftAP, group cipher will be derived using this.
826  conf.ap.pairwise_cipher = WIFI_CIPHER_TYPE_CCMP;
827 #endif
828 
829  esp_err_t err = esp_wifi_set_config(WIFI_IF_AP, &conf);
830  if (err != ESP_OK) {
831  ESP_LOGV(TAG, "esp_wifi_set_config failed! %d", err);
832  return false;
833  }
834 
835  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
836  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
837  return false;
838  }
839 
840  return true;
841 }
843  tcpip_adapter_ip_info_t ip;
844  tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ip);
845  return {ip.ip.addr};
846 }
847 bool WiFiComponent::wifi_disconnect_() { return esp_wifi_disconnect(); }
848 
850  wifi_ap_record_t info;
851  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
852  bssid_t res{};
853  if (err != ESP_OK) {
854  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
855  return res;
856  }
857  std::copy(info.bssid, info.bssid + 6, res.begin());
858  return res;
859 }
860 std::string WiFiComponent::wifi_ssid() {
861  wifi_ap_record_t info{};
862  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
863  if (err != ESP_OK) {
864  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
865  return "";
866  }
867  auto *ssid_s = reinterpret_cast<const char *>(info.ssid);
868  size_t len = strnlen(ssid_s, sizeof(info.ssid));
869  return {ssid_s, len};
870 }
871 int8_t WiFiComponent::wifi_rssi() {
872  wifi_ap_record_t info;
873  esp_err_t err = esp_wifi_sta_get_ap_info(&info);
874  if (err != ESP_OK) {
875  ESP_LOGW(TAG, "esp_wifi_sta_get_ap_info failed: %s", esp_err_to_name(err));
876  return 0;
877  }
878  return info.rssi;
879 }
881  uint8_t primary;
882  wifi_second_chan_t second;
883  esp_err_t err = esp_wifi_get_channel(&primary, &second);
884  if (err != ESP_OK) {
885  ESP_LOGW(TAG, "esp_wifi_get_channel failed: %s", esp_err_to_name(err));
886  return 0;
887  }
888  return primary;
889 }
891  esp_netif_ip_info_t ip;
892  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
893  if (err != ESP_OK) {
894  ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
895  return {};
896  }
897  return {ip.netmask.addr};
898 }
900  esp_netif_ip_info_t ip;
901  esp_err_t err = esp_netif_get_ip_info(s_sta_netif, &ip);
902  if (err != ESP_OK) {
903  ESP_LOGW(TAG, "esp_netif_get_ip_info failed: %s", esp_err_to_name(err));
904  return {};
905  }
906  return {ip.gw.addr};
907 }
909  const ip_addr_t *dns_ip = dns_getserver(num);
910  return {dns_ip->u_addr.ip4.addr};
911 }
912 
913 } // namespace wifi
914 } // namespace esphome
915 
916 #endif
BedjetMode mode
BedJet operating mode.
Definition: bedjet_base.h:102
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
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:397
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:278
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:391
std::string str_snprintf(const char *fmt, size_t len,...)
Definition: helpers.cpp:136
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:371