ESPHome  2024.12.2
wifi_component_libretiny.cpp
Go to the documentation of this file.
1 #include "wifi_component.h"
2 
3 #ifdef USE_WIFI
4 #ifdef USE_LIBRETINY
5 
6 #include <utility>
7 #include <algorithm>
8 #include "lwip/ip_addr.h"
9 #include "lwip/err.h"
10 #include "lwip/dns.h"
11 
12 #include "esphome/core/helpers.h"
13 #include "esphome/core/log.h"
14 #include "esphome/core/hal.h"
16 #include "esphome/core/util.h"
17 
18 namespace esphome {
19 namespace wifi {
20 
21 static const char *const TAG = "wifi_lt";
22 
23 static bool s_sta_connecting = false; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
24 
25 bool WiFiComponent::wifi_mode_(optional<bool> sta, optional<bool> ap) {
26  uint8_t current_mode = WiFi.getMode();
27  bool current_sta = current_mode & 0b01;
28  bool current_ap = current_mode & 0b10;
29  bool enable_sta = sta.value_or(current_sta);
30  bool enable_ap = ap.value_or(current_ap);
31  if (current_sta == enable_sta && current_ap == enable_ap)
32  return true;
33 
34  if (enable_sta && !current_sta) {
35  ESP_LOGV(TAG, "Enabling STA.");
36  } else if (!enable_sta && current_sta) {
37  ESP_LOGV(TAG, "Disabling STA.");
38  }
39  if (enable_ap && !current_ap) {
40  ESP_LOGV(TAG, "Enabling AP.");
41  } else if (!enable_ap && current_ap) {
42  ESP_LOGV(TAG, "Disabling AP.");
43  }
44 
45  uint8_t mode = 0;
46  if (enable_sta)
47  mode |= 0b01;
48  if (enable_ap)
49  mode |= 0b10;
50  bool ret = WiFi.mode(static_cast<wifi_mode_t>(mode));
51 
52  if (!ret) {
53  ESP_LOGW(TAG, "Setting WiFi mode failed!");
54  }
55 
56  return ret;
57 }
58 bool WiFiComponent::wifi_apply_output_power_(float output_power) {
59  int8_t val = static_cast<int8_t>(output_power * 4);
60  return WiFi.setTxPower(val);
61 }
63  if (!this->wifi_mode_(true, {}))
64  return false;
65 
66  WiFi.setAutoReconnect(false);
67  delay(10);
68  return true;
69 }
70 bool WiFiComponent::wifi_apply_power_save_() { return WiFi.setSleep(this->power_save_ != WIFI_POWER_SAVE_NONE); }
71 bool WiFiComponent::wifi_sta_ip_config_(optional<ManualIP> manual_ip) {
72  // enable STA
73  if (!this->wifi_mode_(true, {}))
74  return false;
75 
76  if (!manual_ip.has_value()) {
77  return true;
78  }
79 
80  WiFi.config(manual_ip->static_ip, manual_ip->gateway, manual_ip->subnet, manual_ip->dns1, manual_ip->dns2);
81 
82  return true;
83 }
84 
86  if (!this->has_sta())
87  return {};
88  network::IPAddresses addresses;
89  addresses[0] = WiFi.localIP();
90 #if USE_NETWORK_IPV6
91  int i = 1;
92  auto v6_addresses = WiFi.allLocalIPv6();
93  for (auto address : v6_addresses) {
94  addresses[i++] = network::IPAddress(address.toString().c_str());
95  }
96 #endif /* USE_NETWORK_IPV6 */
97  return addresses;
98 }
99 
101  // setting is done in SYSTEM_EVENT_STA_START callback too
102  WiFi.setHostname(App.get_name().c_str());
103  return true;
104 }
105 bool WiFiComponent::wifi_sta_connect_(const WiFiAP &ap) {
106  // enable STA
107  if (!this->wifi_mode_(true, {}))
108  return false;
109 
110  String ssid = WiFi.SSID();
111  if (ssid && strcmp(ssid.c_str(), ap.get_ssid().c_str()) != 0) {
112  WiFi.disconnect();
113  }
114 
115  if (!this->wifi_sta_ip_config_(ap.get_manual_ip())) {
116  return false;
117  }
118 
119  this->wifi_apply_hostname_();
120 
121  s_sta_connecting = true;
122 
123  WiFiStatus status = WiFi.begin(ap.get_ssid().c_str(), ap.get_password().empty() ? NULL : ap.get_password().c_str(),
124  ap.get_channel().has_value() ? *ap.get_channel() : 0,
125  ap.get_bssid().has_value() ? ap.get_bssid()->data() : NULL);
126  if (status != WL_CONNECTED) {
127  ESP_LOGW(TAG, "esp_wifi_connect failed! %d", status);
128  return false;
129  }
130 
131  return true;
132 }
133 const char *get_auth_mode_str(uint8_t mode) {
134  switch (mode) {
135  case WIFI_AUTH_OPEN:
136  return "OPEN";
137  case WIFI_AUTH_WEP:
138  return "WEP";
139  case WIFI_AUTH_WPA_PSK:
140  return "WPA PSK";
141  case WIFI_AUTH_WPA2_PSK:
142  return "WPA2 PSK";
143  case WIFI_AUTH_WPA_WPA2_PSK:
144  return "WPA/WPA2 PSK";
145  default:
146  return "UNKNOWN";
147  }
148 }
149 
150 using esphome_ip4_addr_t = IPAddress;
151 
152 std::string format_ip4_addr(const esphome_ip4_addr_t &ip) {
153  char buf[20];
154  uint32_t addr = ip;
155  sprintf(buf, "%u.%u.%u.%u", uint8_t(addr >> 0), uint8_t(addr >> 8), uint8_t(addr >> 16), uint8_t(addr >> 24));
156  return buf;
157 }
158 const char *get_op_mode_str(uint8_t mode) {
159  switch (mode) {
160  case WIFI_OFF:
161  return "OFF";
162  case WIFI_STA:
163  return "STA";
164  case WIFI_AP:
165  return "AP";
166  case WIFI_AP_STA:
167  return "AP+STA";
168  default:
169  return "UNKNOWN";
170  }
171 }
172 const char *get_disconnect_reason_str(uint8_t reason) {
173  switch (reason) {
174  case WIFI_REASON_AUTH_EXPIRE:
175  return "Auth Expired";
176  case WIFI_REASON_AUTH_LEAVE:
177  return "Auth Leave";
178  case WIFI_REASON_ASSOC_EXPIRE:
179  return "Association Expired";
180  case WIFI_REASON_ASSOC_TOOMANY:
181  return "Too Many Associations";
182  case WIFI_REASON_NOT_AUTHED:
183  return "Not Authenticated";
184  case WIFI_REASON_NOT_ASSOCED:
185  return "Not Associated";
186  case WIFI_REASON_ASSOC_LEAVE:
187  return "Association Leave";
188  case WIFI_REASON_ASSOC_NOT_AUTHED:
189  return "Association not Authenticated";
190  case WIFI_REASON_DISASSOC_PWRCAP_BAD:
191  return "Disassociate Power Cap Bad";
192  case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
193  return "Disassociate Supported Channel Bad";
194  case WIFI_REASON_IE_INVALID:
195  return "IE Invalid";
196  case WIFI_REASON_MIC_FAILURE:
197  return "Mic Failure";
198  case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
199  return "4-Way Handshake Timeout";
200  case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
201  return "Group Key Update Timeout";
202  case WIFI_REASON_IE_IN_4WAY_DIFFERS:
203  return "IE In 4-Way Handshake Differs";
204  case WIFI_REASON_GROUP_CIPHER_INVALID:
205  return "Group Cipher Invalid";
206  case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
207  return "Pairwise Cipher Invalid";
208  case WIFI_REASON_AKMP_INVALID:
209  return "AKMP Invalid";
210  case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
211  return "Unsupported RSN IE version";
212  case WIFI_REASON_INVALID_RSN_IE_CAP:
213  return "Invalid RSN IE Cap";
214  case WIFI_REASON_802_1X_AUTH_FAILED:
215  return "802.1x Authentication Failed";
216  case WIFI_REASON_CIPHER_SUITE_REJECTED:
217  return "Cipher Suite Rejected";
218  case WIFI_REASON_BEACON_TIMEOUT:
219  return "Beacon Timeout";
220  case WIFI_REASON_NO_AP_FOUND:
221  return "AP Not Found";
222  case WIFI_REASON_AUTH_FAIL:
223  return "Authentication Failed";
224  case WIFI_REASON_ASSOC_FAIL:
225  return "Association Failed";
226  case WIFI_REASON_HANDSHAKE_TIMEOUT:
227  return "Handshake Failed";
228  case WIFI_REASON_CONNECTION_FAIL:
229  return "Connection Failed";
230  case WIFI_REASON_UNSPECIFIED:
231  default:
232  return "Unspecified";
233  }
234 }
235 
236 #define ESPHOME_EVENT_ID_WIFI_READY ARDUINO_EVENT_WIFI_READY
237 #define ESPHOME_EVENT_ID_WIFI_SCAN_DONE ARDUINO_EVENT_WIFI_SCAN_DONE
238 #define ESPHOME_EVENT_ID_WIFI_STA_START ARDUINO_EVENT_WIFI_STA_START
239 #define ESPHOME_EVENT_ID_WIFI_STA_STOP ARDUINO_EVENT_WIFI_STA_STOP
240 #define ESPHOME_EVENT_ID_WIFI_STA_CONNECTED ARDUINO_EVENT_WIFI_STA_CONNECTED
241 #define ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED ARDUINO_EVENT_WIFI_STA_DISCONNECTED
242 #define ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE
243 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP ARDUINO_EVENT_WIFI_STA_GOT_IP
244 #define ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6 ARDUINO_EVENT_WIFI_STA_GOT_IP6
245 #define ESPHOME_EVENT_ID_WIFI_STA_LOST_IP ARDUINO_EVENT_WIFI_STA_LOST_IP
246 #define ESPHOME_EVENT_ID_WIFI_AP_START ARDUINO_EVENT_WIFI_AP_START
247 #define ESPHOME_EVENT_ID_WIFI_AP_STOP ARDUINO_EVENT_WIFI_AP_STOP
248 #define ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED ARDUINO_EVENT_WIFI_AP_STACONNECTED
249 #define ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED ARDUINO_EVENT_WIFI_AP_STADISCONNECTED
250 #define ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED
251 #define ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED
252 #define ESPHOME_EVENT_ID_WIFI_AP_GOT_IP6 ARDUINO_EVENT_WIFI_AP_GOT_IP6
253 using esphome_wifi_event_id_t = arduino_event_id_t;
254 using esphome_wifi_event_info_t = arduino_event_info_t;
255 
257  switch (event) {
258  case ESPHOME_EVENT_ID_WIFI_READY: {
259  ESP_LOGV(TAG, "Event: WiFi ready");
260  break;
261  }
262  case ESPHOME_EVENT_ID_WIFI_SCAN_DONE: {
263  auto it = info.wifi_scan_done;
264  ESP_LOGV(TAG, "Event: WiFi Scan Done status=%u number=%u scan_id=%u", it.status, it.number, it.scan_id);
265 
266  this->wifi_scan_done_callback_();
267  break;
268  }
269  case ESPHOME_EVENT_ID_WIFI_STA_START: {
270  ESP_LOGV(TAG, "Event: WiFi STA start");
271  WiFi.setHostname(App.get_name().c_str());
272  break;
273  }
274  case ESPHOME_EVENT_ID_WIFI_STA_STOP: {
275  ESP_LOGV(TAG, "Event: WiFi STA stop");
276  break;
277  }
278  case ESPHOME_EVENT_ID_WIFI_STA_CONNECTED: {
279  auto it = info.wifi_sta_connected;
280  char buf[33];
281  memcpy(buf, it.ssid, it.ssid_len);
282  buf[it.ssid_len] = '\0';
283  ESP_LOGV(TAG, "Event: Connected ssid='%s' bssid=" LOG_SECRET("%s") " channel=%u, authmode=%s", buf,
284  format_mac_addr(it.bssid).c_str(), it.channel, get_auth_mode_str(it.authmode));
285 
286  break;
287  }
288  case ESPHOME_EVENT_ID_WIFI_STA_DISCONNECTED: {
289  auto it = info.wifi_sta_disconnected;
290  char buf[33];
291  memcpy(buf, it.ssid, it.ssid_len);
292  buf[it.ssid_len] = '\0';
293  if (it.reason == WIFI_REASON_NO_AP_FOUND) {
294  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' reason='Probe Request Unsuccessful'", buf);
295  } else {
296  ESP_LOGW(TAG, "Event: Disconnected ssid='%s' bssid=" LOG_SECRET("%s") " reason='%s'", buf,
297  format_mac_addr(it.bssid).c_str(), get_disconnect_reason_str(it.reason));
298  }
299 
300  uint8_t reason = it.reason;
301  if (reason == WIFI_REASON_AUTH_EXPIRE || reason == WIFI_REASON_BEACON_TIMEOUT ||
302  reason == WIFI_REASON_NO_AP_FOUND || reason == WIFI_REASON_ASSOC_FAIL ||
303  reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
304  WiFi.disconnect();
305  this->error_from_callback_ = true;
306  }
307 
308  s_sta_connecting = false;
309  break;
310  }
311  case ESPHOME_EVENT_ID_WIFI_STA_AUTHMODE_CHANGE: {
312  auto it = info.wifi_sta_authmode_change;
313  ESP_LOGV(TAG, "Event: Authmode Change old=%s new=%s", get_auth_mode_str(it.old_mode),
314  get_auth_mode_str(it.new_mode));
315  // Mitigate CVE-2020-12638
316  // https://lbsfilm.at/blog/wpa2-authenticationmode-downgrade-in-espressif-microprocessors
317  if (it.old_mode != WIFI_AUTH_OPEN && it.new_mode == WIFI_AUTH_OPEN) {
318  ESP_LOGW(TAG, "Potential Authmode downgrade detected, disconnecting...");
319  // we can't call retry_connect() from this context, so disconnect immediately
320  // and notify main thread with error_from_callback_
321  WiFi.disconnect();
322  this->error_from_callback_ = true;
323  }
324  break;
325  }
326  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP: {
327  // auto it = info.got_ip.ip_info;
328  ESP_LOGV(TAG, "Event: Got IP static_ip=%s gateway=%s", format_ip4_addr(WiFi.localIP()).c_str(),
329  format_ip4_addr(WiFi.gatewayIP()).c_str());
330  s_sta_connecting = false;
331  break;
332  }
333  case ESPHOME_EVENT_ID_WIFI_STA_GOT_IP6: {
334  // auto it = info.got_ip.ip_info;
335  ESP_LOGV(TAG, "Event: Got IPv6");
336  break;
337  }
338  case ESPHOME_EVENT_ID_WIFI_STA_LOST_IP: {
339  ESP_LOGV(TAG, "Event: Lost IP");
340  break;
341  }
342  case ESPHOME_EVENT_ID_WIFI_AP_START: {
343  ESP_LOGV(TAG, "Event: WiFi AP start");
344  break;
345  }
346  case ESPHOME_EVENT_ID_WIFI_AP_STOP: {
347  ESP_LOGV(TAG, "Event: WiFi AP stop");
348  break;
349  }
350  case ESPHOME_EVENT_ID_WIFI_AP_STACONNECTED: {
351  auto it = info.wifi_sta_connected;
352  auto &mac = it.bssid;
353  ESP_LOGV(TAG, "Event: AP client connected MAC=%s", format_mac_addr(mac).c_str());
354  break;
355  }
356  case ESPHOME_EVENT_ID_WIFI_AP_STADISCONNECTED: {
357  auto it = info.wifi_sta_disconnected;
358  auto &mac = it.bssid;
359  ESP_LOGV(TAG, "Event: AP client disconnected MAC=%s", format_mac_addr(mac).c_str());
360  break;
361  }
362  case ESPHOME_EVENT_ID_WIFI_AP_STAIPASSIGNED: {
363  ESP_LOGV(TAG, "Event: AP client assigned IP");
364  break;
365  }
366  case ESPHOME_EVENT_ID_WIFI_AP_PROBEREQRECVED: {
367  auto it = info.wifi_ap_probereqrecved;
368  ESP_LOGVV(TAG, "Event: AP receive Probe Request MAC=%s RSSI=%d", format_mac_addr(it.mac).c_str(), it.rssi);
369  break;
370  }
371  default:
372  break;
373  }
374 }
376  auto f = std::bind(&WiFiComponent::wifi_event_callback_, this, std::placeholders::_1, std::placeholders::_2);
377  WiFi.onEvent(f);
378  // Make sure WiFi is in clean state before anything starts
379  this->wifi_mode_(false, false);
380 }
382  auto status = WiFi.status();
383  if (status == WL_CONNECTED) {
385  } else if (status == WL_CONNECT_FAILED || status == WL_CONNECTION_LOST) {
387  } else if (status == WL_NO_SSID_AVAIL) {
389  } else if (s_sta_connecting) {
391  }
393 }
394 bool WiFiComponent::wifi_scan_start_(bool passive) {
395  // enable STA
396  if (!this->wifi_mode_(true, {}))
397  return false;
398 
399  // need to use WiFi because of WiFiScanClass allocations :(
400  int16_t err = WiFi.scanNetworks(true, true, passive, 200);
401  if (err != WIFI_SCAN_RUNNING) {
402  ESP_LOGV(TAG, "WiFi.scanNetworks failed! %d", err);
403  return false;
404  }
405 
406  return true;
407 }
409  this->scan_result_.clear();
410 
411  int16_t num = WiFi.scanComplete();
412  if (num < 0)
413  return;
414 
415  this->scan_result_.reserve(static_cast<unsigned int>(num));
416  for (int i = 0; i < num; i++) {
417  String ssid = WiFi.SSID(i);
418  wifi_auth_mode_t authmode = WiFi.encryptionType(i);
419  int32_t rssi = WiFi.RSSI(i);
420  uint8_t *bssid = WiFi.BSSID(i);
421  int32_t channel = WiFi.channel(i);
422 
423  WiFiScanResult scan({bssid[0], bssid[1], bssid[2], bssid[3], bssid[4], bssid[5]}, std::string(ssid.c_str()),
424  channel, rssi, authmode != WIFI_AUTH_OPEN, ssid.length() == 0);
425  this->scan_result_.push_back(scan);
426  }
427  WiFi.scanDelete();
428  this->scan_done_ = true;
429 }
430 
431 #ifdef USE_WIFI_AP
432 bool WiFiComponent::wifi_ap_ip_config_(optional<ManualIP> manual_ip) {
433  // enable AP
434  if (!this->wifi_mode_({}, true))
435  return false;
436 
437  if (manual_ip.has_value()) {
438  return WiFi.softAPConfig(manual_ip->static_ip, manual_ip->gateway, manual_ip->subnet);
439  } else {
440  return WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));
441  }
442 }
443 
444 bool WiFiComponent::wifi_start_ap_(const WiFiAP &ap) {
445  // enable AP
446  if (!this->wifi_mode_({}, true))
447  return false;
448 
449  if (!this->wifi_ap_ip_config_(ap.get_manual_ip())) {
450  ESP_LOGV(TAG, "wifi_ap_ip_config_ failed!");
451  return false;
452  }
453 
454  yield();
455 
456  return WiFi.softAP(ap.get_ssid().c_str(), ap.get_password().empty() ? NULL : ap.get_password().c_str(),
457  ap.get_channel().value_or(1), ap.get_hidden());
458 }
459 
460 network::IPAddress WiFiComponent::wifi_soft_ap_ip() { return {WiFi.softAPIP()}; }
461 #endif // USE_WIFI_AP
462 
463 bool WiFiComponent::wifi_disconnect_() { return WiFi.disconnect(); }
464 
466  bssid_t bssid{};
467  uint8_t *raw_bssid = WiFi.BSSID();
468  if (raw_bssid != nullptr) {
469  for (size_t i = 0; i < bssid.size(); i++)
470  bssid[i] = raw_bssid[i];
471  }
472  return bssid;
473 }
474 std::string WiFiComponent::wifi_ssid() { return WiFi.SSID().c_str(); }
475 int8_t WiFiComponent::wifi_rssi() { return WiFi.RSSI(); }
476 int32_t WiFiComponent::get_wifi_channel() { return WiFi.channel(); }
477 network::IPAddress WiFiComponent::wifi_subnet_mask_() { return {WiFi.subnetMask()}; }
478 network::IPAddress WiFiComponent::wifi_gateway_ip_() { return {WiFi.gatewayIP()}; }
479 network::IPAddress WiFiComponent::wifi_dns_ip_(int num) { return {WiFi.dnsIP(num)}; }
481 
482 } // namespace wifi
483 } // namespace esphome
484 
485 #endif // USE_LIBRETINY
486 #endif
std::array< uint8_t, 6 > bssid_t
static std::string format_mac_addr(const uint8_t mac[6])
WiFiPowerSaveMode power_save_
network::IPAddress wifi_dns_ip_(int num)
bool wifi_mode_(optional< bool > sta, optional< bool > ap)
bool wifi_apply_output_power_(float output_power)
bool wifi_sta_ip_config_(optional< ManualIP > manual_ip)
mopeka_std_values val[4]
const char * get_op_mode_str(uint8_t mode)
std::vector< WiFiScanResult > scan_result_
const char *const TAG
Definition: spi.cpp:8
arduino_event_id_t esphome_wifi_event_id_t
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:183
Application App
Global storage of Application pointer - only one Application can exist.
bool wifi_ap_ip_config_(optional< ManualIP > manual_ip)
const std::string & get_name() const
Get the name of this Application set by pre_setup().
Definition: application.h:202
std::array< IPAddress, 5 > IPAddresses
Definition: ip_address.h:141
void wifi_event_callback_(arduino_event_id_t event, arduino_event_info_t info)
arduino_event_info_t esphome_wifi_event_info_t
uint8_t status
Definition: bl0942.h:74
const char * get_auth_mode_str(uint8_t mode)
void IRAM_ATTR HOT yield()
Definition: core.cpp:24
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
std::string format_ip4_addr(const esphome_ip4_addr_t &ip)
uint8_t address
Definition: bl0906.h:211
const char * get_disconnect_reason_str(uint8_t reason)
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26