connect_wlan.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. #include "connect_wlan.h"
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <fstream>
  5. #include <vector>
  6. #include <sstream>
  7. #include <iostream>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/task.h"
  10. #include "freertos/event_groups.h"
  11. #include "driver/gpio.h"
  12. #include "esp_system.h"
  13. #include "esp_wifi.h"
  14. #include "esp_wnm.h"
  15. #include "esp_rrm.h"
  16. #include "esp_mbo.h"
  17. #include "esp_mac.h"
  18. #include "esp_netif.h"
  19. #include <netdb.h>
  20. #include "esp_log.h"
  21. #include "nvs_flash.h"
  22. #include "lwip/err.h"
  23. #include "lwip/sys.h"
  24. #ifdef ENABLE_MQTT
  25. #include "interface_mqtt.h"
  26. #endif //ENABLE_MQTT
  27. #include "ClassLogFile.h"
  28. #include "read_wlanini.h"
  29. #include "Helper.h"
  30. #include "statusled.h"
  31. #include "../../include/defines.h"
  32. #if (ESP_IDF_VERSION_MAJOR >= 5)
  33. #include "soc/periph_defs.h"
  34. #include "esp_private/periph_ctrl.h"
  35. #include "soc/gpio_sig_map.h"
  36. #include "soc/gpio_periph.h"
  37. #include "soc/io_mux_reg.h"
  38. #include "esp_rom_gpio.h"
  39. #define gpio_pad_select_gpio esp_rom_gpio_pad_select_gpio
  40. #define gpio_matrix_in(a,b,c) esp_rom_gpio_connect_in_signal(a,b,c)
  41. #define gpio_matrix_out(a,b,c,d) esp_rom_gpio_connect_out_signal(a,b,c,d)
  42. #define ets_delay_us(a) esp_rom_delay_us(a)
  43. #endif
  44. #include "../esp-protocols/components/mdns/include/mdns.h"
  45. static const char *TAG = "WIFI";
  46. static bool APWithBetterRSSI = false;
  47. bool WIFIConnected = false;
  48. static int WIFIReconnectCnt = 0;
  49. esp_netif_t *my_sta;
  50. void strinttoip4(const char *ip, int &a, int &b, int &c, int &d) {
  51. std::string zw = std::string(ip);
  52. std::stringstream s(zw);
  53. char ch; //to temporarily store the '.'
  54. s >> a >> ch >> b >> ch >> c >> ch >> d;
  55. }
  56. std::string BssidToString(const char* c) {
  57. char cBssid[25];
  58. sprintf(cBssid, "%02x:%02x:%02x:%02x:%02x:%02x", c[0], c[1], c[2], c[3], c[4], c[5]);
  59. return std::string(cBssid);
  60. }
  61. #ifdef WLAN_USE_MESH_ROAMING
  62. /* rrm ctx */
  63. int rrm_ctx = 0;
  64. static inline uint32_t WPA_GET_LE32(const uint8_t *a)
  65. {
  66. return ((uint32_t) a[3] << 24) | (a[2] << 16) | (a[1] << 8) | a[0];
  67. }
  68. #ifndef WLAN_EID_MEASURE_REPORT
  69. #define WLAN_EID_MEASURE_REPORT 39
  70. #endif
  71. #ifndef MEASURE_TYPE_LCI
  72. #define MEASURE_TYPE_LCI 9
  73. #endif
  74. #ifndef MEASURE_TYPE_LOCATION_CIVIC
  75. #define MEASURE_TYPE_LOCATION_CIVIC 11
  76. #endif
  77. #ifndef WLAN_EID_NEIGHBOR_REPORT
  78. #define WLAN_EID_NEIGHBOR_REPORT 52
  79. #endif
  80. #ifndef ETH_ALEN
  81. #define ETH_ALEN 6
  82. #endif
  83. #define MAX_NEIGHBOR_LEN 512
  84. static char * get_btm_neighbor_list(uint8_t *report, size_t report_len)
  85. {
  86. size_t len = 0;
  87. const uint8_t *data;
  88. int ret = 0;
  89. /*
  90. * Neighbor Report element (IEEE P802.11-REVmc/D5.0)
  91. * BSSID[6]
  92. * BSSID Information[4]
  93. * Operating Class[1]
  94. * Channel Number[1]
  95. * PHY Type[1]
  96. * Optional Subelements[variable]
  97. */
  98. #define NR_IE_MIN_LEN (ETH_ALEN + 4 + 1 + 1 + 1)
  99. if (!report || report_len == 0) {
  100. ESP_LOGD(TAG, "Roaming: RRM neighbor report is not valid");
  101. return NULL;
  102. }
  103. char *buf = (char*) calloc(1, MAX_NEIGHBOR_LEN);
  104. data = report;
  105. while (report_len >= 2 + NR_IE_MIN_LEN) {
  106. const uint8_t *nr;
  107. char lci[256 * 2 + 1];
  108. char civic[256 * 2 + 1];
  109. uint8_t nr_len = data[1];
  110. const uint8_t *pos = data, *end;
  111. if (pos[0] != WLAN_EID_NEIGHBOR_REPORT ||
  112. nr_len < NR_IE_MIN_LEN) {
  113. ESP_LOGD(TAG, "Roaming CTRL: Invalid Neighbor Report element: id=%u len=%u",
  114. data[0], nr_len);
  115. ret = -1;
  116. goto cleanup;
  117. }
  118. if (2U + nr_len > report_len) {
  119. ESP_LOGD(TAG, "Roaming CTRL: Invalid Neighbor Report element: id=%u len=%zu nr_len=%u",
  120. data[0], report_len, nr_len);
  121. ret = -1;
  122. goto cleanup;
  123. }
  124. pos += 2;
  125. end = pos + nr_len;
  126. nr = pos;
  127. pos += NR_IE_MIN_LEN;
  128. lci[0] = '\0';
  129. civic[0] = '\0';
  130. while (end - pos > 2) {
  131. uint8_t s_id, s_len;
  132. s_id = *pos++;
  133. s_len = *pos++;
  134. if (s_len > end - pos) {
  135. ret = -1;
  136. goto cleanup;
  137. }
  138. if (s_id == WLAN_EID_MEASURE_REPORT && s_len > 3) {
  139. /* Measurement Token[1] */
  140. /* Measurement Report Mode[1] */
  141. /* Measurement Type[1] */
  142. /* Measurement Report[variable] */
  143. switch (pos[2]) {
  144. case MEASURE_TYPE_LCI:
  145. if (lci[0])
  146. break;
  147. memcpy(lci, pos, s_len);
  148. break;
  149. case MEASURE_TYPE_LOCATION_CIVIC:
  150. if (civic[0])
  151. break;
  152. memcpy(civic, pos, s_len);
  153. break;
  154. }
  155. }
  156. pos += s_len;
  157. }
  158. ESP_LOGI(TAG, "Roaming: RMM neighbor report bssid=" MACSTR
  159. " info=0x%x op_class=%u chan=%u phy_type=%u%s%s%s%s",
  160. MAC2STR(nr), WPA_GET_LE32(nr + ETH_ALEN),
  161. nr[ETH_ALEN + 4], nr[ETH_ALEN + 5],
  162. nr[ETH_ALEN + 6],
  163. lci[0] ? " lci=" : "", lci,
  164. civic[0] ? " civic=" : "", civic);
  165. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: RMM neighbor report BSSID: " + BssidToString((char*)nr) +
  166. ", Channel: " + std::to_string(nr[ETH_ALEN + 5]));
  167. /* neighbor start */
  168. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, " neighbor=");
  169. /* bssid */
  170. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, MACSTR, MAC2STR(nr));
  171. /* , */
  172. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  173. /* bssid info */
  174. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "0x%04x", WPA_GET_LE32(nr + ETH_ALEN));
  175. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  176. /* operating class */
  177. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 4]);
  178. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  179. /* channel number */
  180. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 5]);
  181. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  182. /* phy type */
  183. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 6]);
  184. /* optional elements, skip */
  185. data = end;
  186. report_len -= 2 + nr_len;
  187. }
  188. cleanup:
  189. if (ret < 0) {
  190. free(buf);
  191. buf = NULL;
  192. }
  193. return buf;
  194. }
  195. void neighbor_report_recv_cb(void *ctx, const uint8_t *report, size_t report_len)
  196. {
  197. int *val = (int*) ctx;
  198. uint8_t *pos = (uint8_t *)report;
  199. int cand_list = 0;
  200. int ret;
  201. if (!report) {
  202. ESP_LOGD(TAG, "Roaming: Neighbor report is null");
  203. return;
  204. }
  205. if (*val != rrm_ctx) {
  206. ESP_LOGE(TAG, "Roaming: rrm_ctx value didn't match, not initiated by us");
  207. return;
  208. }
  209. /* dump report info */
  210. ESP_LOGD(TAG, "Roaming: RRM neighbor report len=%d", report_len);
  211. ESP_LOG_BUFFER_HEXDUMP(TAG, pos, report_len, ESP_LOG_DEBUG);
  212. /* create neighbor list */
  213. char *neighbor_list = get_btm_neighbor_list(pos + 1, report_len - 1);
  214. /* In case neighbor list is not present issue a scan and get the list from that */
  215. if (!neighbor_list) {
  216. /* issue scan */
  217. wifi_scan_config_t params;
  218. memset(&params, 0, sizeof(wifi_scan_config_t));
  219. if (esp_wifi_scan_start(&params, true) < 0) {
  220. goto cleanup;
  221. }
  222. /* cleanup from net802.11 */
  223. uint16_t number = 1;
  224. wifi_ap_record_t ap_records;
  225. esp_wifi_scan_get_ap_records(&number, &ap_records);
  226. cand_list = 1;
  227. }
  228. /* send AP btm query requesting to roam depending on candidate list of AP */
  229. // btm_query_reasons: https://github.com/espressif/esp-idf/blob/release/v4.4/components/wpa_supplicant/esp_supplicant/include/esp_wnm.h
  230. ret = esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, neighbor_list, cand_list); // query reason 16 -> LOW RSSI --> (btm_query_reason)16
  231. ESP_LOGD(TAG, "neighbor_report_recv_cb retval - bss_transisition_query: %d", ret);
  232. cleanup:
  233. if (neighbor_list)
  234. free(neighbor_list);
  235. }
  236. static void esp_bss_rssi_low_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
  237. {
  238. int retval = -1;
  239. wifi_event_bss_rssi_low_t *event = (wifi_event_bss_rssi_low_t*) event_data;
  240. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming Event: RSSI " + std::to_string(event->rssi) +
  241. " < RSSI_Threshold " + std::to_string(wlan_config.rssi_threshold));
  242. /* If RRM is supported, call RRM and then send BTM query to AP */
  243. if (esp_rrm_is_rrm_supported_connection() && esp_wnm_is_btm_supported_connection())
  244. {
  245. /* Lets check channel conditions */
  246. rrm_ctx++;
  247. retval = esp_rrm_send_neighbor_rep_request(neighbor_report_recv_cb, &rrm_ctx);
  248. ESP_LOGD(TAG, "esp_rrm_send_neighbor_rep_request retval: %d", retval);
  249. if (retval == 0)
  250. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: RRM + BTM query sent");
  251. else
  252. ESP_LOGD(TAG, "esp_rrm_send_neighbor_rep_request retval: %d", retval);
  253. }
  254. /* If RRM is not supported or RRM request failed, send directly BTM query to AP */
  255. if (retval < 0 && esp_wnm_is_btm_supported_connection())
  256. {
  257. // btm_query_reasons: https://github.com/espressif/esp-idf/blob/release/v4.4/components/wpa_supplicant/esp_supplicant/include/esp_wnm.h
  258. retval = esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, NULL, 0); // query reason 16 -> LOW RSSI --> (btm_query_reason)16
  259. ESP_LOGD(TAG, "esp_wnm_send_bss_transition_mgmt_query retval: %d", retval);
  260. if (retval == 0)
  261. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: BTM query sent");
  262. else
  263. ESP_LOGD(TAG, "esp_wnm_send_bss_transition_mgmt_query retval: %d", retval);
  264. }
  265. }
  266. void printRoamingFeatureSupport(void)
  267. {
  268. if (esp_rrm_is_rrm_supported_connection())
  269. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: RRM (802.11k) supported by AP");
  270. else
  271. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: RRM (802.11k) NOT supported by AP");
  272. if (esp_wnm_is_btm_supported_connection())
  273. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: BTM (802.11v) supported by AP");
  274. else
  275. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: BTM (802.11v) NOT supported by AP");
  276. }
  277. #ifdef WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  278. void wifiRoamingQuery(void)
  279. {
  280. /* Query only if WIFI is connected and feature is supported by AP */
  281. if (WIFIConnected && (esp_rrm_is_rrm_supported_connection() || esp_wnm_is_btm_supported_connection())) {
  282. /* Client is allowed to send query to AP for roaming request if RSSI is lower than threshold */
  283. /* Note 1: Set RSSI threshold funtion needs to be called to trigger WIFI_EVENT_STA_BSS_RSSI_LOW */
  284. /* Note 2: Additional querys will be sent after flow round is finshed --> server_tflite.cpp - function "task_autodoFlow" */
  285. /* Note 3: RSSI_Threshold = 0 --> Disable client query by application (WebUI parameter) */
  286. if (wlan_config.rssi_threshold != 0 && get_WIFI_RSSI() != -127 && (get_WIFI_RSSI() < wlan_config.rssi_threshold))
  287. esp_wifi_set_rssi_threshold(wlan_config.rssi_threshold);
  288. }
  289. }
  290. #endif // WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  291. #endif // WLAN_USE_MESH_ROAMING
  292. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  293. std::string getAuthModeName(const wifi_auth_mode_t auth_mode)
  294. {
  295. std::string AuthModeNames[] = {"OPEN", "WEP", "WPA PSK", "WPA2 PSK", "WPA WPA2 PSK", "WPA2 ENTERPRISE",
  296. "WPA3 PSK", "WPA2 WPA3 PSK", "WAPI_PSK", "MAX"};
  297. return AuthModeNames[auth_mode];
  298. }
  299. void wifi_scan(void)
  300. {
  301. wifi_scan_config_t wifi_scan_config;
  302. memset(&wifi_scan_config, 0, sizeof(wifi_scan_config));
  303. wifi_scan_config.ssid = (uint8_t*)wlan_config.ssid.c_str(); // only scan for configured SSID
  304. wifi_scan_config.show_hidden = true; // scan also hidden SSIDs
  305. wifi_scan_config.channel = 0; // scan all channels
  306. esp_wifi_scan_start(&wifi_scan_config, true); // not using event handler SCAN_DONE by purpose to keep SYS_EVENT heap smaller
  307. // and the calling task task_autodoFlow is after scan is finish in wait state anyway
  308. // Scan duration: ca. (120ms + 30ms) * Number of channels -> ca. 1,5 - 2s
  309. uint16_t max_number_of_ap_found = 10; // max. number of APs, value will be updated by function "esp_wifi_scan_get_ap_num"
  310. esp_wifi_scan_get_ap_num(&max_number_of_ap_found); // get actual found APs
  311. wifi_ap_record_t* wifi_ap_records = new wifi_ap_record_t[max_number_of_ap_found]; // Allocate necessary record datasets
  312. if (wifi_ap_records == NULL) {
  313. esp_wifi_scan_get_ap_records(0, NULL); // free internal heap
  314. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "wifi_scan: Failed to allocate heap for wifi_ap_records");
  315. return;
  316. }
  317. else {
  318. if (esp_wifi_scan_get_ap_records(&max_number_of_ap_found, wifi_ap_records) != ESP_OK) { // Retrieve results (and free internal heap)
  319. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "wifi_scan: esp_wifi_scan_get_ap_records: Error retrieving datasets");
  320. delete[] wifi_ap_records;
  321. return;
  322. }
  323. }
  324. wifi_ap_record_t currentAP;
  325. esp_wifi_sta_get_ap_info(&currentAP);
  326. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Current AP BSSID=" + BssidToString((char*)currentAP.bssid));
  327. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Scan completed, APs found with configured SSID: " + std::to_string(max_number_of_ap_found));
  328. for (int i = 0; i < max_number_of_ap_found; i++) {
  329. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: " + std::to_string(i+1) +
  330. ": SSID=" + std::string((char*)wifi_ap_records[i].ssid) +
  331. ", BSSID=" + BssidToString((char*)wifi_ap_records[i].bssid) +
  332. ", RSSI=" + std::to_string(wifi_ap_records[i].rssi) +
  333. ", CH=" + std::to_string(wifi_ap_records[i].primary) +
  334. ", AUTH=" + getAuthModeName(wifi_ap_records[i].authmode));
  335. if (wifi_ap_records[i].rssi > (currentAP.rssi + 5) && // RSSI is better than actual RSSI + 5 --> Avoid switching to AP with roughly same RSSI
  336. (strcmp(BssidToString((char*)wifi_ap_records[i].bssid).c_str(), BssidToString((char*)currentAP.bssid).c_str()) != 0))
  337. {
  338. APWithBetterRSSI = true;
  339. }
  340. }
  341. delete[] wifi_ap_records;
  342. }
  343. void wifiRoamByScanning(void)
  344. {
  345. if (wlan_config.rssi_threshold != 0 && get_WIFI_RSSI() != -127 && (get_WIFI_RSSI() < wlan_config.rssi_threshold)) {
  346. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Start scan of all channels for SSID " + wlan_config.ssid);
  347. wifi_scan();
  348. if (APWithBetterRSSI) {
  349. APWithBetterRSSI = false;
  350. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Roaming: AP with better RSSI in range, disconnecting to switch AP...");
  351. esp_wifi_disconnect();
  352. }
  353. else {
  354. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Scan completed, stay on current AP");
  355. }
  356. }
  357. }
  358. #endif // WLAN_USE_ROAMING_BY_SCANNING
  359. std::string* getIPAddress()
  360. {
  361. return &wlan_config.ipaddress;
  362. }
  363. std::string* getSSID()
  364. {
  365. return &wlan_config.ssid;
  366. }
  367. static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
  368. {
  369. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
  370. {
  371. WIFIConnected = false;
  372. esp_wifi_connect();
  373. }
  374. else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
  375. {
  376. /* Disconnect reason: https://github.com/espressif/esp-idf/blob/d825753387c1a64463779bbd2369e177e5d59a79/components/esp_wifi/include/esp_wifi_types.h */
  377. wifi_event_sta_disconnected_t *disconn = (wifi_event_sta_disconnected_t *)event_data;
  378. if (disconn->reason == WIFI_REASON_ROAMING) {
  379. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Roaming 802.11kv)");
  380. // --> no reconnect neccessary, it should automatically reconnect to new AP
  381. }
  382. else {
  383. WIFIConnected = false;
  384. if (disconn->reason == WIFI_REASON_NO_AP_FOUND) {
  385. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", No AP)");
  386. StatusLED(WLAN_CONN, 1, false);
  387. }
  388. else if (disconn->reason == WIFI_REASON_AUTH_EXPIRE ||
  389. disconn->reason == WIFI_REASON_AUTH_FAIL ||
  390. disconn->reason == WIFI_REASON_NOT_AUTHED ||
  391. disconn->reason == WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT ||
  392. disconn->reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
  393. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Auth fail)");
  394. StatusLED(WLAN_CONN, 2, false);
  395. }
  396. else if (disconn->reason == WIFI_REASON_BEACON_TIMEOUT) {
  397. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Timeout)");
  398. StatusLED(WLAN_CONN, 3, false);
  399. }
  400. else {
  401. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ")");
  402. StatusLED(WLAN_CONN, 4, false);
  403. }
  404. WIFIReconnectCnt++;
  405. esp_wifi_connect(); // Try to connect again
  406. }
  407. if (WIFIReconnectCnt >= 10) {
  408. WIFIReconnectCnt = 0;
  409. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed (" +
  410. std::to_string(disconn->reason) + "), retrying after 5s");
  411. vTaskDelay(5000 / portTICK_PERIOD_MS); // Delay between the reconnections
  412. }
  413. }
  414. else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
  415. {
  416. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to: " + wlan_config.ssid + ", RSSI: " +
  417. std::to_string(get_WIFI_RSSI()));
  418. #ifdef WLAN_USE_MESH_ROAMING
  419. printRoamingFeatureSupport();
  420. #ifdef WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  421. // wifiRoamingQuery(); // Avoid client triggered query during processing flow (reduce risk of heap shortage). Request will be triggered at the end of every round anyway
  422. #endif //WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  423. #endif //WLAN_USE_MESH_ROAMING
  424. }
  425. else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
  426. {
  427. WIFIConnected = true;
  428. WIFIReconnectCnt = 0;
  429. ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
  430. wlan_config.ipaddress = std::string(ip4addr_ntoa((const ip4_addr*) &event->ip_info.ip));
  431. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Assigned IP: " + wlan_config.ipaddress);
  432. #ifdef ENABLE_MQTT
  433. if (getMQTTisEnabled()) {
  434. vTaskDelay(5000 / portTICK_PERIOD_MS);
  435. MQTT_Init(); // Init when WIFI is getting connected
  436. }
  437. #endif //ENABLE_MQTT
  438. }
  439. }
  440. esp_err_t wifi_init_sta(void)
  441. {
  442. esp_err_t retval = esp_netif_init();
  443. if (retval != ESP_OK) {
  444. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_netif_init: Error: " + std::to_string(retval));
  445. return retval;
  446. }
  447. retval = esp_event_loop_create_default();
  448. if (retval != ESP_OK) {
  449. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_loop_create_default: Error: " + std::to_string(retval));
  450. return retval;
  451. }
  452. my_sta = esp_netif_create_default_wifi_sta();
  453. if (!wlan_config.ipaddress.empty() && !wlan_config.gateway.empty() && !wlan_config.netmask.empty())
  454. {
  455. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Manual interface config -> IP: " + wlan_config.ipaddress + ", Gateway: " +
  456. std::string(wlan_config.gateway) + ", Netmask: " + std::string(wlan_config.netmask));
  457. esp_netif_dhcpc_stop(my_sta); // Stop DHCP service
  458. esp_netif_ip_info_t ip_info;
  459. int a, b, c, d;
  460. strinttoip4(wlan_config.ipaddress.c_str(), a, b, c, d);
  461. IP4_ADDR(&ip_info.ip, a, b, c, d); // Set static IP address
  462. strinttoip4(wlan_config.gateway.c_str(), a, b, c, d);
  463. IP4_ADDR(&ip_info.gw, a, b, c, d); // Set gateway
  464. strinttoip4(wlan_config.netmask.c_str(), a, b, c, d);
  465. IP4_ADDR(&ip_info.netmask, a, b, c, d); // Set netmask
  466. esp_netif_set_ip_info(my_sta, &ip_info); // Set static IP configuration
  467. }
  468. else {
  469. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Automatic interface config --> Use DHCP service");
  470. }
  471. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  472. retval = esp_wifi_init(&cfg);
  473. if (retval != ESP_OK) {
  474. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_init: Error: " + std::to_string(retval));
  475. return retval;
  476. }
  477. if (!wlan_config.ipaddress.empty() && !wlan_config.gateway.empty() && !wlan_config.netmask.empty())
  478. {
  479. if (wlan_config.dns.empty()) {
  480. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "No DNS server, use gateway");
  481. wlan_config.dns = wlan_config.gateway;
  482. }
  483. else {
  484. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Manual interface config -> DNS: " + wlan_config.dns);
  485. }
  486. esp_netif_dns_info_t dns_info;
  487. ip4_addr_t ip;
  488. ip.addr = esp_ip4addr_aton(wlan_config.dns.c_str());
  489. ip_addr_set_ip4_u32(&dns_info.ip, ip.addr);
  490. retval = esp_netif_set_dns_info(my_sta, ESP_NETIF_DNS_MAIN, &dns_info);
  491. if (retval != ESP_OK) {
  492. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_netif_set_dns_info: Error: " + std::to_string(retval));
  493. return retval;
  494. }
  495. }
  496. retval = esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
  497. &event_handler, NULL, NULL);
  498. if (retval != ESP_OK) {
  499. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - WIFI_ANY: Error: " + std::to_string(retval));
  500. return retval;
  501. }
  502. retval = esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
  503. &event_handler, NULL, NULL);
  504. if (retval != ESP_OK) {
  505. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - GOT_IP: Error: " + std::to_string(retval));
  506. return retval;
  507. }
  508. #ifdef WLAN_USE_MESH_ROAMING
  509. retval = esp_event_handler_instance_register(WIFI_EVENT, WIFI_EVENT_STA_BSS_RSSI_LOW,
  510. &esp_bss_rssi_low_handler, NULL, NULL);
  511. if (retval != ESP_OK) {
  512. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - BSS_RSSI_LOW: Error: " + std::to_string(retval));
  513. return retval;
  514. }
  515. #endif
  516. wifi_config_t wifi_config = { };
  517. wifi_config.sta.scan_method = WIFI_ALL_CHANNEL_SCAN; // Scan all channels instead of stopping after first match
  518. wifi_config.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL; // Sort by signal strength and keep up to 4 best APs
  519. //wifi_config.sta.failure_retry_cnt = 3; // IDF version 5.0 will support this
  520. #ifdef WLAN_USE_MESH_ROAMING
  521. wifi_config.sta.rm_enabled = 1; // 802.11k (Radio Resource Management)
  522. wifi_config.sta.btm_enabled = 1; // 802.11v (BSS Transition Management)
  523. //wifi_config.sta.mbo_enabled = 1; // Multiband Operation (better use of Wi-Fi network resources in roaming decisions) -> not activated to save heap
  524. wifi_config.sta.pmf_cfg.capable = 1; // 802.11w (Protected Management Frame, activated by default if other device also advertizes PMF capability)
  525. //wifi_config.sta.ft_enabled = 1; // 802.11r (BSS Fast Transition) -> Upcoming IDF version 5.0 will support 11r
  526. #endif
  527. strcpy((char*)wifi_config.sta.ssid, (const char*)wlan_config.ssid.c_str());
  528. strcpy((char*)wifi_config.sta.password, (const char*)wlan_config.password.c_str());
  529. retval = esp_wifi_set_mode(WIFI_MODE_STA);
  530. if (retval != ESP_OK) {
  531. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_mode: Error: " + std::to_string(retval));
  532. return retval;
  533. }
  534. retval = esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
  535. if (retval != ESP_OK) {
  536. if (retval == ESP_ERR_WIFI_PASSWORD) {
  537. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_config: SSID password invalid! Error: " + std::to_string(retval));
  538. }
  539. else {
  540. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_config: Error: " + std::to_string(retval));
  541. }
  542. return retval;
  543. }
  544. retval = esp_wifi_start();
  545. if (retval != ESP_OK) {
  546. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_start: Error: " + std::to_string(retval));
  547. return retval;
  548. }
  549. if (!wlan_config.hostname.empty())
  550. {
  551. retval = esp_netif_set_hostname(my_sta, wlan_config.hostname.c_str());
  552. if(retval != ESP_OK ) {
  553. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set hostname! Error: " + std::to_string(retval));
  554. }
  555. else {
  556. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Set hostname to: " + wlan_config.hostname);
  557. }
  558. //initialize mDNS service
  559. retval = mdns_init();
  560. if (retval != ESP_OK) {
  561. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "mdns_init failed! Error: " + std::to_string(retval));
  562. } else {
  563. //set mdns hostname
  564. mdns_hostname_set(wlan_config.hostname.c_str());
  565. }
  566. }
  567. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init successful");
  568. return ESP_OK;
  569. }
  570. int get_WIFI_RSSI()
  571. {
  572. wifi_ap_record_t ap;
  573. if (esp_wifi_sta_get_ap_info(&ap) == ESP_OK)
  574. return ap.rssi;
  575. else
  576. return -127; // Return -127 if no info available e.g. not connected
  577. }
  578. /*std::string getIp() {
  579. esp_netif_ip_info_t ip_info;
  580. ESP_ERROR_CHECK(esp_netif_get_ip_info(my_sta, ip_info));
  581. char ipFormated[4*3+3+1];
  582. sprintf(ipFormated, IPSTR, IP2STR(&ip_info.ip));
  583. return std::string(ipFormated);
  584. }*/
  585. std::string* getHostname() {
  586. return &wlan_config.hostname;
  587. }
  588. bool getWIFIisConnected()
  589. {
  590. return WIFIConnected;
  591. }
  592. void WIFIDestroy()
  593. {
  594. esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler);
  595. esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler);
  596. #ifdef WLAN_USE_MESH_ROAMING
  597. esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_BSS_RSSI_LOW, esp_bss_rssi_low_handler);
  598. #endif
  599. esp_wifi_disconnect();
  600. esp_wifi_stop();
  601. esp_wifi_deinit();
  602. }