connect_wlan.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. bool WIFIConnected = false;
  34. int WIFIReconnectCnt = 0;
  35. #ifdef WLAN_USE_MESH_ROAMING
  36. int RSSI_Threshold = WLAN_WIFI_RSSI_THRESHOLD;
  37. /* rrm ctx */
  38. int rrm_ctx = 0;
  39. /* FreeRTOS event group to signal when we are connected & ready to make a request */
  40. static EventGroupHandle_t wifi_event_group;
  41. /* esp netif object representing the WIFI station */
  42. static esp_netif_t *sta_netif = NULL;
  43. //static const char *TAG = "roaming_example";
  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. ESP_LOGI(TAG, "RRM neighbor report is not valid");
  81. return NULL;
  82. }
  83. char *buf = (char*) calloc(1, MAX_NEIGHBOR_LEN);
  84. data = report;
  85. while (report_len >= 2 + NR_IE_MIN_LEN) {
  86. const uint8_t *nr;
  87. char lci[256 * 2 + 1];
  88. char civic[256 * 2 + 1];
  89. uint8_t nr_len = data[1];
  90. const uint8_t *pos = data, *end;
  91. if (pos[0] != WLAN_EID_NEIGHBOR_REPORT ||
  92. nr_len < NR_IE_MIN_LEN) {
  93. ESP_LOGI(TAG, "CTRL: Invalid Neighbor Report element: id=%u len=%u",
  94. data[0], nr_len);
  95. ret = -1;
  96. goto cleanup;
  97. }
  98. if (2U + nr_len > report_len) {
  99. ESP_LOGI(TAG, "CTRL: Invalid Neighbor Report element: id=%u len=%zu nr_len=%u",
  100. data[0], report_len, nr_len);
  101. ret = -1;
  102. goto cleanup;
  103. }
  104. pos += 2;
  105. end = pos + nr_len;
  106. nr = pos;
  107. pos += NR_IE_MIN_LEN;
  108. lci[0] = '\0';
  109. civic[0] = '\0';
  110. while (end - pos > 2) {
  111. uint8_t s_id, s_len;
  112. s_id = *pos++;
  113. s_len = *pos++;
  114. if (s_len > end - pos) {
  115. ret = -1;
  116. goto cleanup;
  117. }
  118. if (s_id == WLAN_EID_MEASURE_REPORT && s_len > 3) {
  119. /* Measurement Token[1] */
  120. /* Measurement Report Mode[1] */
  121. /* Measurement Type[1] */
  122. /* Measurement Report[variable] */
  123. switch (pos[2]) {
  124. case MEASURE_TYPE_LCI:
  125. if (lci[0])
  126. break;
  127. memcpy(lci, pos, s_len);
  128. break;
  129. case MEASURE_TYPE_LOCATION_CIVIC:
  130. if (civic[0])
  131. break;
  132. memcpy(civic, pos, s_len);
  133. break;
  134. }
  135. }
  136. pos += s_len;
  137. }
  138. ESP_LOGI(TAG, "RMM neigbor report bssid=" MACSTR
  139. " info=0x%x op_class=%u chan=%u phy_type=%u%s%s%s%s",
  140. MAC2STR(nr), WPA_GET_LE32(nr + ETH_ALEN),
  141. nr[ETH_ALEN + 4], nr[ETH_ALEN + 5],
  142. nr[ETH_ALEN + 6],
  143. lci[0] ? " lci=" : "", lci,
  144. civic[0] ? " civic=" : "", civic);
  145. /* neighbor start */
  146. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, " neighbor=");
  147. /* bssid */
  148. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, MACSTR, MAC2STR(nr));
  149. /* , */
  150. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  151. /* bssid info */
  152. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "0x%04x", WPA_GET_LE32(nr + ETH_ALEN));
  153. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  154. /* operating class */
  155. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 4]);
  156. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  157. /* channel number */
  158. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 5]);
  159. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, ",");
  160. /* phy type */
  161. len += snprintf(buf + len, MAX_NEIGHBOR_LEN - len, "%u", nr[ETH_ALEN + 6]);
  162. /* optional elements, skip */
  163. data = end;
  164. report_len -= 2 + nr_len;
  165. }
  166. cleanup:
  167. if (ret < 0) {
  168. free(buf);
  169. buf = NULL;
  170. }
  171. return buf;
  172. }
  173. void neighbor_report_recv_cb(void *ctx, const uint8_t *report, size_t report_len)
  174. {
  175. int *val = (int*) ctx;
  176. uint8_t *pos = (uint8_t *)report;
  177. int cand_list = 0;
  178. if (!report) {
  179. ESP_LOGE(TAG, "report is null");
  180. return;
  181. }
  182. if (*val != rrm_ctx) {
  183. ESP_LOGE(TAG, "rrm_ctx value didn't match, not initiated by us");
  184. return;
  185. }
  186. /* dump report info */
  187. ESP_LOGI(TAG, "rrm: neighbor report len=%d", report_len);
  188. ESP_LOG_BUFFER_HEXDUMP(TAG, pos, report_len, ESP_LOG_INFO);
  189. /* create neighbor list */
  190. char *neighbor_list = get_btm_neighbor_list(pos + 1, report_len - 1);
  191. /* In case neighbor list is not present issue a scan and get the list from that */
  192. if (!neighbor_list) {
  193. /* issue scan */
  194. wifi_scan_config_t params;
  195. memset(&params, 0, sizeof(wifi_scan_config_t));
  196. if (esp_wifi_scan_start(&params, true) < 0) {
  197. goto cleanup;
  198. }
  199. /* cleanup from net802.11 */
  200. uint16_t number = 1;
  201. wifi_ap_record_t ap_records;
  202. esp_wifi_scan_get_ap_records(&number, &ap_records);
  203. cand_list = 1;
  204. }
  205. /* send AP btm query, this will cause STA to roam as well */
  206. esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, neighbor_list, cand_list);
  207. cleanup:
  208. if (neighbor_list)
  209. free(neighbor_list);
  210. }
  211. static void esp_bss_rssi_low_handler(void* arg, esp_event_base_t event_base,
  212. int32_t event_id, void* event_data)
  213. {
  214. wifi_event_bss_rssi_low_t *event = (wifi_event_bss_rssi_low_t*) event_data;
  215. ESP_LOGI(TAG, "%s:bss rssi is=%d", __func__, event->rssi);
  216. /* Lets check channel conditions */
  217. rrm_ctx++;
  218. if (esp_rrm_send_neighbor_rep_request(neighbor_report_recv_cb, &rrm_ctx) < 0) {
  219. /* failed to send neighbor report request */
  220. ESP_LOGI(TAG, "failed to send neighbor report request");
  221. if (esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, NULL, 0) < 0) {
  222. ESP_LOGI(TAG, "failed to send btm query");
  223. }
  224. }
  225. }
  226. #endif
  227. //////////////////////////////////
  228. //////////////////////////////////
  229. std::string* getIPAddress()
  230. {
  231. return &wlan_config.ipaddress;
  232. }
  233. std::string* getSSID()
  234. {
  235. return &wlan_config.ssid;
  236. }
  237. static void event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data)
  238. {
  239. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START)
  240. {
  241. WIFIConnected = false;
  242. esp_wifi_connect();
  243. }
  244. else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
  245. {
  246. /* Disconnect reason: https://github.com/espressif/esp-idf/blob/d825753387c1a64463779bbd2369e177e5d59a79/components/esp_wifi/include/esp_wifi_types.h */
  247. wifi_event_sta_disconnected_t *disconn = (wifi_event_sta_disconnected_t *)event_data;
  248. if (disconn->reason == WIFI_REASON_ROAMING) {
  249. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Roaming)");
  250. // --> no reconnect neccessary, it should automatically reconnect to new AP
  251. }
  252. else {
  253. WIFIConnected = false;
  254. if (disconn->reason == WIFI_REASON_NO_AP_FOUND) {
  255. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", No AP)");
  256. StatusLED(WLAN_CONN, 1, false);
  257. }
  258. else if (disconn->reason == WIFI_REASON_AUTH_EXPIRE ||
  259. disconn->reason == WIFI_REASON_AUTH_FAIL ||
  260. disconn->reason == WIFI_REASON_NOT_AUTHED ||
  261. disconn->reason == WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT ||
  262. disconn->reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
  263. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Auth fail)");
  264. StatusLED(WLAN_CONN, 2, false);
  265. }
  266. else if (disconn->reason == WIFI_REASON_BEACON_TIMEOUT) {
  267. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ", Timeout)");
  268. StatusLED(WLAN_CONN, 3, false);
  269. }
  270. else {
  271. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Disconnected (" + std::to_string(disconn->reason) + ")");
  272. StatusLED(WLAN_CONN, 4, false);
  273. }
  274. WIFIReconnectCnt++;
  275. esp_wifi_connect(); // Try to connect again
  276. }
  277. if (WIFIReconnectCnt >= 10) {
  278. WIFIReconnectCnt = 0;
  279. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Disconnected, multiple reconnect attempts failed (" +
  280. std::to_string(disconn->reason) + "), still retrying...");
  281. }
  282. }
  283. else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED)
  284. {
  285. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Connected to: " + wlan_config.ssid + ", RSSI: " +
  286. std::to_string(get_WIFI_RSSI()));
  287. }
  288. else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP)
  289. {
  290. WIFIConnected = true;
  291. WIFIReconnectCnt = 0;
  292. ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
  293. wlan_config.ipaddress = std::string(ip4addr_ntoa((const ip4_addr*) &event->ip_info.ip));
  294. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Got IP: " + wlan_config.ipaddress);
  295. #ifdef ENABLE_MQTT
  296. if (getMQTTisEnabled()) {
  297. vTaskDelay(5000 / portTICK_PERIOD_MS);
  298. MQTT_Init(); // Init when WIFI is getting connected
  299. }
  300. #endif //ENABLE_MQTT
  301. }
  302. }
  303. void strinttoip4(const char *ip, int &a, int &b, int &c, int &d) {
  304. std::string zw = std::string(ip);
  305. std::stringstream s(zw);
  306. char ch; //to temporarily store the '.'
  307. s >> a >> ch >> b >> ch >> c >> ch >> d;
  308. }
  309. esp_err_t wifi_init_sta(void)
  310. {
  311. esp_err_t retval = esp_netif_init();
  312. if (retval != ESP_OK) {
  313. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_netif_init: Error: " + std::to_string(retval));
  314. return retval;
  315. }
  316. retval = esp_event_loop_create_default();
  317. if (retval != ESP_OK) {
  318. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_loop_create_default: Error: " + std::to_string(retval));
  319. return retval;
  320. }
  321. esp_netif_t *my_sta = esp_netif_create_default_wifi_sta();
  322. if (!wlan_config.ipaddress.empty() && !wlan_config.gateway.empty() && !wlan_config.netmask.empty())
  323. {
  324. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Manual interface config -> IP: " + wlan_config.ipaddress + ", Gateway: " +
  325. std::string(wlan_config.gateway) + ", Netmask: " + std::string(wlan_config.netmask));
  326. esp_netif_dhcpc_stop(my_sta); // Stop DHCP service
  327. esp_netif_ip_info_t ip_info;
  328. int a, b, c, d;
  329. strinttoip4(wlan_config.ipaddress.c_str(), a, b, c, d);
  330. IP4_ADDR(&ip_info.ip, a, b, c, d); // Set static IP address
  331. strinttoip4(wlan_config.gateway.c_str(), a, b, c, d);
  332. IP4_ADDR(&ip_info.gw, a, b, c, d); // Set gateway
  333. strinttoip4(wlan_config.netmask.c_str(), a, b, c, d);
  334. IP4_ADDR(&ip_info.netmask, a, b, c, d); // Set netmask
  335. esp_netif_set_ip_info(my_sta, &ip_info); // Set static IP configuration
  336. }
  337. else {
  338. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Automatic interface config --> Use DHCP service");
  339. }
  340. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  341. retval = esp_wifi_init(&cfg);
  342. if (retval != ESP_OK) {
  343. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_init: Error: " + std::to_string(retval));
  344. return retval;
  345. }
  346. if (!wlan_config.ipaddress.empty() && !wlan_config.gateway.empty() && !wlan_config.netmask.empty())
  347. {
  348. if (wlan_config.dns.empty()) {
  349. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "No DNS server, use gateway");
  350. wlan_config.dns = wlan_config.gateway;
  351. }
  352. else {
  353. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Manual interface config -> DNS: " + wlan_config.dns);
  354. }
  355. esp_netif_dns_info_t dns_info;
  356. ip4_addr_t ip;
  357. ip.addr = esp_ip4addr_aton(wlan_config.dns.c_str());
  358. ip_addr_set_ip4_u32(&dns_info.ip, ip.addr);
  359. retval = esp_netif_set_dns_info(my_sta, ESP_NETIF_DNS_MAIN, &dns_info);
  360. if (retval != ESP_OK) {
  361. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_netif_set_dns_info: Error: " + std::to_string(retval));
  362. return retval;
  363. }
  364. }
  365. retval = esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
  366. &event_handler, NULL, NULL);
  367. if (retval != ESP_OK) {
  368. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - WIFI_ANY: Error: " + std::to_string(retval));
  369. return retval;
  370. }
  371. retval = esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
  372. &event_handler, NULL, NULL);
  373. if (retval != ESP_OK) {
  374. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - GOT_IP: Error: " + std::to_string(retval));
  375. return retval;
  376. }
  377. #ifdef WLAN_USE_MESH_ROAMING
  378. retval = esp_event_handler_instance_register(WIFI_EVENT, WIFI_EVENT_STA_BSS_RSSI_LOW,
  379. &esp_bss_rssi_low_handler, NULL, NULL);
  380. if (retval != ESP_OK) {
  381. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_event_handler_instance_register - BSS_RSSI_LOW: Error: " + std::to_string(retval));
  382. return retval;
  383. }
  384. #endif
  385. wifi_config_t wifi_config = { };
  386. strcpy((char*)wifi_config.sta.ssid, (const char*)wlan_config.ssid.c_str());
  387. strcpy((char*)wifi_config.sta.password, (const char*)wlan_config.password.c_str());
  388. retval = esp_wifi_set_mode(WIFI_MODE_STA);
  389. if (retval != ESP_OK) {
  390. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_mode: Error: " + std::to_string(retval));
  391. return retval;
  392. }
  393. retval = esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
  394. if (retval != ESP_OK) {
  395. if (retval == ESP_ERR_WIFI_PASSWORD) {
  396. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_config: SSID password invalid! Error: " + std::to_string(retval));
  397. }
  398. else {
  399. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_set_config: Error: " + std::to_string(retval));
  400. }
  401. return retval;
  402. }
  403. retval = esp_wifi_start();
  404. if (retval != ESP_OK) {
  405. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "esp_wifi_start: Error: " + std::to_string(retval));
  406. return retval;
  407. }
  408. if (!wlan_config.hostname.empty())
  409. {
  410. retval = tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA , wlan_config.hostname.c_str());
  411. if(retval != ESP_OK ) {
  412. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to set hostname! Error: " + std::to_string(retval));
  413. }
  414. else {
  415. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Set hostname to: " + wlan_config.hostname);
  416. }
  417. }
  418. LogFile.WriteToFile(ESP_LOG_INFO, TAG, "Init successful");
  419. return ESP_OK;
  420. }
  421. int get_WIFI_RSSI()
  422. {
  423. wifi_ap_record_t ap;
  424. if (esp_wifi_sta_get_ap_info(&ap) == ESP_OK)
  425. return ap.rssi;
  426. else
  427. return -127; // Return -127 if no info available e.g. not connected
  428. }
  429. bool getWIFIisConnected()
  430. {
  431. return WIFIConnected;
  432. }
  433. void WIFIDestroy()
  434. {
  435. esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler);
  436. esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler);
  437. #ifdef WLAN_USE_MESH_ROAMING
  438. esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_BSS_RSSI_LOW, esp_bss_rssi_low_handler);
  439. #endif
  440. esp_wifi_disconnect();
  441. esp_wifi_stop();
  442. esp_wifi_deinit();
  443. }