connect_wlan.cpp 23 KB

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