connect_roaming.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #include "connect_roaming.h"
  2. #include "connect_wifi_sta.h"
  3. #include <string.h>
  4. #include <stdlib.h>
  5. #include <fstream>
  6. #include <vector>
  7. #include <sstream>
  8. #include <iostream>
  9. #include <driver/gpio.h>
  10. #include <esp_system.h>
  11. #include <esp_wifi.h>
  12. #include <esp_wnm.h>
  13. #include <esp_rrm.h>
  14. #include <esp_mbo.h>
  15. #include <esp_mac.h>
  16. #include <esp_netif.h>
  17. #include <netdb.h>
  18. #include <esp_log.h>
  19. #include <nvs_flash.h>
  20. #include <lwip/err.h>
  21. #include <lwip/sys.h>
  22. #include <interface_mqtt.h>
  23. #include <freertos/FreeRTOS.h>
  24. #include <freertos/task.h>
  25. #include <freertos/event_groups.h>
  26. #include "defines.h"
  27. #include "Helper.h"
  28. #include "ClassLogFile.h"
  29. #include "read_network_config.h"
  30. #include "statusled.h"
  31. #include "../include/mdns.h"
  32. #if defined HEAP_TRACING_MAIN_WIFI
  33. #include <esp_heap_trace.h>
  34. #endif
  35. static const char *TAG = "WIFI ROAMING";
  36. static bool wifi_sta_with_better_rssi = false;
  37. std::string get_auth_mode_name(const wifi_auth_mode_t auth_mode)
  38. {
  39. std::string AuthModeNames[] = {"OPEN", "WEP", "WPA PSK", "WPA2 PSK", "WPA WPA2 PSK", "WPA2 ENTERPRISE", "WPA3 PSK", "WPA2 WPA3 PSK", "WAPI_PSK", "MAX"};
  40. return AuthModeNames[auth_mode];
  41. }
  42. #ifdef WLAN_USE_MESH_ROAMING
  43. int rrm_ctx = 0;
  44. static inline uint32_t WPA_GET_LE32(const uint8_t *a)
  45. {
  46. return ((uint32_t)a[3] << 24) | (a[2] << 16) | (a[1] << 8) | a[0];
  47. }
  48. #ifndef WLAN_EID_MEASURE_REPORT
  49. #define WLAN_EID_MEASURE_REPORT 39
  50. #endif
  51. #ifndef MEASURE_TYPE_LCI
  52. #define MEASURE_TYPE_LCI 9
  53. #endif
  54. #ifndef MEASURE_TYPE_LOCATION_CIVIC
  55. #define MEASURE_TYPE_LOCATION_CIVIC 11
  56. #endif
  57. #ifndef WLAN_EID_NEIGHBOR_REPORT
  58. #define WLAN_EID_NEIGHBOR_REPORT 52
  59. #endif
  60. #ifndef ETH_ALEN
  61. #define ETH_ALEN 6
  62. #endif
  63. #define MAX_NEIGHBOR_LEN 512
  64. static char *get_btm_neighbor_list(uint8_t *report, size_t report_len)
  65. {
  66. size_t len = 0;
  67. const uint8_t *data;
  68. int ret = 0;
  69. /*
  70. * Neighbor Report element (IEEE P802.11-REVmc/D5.0)
  71. * BSSID[6]
  72. * BSSID Information[4]
  73. * Operating Class[1]
  74. * Channel Number[1]
  75. * PHY Type[1]
  76. * Optional Subelements[variable]
  77. */
  78. #define NR_IE_MIN_LEN (ETH_ALEN + 4 + 1 + 1 + 1)
  79. if (!report || report_len == 0)
  80. {
  81. ESP_LOGD(TAG, "Roaming: RRM neighbor report is not valid");
  82. return NULL;
  83. }
  84. char *buf = (char *)calloc(1, MAX_NEIGHBOR_LEN);
  85. data = report;
  86. while (report_len >= 2 + NR_IE_MIN_LEN)
  87. {
  88. const uint8_t *nr;
  89. char lci[256 * 2 + 1];
  90. char civic[256 * 2 + 1];
  91. uint8_t nr_len = data[1];
  92. const uint8_t *pos = data, *end;
  93. if (pos[0] != WLAN_EID_NEIGHBOR_REPORT ||
  94. nr_len < NR_IE_MIN_LEN)
  95. {
  96. ESP_LOGD(TAG, "Roaming CTRL: Invalid Neighbor Report element: id=%u len=%u",
  97. data[0], nr_len);
  98. ret = -1;
  99. goto cleanup;
  100. }
  101. if (2U + nr_len > report_len)
  102. {
  103. ESP_LOGD(TAG, "Roaming CTRL: Invalid Neighbor Report element: id=%u len=%zu nr_len=%u",
  104. data[0], report_len, nr_len);
  105. ret = -1;
  106. goto cleanup;
  107. }
  108. pos += 2;
  109. end = pos + nr_len;
  110. nr = pos;
  111. pos += NR_IE_MIN_LEN;
  112. lci[0] = '\0';
  113. civic[0] = '\0';
  114. while (end - pos > 2)
  115. {
  116. uint8_t s_id, s_len;
  117. s_id = *pos++;
  118. s_len = *pos++;
  119. if (s_len > end - pos)
  120. {
  121. ret = -1;
  122. goto cleanup;
  123. }
  124. if (s_id == WLAN_EID_MEASURE_REPORT && s_len > 3)
  125. {
  126. /* Measurement Token[1] */
  127. /* Measurement Report Mode[1] */
  128. /* Measurement Type[1] */
  129. /* Measurement Report[variable] */
  130. switch (pos[2])
  131. {
  132. case MEASURE_TYPE_LCI:
  133. if (lci[0])
  134. break;
  135. memcpy(lci, pos, s_len);
  136. break;
  137. case MEASURE_TYPE_LOCATION_CIVIC:
  138. if (civic[0])
  139. break;
  140. memcpy(civic, pos, s_len);
  141. break;
  142. }
  143. }
  144. pos += s_len;
  145. }
  146. ESP_LOGI(TAG, "Roaming: RMM neighbor report bssid=" MACSTR " info=0x%04lx op_class=%u chan=%u phy_type=%u%s%s%s%s",
  147. MAC2STR(nr), WPA_GET_LE32(nr + ETH_ALEN),
  148. nr[ETH_ALEN + 4], nr[ETH_ALEN + 5],
  149. nr[ETH_ALEN + 6],
  150. lci[0] ? " lci=" : "", lci,
  151. civic[0] ? " civic=" : "", civic);
  152. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: RMM neighbor report BSSID: " + bssid_to_string((char *)nr) + ", 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%04lx", 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. {
  177. free(buf);
  178. buf = NULL;
  179. }
  180. return buf;
  181. }
  182. void neighbor_report_recv_cb(void *ctx, const uint8_t *report, size_t report_len)
  183. {
  184. int *val = (int *)ctx;
  185. uint8_t *pos = (uint8_t *)report;
  186. int cand_list = 0;
  187. int ret;
  188. if (!report)
  189. {
  190. ESP_LOGD(TAG, "Roaming: Neighbor report is null");
  191. return;
  192. }
  193. if (*val != rrm_ctx)
  194. {
  195. ESP_LOGE(TAG, "Roaming: rrm_ctx value didn't match, not initiated by us");
  196. return;
  197. }
  198. /* dump report info */
  199. ESP_LOGD(TAG, "Roaming: RRM neighbor report len=%d", report_len);
  200. ESP_LOG_BUFFER_HEXDUMP(TAG, pos, report_len, ESP_LOG_DEBUG);
  201. /* create neighbor list */
  202. char *neighbor_list = get_btm_neighbor_list(pos + 1, report_len - 1);
  203. /* In case neighbor list is not present issue a scan and get the list from that */
  204. if (!neighbor_list)
  205. {
  206. /* issue scan */
  207. wifi_scan_config_t params;
  208. memset(&params, 0, sizeof(wifi_scan_config_t));
  209. if (esp_wifi_scan_start(&params, true) < 0)
  210. {
  211. goto cleanup;
  212. }
  213. /* cleanup from net802.11 */
  214. uint16_t number = 1;
  215. wifi_ap_record_t ap_records;
  216. esp_wifi_scan_get_ap_records(&number, &ap_records);
  217. cand_list = 1;
  218. }
  219. /* send AP btm query requesting to roam depending on candidate list of AP */
  220. // btm_query_reasons: https://github.com/espressif/esp-idf/blob/release/v4.4/components/wpa_supplicant/esp_supplicant/include/esp_wnm.h
  221. ret = esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, neighbor_list, cand_list); // query reason 16 -> LOW RSSI --> (btm_query_reason)16
  222. ESP_LOGD(TAG, "neighbor_report_recv_cb retval - bss_transisition_query: %d", ret);
  223. cleanup:
  224. if (neighbor_list)
  225. {
  226. free(neighbor_list);
  227. }
  228. }
  229. void esp_bss_rssi_low_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
  230. {
  231. int retval = -1;
  232. wifi_event_bss_rssi_low_t *event = (wifi_event_bss_rssi_low_t *)event_data;
  233. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming Event: RSSI " + std::to_string(event->rssi) + " < RSSI_Threshold " + std::to_string(network_config.rssi_threshold));
  234. /* If RRM is supported, call RRM and then send BTM query to AP */
  235. if (esp_rrm_is_rrm_supported_connection() && esp_wnm_is_btm_supported_connection())
  236. {
  237. /* Lets check channel conditions */
  238. rrm_ctx++;
  239. retval = esp_rrm_send_neighbor_rep_request(neighbor_report_recv_cb, &rrm_ctx);
  240. ESP_LOGD(TAG, "esp_rrm_send_neighbor_rep_request retval: %d", retval);
  241. if (retval == 0)
  242. {
  243. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: RRM + BTM query sent");
  244. }
  245. else
  246. {
  247. ESP_LOGD(TAG, "esp_rrm_send_neighbor_rep_request retval: %d", retval);
  248. }
  249. }
  250. /* If RRM is not supported or RRM request failed, send directly BTM query to AP */
  251. if (retval < 0 && esp_wnm_is_btm_supported_connection())
  252. {
  253. // btm_query_reasons: https://github.com/espressif/esp-idf/blob/release/v4.4/components/wpa_supplicant/esp_supplicant/include/esp_wnm.h
  254. retval = esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, NULL, 0); // query reason 16 -> LOW RSSI --> (btm_query_reason)16
  255. ESP_LOGD(TAG, "esp_wnm_send_bss_transition_mgmt_query retval: %d", retval);
  256. if (retval == 0)
  257. {
  258. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: BTM query sent");
  259. }
  260. else
  261. {
  262. ESP_LOGD(TAG, "esp_wnm_send_bss_transition_mgmt_query retval: %d", retval);
  263. }
  264. }
  265. }
  266. void printRoamingFeatureSupport(void)
  267. {
  268. if (esp_rrm_is_rrm_supported_connection())
  269. {
  270. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: RRM (802.11k) supported by AP");
  271. }
  272. else
  273. {
  274. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: RRM (802.11k) NOT supported by AP");
  275. }
  276. if (esp_wnm_is_btm_supported_connection())
  277. {
  278. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: BTM (802.11v) supported by AP");
  279. }
  280. else
  281. {
  282. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Roaming: BTM (802.11v) NOT supported by AP");
  283. }
  284. }
  285. #ifdef WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  286. void wifi_roaming_query(void)
  287. {
  288. /* Query only if WIFI is connected and feature is supported by AP */
  289. if (WIFIConnected && (esp_rrm_is_rrm_supported_connection() || esp_wnm_is_btm_supported_connection()))
  290. {
  291. /* Client is allowed to send query to AP for roaming request if RSSI is lower than threshold */
  292. /* Note 1: Set RSSI threshold funtion needs to be called to trigger WIFI_EVENT_STA_BSS_RSSI_LOW */
  293. /* Note 2: Additional querys will be sent after flow round is finshed --> server_tflite.cpp - function "task_autodoFlow" */
  294. /* Note 3: RSSI_Threshold = 0 --> Disable client query by application (WebUI parameter) */
  295. if (network_config.rssi_threshold != 0 && get_WIFI_RSSI() != -127 && (get_WIFI_RSSI() < network_config.rssi_threshold))
  296. {
  297. esp_wifi_set_rssi_threshold(network_config.rssi_threshold);
  298. }
  299. }
  300. }
  301. #endif // WLAN_USE_MESH_ROAMING_ACTIVATE_CLIENT_TRIGGERED_QUERIES
  302. #endif // WLAN_USE_MESH_ROAMING
  303. #ifdef WLAN_USE_ROAMING_BY_SCANNING
  304. void wifi_scan(void)
  305. {
  306. wifi_scan_config_t wifi_scan_config;
  307. memset(&wifi_scan_config, 0, sizeof(wifi_scan_config));
  308. wifi_scan_config.ssid = (uint8_t *)network_config.ssid.c_str(); // only scan for configured SSID
  309. wifi_scan_config.show_hidden = true; // scan also hidden SSIDs
  310. wifi_scan_config.channel = 0; // scan all channels
  311. esp_wifi_scan_start(&wifi_scan_config, true); // not using event handler SCAN_DONE by purpose to keep SYS_EVENT heap smaller
  312. // and the calling task task_autodoFlow is after scan is finish in wait state anyway
  313. // Scan duration: ca. (120ms + 30ms) * Number of channels -> ca. 1,5 - 2s
  314. uint16_t max_number_of_ap_found = 10; // max. number of APs, value will be updated by function "esp_wifi_scan_get_ap_num"
  315. esp_wifi_scan_get_ap_num(&max_number_of_ap_found); // get actual found APs
  316. wifi_ap_record_t *wifi_ap_records = new wifi_ap_record_t[max_number_of_ap_found]; // Allocate necessary record datasets
  317. if (wifi_ap_records == NULL)
  318. {
  319. esp_wifi_scan_get_ap_records(0, NULL); // free internal heap
  320. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "wifi_scan: Failed to allocate heap for wifi_ap_records");
  321. return;
  322. }
  323. else
  324. {
  325. if (esp_wifi_scan_get_ap_records(&max_number_of_ap_found, wifi_ap_records) != ESP_OK)
  326. {
  327. // Retrieve results (and free internal heap)
  328. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "wifi_scan: esp_wifi_scan_get_ap_records: Error retrieving datasets");
  329. delete[] wifi_ap_records;
  330. return;
  331. }
  332. }
  333. wifi_ap_record_t currentAP;
  334. esp_wifi_sta_get_ap_info(&currentAP);
  335. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Current AP BSSID=" + bssid_to_string((char *)currentAP.bssid));
  336. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Scan completed, APs found with configured SSID: " + std::to_string(max_number_of_ap_found));
  337. for (int i = 0; i < max_number_of_ap_found; i++)
  338. {
  339. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: " + std::to_string(i + 1) + ": SSID=" + std::string((char *)wifi_ap_records[i].ssid) + ", BSSID=" + bssid_to_string((char *)wifi_ap_records[i].bssid) + ", RSSI=" + std::to_string(wifi_ap_records[i].rssi) + ", CH=" + std::to_string(wifi_ap_records[i].primary) + ", AUTH=" + get_auth_mode_name(wifi_ap_records[i].authmode));
  340. // RSSI is better than actual RSSI + 5 --> Avoid switching to AP with roughly same RSSI
  341. if (wifi_ap_records[i].rssi > (currentAP.rssi + 5) && (strcmp(bssid_to_string((char *)wifi_ap_records[i].bssid).c_str(), bssid_to_string((char *)currentAP.bssid).c_str()) != 0))
  342. {
  343. wifi_sta_with_better_rssi = true;
  344. }
  345. }
  346. delete[] wifi_ap_records;
  347. }
  348. void wifi_roaming_by_scanning(void)
  349. {
  350. #ifdef HEAP_TRACING_MAIN_WIFI
  351. ESP_LOGI(TAG, "---- HEAP_TRACING_MAIN_WIFI ----");
  352. ESP_ERROR_CHECK(heap_trace_start(HEAP_TRACE_LEAKS));
  353. #endif
  354. if (network_config.rssi_threshold != 0 && get_wifi_rssi() != -127 && (get_wifi_rssi() < network_config.rssi_threshold))
  355. {
  356. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Start scan of all channels for SSID " + network_config.ssid);
  357. wifi_scan();
  358. if (wifi_sta_with_better_rssi)
  359. {
  360. wifi_sta_with_better_rssi = false;
  361. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Roaming: AP with better RSSI in range, disconnecting to switch AP...");
  362. esp_wifi_disconnect();
  363. }
  364. else
  365. {
  366. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Roaming: Scan completed, stay on current AP");
  367. }
  368. }
  369. #ifdef HEAP_TRACING_MAIN_WIFI
  370. ESP_ERROR_CHECK(heap_trace_stop());
  371. heap_trace_dump();
  372. #endif
  373. }
  374. #endif // WLAN_USE_ROAMING_BY_SCANNING