network_wifi.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  1. #ifdef NETWORK_WIFI_LOG_LEVEL
  2. #define LOG_LOCAL_LEVEL NETWORK_WIFI_LOG_LEVEL
  3. #endif
  4. #include "network_wifi.h"
  5. #include <string.h>
  6. #include "cJSON.h"
  7. #include "dns_server.h"
  8. #include "esp_event.h"
  9. #include "esp_log.h"
  10. #include "esp_system.h"
  11. #include "esp_wifi.h"
  12. #include "esp_wifi_types.h"
  13. #include "lwip/sockets.h"
  14. #include "messaging.h"
  15. #include "network_status.h"
  16. #include "nvs.h"
  17. #include "nvs_flash.h"
  18. #include "nvs_utilities.h"
  19. #include "platform_config.h"
  20. #include "platform_esp32.h"
  21. #include "tools.h"
  22. #include "trace.h"
  23. static void network_wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
  24. static char* get_disconnect_code_desc(uint8_t reason);
  25. esp_err_t network_wifi_get_blob(void* target, size_t size, const char* key);
  26. static inline const char* ssid_string(const wifi_sta_config_t* sta);
  27. static inline const char* password_string(const wifi_sta_config_t* sta);
  28. cJSON* accessp_cjson = NULL;
  29. static const char TAG[] = "network_wifi";
  30. const char network_wifi_nvs_namespace[] = "config";
  31. const char ap_list_nsv_namespace[] = "aplist";
  32. /* rrm ctx */
  33. //Roaming support - int rrm_ctx = 0;
  34. uint16_t ap_num = 0;
  35. esp_netif_t* wifi_netif;
  36. esp_netif_t* wifi_ap_netif;
  37. wifi_ap_record_t* accessp_records = NULL;
  38. #define UINT_TO_STRING(val) \
  39. static char loc[sizeof(val) + 1]; \
  40. memset(loc, 0x00, sizeof(loc)); \
  41. strlcpy(loc, (char*)val, sizeof(loc)); \
  42. return loc;
  43. static inline const char* ssid_string(const wifi_sta_config_t* sta) {
  44. UINT_TO_STRING(sta->ssid);
  45. }
  46. static inline const char* password_string(const wifi_sta_config_t* sta) {
  47. UINT_TO_STRING(sta->password);
  48. }
  49. static inline const char* ap_ssid_string(const wifi_ap_record_t* ap) {
  50. UINT_TO_STRING(ap->ssid);
  51. }
  52. typedef struct known_access_point {
  53. char* ssid;
  54. char* password;
  55. bool found;
  56. uint8_t bssid[6]; /**< MAC address of AP */
  57. uint8_t primary; /**< channel of AP */
  58. wifi_auth_mode_t authmode; /**< authmode of AP */
  59. uint32_t phy_11b : 1; /**< bit: 0 flag to identify if 11b mode is enabled or not */
  60. uint32_t phy_11g : 1; /**< bit: 1 flag to identify if 11g mode is enabled or not */
  61. uint32_t phy_11n : 1; /**< bit: 2 flag to identify if 11n mode is enabled or not */
  62. uint32_t phy_lr : 1; /**< bit: 3 flag to identify if low rate is enabled or not */
  63. time_t last_try;
  64. SLIST_ENTRY(known_access_point)
  65. next; //!< next callback
  66. } known_access_point_t;
  67. /** linked list of command structures */
  68. static EXT_RAM_ATTR SLIST_HEAD(ap_list, known_access_point) s_ap_list;
  69. known_access_point_t* network_wifi_get_ap_entry(const char* ssid) {
  70. known_access_point_t* it;
  71. if (!ssid || strlen(ssid) == 0) {
  72. ESP_LOGW(TAG, "network_wifi_get_ap_entry Invalid SSID %s", !ssid ? "IS NULL" : "IS BLANK");
  73. return NULL;
  74. }
  75. SLIST_FOREACH(it, &s_ap_list, next) {
  76. ESP_LOGD(TAG, "Looking for SSID %s = %s ?", ssid, it->ssid);
  77. if (strcmp(it->ssid, ssid) == 0) {
  78. ESP_LOGD(TAG, "network_wifi_get_ap_entry SSID %s found! ", ssid);
  79. return it;
  80. }
  81. }
  82. return NULL;
  83. }
  84. void network_wifi_remove_ap_entry(const char* ssid) {
  85. if (!ssid || strlen(ssid) == 0) {
  86. ESP_LOGE(TAG, "network_wifi_remove_ap_entry error empty SSID");
  87. }
  88. known_access_point_t* it = network_wifi_get_ap_entry(ssid);
  89. if (it) {
  90. ESP_LOGW(TAG, "Removing %s from known list of access points", ssid);
  91. FREE_AND_NULL(it->ssid);
  92. FREE_AND_NULL(it->password);
  93. SLIST_REMOVE(&s_ap_list, it, known_access_point, next);
  94. FREE_AND_NULL(it);
  95. }
  96. }
  97. void network_wifi_empty_known_list() {
  98. known_access_point_t* it;
  99. while ((it = SLIST_FIRST(&s_ap_list)) != NULL) {
  100. network_wifi_remove_ap_entry(it->ssid);
  101. }
  102. }
  103. const wifi_sta_config_t* network_wifi_get_active_config() {
  104. static wifi_config_t config;
  105. esp_err_t err = ESP_OK;
  106. memset(&config, 0x00, sizeof(config));
  107. if ((err = esp_wifi_get_config(WIFI_IF_STA, &config)) == ESP_OK) {
  108. return &config.sta;
  109. } else {
  110. ESP_LOGD(TAG, "Could not get wifi STA config: %s", esp_err_to_name(err));
  111. }
  112. return NULL;
  113. }
  114. size_t network_wifi_get_known_count() {
  115. size_t count = 0;
  116. known_access_point_t* it;
  117. SLIST_FOREACH(it, &s_ap_list, next) {
  118. count++;
  119. }
  120. return count;
  121. }
  122. size_t network_wifi_get_known_count_in_range() {
  123. size_t count = 0;
  124. known_access_point_t* it;
  125. SLIST_FOREACH(it, &s_ap_list, next) {
  126. if(it->found) count++;
  127. }
  128. return count;
  129. }
  130. esp_err_t network_wifi_add_ap(known_access_point_t* item) {
  131. known_access_point_t* last = SLIST_FIRST(&s_ap_list);
  132. if (last == NULL) {
  133. SLIST_INSERT_HEAD(&s_ap_list, item, next);
  134. } else {
  135. known_access_point_t* it;
  136. while ((it = SLIST_NEXT(last, next)) != NULL) {
  137. last = it;
  138. }
  139. SLIST_INSERT_AFTER(last, item, next);
  140. }
  141. return ESP_OK;
  142. }
  143. esp_err_t network_wifi_add_ap_copy(const known_access_point_t* known_ap) {
  144. known_access_point_t* item = NULL;
  145. esp_err_t err = ESP_OK;
  146. if (!known_ap) {
  147. ESP_LOGE(TAG, "Invalid access point entry");
  148. return ESP_ERR_INVALID_ARG;
  149. }
  150. if (!known_ap->ssid || strlen(known_ap->ssid) == 0) {
  151. ESP_LOGE(TAG, "Invalid access point ssid");
  152. return ESP_ERR_INVALID_ARG;
  153. }
  154. item = malloc_init_external(sizeof(known_access_point_t));
  155. if (item == NULL) {
  156. ESP_LOGE(TAG, "Memory allocation failed");
  157. return ESP_ERR_NO_MEM;
  158. }
  159. item->ssid = strdup_psram(known_ap->ssid);
  160. item->password = strdup_psram(known_ap->password);
  161. memcpy(&item->bssid, known_ap->bssid, sizeof(item->bssid));
  162. item->primary = known_ap->primary;
  163. item->authmode = known_ap->authmode;
  164. item->phy_11b = known_ap->phy_11b;
  165. item->phy_11g = known_ap->phy_11g;
  166. item->phy_11n = known_ap->phy_11n;
  167. item->phy_lr = known_ap->phy_lr;
  168. err = network_wifi_add_ap(item);
  169. return err;
  170. }
  171. const wifi_ap_record_t* network_wifi_get_ssid_info(const char* ssid) {
  172. if (!accessp_records)
  173. return NULL;
  174. for (int i = 0; i < ap_num; i++) {
  175. if (strcmp(ap_ssid_string(&accessp_records[i]), ssid) == 0) {
  176. return &accessp_records[i];
  177. }
  178. }
  179. return NULL;
  180. }
  181. esp_err_t network_wifi_add_ap_from_sta_copy(const wifi_sta_config_t* sta) {
  182. known_access_point_t* item = NULL;
  183. esp_err_t err = ESP_OK;
  184. if (!sta) {
  185. ESP_LOGE(TAG, "Invalid access point entry");
  186. return ESP_ERR_INVALID_ARG;
  187. }
  188. if (!sta->ssid || strlen((char*)sta->ssid) == 0) {
  189. ESP_LOGE(TAG, "Invalid access point ssid");
  190. return ESP_ERR_INVALID_ARG;
  191. }
  192. item = malloc_init_external(sizeof(known_access_point_t));
  193. if (item == NULL) {
  194. ESP_LOGE(TAG, "Memory allocation failed");
  195. return ESP_ERR_NO_MEM;
  196. }
  197. item->ssid = strdup_psram(ssid_string(sta));
  198. item->password = strdup_psram(password_string(sta));
  199. memcpy(&item->bssid, sta->bssid, sizeof(item->bssid));
  200. item->primary = sta->channel;
  201. const wifi_ap_record_t* seen = network_wifi_get_ssid_info(item->ssid);
  202. if (seen) {
  203. item->authmode = seen->authmode;
  204. item->phy_11b = seen->phy_11b;
  205. item->phy_11g = seen->phy_11g;
  206. item->phy_11n = seen->phy_11n;
  207. item->phy_lr = seen->phy_lr;
  208. }
  209. err = network_wifi_add_ap(item);
  210. return err;
  211. }
  212. bool network_wifi_is_known_ap(const char* ssid) {
  213. return network_wifi_get_ap_entry(ssid) != NULL;
  214. }
  215. static bool network_wifi_was_ssid_seen(const char* ssid) {
  216. if (!accessp_records || ap_num == 0 || ap_num == MAX_AP_NUM) {
  217. return false;
  218. }
  219. for (int i = 0; i < ap_num; i++) {
  220. if (strcmp(ap_ssid_string(&accessp_records[i]), ssid) == 0) {
  221. return true;
  222. }
  223. }
  224. return false;
  225. }
  226. void network_wifi_set_found_ap() {
  227. known_access_point_t* it;
  228. SLIST_FOREACH(it, &s_ap_list, next) {
  229. if (network_wifi_was_ssid_seen(it->ssid)) {
  230. it->found = true;
  231. } else {
  232. it->found = false;
  233. }
  234. }
  235. }
  236. bool network_wifi_known_ap_in_range(){
  237. known_access_point_t* it;
  238. SLIST_FOREACH(it, &s_ap_list, next) {
  239. if (it->found) {
  240. return true;
  241. }
  242. }
  243. return false;
  244. }
  245. const char * network_wifi_get_next_ap_in_range(){
  246. known_access_point_t* it;
  247. time_t last_try_min=(esp_timer_get_time() / 1000);
  248. SLIST_FOREACH(it, &s_ap_list, next) {
  249. if (it->found && it->last_try < last_try_min) {
  250. last_try_min = it->last_try;
  251. }
  252. }
  253. SLIST_FOREACH(it, &s_ap_list, next) {
  254. if (it->found && it->last_try == last_try_min) {
  255. return it->ssid;
  256. }
  257. }
  258. return NULL;
  259. }
  260. esp_err_t network_wifi_alloc_ap_json(known_access_point_t* item, char** json_string) {
  261. esp_err_t err = ESP_OK;
  262. if (!item || !json_string) {
  263. return ESP_ERR_INVALID_ARG;
  264. }
  265. cJSON* cjson_item = cJSON_CreateObject();
  266. if (!cjson_item) {
  267. ESP_LOGE(TAG, "Memory allocation failure. Cannot save ap json");
  268. return ESP_ERR_NO_MEM;
  269. }
  270. cJSON_AddStringToObject(cjson_item, "ssid", item->ssid);
  271. cJSON_AddStringToObject(cjson_item, "pass", item->password);
  272. cJSON_AddNumberToObject(cjson_item, "chan", item->primary);
  273. cJSON_AddNumberToObject(cjson_item, "auth", item->authmode);
  274. char* bssid = network_manager_alloc_get_mac_string(item->bssid);
  275. if (bssid) {
  276. cJSON_AddItemToObject(cjson_item, "bssid", cJSON_CreateString(STR_OR_BLANK(bssid)));
  277. }
  278. FREE_AND_NULL(bssid);
  279. cJSON_AddNumberToObject(cjson_item, "b", item->phy_11b ? 1 : 0);
  280. cJSON_AddNumberToObject(cjson_item, "g", item->phy_11g ? 1 : 0);
  281. cJSON_AddNumberToObject(cjson_item, "n", item->phy_11n ? 1 : 0);
  282. cJSON_AddNumberToObject(cjson_item, "low_rate", item->phy_lr ? 1 : 0);
  283. *json_string = cJSON_PrintUnformatted(cjson_item);
  284. if (!*json_string) {
  285. ESP_LOGE(TAG, "Memory allocaiton failed. Cannot save ap entry.");
  286. err = ESP_ERR_NO_MEM;
  287. }
  288. cJSON_Delete(cjson_item);
  289. return err;
  290. }
  291. bool network_wifi_str2mac(const char* mac, uint8_t* values) {
  292. if (6 == sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5])) {
  293. return true;
  294. } else {
  295. return false;
  296. }
  297. }
  298. esp_err_t network_wifi_add_json_entry(const char* json_text) {
  299. esp_err_t err = ESP_OK;
  300. known_access_point_t known_ap;
  301. if (!json_text || strlen(json_text) == 0) {
  302. ESP_LOGE(TAG, "Invalid access point json");
  303. return ESP_ERR_INVALID_ARG;
  304. }
  305. cJSON* cjson_item = cJSON_Parse(json_text);
  306. if (!cjson_item) {
  307. ESP_LOGE(TAG, "Invalid JSON %s", json_text);
  308. return ESP_ERR_INVALID_ARG;
  309. }
  310. cJSON* value = cJSON_GetObjectItemCaseSensitive(cjson_item, "ssid");
  311. if (!value || !cJSON_IsString(value) || strlen(cJSON_GetStringValue(value)) == 0) {
  312. ESP_LOGE(TAG, "Missing ssid in : %s", json_text);
  313. err = ESP_ERR_INVALID_ARG;
  314. } else {
  315. if (!network_wifi_get_ap_entry(cJSON_GetStringValue(value))) {
  316. known_ap.ssid = strdup_psram(cJSON_GetStringValue(value));
  317. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "pass");
  318. if (value && cJSON_IsString(value) && strlen(cJSON_GetStringValue(value)) > 0) {
  319. known_ap.password = strdup_psram(cJSON_GetStringValue(value));
  320. }
  321. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "chan");
  322. if (value) {
  323. known_ap.primary = value->valueint;
  324. }
  325. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "auth");
  326. if (value) {
  327. known_ap.authmode = value->valueint;
  328. }
  329. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "b");
  330. if (value) {
  331. known_ap.phy_11b = value->valueint;
  332. }
  333. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "g");
  334. if (value) {
  335. known_ap.phy_11g = value->valueint;
  336. }
  337. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "n");
  338. if (value) {
  339. known_ap.phy_11n = value->valueint;
  340. }
  341. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "low_rate");
  342. if (value) {
  343. known_ap.phy_lr = value->valueint;
  344. }
  345. value = cJSON_GetObjectItemCaseSensitive(cjson_item, "bssid");
  346. if (value && cJSON_IsString(value) && strlen(cJSON_GetStringValue(value)) > 0) {
  347. network_wifi_str2mac(cJSON_GetStringValue(value), known_ap.bssid);
  348. }
  349. err = network_wifi_add_ap_copy(&known_ap);
  350. } else {
  351. ESP_LOGE(TAG, "Duplicate ssid %s found in storage", cJSON_GetStringValue(value));
  352. }
  353. }
  354. cJSON_Delete(cjson_item);
  355. return err;
  356. }
  357. esp_err_t network_wifi_delete_ap(const char* key) {
  358. esp_err_t esp_err = ESP_OK;
  359. if (!key || strlen(key) == 0) {
  360. ESP_LOGE(TAG, "SSID Empty. Cannot remove ");
  361. return ESP_ERR_INVALID_ARG;
  362. }
  363. known_access_point_t* it = network_wifi_get_ap_entry(key);
  364. if (!it) {
  365. ESP_LOGE(TAG, "Unknown AP entry");
  366. return ESP_ERR_INVALID_ARG;
  367. }
  368. /*
  369. * Check if we're deleting the active network
  370. */
  371. ESP_LOGD(TAG, "Deleting AP %s. Checking if this is the active AP", key);
  372. const wifi_sta_config_t* config = network_wifi_load_active_config();
  373. if (config && strlen(ssid_string(config)) > 0 && strcmp(ssid_string(config), it->ssid) == 0) {
  374. ESP_LOGD(TAG, "Confirmed %s to be the active network. Removing it from flash.", key);
  375. esp_err = network_wifi_erase_legacy();
  376. if (esp_err != ESP_OK) {
  377. ESP_LOGW(TAG, "Legacy network details could not be removed from flash : %s", esp_err_to_name(esp_err));
  378. }
  379. }
  380. ESP_LOGD(TAG, "Removing network %s from the flash AP list", key);
  381. esp_err = erase_nvs_for_partition(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace, it->ssid);
  382. if (esp_err != ESP_OK) {
  383. messaging_post_message(MESSAGING_ERROR, MESSAGING_CLASS_SYSTEM, "Deleting network entry %s error (%s). Error %s", key, ap_list_nsv_namespace, esp_err_to_name(esp_err));
  384. }
  385. ESP_LOGD(TAG, "Removing network %s from the known AP list", key);
  386. network_wifi_remove_ap_entry(it->ssid);
  387. return esp_err;
  388. }
  389. esp_err_t network_wifi_erase_legacy() {
  390. esp_err_t err = erase_nvs_partition(NVS_DEFAULT_PART_NAME, network_wifi_nvs_namespace);
  391. if (err == ESP_OK) {
  392. ESP_LOGW(TAG, "Erased wifi configuration. Disconnecting from network");
  393. if ((err = esp_wifi_disconnect()) != ESP_OK) {
  394. ESP_LOGW(TAG, "Could not disconnect from deleted network : %s", esp_err_to_name(err));
  395. }
  396. }
  397. return err;
  398. }
  399. esp_err_t network_wifi_erase_known_ap() {
  400. network_wifi_empty_known_list();
  401. esp_err_t err = erase_nvs_partition(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace);
  402. return err;
  403. }
  404. esp_err_t network_wifi_write_ap(const char* key, const char* value, size_t size) {
  405. size_t size_override = size > 0 ? size : strlen(value) + 1;
  406. esp_err_t esp_err = store_nvs_value_len_for_partition(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace, NVS_TYPE_BLOB, key, value, size_override);
  407. if (esp_err != ESP_OK) {
  408. messaging_post_message(MESSAGING_ERROR, MESSAGING_CLASS_SYSTEM, "%s (%s). Error %s", key, network_wifi_nvs_namespace, esp_err_to_name(esp_err));
  409. }
  410. return esp_err;
  411. }
  412. esp_err_t network_wifi_write_nvs(const char* key, const char* value, size_t size) {
  413. size_t size_override = size > 0 ? size : strlen(value) + 1;
  414. esp_err_t esp_err = store_nvs_value_len_for_partition(NVS_DEFAULT_PART_NAME, network_wifi_nvs_namespace, NVS_TYPE_BLOB, key, value, size_override);
  415. if (esp_err != ESP_OK) {
  416. messaging_post_message(MESSAGING_ERROR, MESSAGING_CLASS_SYSTEM, "%s (%s). Error %s", key, network_wifi_nvs_namespace, esp_err_to_name(esp_err));
  417. }
  418. return esp_err;
  419. }
  420. esp_err_t network_wifi_store_ap_json(known_access_point_t* item) {
  421. esp_err_t err = ESP_OK;
  422. size_t size = 0;
  423. char* json_string = NULL;
  424. const wifi_sta_config_t* sta = network_wifi_get_active_config();
  425. if ((err = network_wifi_alloc_ap_json(item, &json_string)) == ESP_OK) {
  426. // get any existing entry from the nvs and compare
  427. char* existing = get_nvs_value_alloc_for_partition(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace, NVS_TYPE_BLOB, item->ssid, &size);
  428. if (!existing || strncmp(existing, json_string, strlen(json_string)) != 0) {
  429. ESP_LOGI(TAG, "SSID %s was changed or is new. Committing to flash", item->ssid);
  430. err = network_wifi_write_ap(item->ssid, json_string, 0);
  431. if (sta && strlen(ssid_string(sta)) > 0 && strcmp(ssid_string(sta), item->ssid) == 0) {
  432. ESP_LOGI(TAG, "Committing active access point");
  433. err = network_wifi_write_nvs("ssid", ssid_string(sta), 0);
  434. if (err == ESP_OK) {
  435. err = network_wifi_write_nvs("password", STR_OR_BLANK(password_string(sta)), 0);
  436. }
  437. if (err != ESP_OK) {
  438. ESP_LOGE(TAG, "Error committing active access point : %s", esp_err_to_name(err));
  439. }
  440. }
  441. }
  442. FREE_AND_NULL(existing);
  443. FREE_AND_NULL(json_string);
  444. }
  445. return err;
  446. }
  447. esp_netif_t* network_wifi_get_interface() {
  448. return wifi_netif;
  449. }
  450. esp_netif_t* network_wifi_get_ap_interface() {
  451. return wifi_ap_netif;
  452. }
  453. esp_err_t network_wifi_set_sta_mode() {
  454. if (!wifi_netif) {
  455. ESP_LOGE(TAG, "Wifi not initialized. Cannot set sta mode");
  456. return ESP_ERR_INVALID_STATE;
  457. }
  458. ESP_LOGD(TAG, "Set Mode to STA");
  459. esp_err_t err = esp_wifi_set_mode(WIFI_MODE_STA);
  460. if (err != ESP_OK) {
  461. ESP_LOGE(TAG, "Error setting mode to STA: %s", esp_err_to_name(err));
  462. } else {
  463. ESP_LOGI(TAG, "Starting wifi");
  464. err = esp_wifi_start();
  465. if (err != ESP_OK) {
  466. ESP_LOGE(TAG, "Error starting wifi: %s", esp_err_to_name(err));
  467. }
  468. }
  469. return err;
  470. }
  471. esp_netif_t* network_wifi_start() {
  472. MEMTRACE_PRINT_DELTA_MESSAGE( "Starting wifi interface as STA mode");
  473. accessp_cjson = network_manager_clear_ap_list_json(&accessp_cjson);
  474. if (!wifi_netif) {
  475. MEMTRACE_PRINT_DELTA_MESSAGE("Init STA mode - creating default interface. ");
  476. wifi_netif = esp_netif_create_default_wifi_sta();
  477. MEMTRACE_PRINT_DELTA_MESSAGE("Initializing Wifi. ");
  478. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  479. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_wifi_init(&cfg));
  480. MEMTRACE_PRINT_DELTA_MESSAGE("Registering wifi Handlers");
  481. //network_wifi_register_handlers();
  482. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_event_handler_instance_register(WIFI_EVENT,
  483. ESP_EVENT_ANY_ID,
  484. &network_wifi_event_handler,
  485. NULL,
  486. NULL));
  487. MEMTRACE_PRINT_DELTA_MESSAGE("Setting up wifi Storage");
  488. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_wifi_set_storage(WIFI_STORAGE_RAM));
  489. }
  490. MEMTRACE_PRINT_DELTA_MESSAGE("Setting up wifi mode as STA");
  491. network_wifi_set_sta_mode();
  492. MEMTRACE_PRINT_DELTA_MESSAGE("Setting hostname");
  493. network_set_hostname(wifi_netif);
  494. MEMTRACE_PRINT_DELTA_MESSAGE("Done starting wifi interface");
  495. return wifi_netif;
  496. }
  497. void destroy_network_wifi() {
  498. cJSON_Delete(accessp_cjson);
  499. accessp_cjson = NULL;
  500. }
  501. bool network_wifi_sta_config_changed() {
  502. bool changed = true;
  503. const wifi_sta_config_t* sta = network_wifi_get_active_config();
  504. if (!sta || strlen(ssid_string(sta)) == 0)
  505. return false;
  506. known_access_point_t* known = network_wifi_get_ap_entry(ssid_string(sta));
  507. if (known && strcmp(known->ssid, ssid_string(sta)) == 0 &&
  508. strcmp((char*)known->password, password_string(sta)) == 0) {
  509. changed = false;
  510. } else {
  511. ESP_LOGI(TAG, "New network configuration found");
  512. }
  513. return changed;
  514. }
  515. esp_err_t network_wifi_save_sta_config() {
  516. esp_err_t esp_err = ESP_OK;
  517. known_access_point_t* item = NULL;
  518. MEMTRACE_PRINT_DELTA_MESSAGE("Config Save");
  519. const wifi_sta_config_t* sta = network_wifi_get_active_config();
  520. if (sta && strlen(ssid_string(sta)) > 0) {
  521. MEMTRACE_PRINT_DELTA_MESSAGE("Checking if current SSID is known");
  522. item = network_wifi_get_ap_entry(ssid_string(sta));
  523. if (!item) {
  524. ESP_LOGD(TAG,"New SSID %s found", ssid_string(sta));
  525. // this is a new access point. First add it to the end of the AP list
  526. esp_err = network_wifi_add_ap_from_sta_copy(sta);
  527. }
  528. }
  529. // now traverse the list and commit
  530. MEMTRACE_PRINT_DELTA_MESSAGE("Saving all known ap as json strings");
  531. known_access_point_t* it;
  532. SLIST_FOREACH(it, &s_ap_list, next) {
  533. if ((esp_err = network_wifi_store_ap_json(it)) != ESP_OK) {
  534. ESP_LOGW(TAG, "Error saving wifi ap entry %s : %s", it->ssid, esp_err_to_name(esp_err));
  535. break;
  536. }
  537. }
  538. return esp_err;
  539. }
  540. void network_wifi_load_known_access_points() {
  541. esp_err_t esp_err;
  542. size_t size = 0;
  543. if (network_wifi_get_known_count() > 0) {
  544. ESP_LOGW(TAG, "Access points already loaded");
  545. return;
  546. }
  547. nvs_iterator_t it = nvs_entry_find(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace, NVS_TYPE_ANY);
  548. if (it == NULL) {
  549. ESP_LOGW(TAG, "No known access point found");
  550. return;
  551. }
  552. do {
  553. nvs_entry_info_t info;
  554. nvs_entry_info(it, &info);
  555. if (strstr(info.namespace_name, ap_list_nsv_namespace)) {
  556. void* value = get_nvs_value_alloc_for_partition(NVS_DEFAULT_PART_NAME, ap_list_nsv_namespace, info.type, info.key, &size);
  557. if (value == NULL) {
  558. ESP_LOGE(TAG, "nvs read failed for %s.", info.key);
  559. } else if ((esp_err = network_wifi_add_json_entry(value)) != ESP_OK) {
  560. ESP_LOGE(TAG, "Invalid entry or error for %s.", (char*)value);
  561. }
  562. FREE_AND_NULL(value);
  563. }
  564. it = nvs_entry_next(it);
  565. } while (it != NULL);
  566. return;
  567. }
  568. esp_err_t network_wifi_get_blob(void* target, size_t size, const char* key) {
  569. esp_err_t esp_err = ESP_OK;
  570. size_t found_size = 0;
  571. if (!target) {
  572. ESP_LOGE(TAG, "%s invalid target pointer", __FUNCTION__);
  573. return ESP_ERR_INVALID_ARG;
  574. }
  575. memset(target, 0x00, size);
  576. char* value = (char*)get_nvs_value_alloc_for_partition(NVS_DEFAULT_PART_NAME, network_wifi_nvs_namespace, NVS_TYPE_BLOB, key, &found_size);
  577. if (!value) {
  578. ESP_LOGD(TAG,"nvs key %s not found.", key);
  579. esp_err = ESP_FAIL;
  580. } else {
  581. memcpy((char*)target, value, size > found_size ? found_size : size);
  582. FREE_AND_NULL(value);
  583. ESP_LOGD(TAG,"Successfully loaded key %s", key);
  584. }
  585. return esp_err;
  586. }
  587. const wifi_sta_config_t* network_wifi_load_active_config() {
  588. static wifi_sta_config_t config;
  589. esp_err_t esp_err = ESP_OK;
  590. memset(&config, 0x00, sizeof(config));
  591. config.scan_method = WIFI_ALL_CHANNEL_SCAN;
  592. MEMTRACE_PRINT_DELTA_MESSAGE("Fetching wifi sta config - ssid.");
  593. esp_err = network_wifi_get_blob(&config.ssid, sizeof(config.ssid), "ssid");
  594. if (esp_err == ESP_OK && strlen((char*)config.ssid) > 0) {
  595. ESP_LOGD(TAG,"network_wifi_load_active_config: ssid:%s. Fetching password (if any) ", ssid_string(&config));
  596. if (network_wifi_get_blob(&config.password, sizeof(config.password), "password") != ESP_OK) {
  597. ESP_LOGW(TAG, "No wifi password found in nvs");
  598. }
  599. } else {
  600. if(network_wifi_get_known_count() > 0) {
  601. ESP_LOGW(TAG, "No wifi ssid found in nvs, but known access points found. Using first known access point.");
  602. known_access_point_t* ap = SLIST_FIRST(&s_ap_list);
  603. if (ap) {
  604. strncpy((char*)&config.ssid, ap->ssid, sizeof(config.ssid));
  605. strncpy((char*)&config.password, ap->password, sizeof(config.password));
  606. }
  607. esp_err = ESP_OK;
  608. } else {
  609. ESP_LOGW(TAG, "network manager has no previous configuration. %s", esp_err_to_name(esp_err));
  610. return NULL;
  611. }
  612. }
  613. return &config;
  614. }
  615. bool network_wifi_load_wifi_sta_config() {
  616. network_wifi_load_known_access_points();
  617. const wifi_sta_config_t* config = network_wifi_load_active_config();
  618. if (config) {
  619. known_access_point_t* item = network_wifi_get_ap_entry(ssid_string(config));
  620. if (!item) {
  621. ESP_LOGI(TAG, "Adding legacy/active wifi connection to the known list");
  622. network_wifi_add_ap_from_sta_copy(config);
  623. }
  624. }
  625. return config && config->ssid[0] != '\0';
  626. }
  627. bool network_wifi_get_config_for_ssid(wifi_config_t* config, const char* ssid) {
  628. known_access_point_t* item = network_wifi_get_ap_entry(ssid);
  629. if (!item) {
  630. ESP_LOGE(TAG, "Unknown ssid %s", ssid);
  631. return false;
  632. }
  633. memset(&config->ap, 0x00, sizeof(config->ap));
  634. strncpy((char*)config->ap.ssid, item->ssid, sizeof(config->ap.ssid));
  635. strncpy((char*)config->ap.password, item->password, sizeof(config->ap.ssid));
  636. config->sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
  637. return true;
  638. }
  639. static void network_wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
  640. if (event_base != WIFI_EVENT)
  641. return;
  642. switch (event_id) {
  643. case WIFI_EVENT_WIFI_READY:
  644. ESP_LOGD(TAG, "WIFI_EVENT_WIFI_READY");
  645. break;
  646. case WIFI_EVENT_SCAN_DONE:
  647. ESP_LOGD(TAG, "WIFI_EVENT_SCAN_DONE");
  648. network_async_scan_done();
  649. break;
  650. case WIFI_EVENT_STA_AUTHMODE_CHANGE:
  651. ESP_LOGD(TAG, "WIFI_EVENT_STA_AUTHMODE_CHANGE");
  652. break;
  653. case WIFI_EVENT_AP_START:
  654. ESP_LOGD(TAG, "WIFI_EVENT_AP_START");
  655. break;
  656. case WIFI_EVENT_AP_STOP:
  657. ESP_LOGD(TAG, "WIFI_EVENT_AP_STOP");
  658. break;
  659. case WIFI_EVENT_AP_PROBEREQRECVED: {
  660. wifi_event_ap_probe_req_rx_t* s = (wifi_event_ap_probe_req_rx_t*)event_data;
  661. char* mac = network_manager_alloc_get_mac_string(s->mac);
  662. if (mac) {
  663. ESP_LOGD(TAG, "WIFI_EVENT_AP_PROBEREQRECVED. RSSI: %d, MAC: %s", s->rssi, STR_OR_BLANK(mac));
  664. }
  665. FREE_AND_NULL(mac);
  666. } break;
  667. case WIFI_EVENT_STA_WPS_ER_SUCCESS:
  668. ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_SUCCESS");
  669. break;
  670. case WIFI_EVENT_STA_WPS_ER_FAILED:
  671. ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_FAILED");
  672. break;
  673. case WIFI_EVENT_STA_WPS_ER_TIMEOUT:
  674. ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_TIMEOUT");
  675. break;
  676. case WIFI_EVENT_STA_WPS_ER_PIN:
  677. ESP_LOGD(TAG, "WIFI_EVENT_STA_WPS_ER_PIN");
  678. break;
  679. case WIFI_EVENT_AP_STACONNECTED: {
  680. wifi_event_ap_staconnected_t* stac = (wifi_event_ap_staconnected_t*)event_data;
  681. char* mac = network_manager_alloc_get_mac_string(stac->mac);
  682. if (mac) {
  683. ESP_LOGD(TAG, "WIFI_EVENT_AP_STACONNECTED. aid: %d, mac: %s", stac->aid, STR_OR_BLANK(mac));
  684. }
  685. FREE_AND_NULL(mac);
  686. } break;
  687. case WIFI_EVENT_AP_STADISCONNECTED:
  688. ESP_LOGD(TAG, "WIFI_EVENT_AP_STADISCONNECTED");
  689. break;
  690. case WIFI_EVENT_STA_START:
  691. ESP_LOGD(TAG, "WIFI_EVENT_STA_START");
  692. break;
  693. case WIFI_EVENT_STA_STOP:
  694. ESP_LOGD(TAG, "WIFI_EVENT_STA_STOP");
  695. break;
  696. case WIFI_EVENT_STA_CONNECTED: {
  697. ESP_LOGD(TAG, "WIFI_EVENT_STA_CONNECTED. ");
  698. wifi_event_sta_connected_t* s = (wifi_event_sta_connected_t*)event_data;
  699. char* bssid = network_manager_alloc_get_mac_string(s->bssid);
  700. char* ssid = strdup_psram((char*)s->ssid);
  701. if (bssid && ssid) {
  702. ESP_LOGD(TAG, "WIFI_EVENT_STA_CONNECTED. Channel: %d, Access point: %s, BSSID: %s ", s->channel, STR_OR_BLANK(ssid), (bssid));
  703. }
  704. FREE_AND_NULL(bssid);
  705. FREE_AND_NULL(ssid);
  706. network_async(EN_CONNECTED);
  707. } break;
  708. case WIFI_EVENT_STA_DISCONNECTED: {
  709. // structwifi_event_sta_disconnected_t
  710. // Argument structure for WIFI_EVENT_STA_DISCONNECTED event
  711. //
  712. // Public Members
  713. //
  714. // uint8_t ssid[32]
  715. // SSID of disconnected AP
  716. //
  717. // uint8_t ssid_len
  718. // SSID length of disconnected AP
  719. //
  720. // uint8_t bssid[6]
  721. // BSSID of disconnected AP
  722. //
  723. // uint8_t reason
  724. // reason of disconnection
  725. wifi_event_sta_disconnected_t* s = (wifi_event_sta_disconnected_t*)event_data;
  726. char* bssid = network_manager_alloc_get_mac_string(s->bssid);
  727. ESP_LOGW(TAG, "WIFI_EVENT_STA_DISCONNECTED. From BSSID: %s, reason code: %d (%s)", STR_OR_BLANK(bssid), s->reason, get_disconnect_code_desc(s->reason));
  728. FREE_AND_NULL(bssid);
  729. if (s->reason == WIFI_REASON_ROAMING) {
  730. ESP_LOGI(TAG, "WiFi Roaming to new access point");
  731. } else {
  732. network_async_lost_connection((wifi_event_sta_disconnected_t*)event_data);
  733. }
  734. } break;
  735. default:
  736. break;
  737. }
  738. }
  739. cJSON* network_wifi_get_new_array_json(cJSON** old) {
  740. ESP_LOGV(TAG, "network_wifi_get_new_array_json called");
  741. cJSON* root = *old;
  742. if (root != NULL) {
  743. cJSON_Delete(root);
  744. *old = NULL;
  745. }
  746. ESP_LOGV(TAG, "network_wifi_get_new_array_json done");
  747. return cJSON_CreateArray();
  748. }
  749. void network_wifi_global_init() {
  750. network_wifi_get_new_array_json(&accessp_cjson);
  751. ESP_LOGD(TAG, "Loading existing wifi configuration (if any)");
  752. network_wifi_load_wifi_sta_config();
  753. }
  754. void network_wifi_add_access_point_json(cJSON* ap_list, wifi_ap_record_t* ap_rec) {
  755. cJSON* ap = cJSON_CreateObject();
  756. if (ap == NULL) {
  757. ESP_LOGE(TAG, "Unable to allocate memory for access point %s", ap_rec->ssid);
  758. return;
  759. }
  760. cJSON* radio = cJSON_CreateObject();
  761. if (radio == NULL) {
  762. ESP_LOGE(TAG, "Unable to allocate memory for access point %s", ap_rec->ssid);
  763. cJSON_Delete(ap);
  764. return;
  765. }
  766. cJSON_AddItemToObject(ap, "ssid", cJSON_CreateString(ap_ssid_string(ap_rec)));
  767. cJSON_AddBoolToObject(ap, "known", network_wifi_is_known_ap(ap_ssid_string(ap_rec)));
  768. if (ap_rec->rssi != 0) {
  769. // only add the rest of the details when record doesn't come from
  770. // "known" access points that aren't in range
  771. cJSON_AddNumberToObject(ap, "chan", ap_rec->primary);
  772. cJSON_AddNumberToObject(ap, "rssi", ap_rec->rssi);
  773. cJSON_AddNumberToObject(ap, "auth", ap_rec->authmode);
  774. char* bssid = network_manager_alloc_get_mac_string(ap_rec->bssid);
  775. if (bssid) {
  776. cJSON_AddItemToObject(ap, "bssid", cJSON_CreateString(STR_OR_BLANK(bssid)));
  777. }
  778. FREE_AND_NULL(bssid);
  779. cJSON_AddNumberToObject(radio, "b", ap_rec->phy_11b ? 1 : 0);
  780. cJSON_AddNumberToObject(radio, "g", ap_rec->phy_11g ? 1 : 0);
  781. cJSON_AddNumberToObject(radio, "n", ap_rec->phy_11n ? 1 : 0);
  782. cJSON_AddNumberToObject(radio, "low_rate", ap_rec->phy_lr ? 1 : 0);
  783. cJSON_AddItemToObject(ap, "radio", radio);
  784. }
  785. cJSON_AddItemToArray(ap_list, ap);
  786. char* ap_json = cJSON_PrintUnformatted(ap);
  787. if (ap_json != NULL) {
  788. ESP_LOGD(TAG, "New access point found: %s", ap_json);
  789. free(ap_json);
  790. }
  791. }
  792. void network_wifi_generate_access_points_json(cJSON** ap_list) {
  793. *ap_list = network_wifi_get_new_array_json(ap_list);
  794. wifi_ap_record_t known_ap;
  795. known_access_point_t* it;
  796. if (*ap_list == NULL)
  797. return;
  798. for (int i = 0; i < ap_num; i++) {
  799. network_wifi_add_access_point_json(*ap_list, &accessp_records[i]);
  800. }
  801. SLIST_FOREACH(it, &s_ap_list, next) {
  802. if (!network_wifi_was_ssid_seen(it->ssid)) {
  803. memset(&known_ap, 0x00, sizeof(known_ap));
  804. strlcpy((char*)known_ap.ssid, it->ssid, sizeof(known_ap.ssid));
  805. ESP_LOGD(TAG, "Adding known access point that is not in range: %s", it->ssid);
  806. network_wifi_add_access_point_json(*ap_list, &known_ap);
  807. }
  808. }
  809. char* ap_list_json = cJSON_PrintUnformatted(*ap_list);
  810. if (ap_list_json != NULL) {
  811. ESP_LOGV(TAG, "Full access point list: %s", ap_list_json);
  812. free(ap_list_json);
  813. }
  814. }
  815. void network_wifi_set_ipv4val(const char* key, char* default_value, ip4_addr_t* target) {
  816. char* value = config_alloc_get_default(NVS_TYPE_STR, key, default_value, 0);
  817. if (value != NULL) {
  818. ESP_LOGD(TAG, "%s: %s", key, value);
  819. inet_pton(AF_INET, value, target); /* access point is on a static IP */
  820. }
  821. FREE_AND_NULL(value);
  822. }
  823. esp_netif_t* network_wifi_config_ap() {
  824. esp_netif_ip_info_t info;
  825. esp_err_t err = ESP_OK;
  826. char* value = NULL;
  827. wifi_config_t ap_config = {
  828. .ap = {
  829. .ssid_len = 0,
  830. },
  831. };
  832. ESP_LOGI(TAG, "Configuring Access Point.");
  833. if (!wifi_ap_netif) {
  834. wifi_ap_netif = esp_netif_create_default_wifi_ap();
  835. }
  836. network_wifi_set_ipv4val("ap_ip_address", DEFAULT_AP_IP, (ip4_addr_t*)&info.ip);
  837. network_wifi_set_ipv4val("ap_ip_gateway", CONFIG_DEFAULT_AP_GATEWAY, (ip4_addr_t*)&info.gw);
  838. network_wifi_set_ipv4val("ap_ip_netmask", CONFIG_DEFAULT_AP_NETMASK, (ip4_addr_t*)&info.netmask);
  839. /* In order to change the IP info structure, we have to first stop
  840. * the DHCP server on the new interface
  841. */
  842. network_start_stop_dhcps(wifi_ap_netif, false);
  843. ESP_LOGD(TAG, "Setting tcp_ip info for access point");
  844. if ((err = esp_netif_set_ip_info(wifi_ap_netif, &info)) != ESP_OK) {
  845. ESP_LOGE(TAG, "Setting tcp_ip info for interface TCPIP_ADAPTER_IF_AP. Error %s", esp_err_to_name(err));
  846. return wifi_ap_netif;
  847. }
  848. network_start_stop_dhcps(wifi_ap_netif, true);
  849. /*
  850. * Set Access Point configuration
  851. */
  852. value = config_alloc_get_default(NVS_TYPE_STR, "ap_ssid", CONFIG_DEFAULT_AP_SSID, 0);
  853. if (value != NULL) {
  854. strlcpy((char*)ap_config.ap.ssid, value, sizeof(ap_config.ap.ssid));
  855. ESP_LOGI(TAG, "AP SSID: %s", (char*)ap_config.ap.ssid);
  856. }
  857. FREE_AND_NULL(value);
  858. value = config_alloc_get_default(NVS_TYPE_STR, "ap_pwd", DEFAULT_AP_PASSWORD, 0);
  859. if (value != NULL) {
  860. strlcpy((char*)ap_config.ap.password, value, sizeof(ap_config.ap.password));
  861. ESP_LOGI(TAG, "AP Password: %s", (char*)ap_config.ap.password);
  862. }
  863. FREE_AND_NULL(value);
  864. value = config_alloc_get_default(NVS_TYPE_STR, "ap_channel", STR(CONFIG_DEFAULT_AP_CHANNEL), 0);
  865. if (value != NULL) {
  866. ESP_LOGD(TAG, "Channel: %s", value);
  867. ap_config.ap.channel = atoi(value);
  868. }
  869. FREE_AND_NULL(value);
  870. ap_config.ap.authmode = AP_AUTHMODE;
  871. ap_config.ap.ssid_hidden = DEFAULT_AP_SSID_HIDDEN;
  872. ap_config.ap.max_connection = DEFAULT_AP_MAX_CONNECTIONS;
  873. ap_config.ap.beacon_interval = DEFAULT_AP_BEACON_INTERVAL;
  874. ESP_LOGD(TAG, "Auth Mode: %d", ap_config.ap.authmode);
  875. ESP_LOGD(TAG, "SSID Hidden: %d", ap_config.ap.ssid_hidden);
  876. ESP_LOGD(TAG, "Max Connections: %d", ap_config.ap.max_connection);
  877. ESP_LOGD(TAG, "Beacon interval: %d", ap_config.ap.beacon_interval);
  878. const char* msg = "Setting wifi mode as WIFI_MODE_APSTA";
  879. ESP_LOGD(TAG, "%s", msg);
  880. if ((err = esp_wifi_set_mode(WIFI_MODE_APSTA)) != ESP_OK) {
  881. ESP_LOGE(TAG, "%s. Error %s", msg, esp_err_to_name(err));
  882. return wifi_ap_netif;
  883. }
  884. msg = "Setting wifi AP configuration for WIFI_IF_AP";
  885. ESP_LOGD(TAG, "%s", msg);
  886. if ((err = esp_wifi_set_config(WIFI_IF_AP, &ap_config)) != ESP_OK) /* stop AP DHCP server */
  887. {
  888. ESP_LOGE(TAG, "%s . Error %s", msg, esp_err_to_name(err));
  889. return wifi_ap_netif;
  890. }
  891. msg = "Setting wifi bandwidth";
  892. ESP_LOGD(TAG, "%s (%d)", msg, DEFAULT_AP_BANDWIDTH);
  893. if ((err = esp_wifi_set_bandwidth(WIFI_IF_AP, DEFAULT_AP_BANDWIDTH)) != ESP_OK) /* stop AP DHCP server */
  894. {
  895. ESP_LOGE(TAG, "%s failed. Error %s", msg, esp_err_to_name(err));
  896. return wifi_ap_netif;
  897. }
  898. msg = "Setting wifi power save";
  899. ESP_LOGD(TAG, "%s (%d)", msg, DEFAULT_STA_POWER_SAVE);
  900. if ((err = esp_wifi_set_ps(DEFAULT_STA_POWER_SAVE)) != ESP_OK) /* stop AP DHCP server */
  901. {
  902. ESP_LOGE(TAG, "%s failed. Error %s", msg, esp_err_to_name(err));
  903. return wifi_ap_netif;
  904. }
  905. ESP_LOGD(TAG, "Done configuring Soft Access Point");
  906. return wifi_ap_netif;
  907. }
  908. void network_wifi_filter_unique(wifi_ap_record_t* aplist, uint16_t* aps) {
  909. int total_unique;
  910. wifi_ap_record_t* first_free;
  911. total_unique = *aps;
  912. first_free = NULL;
  913. for (int i = 0; i < *aps - 1; i++) {
  914. wifi_ap_record_t* ap = &aplist[i];
  915. /* skip the previously removed APs */
  916. if (ap->ssid[0] == 0)
  917. continue;
  918. /* remove the identical SSID+authmodes */
  919. for (int j = i + 1; j < *aps; j++) {
  920. wifi_ap_record_t* ap1 = &aplist[j];
  921. if ((strcmp((const char*)ap->ssid, (const char*)ap1->ssid) == 0) &&
  922. (ap->authmode == ap1->authmode)) { /* same SSID, different auth mode is skipped */
  923. /* save the rssi for the display */
  924. if ((ap1->rssi) > (ap->rssi))
  925. ap->rssi = ap1->rssi;
  926. /* clearing the record */
  927. memset(ap1, 0, sizeof(wifi_ap_record_t));
  928. }
  929. }
  930. }
  931. /* reorder the list so APs follow each other in the list */
  932. for (int i = 0; i < *aps; i++) {
  933. wifi_ap_record_t* ap = &aplist[i];
  934. /* skipping all that has no name */
  935. if (ap->ssid[0] == 0) {
  936. /* mark the first free slot */
  937. if (first_free == NULL)
  938. first_free = ap;
  939. total_unique--;
  940. continue;
  941. }
  942. if (first_free != NULL) {
  943. memcpy(first_free, ap, sizeof(wifi_ap_record_t));
  944. memset(ap, 0, sizeof(wifi_ap_record_t));
  945. /* find the next free slot */
  946. for (int j = 0; j < *aps; j++) {
  947. if (aplist[j].ssid[0] == 0) {
  948. first_free = &aplist[j];
  949. break;
  950. }
  951. }
  952. }
  953. }
  954. /* update the length of the list */
  955. *aps = total_unique;
  956. }
  957. char* network_status_alloc_get_ap_list_json() {
  958. return cJSON_PrintUnformatted(accessp_cjson);
  959. }
  960. cJSON* network_manager_clear_ap_list_json(cJSON** old) {
  961. ESP_LOGV(TAG, "network_manager_clear_ap_list_json called");
  962. cJSON* root = network_wifi_get_new_array_json(old);
  963. ESP_LOGV(TAG, "network_manager_clear_ap_list_json done");
  964. return root;
  965. }
  966. esp_err_t network_wifi_built_known_ap_list() {
  967. if (network_status_lock_json_buffer(pdMS_TO_TICKS(1000))) {
  968. ESP_LOGD(TAG,"Building known AP list");
  969. accessp_cjson = network_manager_clear_ap_list_json(&accessp_cjson);
  970. network_wifi_generate_access_points_json(&accessp_cjson);
  971. network_status_unlock_json_buffer();
  972. ESP_LOGD(TAG, "Done building ap JSON list");
  973. } else {
  974. ESP_LOGE(TAG, "Failed to lock json buffer");
  975. return ESP_FAIL;
  976. }
  977. return ESP_OK;
  978. }
  979. esp_err_t wifi_scan_done() {
  980. esp_err_t err = ESP_OK;
  981. /* As input param, it stores max AP number ap_records can hold. As output param, it receives the actual AP number this API returns.
  982. * As a consequence, ap_num MUST be reset to MAX_AP_NUM at every scan */
  983. ESP_LOGD(TAG, "Getting AP list records");
  984. ap_num = MAX_AP_NUM;
  985. if ((err = esp_wifi_scan_get_ap_num(&ap_num)) != ESP_OK) {
  986. ESP_LOGE(TAG, "Failed to retrieve scan results count. Error %s", esp_err_to_name(err));
  987. return err;
  988. }
  989. FREE_AND_NULL(accessp_records);
  990. if (ap_num > 0) {
  991. accessp_records = (wifi_ap_record_t*)malloc_init_external(sizeof(wifi_ap_record_t) * ap_num);
  992. if ((err = esp_wifi_scan_get_ap_records(&ap_num, accessp_records)) != ESP_OK) {
  993. ESP_LOGE(TAG, "Failed to retrieve scan results list. Error %s", esp_err_to_name(err));
  994. return err;
  995. }
  996. /* make sure the http server isn't trying to access the list while it gets refreshed */
  997. ESP_LOGD(TAG, "Preparing to build ap JSON list");
  998. if (network_status_lock_json_buffer(pdMS_TO_TICKS(1000))) {
  999. /* Will remove the duplicate SSIDs from the list and update ap_num */
  1000. network_wifi_filter_unique(accessp_records, &ap_num);
  1001. network_wifi_set_found_ap();
  1002. network_wifi_generate_access_points_json(&accessp_cjson);
  1003. network_status_unlock_json_buffer();
  1004. ESP_LOGD(TAG, "Done building ap JSON list");
  1005. } else {
  1006. ESP_LOGE(TAG, "could not get access to json mutex in wifi_scan");
  1007. err = ESP_FAIL;
  1008. }
  1009. } else {
  1010. //
  1011. ESP_LOGD(TAG, "No AP Found. Emptying the list.");
  1012. accessp_cjson = network_wifi_get_new_array_json(&accessp_cjson);
  1013. }
  1014. return err;
  1015. }
  1016. bool is_wifi_up() {
  1017. return wifi_netif != NULL;
  1018. }
  1019. esp_err_t network_wifi_start_scan() {
  1020. wifi_scan_config_t scan_config = {
  1021. .ssid = 0,
  1022. .bssid = 0,
  1023. .channel = 0,
  1024. .scan_type = WIFI_SCAN_TYPE_ACTIVE,
  1025. .show_hidden = true};
  1026. esp_err_t err = ESP_OK;
  1027. ESP_LOGI(TAG, "Initiating wifi network scan");
  1028. if (!is_wifi_up()) {
  1029. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Wifi not started. Cannot scan");
  1030. return ESP_FAIL;
  1031. }
  1032. /* if a scan is already in progress this message is simply ignored thanks to the WIFI_MANAGER_SCAN_BIT uxBit */
  1033. if ((err = esp_wifi_scan_start(&scan_config, false)) != ESP_OK) {
  1034. ESP_LOGW(TAG, "Unable to start scan; %s ", esp_err_to_name(err));
  1035. // set_status_message(WARNING, "Wifi Connecting. Cannot start scan.");
  1036. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Scanning failed: %s", esp_err_to_name(err));
  1037. }
  1038. return err;
  1039. }
  1040. bool network_wifi_is_ap_mode() {
  1041. wifi_mode_t mode;
  1042. /* update config to latest and attempt connection */
  1043. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_AP;
  1044. }
  1045. bool network_wifi_is_sta_mode() {
  1046. wifi_mode_t mode;
  1047. /* update config to latest and attempt connection */
  1048. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_STA;
  1049. }
  1050. bool network_wifi_is_ap_sta_mode() {
  1051. wifi_mode_t mode;
  1052. /* update config to latest and attempt connection */
  1053. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_APSTA;
  1054. }
  1055. esp_err_t network_wifi_connect(const char* ssid, const char* password) {
  1056. esp_err_t err = ESP_OK;
  1057. wifi_config_t config;
  1058. memset(&config, 0x00, sizeof(config));
  1059. ESP_LOGD(TAG, "network_wifi_connect");
  1060. if (!is_wifi_up()) {
  1061. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Wifi not started. Cannot connect");
  1062. return ESP_FAIL;
  1063. }
  1064. if (!ssid || !password || strlen(ssid) == 0) {
  1065. ESP_LOGE(TAG, "Cannot connect wifi. wifi config is null!");
  1066. return ESP_ERR_INVALID_ARG;
  1067. }
  1068. wifi_mode_t wifi_mode;
  1069. err = esp_wifi_get_mode(&wifi_mode);
  1070. if (err == ESP_ERR_WIFI_NOT_INIT) {
  1071. ESP_LOGW(TAG, "Wifi not initialized. Attempting to start sta mode");
  1072. network_wifi_start();
  1073. } else if (err != ESP_OK) {
  1074. ESP_LOGE(TAG, "Could not retrieve wifi mode : %s", esp_err_to_name(err));
  1075. } else if (wifi_mode != WIFI_MODE_STA && wifi_mode != WIFI_MODE_APSTA) {
  1076. ESP_LOGD(TAG, "Changing wifi mode to STA");
  1077. err = network_wifi_set_sta_mode();
  1078. if (err != ESP_OK) {
  1079. ESP_LOGE(TAG, "Could not set mode to STA. Cannot connect to SSID %s", ssid);
  1080. return err;
  1081. }
  1082. }
  1083. // copy configuration and connect
  1084. strlcpy((char*)config.sta.ssid, ssid, sizeof(config.sta.ssid));
  1085. if (password) {
  1086. strlcpy((char*)config.sta.password, password, sizeof(config.sta.password));
  1087. }
  1088. // First Disconnect
  1089. esp_wifi_disconnect();
  1090. config.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
  1091. if ((err = esp_wifi_set_config(WIFI_IF_STA, &config)) != ESP_OK) {
  1092. ESP_LOGE(TAG, "Failed to set STA configuration. Error %s", esp_err_to_name(err));
  1093. }
  1094. if (err == ESP_OK) {
  1095. ESP_LOGI(TAG, "Wifi Connecting to %s...", ssid);
  1096. if ((err = esp_wifi_connect()) != ESP_OK) {
  1097. ESP_LOGE(TAG, "Failed to initiate wifi connection. Error %s", esp_err_to_name(err));
  1098. }
  1099. }
  1100. return err;
  1101. }
  1102. esp_err_t network_wifi_connect_next_in_range(){
  1103. const char * ssid = network_wifi_get_next_ap_in_range();
  1104. if(ssid){
  1105. return network_wifi_connect_ssid(ssid);
  1106. }
  1107. return ESP_FAIL;
  1108. }
  1109. esp_err_t network_wifi_connect_ssid(const char* ssid) {
  1110. known_access_point_t* item = network_wifi_get_ap_entry(ssid);
  1111. if (item) {
  1112. item->last_try = (esp_timer_get_time() / 1000);
  1113. return network_wifi_connect(item->ssid, item->password);
  1114. }
  1115. return ESP_FAIL;
  1116. }
  1117. esp_err_t network_wifi_connect_active_ssid() {
  1118. const wifi_sta_config_t* config = network_wifi_load_active_config();
  1119. if (config) {
  1120. return network_wifi_connect(ssid_string(config), password_string(config));
  1121. }
  1122. return ESP_FAIL;
  1123. }
  1124. void network_wifi_clear_config() {
  1125. /* erase configuration */
  1126. const wifi_sta_config_t* sta = network_wifi_get_active_config();
  1127. network_wifi_delete_ap(ssid_string(sta));
  1128. esp_err_t err = ESP_OK;
  1129. if ((err = esp_wifi_disconnect()) != ESP_OK) {
  1130. ESP_LOGW(TAG, "Could not disconnect from deleted network : %s", esp_err_to_name(err));
  1131. }
  1132. }
  1133. char* get_disconnect_code_desc(uint8_t reason) {
  1134. switch (reason) {
  1135. ENUM_TO_STRING(WIFI_REASON_UNSPECIFIED);
  1136. ENUM_TO_STRING(WIFI_REASON_AUTH_EXPIRE);
  1137. ENUM_TO_STRING(WIFI_REASON_AUTH_LEAVE);
  1138. ENUM_TO_STRING(WIFI_REASON_ASSOC_EXPIRE);
  1139. ENUM_TO_STRING(WIFI_REASON_ASSOC_TOOMANY);
  1140. ENUM_TO_STRING(WIFI_REASON_NOT_AUTHED);
  1141. ENUM_TO_STRING(WIFI_REASON_NOT_ASSOCED);
  1142. ENUM_TO_STRING(WIFI_REASON_ASSOC_LEAVE);
  1143. ENUM_TO_STRING(WIFI_REASON_ASSOC_NOT_AUTHED);
  1144. ENUM_TO_STRING(WIFI_REASON_DISASSOC_PWRCAP_BAD);
  1145. ENUM_TO_STRING(WIFI_REASON_DISASSOC_SUPCHAN_BAD);
  1146. ENUM_TO_STRING(WIFI_REASON_IE_INVALID);
  1147. ENUM_TO_STRING(WIFI_REASON_MIC_FAILURE);
  1148. ENUM_TO_STRING(WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT);
  1149. ENUM_TO_STRING(WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT);
  1150. ENUM_TO_STRING(WIFI_REASON_IE_IN_4WAY_DIFFERS);
  1151. ENUM_TO_STRING(WIFI_REASON_GROUP_CIPHER_INVALID);
  1152. ENUM_TO_STRING(WIFI_REASON_PAIRWISE_CIPHER_INVALID);
  1153. ENUM_TO_STRING(WIFI_REASON_AKMP_INVALID);
  1154. ENUM_TO_STRING(WIFI_REASON_UNSUPP_RSN_IE_VERSION);
  1155. ENUM_TO_STRING(WIFI_REASON_INVALID_RSN_IE_CAP);
  1156. ENUM_TO_STRING(WIFI_REASON_802_1X_AUTH_FAILED);
  1157. ENUM_TO_STRING(WIFI_REASON_CIPHER_SUITE_REJECTED);
  1158. ENUM_TO_STRING(WIFI_REASON_INVALID_PMKID);
  1159. ENUM_TO_STRING(WIFI_REASON_BEACON_TIMEOUT);
  1160. ENUM_TO_STRING(WIFI_REASON_NO_AP_FOUND);
  1161. ENUM_TO_STRING(WIFI_REASON_AUTH_FAIL);
  1162. ENUM_TO_STRING(WIFI_REASON_ASSOC_FAIL);
  1163. ENUM_TO_STRING(WIFI_REASON_HANDSHAKE_TIMEOUT);
  1164. ENUM_TO_STRING(WIFI_REASON_CONNECTION_FAIL);
  1165. ENUM_TO_STRING(WIFI_REASON_AP_TSF_RESET);
  1166. ENUM_TO_STRING(WIFI_REASON_ROAMING);
  1167. }
  1168. return "";
  1169. }