connect_wlan.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. #include "connect_wlan.h"
  2. #include <string.h>
  3. #include "freertos/FreeRTOS.h"
  4. #include "freertos/task.h"
  5. #include "freertos/event_groups.h"
  6. #include "driver/gpio.h"
  7. #include "esp_system.h"
  8. #include "esp_wifi.h"
  9. #include "esp_event.h"
  10. #include "esp_log.h"
  11. #include "nvs_flash.h"
  12. #include "lwip/err.h"
  13. #include "lwip/sys.h"
  14. #ifdef ENABLE_MQTT
  15. #include "interface_mqtt.h"
  16. #endif //ENABLE_MQTT
  17. #include <fstream>
  18. #include <string>
  19. #include <vector>
  20. #include <sstream>
  21. #include <iostream>
  22. //////////////////////
  23. #include <string.h>
  24. #include <stdlib.h>
  25. #include "freertos/FreeRTOS.h"
  26. #include "freertos/task.h"
  27. #include "freertos/event_groups.h"
  28. #include "esp_wifi.h"
  29. #include "esp_wnm.h"
  30. #include "esp_rrm.h"
  31. #include "esp_mbo.h"
  32. #include "esp_event.h"
  33. #include "esp_log.h"
  34. #include "esp_mac.h"
  35. #include "nvs_flash.h"
  36. #include "esp_netif.h"
  37. /////////////////////
  38. #include "../../include/defines.h"
  39. /* FreeRTOS event group to signal when we are connected*/
  40. static EventGroupHandle_t s_wifi_event_group;
  41. static const char *TAG = "WIFI";
  42. static int s_retry_num = 0;
  43. bool WIFIConnected = false;
  44. ///////////////////////////////////////////////////////////
  45. int BlinkDauer;
  46. int BlinkAnzahl;
  47. bool BlinkOff;
  48. bool BlinkIsRunning = false;
  49. std::string hostname = "";
  50. std::string std_hostname = "watermeter";
  51. std::string ipadress = "";
  52. std::string ssid = "";
  53. int RSSIThreashold;
  54. /////////////////////////////////
  55. /////////////////////////////////
  56. #ifdef WLAN_USE_MESH_ROAMING
  57. int RSSI_Threshold = WLAN_WIFI_RSSI_THRESHOLD;
  58. /* rrm ctx */
  59. int rrm_ctx = 0;
  60. /* FreeRTOS event group to signal when we are connected & ready to make a request */
  61. static EventGroupHandle_t wifi_event_group;
  62. /* esp netif object representing the WIFI station */
  63. static esp_netif_t *sta_netif = NULL;
  64. //static const char *TAG = "roaming_example";
  65. static inline uint32_t WPA_GET_LE32(const uint8_t *a)
  66. {
  67. return ((uint32_t) a[3] << 24) | (a[2] << 16) | (a[1] << 8) | a[0];
  68. }
  69. #ifndef WLAN_EID_MEASURE_REPORT
  70. #define WLAN_EID_MEASURE_REPORT 39
  71. #endif
  72. #ifndef MEASURE_TYPE_LCI
  73. #define MEASURE_TYPE_LCI 9
  74. #endif
  75. #ifndef MEASURE_TYPE_LOCATION_CIVIC
  76. #define MEASURE_TYPE_LOCATION_CIVIC 11
  77. #endif
  78. #ifndef WLAN_EID_NEIGHBOR_REPORT
  79. #define WLAN_EID_NEIGHBOR_REPORT 52
  80. #endif
  81. #ifndef ETH_ALEN
  82. #define ETH_ALEN 6
  83. #endif
  84. #define MAX_NEIGHBOR_LEN 512
  85. static char * get_btm_neighbor_list(uint8_t *report, size_t report_len)
  86. {
  87. size_t len = 0;
  88. const uint8_t *data;
  89. int ret = 0;
  90. /*
  91. * Neighbor Report element (IEEE P802.11-REVmc/D5.0)
  92. * BSSID[6]
  93. * BSSID Information[4]
  94. * Operating Class[1]
  95. * Channel Number[1]
  96. * PHY Type[1]
  97. * Optional Subelements[variable]
  98. */
  99. #define NR_IE_MIN_LEN (ETH_ALEN + 4 + 1 + 1 + 1)
  100. if (!report || report_len == 0) {
  101. ESP_LOGI(TAG, "RRM neighbor report is not valid");
  102. return NULL;
  103. }
  104. char *buf = (char*) calloc(1, MAX_NEIGHBOR_LEN);
  105. data = report;
  106. while (report_len >= 2 + NR_IE_MIN_LEN) {
  107. const uint8_t *nr;
  108. char lci[256 * 2 + 1];
  109. char civic[256 * 2 + 1];
  110. uint8_t nr_len = data[1];
  111. const uint8_t *pos = data, *end;
  112. if (pos[0] != WLAN_EID_NEIGHBOR_REPORT ||
  113. nr_len < NR_IE_MIN_LEN) {
  114. ESP_LOGI(TAG, "CTRL: Invalid Neighbor Report element: id=%u len=%u",
  115. data[0], nr_len);
  116. ret = -1;
  117. goto cleanup;
  118. }
  119. if (2U + nr_len > report_len) {
  120. ESP_LOGI(TAG, "CTRL: Invalid Neighbor Report element: id=%u len=%zu nr_len=%u",
  121. data[0], report_len, nr_len);
  122. ret = -1;
  123. goto cleanup;
  124. }
  125. pos += 2;
  126. end = pos + nr_len;
  127. nr = pos;
  128. pos += NR_IE_MIN_LEN;
  129. lci[0] = '\0';
  130. civic[0] = '\0';
  131. while (end - pos > 2) {
  132. uint8_t s_id, s_len;
  133. s_id = *pos++;
  134. s_len = *pos++;
  135. if (s_len > end - pos) {
  136. ret = -1;
  137. goto cleanup;
  138. }
  139. if (s_id == WLAN_EID_MEASURE_REPORT && s_len > 3) {
  140. /* Measurement Token[1] */
  141. /* Measurement Report Mode[1] */
  142. /* Measurement Type[1] */
  143. /* Measurement Report[variable] */
  144. switch (pos[2]) {
  145. case MEASURE_TYPE_LCI:
  146. if (lci[0])
  147. break;
  148. memcpy(lci, pos, s_len);
  149. break;
  150. case MEASURE_TYPE_LOCATION_CIVIC:
  151. if (civic[0])
  152. break;
  153. memcpy(civic, pos, s_len);
  154. break;
  155. }
  156. }
  157. pos += s_len;
  158. }
  159. ESP_LOGI(TAG, "RMM neigbor report bssid=" MACSTR
  160. " info=0x%x op_class=%u chan=%u phy_type=%u%s%s%s%s",
  161. MAC2STR(nr), WPA_GET_LE32(nr + ETH_ALEN),
  162. nr[ETH_ALEN + 4], nr[ETH_ALEN + 5],
  163. nr[ETH_ALEN + 6],
  164. lci[0] ? " lci=" : "", lci,
  165. civic[0] ? " civic=" : "", civic);
  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. if (!report) {
  200. ESP_LOGE(TAG, "report is null");
  201. return;
  202. }
  203. if (*val != rrm_ctx) {
  204. ESP_LOGE(TAG, "rrm_ctx value didn't match, not initiated by us");
  205. return;
  206. }
  207. /* dump report info */
  208. ESP_LOGI(TAG, "rrm: neighbor report len=%d", report_len);
  209. ESP_LOG_BUFFER_HEXDUMP(TAG, pos, report_len, ESP_LOG_INFO);
  210. /* create neighbor list */
  211. char *neighbor_list = get_btm_neighbor_list(pos + 1, report_len - 1);
  212. /* In case neighbor list is not present issue a scan and get the list from that */
  213. if (!neighbor_list) {
  214. /* issue scan */
  215. wifi_scan_config_t params;
  216. memset(&params, 0, sizeof(wifi_scan_config_t));
  217. if (esp_wifi_scan_start(&params, true) < 0) {
  218. goto cleanup;
  219. }
  220. /* cleanup from net802.11 */
  221. uint16_t number = 1;
  222. wifi_ap_record_t ap_records;
  223. esp_wifi_scan_get_ap_records(&number, &ap_records);
  224. cand_list = 1;
  225. }
  226. /* send AP btm query, this will cause STA to roam as well */
  227. esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, neighbor_list, cand_list);
  228. cleanup:
  229. if (neighbor_list)
  230. free(neighbor_list);
  231. }
  232. static void esp_bss_rssi_low_handler(void* arg, esp_event_base_t event_base,
  233. int32_t event_id, void* event_data)
  234. {
  235. wifi_event_bss_rssi_low_t *event = (wifi_event_bss_rssi_low_t*) event_data;
  236. ESP_LOGI(TAG, "%s:bss rssi is=%d", __func__, event->rssi);
  237. /* Lets check channel conditions */
  238. rrm_ctx++;
  239. if (esp_rrm_send_neighbor_rep_request(neighbor_report_recv_cb, &rrm_ctx) < 0) {
  240. /* failed to send neighbor report request */
  241. ESP_LOGI(TAG, "failed to send neighbor report request");
  242. if (esp_wnm_send_bss_transition_mgmt_query(REASON_FRAME_LOSS, NULL, 0) < 0) {
  243. ESP_LOGI(TAG, "failed to send btm query");
  244. }
  245. }
  246. }
  247. #endif
  248. //////////////////////////////////
  249. //////////////////////////////////
  250. std::string* getIPAddress()
  251. {
  252. return &ipadress;
  253. }
  254. std::string* getSSID()
  255. {
  256. return &ssid;
  257. }
  258. void task_doBlink(void *pvParameter)
  259. {
  260. ESP_LOGI("BLINK", "Flash - start");
  261. while (BlinkIsRunning)
  262. {
  263. // ESP_LOGI("BLINK", "Blinken - wait");
  264. vTaskDelay(100 / portTICK_PERIOD_MS);
  265. }
  266. BlinkIsRunning = true;
  267. // Init the GPIO
  268. gpio_pad_select_gpio(BLINK_GPIO);
  269. /* Set the GPIO as a push/pull output */
  270. gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
  271. for (int i = 0; i < BlinkAnzahl; ++i)
  272. {
  273. if (BlinkAnzahl > 1)
  274. {
  275. gpio_set_level(BLINK_GPIO, 1);
  276. vTaskDelay(BlinkDauer / portTICK_PERIOD_MS);
  277. }
  278. gpio_set_level(BLINK_GPIO, 0);
  279. vTaskDelay(BlinkDauer / portTICK_PERIOD_MS);
  280. }
  281. if (BlinkOff)
  282. gpio_set_level(BLINK_GPIO, 1);
  283. ESP_LOGI("BLINK", "Flash - done");
  284. BlinkIsRunning = false;
  285. vTaskDelete(NULL); //Delete this task if it exits from the loop above
  286. }
  287. void LEDBlinkTask(int _dauer, int _anz, bool _off)
  288. {
  289. BlinkDauer = _dauer;
  290. BlinkAnzahl = _anz;
  291. BlinkOff = _off;
  292. xTaskCreate(&task_doBlink, "task_doBlink", 4 * 1024, NULL, tskIDLE_PRIORITY+1, NULL);
  293. }
  294. /////////////////////////////////////////////////////////
  295. static void event_handler(void* arg, esp_event_base_t event_base,
  296. int32_t event_id, void* event_data)
  297. {
  298. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  299. WIFIConnected = false;
  300. LEDBlinkTask(200, 1, true);
  301. esp_wifi_connect();
  302. } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
  303. WIFIConnected = false;
  304. // if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
  305. esp_wifi_connect();
  306. s_retry_num++;
  307. ESP_LOGI(TAG, "retrying connection to the AP");
  308. // } else {
  309. // xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
  310. // }
  311. ESP_LOGI(TAG,"connection to the AP failed");
  312. } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  313. ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
  314. ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
  315. ipadress = std::string(ip4addr_ntoa((const ip4_addr*) &event->ip_info.ip));
  316. s_retry_num = 0;
  317. xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
  318. LEDBlinkTask(1000, 5, true);
  319. WIFIConnected = true;
  320. #ifdef ENABLE_MQTT
  321. if (getMQTTisEnabled()) {
  322. vTaskDelay(5000 / portTICK_PERIOD_MS);
  323. MQTT_Init(); // Init when WIFI is getting connected
  324. }
  325. #endif //ENABLE_MQTT
  326. }
  327. }
  328. void strinttoip4(const char *ip, int &a, int &b, int &c, int &d) {
  329. std::string zw = std::string(ip);
  330. std::stringstream s(zw);
  331. char ch; //to temporarily store the '.'
  332. s >> a >> ch >> b >> ch >> c >> ch >> d;
  333. }
  334. void wifi_init_sta(const char *_ssid, const char *_password, const char *_hostname, const char *_ipadr, const char *_gw, const char *_netmask, const char *_dns, int _rssithreashold)
  335. {
  336. RSSI_Threshold = _rssithreashold;
  337. s_wifi_event_group = xEventGroupCreate();
  338. ESP_ERROR_CHECK(esp_netif_init());
  339. ESP_ERROR_CHECK(esp_event_loop_create_default());
  340. esp_netif_t *my_sta = esp_netif_create_default_wifi_sta();
  341. if ((_ipadr != NULL) && (_gw != NULL) && (_netmask != NULL))
  342. {
  343. ESP_LOGI(TAG, "set IP %s, GW %s, Netmask %s manual", _ipadr, _gw, _netmask);
  344. esp_netif_dhcpc_stop(my_sta);
  345. esp_netif_ip_info_t ip_info;
  346. int a, b, c, d;
  347. strinttoip4(_ipadr, a, b, c, d);
  348. IP4_ADDR(&ip_info.ip, a, b, c, d);
  349. strinttoip4(_gw, a, b, c, d);
  350. IP4_ADDR(&ip_info.gw, a, b, c, d);
  351. strinttoip4(_netmask, a, b, c, d);
  352. IP4_ADDR(&ip_info.netmask, a, b, c, d);
  353. esp_netif_set_ip_info(my_sta, &ip_info);
  354. }
  355. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  356. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  357. if ((_ipadr != NULL) && (_gw != NULL) && (_netmask != NULL))
  358. {
  359. if (_dns == NULL)
  360. _dns = _gw;
  361. ESP_LOGI(TAG, "set DNS manual");
  362. esp_netif_dns_info_t dns_info;
  363. ip4_addr_t ip;
  364. ip.addr = esp_ip4addr_aton(_dns);
  365. ip_addr_set_ip4_u32(&dns_info.ip, ip.addr);
  366. ESP_ERROR_CHECK(esp_netif_set_dns_info(my_sta, ESP_NETIF_DNS_MAIN, &dns_info));
  367. }
  368. esp_event_handler_instance_t instance_any_id;
  369. esp_event_handler_instance_t instance_got_ip;
  370. esp_event_handler_instance_t instance_bss_rssi_low;
  371. ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  372. ESP_EVENT_ANY_ID,
  373. &event_handler,
  374. NULL,
  375. &instance_any_id));
  376. ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
  377. IP_EVENT_STA_GOT_IP,
  378. &event_handler,
  379. NULL,
  380. &instance_got_ip));
  381. #ifdef WLAN_USE_MESH_ROAMING
  382. ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
  383. WIFI_EVENT_STA_BSS_RSSI_LOW,
  384. &esp_bss_rssi_low_handler,
  385. NULL,
  386. &instance_bss_rssi_low));
  387. #endif
  388. wifi_config_t wifi_config = { };
  389. strcpy((char*)wifi_config.sta.ssid, (const char*)_ssid);
  390. strcpy((char*)wifi_config.sta.password, (const char*)_password);
  391. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
  392. ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config) );
  393. ESP_ERROR_CHECK(esp_wifi_start() );
  394. if (_hostname != NULL)
  395. {
  396. esp_err_t ret = tcpip_adapter_set_hostname(TCPIP_ADAPTER_IF_STA , _hostname);
  397. hostname = std::string(_hostname);
  398. if(ret != ESP_OK ){
  399. ESP_LOGE(TAG,"Failed to set hostname: %d",ret);
  400. }
  401. else {
  402. ESP_LOGI(TAG,"Set hostname to: %s", _hostname);
  403. }
  404. }
  405. ESP_LOGI(TAG, "wifi_init_sta finished.");
  406. /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
  407. * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
  408. EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
  409. WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  410. pdFALSE,
  411. pdFALSE,
  412. portMAX_DELAY);
  413. /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
  414. * happened. */
  415. if (bits & WIFI_CONNECTED_BIT) {
  416. #ifdef __HIDE_PASSWORD
  417. ESP_LOGI(TAG, "Connected with AP: %s, password: XXXXXXX", _ssid);
  418. #else
  419. ESP_LOGI(TAG, "Connected with AP: %s, password: %s", _ssid, _password);
  420. #endif
  421. } else if (bits & WIFI_FAIL_BIT) {
  422. #ifdef __HIDE_PASSWORD
  423. ESP_LOGI(TAG, "Failed to connect with AP: %s, password: XXXXXXXX", _ssid);
  424. #else
  425. ESP_LOGI(TAG, "Failed to connect with AP: %s, password: %s", _ssid, _password);
  426. #endif
  427. } else {
  428. ESP_LOGE(TAG, "UNEXPECTED EVENT");
  429. }
  430. ssid = std::string(_ssid);
  431. /* The event will not be processed after unregister */
  432. // ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
  433. // ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
  434. // vEventGroupDelete(s_wifi_event_group);
  435. }
  436. int get_WIFI_RSSI()
  437. {
  438. wifi_ap_record_t ap;
  439. esp_wifi_sta_get_ap_info(&ap);
  440. return ap.rssi;
  441. }
  442. void wifi_init_sta(const char *_ssid, const char *_password, const char *_hostname)
  443. {
  444. wifi_init_sta(_ssid, _password, _hostname, NULL, NULL, NULL, NULL, 0);
  445. }
  446. void wifi_init_sta(const char *_ssid, const char *_password)
  447. {
  448. wifi_init_sta(_ssid, _password, NULL, NULL, NULL, NULL, NULL, 0);
  449. }
  450. bool getWIFIisConnected()
  451. {
  452. return WIFIConnected;
  453. }
  454. void WIFIDestroy()
  455. {
  456. esp_wifi_disconnect();
  457. esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler);
  458. esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler);
  459. #ifdef WLAN_USE_MESH_ROAMING
  460. esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_BSS_RSSI_LOW, esp_bss_rssi_low_handler);
  461. #endif
  462. esp_wifi_stop();
  463. esp_wifi_deinit();
  464. }