network_wifi.c 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  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. network_wifi_set_connect_state(NETWORK_WIFI_STATE_CONNECTED);
  702. if (bssid && ssid) {
  703. ESP_LOGD(TAG, "WIFI_EVENT_STA_CONNECTED. Channel: %d, Access point: %s, BSSID: %s ", s->channel, STR_OR_BLANK(ssid), (bssid));
  704. }
  705. FREE_AND_NULL(bssid);
  706. FREE_AND_NULL(ssid);
  707. network_async(EN_CONNECTED);
  708. } break;
  709. case WIFI_EVENT_STA_DISCONNECTED: {
  710. // structwifi_event_sta_disconnected_t
  711. // Argument structure for WIFI_EVENT_STA_DISCONNECTED event
  712. //
  713. // Public Members
  714. //
  715. // uint8_t ssid[32]
  716. // SSID of disconnected AP
  717. //
  718. // uint8_t ssid_len
  719. // SSID length of disconnected AP
  720. //
  721. // uint8_t bssid[6]
  722. // BSSID of disconnected AP
  723. //
  724. // uint8_t reason
  725. // reason of disconnection
  726. wifi_event_sta_disconnected_t* s = (wifi_event_sta_disconnected_t*)event_data;
  727. char* bssid = network_manager_alloc_get_mac_string(s->bssid);
  728. 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));
  729. FREE_AND_NULL(bssid);
  730. if (s->reason == WIFI_REASON_ROAMING) {
  731. ESP_LOGI(TAG, "WiFi Roaming to new access point");
  732. } else {
  733. network_async_lost_connection((wifi_event_sta_disconnected_t*)event_data);
  734. network_wifi_set_connect_state(NETWORK_WIFI_STATE_FAILED);
  735. }
  736. } break;
  737. default:
  738. break;
  739. }
  740. }
  741. cJSON* network_wifi_get_new_array_json(cJSON** old) {
  742. ESP_LOGV(TAG, "network_wifi_get_new_array_json called");
  743. cJSON* root = *old;
  744. if (root != NULL) {
  745. cJSON_Delete(root);
  746. *old = NULL;
  747. }
  748. ESP_LOGV(TAG, "network_wifi_get_new_array_json done");
  749. return cJSON_CreateArray();
  750. }
  751. void network_wifi_global_init() {
  752. network_wifi_get_new_array_json(&accessp_cjson);
  753. ESP_LOGD(TAG, "Loading existing wifi configuration (if any)");
  754. network_wifi_load_wifi_sta_config();
  755. }
  756. void network_wifi_add_access_point_json(cJSON* ap_list, wifi_ap_record_t* ap_rec) {
  757. cJSON* ap = cJSON_CreateObject();
  758. if (ap == NULL) {
  759. ESP_LOGE(TAG, "Unable to allocate memory for access point %s", ap_rec->ssid);
  760. return;
  761. }
  762. cJSON* radio = cJSON_CreateObject();
  763. if (radio == NULL) {
  764. ESP_LOGE(TAG, "Unable to allocate memory for access point %s", ap_rec->ssid);
  765. cJSON_Delete(ap);
  766. return;
  767. }
  768. cJSON_AddItemToObject(ap, "ssid", cJSON_CreateString(ap_ssid_string(ap_rec)));
  769. cJSON_AddBoolToObject(ap, "known", network_wifi_is_known_ap(ap_ssid_string(ap_rec)));
  770. if (ap_rec->rssi != 0) {
  771. // only add the rest of the details when record doesn't come from
  772. // "known" access points that aren't in range
  773. cJSON_AddNumberToObject(ap, "chan", ap_rec->primary);
  774. cJSON_AddNumberToObject(ap, "rssi", ap_rec->rssi);
  775. cJSON_AddNumberToObject(ap, "auth", ap_rec->authmode);
  776. char* bssid = network_manager_alloc_get_mac_string(ap_rec->bssid);
  777. if (bssid) {
  778. cJSON_AddItemToObject(ap, "bssid", cJSON_CreateString(STR_OR_BLANK(bssid)));
  779. }
  780. FREE_AND_NULL(bssid);
  781. cJSON_AddNumberToObject(radio, "b", ap_rec->phy_11b ? 1 : 0);
  782. cJSON_AddNumberToObject(radio, "g", ap_rec->phy_11g ? 1 : 0);
  783. cJSON_AddNumberToObject(radio, "n", ap_rec->phy_11n ? 1 : 0);
  784. cJSON_AddNumberToObject(radio, "low_rate", ap_rec->phy_lr ? 1 : 0);
  785. cJSON_AddItemToObject(ap, "radio", radio);
  786. }
  787. cJSON_AddItemToArray(ap_list, ap);
  788. char* ap_json = cJSON_PrintUnformatted(ap);
  789. if (ap_json != NULL) {
  790. ESP_LOGD(TAG, "New access point found: %s", ap_json);
  791. free(ap_json);
  792. }
  793. }
  794. void network_wifi_generate_access_points_json(cJSON** ap_list) {
  795. *ap_list = network_wifi_get_new_array_json(ap_list);
  796. wifi_ap_record_t known_ap;
  797. known_access_point_t* it;
  798. if (*ap_list == NULL)
  799. return;
  800. improv_wifi_list_allocate(ap_num);
  801. for (int i = 0; i < ap_num; i++) {
  802. network_wifi_add_access_point_json(*ap_list, &accessp_records[i]);
  803. improv_wifi_list_add(ap_ssid_string(&accessp_records[i]),accessp_records[i].rssi, accessp_records[i].authmode!=WIFI_AUTH_OPEN);
  804. }
  805. SLIST_FOREACH(it, &s_ap_list, next) {
  806. if (!network_wifi_was_ssid_seen(it->ssid)) {
  807. memset(&known_ap, 0x00, sizeof(known_ap));
  808. strlcpy((char*)known_ap.ssid, it->ssid, sizeof(known_ap.ssid));
  809. ESP_LOGD(TAG, "Adding known access point that is not in range: %s", it->ssid);
  810. network_wifi_add_access_point_json(*ap_list, &known_ap);
  811. }
  812. }
  813. char* ap_list_json = cJSON_PrintUnformatted(*ap_list);
  814. if (ap_list_json != NULL) {
  815. ESP_LOGV(TAG, "Full access point list: %s", ap_list_json);
  816. free(ap_list_json);
  817. }
  818. }
  819. void network_wifi_set_ipv4val(const char* key, char* default_value, ip4_addr_t* target) {
  820. char* value = config_alloc_get_default(NVS_TYPE_STR, key, default_value, 0);
  821. if (value != NULL) {
  822. ESP_LOGD(TAG, "%s: %s", key, value);
  823. inet_pton(AF_INET, value, target); /* access point is on a static IP */
  824. }
  825. FREE_AND_NULL(value);
  826. }
  827. esp_netif_t* network_wifi_config_ap() {
  828. esp_netif_ip_info_t info;
  829. esp_err_t err = ESP_OK;
  830. char* value = NULL;
  831. wifi_config_t ap_config = {
  832. .ap = {
  833. .ssid_len = 0,
  834. },
  835. };
  836. ESP_LOGI(TAG, "Configuring Access Point.");
  837. if (!wifi_ap_netif) {
  838. wifi_ap_netif = esp_netif_create_default_wifi_ap();
  839. }
  840. network_wifi_set_ipv4val("ap_ip_address", DEFAULT_AP_IP, (ip4_addr_t*)&info.ip);
  841. network_wifi_set_ipv4val("ap_ip_gateway", CONFIG_DEFAULT_AP_GATEWAY, (ip4_addr_t*)&info.gw);
  842. network_wifi_set_ipv4val("ap_ip_netmask", CONFIG_DEFAULT_AP_NETMASK, (ip4_addr_t*)&info.netmask);
  843. /* In order to change the IP info structure, we have to first stop
  844. * the DHCP server on the new interface
  845. */
  846. network_start_stop_dhcps(wifi_ap_netif, false);
  847. ESP_LOGD(TAG, "Setting tcp_ip info for access point");
  848. if ((err = esp_netif_set_ip_info(wifi_ap_netif, &info)) != ESP_OK) {
  849. ESP_LOGE(TAG, "Setting tcp_ip info for interface TCPIP_ADAPTER_IF_AP. Error %s", esp_err_to_name(err));
  850. return wifi_ap_netif;
  851. }
  852. network_start_stop_dhcps(wifi_ap_netif, true);
  853. /*
  854. * Set Access Point configuration
  855. */
  856. value = config_alloc_get_default(NVS_TYPE_STR, "ap_ssid", CONFIG_DEFAULT_AP_SSID, 0);
  857. if (value != NULL) {
  858. strlcpy((char*)ap_config.ap.ssid, value, sizeof(ap_config.ap.ssid));
  859. ESP_LOGI(TAG, "AP SSID: %s", (char*)ap_config.ap.ssid);
  860. }
  861. FREE_AND_NULL(value);
  862. value = config_alloc_get_default(NVS_TYPE_STR, "ap_pwd", DEFAULT_AP_PASSWORD, 0);
  863. if (value != NULL) {
  864. strlcpy((char*)ap_config.ap.password, value, sizeof(ap_config.ap.password));
  865. ESP_LOGI(TAG, "AP Password: %s", (char*)ap_config.ap.password);
  866. }
  867. FREE_AND_NULL(value);
  868. value = config_alloc_get_default(NVS_TYPE_STR, "ap_channel", STR(CONFIG_DEFAULT_AP_CHANNEL), 0);
  869. if (value != NULL) {
  870. ESP_LOGD(TAG, "Channel: %s", value);
  871. ap_config.ap.channel = atoi(value);
  872. }
  873. FREE_AND_NULL(value);
  874. ap_config.ap.authmode = AP_AUTHMODE;
  875. ap_config.ap.ssid_hidden = DEFAULT_AP_SSID_HIDDEN;
  876. ap_config.ap.max_connection = DEFAULT_AP_MAX_CONNECTIONS;
  877. ap_config.ap.beacon_interval = DEFAULT_AP_BEACON_INTERVAL;
  878. ESP_LOGD(TAG, "Auth Mode: %d", ap_config.ap.authmode);
  879. ESP_LOGD(TAG, "SSID Hidden: %d", ap_config.ap.ssid_hidden);
  880. ESP_LOGD(TAG, "Max Connections: %d", ap_config.ap.max_connection);
  881. ESP_LOGD(TAG, "Beacon interval: %d", ap_config.ap.beacon_interval);
  882. const char* msg = "Setting wifi mode as WIFI_MODE_APSTA";
  883. ESP_LOGD(TAG, "%s", msg);
  884. if ((err = esp_wifi_set_mode(WIFI_MODE_APSTA)) != ESP_OK) {
  885. ESP_LOGE(TAG, "%s. Error %s", msg, esp_err_to_name(err));
  886. return wifi_ap_netif;
  887. }
  888. msg = "Setting wifi AP configuration for WIFI_IF_AP";
  889. ESP_LOGD(TAG, "%s", msg);
  890. if ((err = esp_wifi_set_config(WIFI_IF_AP, &ap_config)) != ESP_OK) /* stop AP DHCP server */
  891. {
  892. ESP_LOGE(TAG, "%s . Error %s", msg, esp_err_to_name(err));
  893. return wifi_ap_netif;
  894. }
  895. msg = "Setting wifi bandwidth";
  896. ESP_LOGD(TAG, "%s (%d)", msg, DEFAULT_AP_BANDWIDTH);
  897. if ((err = esp_wifi_set_bandwidth(WIFI_IF_AP, DEFAULT_AP_BANDWIDTH)) != ESP_OK) /* stop AP DHCP server */
  898. {
  899. ESP_LOGE(TAG, "%s failed. Error %s", msg, esp_err_to_name(err));
  900. return wifi_ap_netif;
  901. }
  902. msg = "Setting wifi power save";
  903. ESP_LOGD(TAG, "%s (%d)", msg, DEFAULT_STA_POWER_SAVE);
  904. if ((err = esp_wifi_set_ps(DEFAULT_STA_POWER_SAVE)) != ESP_OK) /* stop AP DHCP server */
  905. {
  906. ESP_LOGE(TAG, "%s failed. Error %s", msg, esp_err_to_name(err));
  907. return wifi_ap_netif;
  908. }
  909. ESP_LOGD(TAG, "Done configuring Soft Access Point");
  910. return wifi_ap_netif;
  911. }
  912. void network_wifi_filter_unique(wifi_ap_record_t* aplist, uint16_t* aps) {
  913. int total_unique;
  914. wifi_ap_record_t* first_free;
  915. total_unique = *aps;
  916. first_free = NULL;
  917. for (int i = 0; i < *aps - 1; i++) {
  918. wifi_ap_record_t* ap = &aplist[i];
  919. /* skip the previously removed APs */
  920. if (ap->ssid[0] == 0)
  921. continue;
  922. /* remove the identical SSID+authmodes */
  923. for (int j = i + 1; j < *aps; j++) {
  924. wifi_ap_record_t* ap1 = &aplist[j];
  925. if ((strcmp((const char*)ap->ssid, (const char*)ap1->ssid) == 0) &&
  926. (ap->authmode == ap1->authmode)) { /* same SSID, different auth mode is skipped */
  927. /* save the rssi for the display */
  928. if ((ap1->rssi) > (ap->rssi))
  929. ap->rssi = ap1->rssi;
  930. /* clearing the record */
  931. memset(ap1, 0, sizeof(wifi_ap_record_t));
  932. }
  933. }
  934. }
  935. /* reorder the list so APs follow each other in the list */
  936. for (int i = 0; i < *aps; i++) {
  937. wifi_ap_record_t* ap = &aplist[i];
  938. /* skipping all that has no name */
  939. if (ap->ssid[0] == 0) {
  940. /* mark the first free slot */
  941. if (first_free == NULL)
  942. first_free = ap;
  943. total_unique--;
  944. continue;
  945. }
  946. if (first_free != NULL) {
  947. memcpy(first_free, ap, sizeof(wifi_ap_record_t));
  948. memset(ap, 0, sizeof(wifi_ap_record_t));
  949. /* find the next free slot */
  950. for (int j = 0; j < *aps; j++) {
  951. if (aplist[j].ssid[0] == 0) {
  952. first_free = &aplist[j];
  953. break;
  954. }
  955. }
  956. }
  957. }
  958. /* update the length of the list */
  959. *aps = total_unique;
  960. }
  961. char* network_status_alloc_get_ap_list_json() {
  962. return cJSON_PrintUnformatted(accessp_cjson);
  963. }
  964. cJSON* network_manager_clear_ap_list_json(cJSON** old) {
  965. ESP_LOGV(TAG, "network_manager_clear_ap_list_json called");
  966. cJSON* root = network_wifi_get_new_array_json(old);
  967. ESP_LOGV(TAG, "network_manager_clear_ap_list_json done");
  968. return root;
  969. }
  970. esp_err_t network_wifi_built_known_ap_list() {
  971. if (network_status_lock_json_buffer(pdMS_TO_TICKS(1000))) {
  972. ESP_LOGD(TAG,"Building known AP list");
  973. accessp_cjson = network_manager_clear_ap_list_json(&accessp_cjson);
  974. network_wifi_generate_access_points_json(&accessp_cjson);
  975. network_status_unlock_json_buffer();
  976. ESP_LOGD(TAG, "Done building ap JSON list");
  977. } else {
  978. ESP_LOGE(TAG, "Failed to lock json buffer");
  979. return ESP_FAIL;
  980. }
  981. return ESP_OK;
  982. }
  983. esp_err_t wifi_scan_done() {
  984. esp_err_t err = ESP_OK;
  985. /* As input param, it stores max AP number ap_records can hold. As output param, it receives the actual AP number this API returns.
  986. * As a consequence, ap_num MUST be reset to MAX_AP_NUM at every scan */
  987. ESP_LOGD(TAG, "Getting AP list records");
  988. ap_num = MAX_AP_NUM;
  989. if ((err = esp_wifi_scan_get_ap_num(&ap_num)) != ESP_OK) {
  990. ESP_LOGE(TAG, "Failed to retrieve scan results count. Error %s", esp_err_to_name(err));
  991. return err;
  992. }
  993. FREE_AND_NULL(accessp_records);
  994. if (ap_num > 0) {
  995. accessp_records = (wifi_ap_record_t*)malloc_init_external(sizeof(wifi_ap_record_t) * ap_num);
  996. if ((err = esp_wifi_scan_get_ap_records(&ap_num, accessp_records)) != ESP_OK) {
  997. ESP_LOGE(TAG, "Failed to retrieve scan results list. Error %s", esp_err_to_name(err));
  998. return err;
  999. }
  1000. /* make sure the http server isn't trying to access the list while it gets refreshed */
  1001. ESP_LOGD(TAG, "Preparing to build ap JSON list");
  1002. if (network_status_lock_json_buffer(pdMS_TO_TICKS(1000))) {
  1003. /* Will remove the duplicate SSIDs from the list and update ap_num */
  1004. network_wifi_filter_unique(accessp_records, &ap_num);
  1005. network_wifi_set_found_ap();
  1006. network_wifi_generate_access_points_json(&accessp_cjson);
  1007. network_status_unlock_json_buffer();
  1008. ESP_LOGD(TAG, "Done building ap JSON list");
  1009. } else {
  1010. ESP_LOGE(TAG, "could not get access to json mutex in wifi_scan");
  1011. err = ESP_FAIL;
  1012. }
  1013. } else {
  1014. //
  1015. ESP_LOGD(TAG, "No AP Found. Emptying the list.");
  1016. accessp_cjson = network_wifi_get_new_array_json(&accessp_cjson);
  1017. }
  1018. return err;
  1019. }
  1020. bool is_wifi_up() {
  1021. return wifi_netif != NULL;
  1022. }
  1023. esp_err_t network_wifi_start_scan() {
  1024. wifi_scan_config_t scan_config = {
  1025. .ssid = 0,
  1026. .bssid = 0,
  1027. .channel = 0,
  1028. .scan_type = WIFI_SCAN_TYPE_ACTIVE,
  1029. .show_hidden = true};
  1030. esp_err_t err = ESP_OK;
  1031. ESP_LOGI(TAG, "Initiating wifi network scan");
  1032. if (!is_wifi_up()) {
  1033. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Wifi not started. Cannot scan");
  1034. return ESP_FAIL;
  1035. }
  1036. /* if a scan is already in progress this message is simply ignored thanks to the WIFI_MANAGER_SCAN_BIT uxBit */
  1037. if ((err = esp_wifi_scan_start(&scan_config, false)) != ESP_OK) {
  1038. ESP_LOGW(TAG, "Unable to start scan; %s ", esp_err_to_name(err));
  1039. // set_status_message(WARNING, "Wifi Connecting. Cannot start scan.");
  1040. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Scanning failed: %s", esp_err_to_name(err));
  1041. }
  1042. return err;
  1043. }
  1044. bool network_wifi_is_ap_mode() {
  1045. wifi_mode_t mode;
  1046. /* update config to latest and attempt connection */
  1047. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_AP;
  1048. }
  1049. bool network_wifi_is_sta_mode() {
  1050. wifi_mode_t mode;
  1051. /* update config to latest and attempt connection */
  1052. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_STA;
  1053. }
  1054. bool network_wifi_is_ap_sta_mode() {
  1055. wifi_mode_t mode;
  1056. /* update config to latest and attempt connection */
  1057. return esp_wifi_get_mode(&mode) == ESP_OK && mode == WIFI_MODE_APSTA;
  1058. }
  1059. esp_err_t network_wifi_connect(const char* ssid, const char* password) {
  1060. esp_err_t err = ESP_OK;
  1061. wifi_config_t config;
  1062. memset(&config, 0x00, sizeof(config));
  1063. ESP_LOGD(TAG, "network_wifi_connect");
  1064. if (!is_wifi_up()) {
  1065. messaging_post_message(MESSAGING_WARNING, MESSAGING_CLASS_SYSTEM, "Wifi not started. Cannot connect");
  1066. network_wifi_set_connect_state(NETWORK_WIFI_STATE_DOWN);
  1067. return ESP_FAIL;
  1068. }
  1069. if (!ssid || !password || strlen(ssid) == 0) {
  1070. ESP_LOGE(TAG, "Cannot connect wifi. wifi config is null!");
  1071. network_wifi_set_connect_state(NETWORK_WIFI_STATE_INVALID_CONFIG);
  1072. return ESP_ERR_INVALID_ARG;
  1073. }
  1074. wifi_mode_t wifi_mode;
  1075. err = esp_wifi_get_mode(&wifi_mode);
  1076. if (err == ESP_ERR_WIFI_NOT_INIT) {
  1077. ESP_LOGW(TAG, "Wifi not initialized. Attempting to start sta mode");
  1078. network_wifi_start();
  1079. } else if (err != ESP_OK) {
  1080. ESP_LOGE(TAG, "Could not retrieve wifi mode : %s", esp_err_to_name(err));
  1081. } else if (wifi_mode != WIFI_MODE_STA && wifi_mode != WIFI_MODE_APSTA) {
  1082. ESP_LOGD(TAG, "Changing wifi mode to STA");
  1083. err = network_wifi_set_sta_mode();
  1084. if (err != ESP_OK) {
  1085. ESP_LOGE(TAG, "Could not set mode to STA. Cannot connect to SSID %s", ssid);
  1086. return err;
  1087. }
  1088. }
  1089. // copy configuration and connect
  1090. strlcpy((char*)config.sta.ssid, ssid, sizeof(config.sta.ssid));
  1091. if (password) {
  1092. strlcpy((char*)config.sta.password, password, sizeof(config.sta.password));
  1093. }
  1094. // First Disconnect
  1095. esp_wifi_disconnect();
  1096. config.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
  1097. if ((err = esp_wifi_set_config(WIFI_IF_STA, &config)) != ESP_OK) {
  1098. network_wifi_set_connect_state(NETWORK_WIFI_STATE_FAILED);
  1099. ESP_LOGE(TAG, "Failed to set STA configuration. Error %s", esp_err_to_name(err));
  1100. }
  1101. if (err == ESP_OK) {
  1102. ESP_LOGI(TAG, "Wifi Connecting to %s...", ssid);
  1103. if ((err = esp_wifi_connect()) != ESP_OK) {
  1104. ESP_LOGE(TAG, "Failed to initiate wifi connection. Error %s", esp_err_to_name(err));
  1105. network_wifi_set_connect_state(NETWORK_WIFI_STATE_FAILED);
  1106. }
  1107. else{
  1108. network_wifi_set_connect_state(NETWORK_WIFI_STATE_CONNECTING);
  1109. }
  1110. }
  1111. return err;
  1112. }
  1113. esp_err_t network_wifi_connect_next_in_range(){
  1114. const char * ssid = network_wifi_get_next_ap_in_range();
  1115. if(ssid){
  1116. return network_wifi_connect_ssid(ssid);
  1117. }
  1118. return ESP_FAIL;
  1119. }
  1120. esp_err_t network_wifi_connect_ssid(const char* ssid) {
  1121. known_access_point_t* item = network_wifi_get_ap_entry(ssid);
  1122. if (item) {
  1123. item->last_try = (esp_timer_get_time() / 1000);
  1124. return network_wifi_connect(item->ssid, item->password);
  1125. }
  1126. return ESP_FAIL;
  1127. }
  1128. esp_err_t network_wifi_connect_active_ssid() {
  1129. const wifi_sta_config_t* config = network_wifi_load_active_config();
  1130. if (config) {
  1131. return network_wifi_connect(ssid_string(config), password_string(config));
  1132. }
  1133. return ESP_FAIL;
  1134. }
  1135. void network_wifi_clear_config() {
  1136. /* erase configuration */
  1137. const wifi_sta_config_t* sta = network_wifi_get_active_config();
  1138. network_wifi_delete_ap(ssid_string(sta));
  1139. esp_err_t err = ESP_OK;
  1140. if ((err = esp_wifi_disconnect()) != ESP_OK) {
  1141. ESP_LOGW(TAG, "Could not disconnect from deleted network : %s", esp_err_to_name(err));
  1142. }
  1143. }
  1144. char* get_disconnect_code_desc(uint8_t reason) {
  1145. switch (reason) {
  1146. ENUM_TO_STRING(WIFI_REASON_UNSPECIFIED);
  1147. ENUM_TO_STRING(WIFI_REASON_AUTH_EXPIRE);
  1148. ENUM_TO_STRING(WIFI_REASON_AUTH_LEAVE);
  1149. ENUM_TO_STRING(WIFI_REASON_ASSOC_EXPIRE);
  1150. ENUM_TO_STRING(WIFI_REASON_ASSOC_TOOMANY);
  1151. ENUM_TO_STRING(WIFI_REASON_NOT_AUTHED);
  1152. ENUM_TO_STRING(WIFI_REASON_NOT_ASSOCED);
  1153. ENUM_TO_STRING(WIFI_REASON_ASSOC_LEAVE);
  1154. ENUM_TO_STRING(WIFI_REASON_ASSOC_NOT_AUTHED);
  1155. ENUM_TO_STRING(WIFI_REASON_DISASSOC_PWRCAP_BAD);
  1156. ENUM_TO_STRING(WIFI_REASON_DISASSOC_SUPCHAN_BAD);
  1157. ENUM_TO_STRING(WIFI_REASON_IE_INVALID);
  1158. ENUM_TO_STRING(WIFI_REASON_MIC_FAILURE);
  1159. ENUM_TO_STRING(WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT);
  1160. ENUM_TO_STRING(WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT);
  1161. ENUM_TO_STRING(WIFI_REASON_IE_IN_4WAY_DIFFERS);
  1162. ENUM_TO_STRING(WIFI_REASON_GROUP_CIPHER_INVALID);
  1163. ENUM_TO_STRING(WIFI_REASON_PAIRWISE_CIPHER_INVALID);
  1164. ENUM_TO_STRING(WIFI_REASON_AKMP_INVALID);
  1165. ENUM_TO_STRING(WIFI_REASON_UNSUPP_RSN_IE_VERSION);
  1166. ENUM_TO_STRING(WIFI_REASON_INVALID_RSN_IE_CAP);
  1167. ENUM_TO_STRING(WIFI_REASON_802_1X_AUTH_FAILED);
  1168. ENUM_TO_STRING(WIFI_REASON_CIPHER_SUITE_REJECTED);
  1169. ENUM_TO_STRING(WIFI_REASON_INVALID_PMKID);
  1170. ENUM_TO_STRING(WIFI_REASON_BEACON_TIMEOUT);
  1171. ENUM_TO_STRING(WIFI_REASON_NO_AP_FOUND);
  1172. ENUM_TO_STRING(WIFI_REASON_AUTH_FAIL);
  1173. ENUM_TO_STRING(WIFI_REASON_ASSOC_FAIL);
  1174. ENUM_TO_STRING(WIFI_REASON_HANDSHAKE_TIMEOUT);
  1175. ENUM_TO_STRING(WIFI_REASON_CONNECTION_FAIL);
  1176. ENUM_TO_STRING(WIFI_REASON_AP_TSF_RESET);
  1177. ENUM_TO_STRING(WIFI_REASON_ROAMING);
  1178. }
  1179. return "";
  1180. }