connect_wlan.cpp 24 KB

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