network_manager.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. /*
  2. Copyright (c) 2017-2021 Sebastien L
  3. */
  4. #ifdef NETWORK_MANAGER_LOG_LEVEL
  5. #define LOG_LOCAL_LEVEL NETWORK_MANAGER_LOG_LEVEL
  6. #endif
  7. #include "network_manager.h"
  8. #include <stdbool.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include "network_ethernet.h"
  13. #include "network_status.h"
  14. #include "network_wifi.h"
  15. #include "dns_server.h"
  16. #include "esp_log.h"
  17. #include "esp_system.h"
  18. #include "freertos/FreeRTOS.h"
  19. #include "platform_esp32.h"
  20. #include "esp_netif.h"
  21. #include "freertos/task.h"
  22. #include "cJSON.h"
  23. #include "cmd_system.h"
  24. #include "esp_app_format.h"
  25. #include "esp_event.h"
  26. #include "esp_ota_ops.h"
  27. #include "esp_wifi.h"
  28. #include "esp_wifi_types.h"
  29. #include "lwip/api.h"
  30. #include "lwip/err.h"
  31. #include "lwip/ip4_addr.h"
  32. #include "lwip/netdb.h"
  33. #include "mdns.h"
  34. #include "messaging.h"
  35. #include "platform_config.h"
  36. #include "tools.h"
  37. #include "trace.h"
  38. #include "accessors.h"
  39. #include "esp_err.h"
  40. #include "http_server_handlers.h"
  41. #include "network_manager.h"
  42. QueueHandle_t network_queue;
  43. BaseType_t network_task_handle;
  44. static const char TAG[] = "network";
  45. static TaskHandle_t task_network_manager = NULL;
  46. RTC_NOINIT_ATTR static bool s_wifi_prioritized;
  47. extern esp_reset_reason_t xReason;
  48. typedef struct network_callback {
  49. network_status_reached_cb cb;
  50. nm_state_t state;
  51. int sub_state;
  52. const char* from;
  53. SLIST_ENTRY(network_callback)
  54. next; //!< next callback
  55. } network_callback_t;
  56. /** linked list of command structures */
  57. static SLIST_HEAD(cb_list, network_callback) s_cb_list;
  58. network_t NM;
  59. //! Create and initialize the array of state machines.
  60. state_machine_t* const SM[] = {(state_machine_t*)&NM};
  61. static void network_timer_cb(void* timer_id);
  62. int get_root_id(const state_t * state);
  63. const state_t* get_root( const state_t* const state);
  64. static void network_task(void* pvParameters);
  65. void network_start_stop_dhcp_client(esp_netif_t* netif, bool start) {
  66. tcpip_adapter_dhcp_status_t status;
  67. esp_err_t err = ESP_OK;
  68. ESP_LOGD(TAG, "Checking if DHCP client for STA interface is running");
  69. if (!netif) {
  70. ESP_LOGE(TAG, "Invalid adapter. Cannot start/stop dhcp. ");
  71. return;
  72. }
  73. if((err=esp_netif_dhcpc_get_status(netif, &status))!=ESP_OK){
  74. ESP_LOGE(TAG,"Error retrieving dhcp status : %s", esp_err_to_name(err));
  75. return;
  76. }
  77. switch (status)
  78. {
  79. case ESP_NETIF_DHCP_STARTED:
  80. if(start){
  81. ESP_LOGD(TAG, "DHCP client already started");
  82. }
  83. else {
  84. ESP_LOGI(TAG, "Stopping DHCP client");
  85. err = esp_netif_dhcpc_stop(netif);
  86. if(err!=ESP_OK){
  87. ESP_LOGE(TAG,"Error stopping DHCP Client : %s",esp_err_to_name(err));
  88. }
  89. }
  90. break;
  91. case ESP_NETIF_DHCP_STOPPED:
  92. if(start){
  93. ESP_LOGI(TAG, "Starting DHCP client");
  94. err = esp_netif_dhcpc_start(netif);
  95. if(err!=ESP_OK){
  96. ESP_LOGE(TAG,"Error stopping DHCP Client : %s",esp_err_to_name(err));
  97. }
  98. }
  99. else {
  100. ESP_LOGI(TAG, "DHCP client already started");
  101. }
  102. break;
  103. case ESP_NETIF_DHCP_INIT:
  104. if(start){
  105. ESP_LOGI(TAG, "Starting DHCP client");
  106. err = esp_netif_dhcpc_start(netif);
  107. if(err!=ESP_OK){
  108. ESP_LOGE(TAG,"Error stopping DHCP Client : %s",esp_err_to_name(err));
  109. }
  110. }
  111. else {
  112. ESP_LOGI(TAG, "Stopping DHCP client");
  113. err = esp_netif_dhcpc_stop(netif);
  114. if(err!=ESP_OK){
  115. ESP_LOGE(TAG,"Error stopping DHCP Client : %s",esp_err_to_name(err));
  116. }
  117. }
  118. break;
  119. default:
  120. ESP_LOGW(TAG,"Unknown DHCP status");
  121. break;
  122. }
  123. }
  124. void network_start_stop_dhcps(esp_netif_t* netif, bool start) {
  125. tcpip_adapter_dhcp_status_t status;
  126. esp_err_t err = ESP_OK;
  127. ESP_LOGD(TAG, "Checking if DHCP server is running");
  128. if (!netif) {
  129. ESP_LOGE(TAG, "Invalid adapter. Cannot start/stop dhcp server. ");
  130. return;
  131. }
  132. if((err=esp_netif_dhcps_get_status(netif, &status))!=ESP_OK){
  133. ESP_LOGE(TAG,"Error retrieving dhcp server status : %s", esp_err_to_name(err));
  134. return;
  135. }
  136. switch (status)
  137. {
  138. case ESP_NETIF_DHCP_STARTED:
  139. if(start){
  140. ESP_LOGD(TAG, "DHCP server already started");
  141. }
  142. else {
  143. ESP_LOGI(TAG, "Stopping DHCP server");
  144. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_netif_dhcps_stop(netif));
  145. }
  146. break;
  147. case ESP_NETIF_DHCP_STOPPED:
  148. if(start){
  149. ESP_LOGI(TAG, "Starting DHCP server");
  150. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_netif_dhcps_start(netif));
  151. }
  152. else {
  153. ESP_LOGI(TAG, "DHCP server already stopped");
  154. }
  155. break;
  156. case ESP_NETIF_DHCP_INIT:
  157. if(start){
  158. ESP_LOGI(TAG, "Starting DHCP server");
  159. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_netif_dhcps_start(netif));
  160. }
  161. else {
  162. ESP_LOGI(TAG, "Stopping DHCP server");
  163. ESP_ERROR_CHECK_WITHOUT_ABORT(esp_netif_dhcps_stop(netif));
  164. }
  165. break;
  166. default:
  167. ESP_LOGW(TAG,"Unknown DHCP status");
  168. break;
  169. }
  170. }
  171. /*********************************************************************************************
  172. * String conversion routines
  173. */
  174. #define ADD_ROOT(name,...) CASE_TO_STR(name);
  175. #define ADD_ROOT_LEAF(name,...) CASE_TO_STR(name);
  176. #define ADD_LEAF(name,...) CASE_TO_STR(name);
  177. #define ADD_EVENT(name) CASE_TO_STR(name);
  178. #define ADD_FIRST_EVENT(name) CASE_TO_STR(name);
  179. static const char* state_to_string(const state_t * state) {
  180. if(!state) {
  181. return "";
  182. }
  183. switch (state->Parent?state->Parent->Id:state->Id) {
  184. ALL_NM_STATE
  185. default:
  186. break;
  187. }
  188. return "Unknown";
  189. }
  190. static const char* wifi_state_to_string(mn_wifi_active_state_t state) {
  191. switch (state) {
  192. ALL_WIFI_STATE(,)
  193. default:
  194. break;
  195. }
  196. return "Unknown";
  197. }
  198. static const char* eth_state_to_string(mn_eth_active_state_t state) {
  199. switch (state) {
  200. ALL_ETH_STATE(,)
  201. default:
  202. break;
  203. }
  204. return "Unknown";
  205. }
  206. static const char* wifi_configuring_state_to_string(mn_wifi_configuring_state_t state) {
  207. switch (state) {
  208. ALL_WIFI_CONFIGURING_STATE(,)
  209. default:
  210. break;
  211. }
  212. return "Unknown";
  213. }
  214. static const char* sub_state_to_string(const state_t * state) {
  215. if(!state) {
  216. return "N/A";
  217. }
  218. int root_id = get_root_id(state);
  219. switch (root_id)
  220. {
  221. case NETWORK_ETH_ACTIVE_STATE:
  222. return eth_state_to_string(state->Id);
  223. break;
  224. case NETWORK_WIFI_ACTIVE_STATE:
  225. return wifi_state_to_string(state->Id);
  226. case NETWORK_WIFI_CONFIGURING_ACTIVE_STATE:
  227. return wifi_configuring_state_to_string(state->Id);
  228. default:
  229. break;
  230. }
  231. return "*";
  232. }
  233. static const char* event_to_string(network_event_t state) {
  234. switch (state) {
  235. ALL_NM_EVENTS
  236. default:
  237. break;
  238. }
  239. return "Unknown";
  240. }
  241. #undef ADD_EVENT
  242. #undef ADD_FIRST_EVENT
  243. #undef ADD_ROOT
  244. #undef ADD_ROOT_LEAF
  245. #undef ADD_LEAF
  246. typedef struct {
  247. int parent_state;
  248. int sub_state_last ;
  249. } max_sub_states_t;
  250. static const max_sub_states_t state_max[] = {
  251. { .parent_state = NETWORK_INSTANTIATED_STATE, .sub_state_last = 0 },
  252. {.parent_state = NETWORK_ETH_ACTIVE_STATE, .sub_state_last = TOTAL_ETH_ACTIVE_STATE-1 },
  253. {.parent_state = NETWORK_WIFI_ACTIVE_STATE, .sub_state_last = TOTAL_WIFI_ACTIVE_STATE-1 },
  254. {.parent_state = WIFI_CONFIGURING_STATE, .sub_state_last = TOTAL_WIFI_CONFIGURING_STATE-1 },
  255. {.parent_state = WIFI_CONFIGURING_STATE, .sub_state_last = TOTAL_WIFI_CONFIGURING_STATE-1 },
  256. {.parent_state =-1}
  257. };
  258. void network_start() {
  259. if(cold_boot){
  260. ESP_LOGI(TAG, "Setting wifi priotitized flag to false");
  261. s_wifi_prioritized = false;
  262. }
  263. ESP_LOGD(TAG, " Creating message queue");
  264. network_queue = xQueueCreate(3, sizeof(queue_message));
  265. ESP_LOGD(TAG, " Creating network manager task");
  266. network_task_handle = xTaskCreate(&network_task, "network", 4096, NULL, WIFI_MANAGER_TASK_PRIORITY, &task_network_manager);
  267. }
  268. static void event_logger(uint32_t state_machine, uint32_t state, uint32_t event) {
  269. ESP_LOGD(TAG, "Handling network manager event state Id %d->[%s]", state, event_to_string(event));
  270. }
  271. static const char * get_state_machine_result_string(state_machine_result_t result) {
  272. switch(result) {
  273. case EVENT_HANDLED:
  274. return "EVENT_HANDLED";
  275. case EVENT_UN_HANDLED:
  276. return "EVENT_UN_HANDLED";
  277. case TRIGGERED_TO_SELF:
  278. return "TRIGGERED_TO_SELF";
  279. }
  280. return "Unknown";
  281. }
  282. static void result_logger(uint32_t state, state_machine_result_t result) {
  283. ESP_LOGD(TAG, "Network Manager Result: %s, New State id: %d", get_state_machine_result_string(result) , state);
  284. }
  285. static void network_task(void* pvParameters) {
  286. queue_message msg;
  287. BaseType_t xStatus;
  288. initialize_network_handlers((state_machine_t*)&NM);
  289. network_async(EN_START);
  290. /* main processing loop */
  291. for (;;) {
  292. xStatus = xQueueReceive(network_queue, &msg, portMAX_DELAY);
  293. if (xStatus == pdPASS) {
  294. // pass the event to the sync processor
  295. NM.event_parameters = &msg;
  296. NM.Machine.Event = msg.trigger;
  297. if (dispatch_event(SM, 1, event_logger, result_logger) == EVENT_UN_HANDLED) {
  298. network_manager_format_from_to_states(ESP_LOG_ERROR,"Unhandled Event",NULL,NM.Machine.State,msg.trigger,false,"network manager");
  299. }
  300. } /* end of if status=pdPASS */
  301. } /* end of for loop */
  302. vTaskDelete(NULL);
  303. }
  304. int get_max_substate(nm_state_t state){
  305. for(int i=0;state_max[i].parent_state!=-1;i++){
  306. if(state_max[i].parent_state == state){
  307. return state_max[i].sub_state_last;
  308. }
  309. }
  310. return -1;
  311. }
  312. esp_err_t network_register_state_callback(nm_state_t state,int sub_state, const char* from, network_status_reached_cb cb) {
  313. network_callback_t* item = NULL;
  314. if (!cb) {
  315. return ESP_ERR_INVALID_ARG;
  316. }
  317. item = calloc(1, sizeof(*item));
  318. if (item == NULL) {
  319. return ESP_ERR_NO_MEM;
  320. }
  321. if(sub_state != -1 && sub_state>get_max_substate(state)){
  322. // sub state has to be valid
  323. return ESP_ERR_INVALID_ARG;
  324. }
  325. item->state = state;
  326. item->cb = cb;
  327. item->from = from;
  328. item->sub_state=sub_state;
  329. network_callback_t* last = SLIST_FIRST(&s_cb_list);
  330. if (last == NULL) {
  331. SLIST_INSERT_HEAD(&s_cb_list, item, next);
  332. } else {
  333. network_callback_t* it;
  334. while ((it = SLIST_NEXT(last, next)) != NULL) {
  335. last = it;
  336. }
  337. SLIST_INSERT_AFTER(last, item, next);
  338. }
  339. return ESP_OK;
  340. }
  341. const state_t* get_root( const state_t* const state){
  342. if(!state) return NULL;
  343. return state->Parent==NULL?state: get_root(state->Parent);
  344. }
  345. int get_root_id(const state_t * state){
  346. if(!state) return -1;
  347. return state->Parent==NULL?state->Id: get_root_id(state->Parent);
  348. }
  349. static bool is_root_state(const state_t * state){
  350. return state->Parent==NULL;
  351. }
  352. static bool is_current_state(const state_t* state, nm_state_t state_id, int sub_state_id){
  353. return get_root(state)->Id == state_id && (sub_state_id==-1 || (!is_root_state(state) && state->Id == sub_state_id) );
  354. }
  355. void network_execute_cb(state_machine_t* const state_machine, const char * caller) {
  356. network_callback_t* it;
  357. SLIST_FOREACH(it, &s_cb_list, next) {
  358. if (is_current_state(state_machine->State,it->state, it->sub_state)) {
  359. char * cb_prefix= messaging_alloc_format_string("BEGIN Executing Callback %s", it->from) ;
  360. NETWORK_DEBUG_STATE_MACHINE(true,STR_OR_BLANK(cb_prefix),state_machine,false, STR_OR_BLANK(caller));
  361. FREE_AND_NULL(cb_prefix);
  362. it->cb((nm_state_t)get_root(state_machine->State)->Id, is_root_state(state_machine->State)?-1:state_machine->State->Id);
  363. cb_prefix= messaging_alloc_format_string("END Executing Callback %s", it->from) ;
  364. NETWORK_DEBUG_STATE_MACHINE(false,STR_OR_BLANK(cb_prefix),state_machine,false, STR_OR_BLANK(caller));
  365. FREE_AND_NULL(cb_prefix);
  366. }
  367. }
  368. }
  369. bool network_is_wifi_prioritized() {
  370. eth_config_t eth_config;
  371. config_eth_init(&eth_config);
  372. // char* prioritize = (char*)config_alloc_get_default(NVS_TYPE_STR, "prio_wifi", "N", 0);
  373. // bool result = strcasecmp("N", prioritize);
  374. bool result = s_wifi_prioritized;
  375. if(result){
  376. result = network_wifi_get_known_count()>0 || !eth_config.valid;
  377. ESP_LOGD(TAG,"Wifi is prioritized with %d known access points.%s %s",network_wifi_get_known_count(),eth_config.valid?" And a valid ethernet adapter":"",result?"Wifi prioritized":"Ethernet prioritized");
  378. }
  379. return result;
  380. }
  381. void network_prioritize_wifi(bool activate) {
  382. if(s_wifi_prioritized == activate) return;
  383. s_wifi_prioritized = activate;
  384. ESP_LOGI(TAG,"Wifi is %s prioritized",activate?"":"not");
  385. // if (network_is_wifi_prioritized() != activate) {
  386. // ESP_LOGW(TAG, "Wifi will %s be prioritized on next boot", activate ? "" : "NOT");
  387. // config_set_value(NVS_TYPE_STR, "prio_wifi", activate ? "Y" : "N");
  388. // }
  389. }
  390. void network_manager_format_state_machine(esp_log_level_t level, const char* prefix, state_machine_t* state_machine, bool show_source, const char * caller) {
  391. state_t const* source_state = NULL;
  392. state_t const* current_state = NULL;
  393. network_event_t event = -1;
  394. MEMTRACE_PRINT_DELTA();
  395. if (state_machine) {
  396. source_state = ((network_t *)state_machine)->source_state;
  397. current_state = state_machine->State;
  398. event = state_machine->Event;
  399. network_manager_format_from_to_states(level, prefix, source_state, current_state, event, show_source,caller);
  400. }
  401. else {
  402. ESP_LOG_LEVEL(level, TAG, "%s - %s -> [%s]",
  403. STR_OR_BLANK(caller),
  404. prefix,
  405. event_to_string(event));
  406. }
  407. }
  408. void network_manager_format_from_to_states(esp_log_level_t level, const char* prefix, const state_t * from_state,const state_t * current_state, network_event_t event,bool show_source, const char * caller) {
  409. const char* source_state = "";
  410. const char* source_sub_state = "";
  411. const char* state = "N/A";
  412. const char* sub_state = "N/A";
  413. if (current_state) {
  414. state = state_to_string(current_state);
  415. sub_state = sub_state_to_string(current_state);
  416. }
  417. if (!from_state) {
  418. source_state = "N/A";
  419. } else {
  420. source_state = state_to_string(from_state);
  421. source_sub_state = sub_state_to_string(from_state);
  422. }
  423. if (show_source) {
  424. ESP_LOG_LEVEL(level, TAG, "%s %s %s(%s)->%s(%s) [%s]",
  425. STR_OR_BLANK(caller),
  426. prefix,
  427. source_state,
  428. source_sub_state,
  429. state,
  430. sub_state,
  431. event_to_string(event));
  432. } else {
  433. ESP_LOG_LEVEL(level, TAG, "%s %s %s(%s) [%s]",
  434. STR_OR_BLANK(caller),
  435. prefix,
  436. state,
  437. sub_state,
  438. event_to_string(event));
  439. }
  440. }
  441. void network_async(network_event_t trigger) {
  442. queue_message msg;
  443. memset(&msg,0x00,sizeof(msg));
  444. msg.trigger = trigger;
  445. ESP_LOGD(TAG, "Posting event %s directly", event_to_string(trigger));
  446. xQueueSendToBack(network_queue, &msg, portMAX_DELAY);
  447. }
  448. void network_async_fail() {
  449. network_async(EN_FAIL);
  450. }
  451. void network_async_success() {
  452. network_async(EN_SUCCESS);
  453. }
  454. void network_async_connected(){
  455. network_async(EN_CONNECTED);
  456. }
  457. void network_async_link_up() {
  458. network_async(EN_LINK_UP);
  459. }
  460. void network_async_link_down() {
  461. network_async(EN_LINK_DOWN);
  462. }
  463. void network_async_configure() {
  464. network_async(EN_CONFIGURE);
  465. }
  466. void network_async_got_ip() {
  467. network_async(EN_GOT_IP);
  468. }
  469. void network_async_eth_got_ip() {
  470. network_async(EN_ETH_GOT_IP);
  471. }
  472. void network_async_timer() {
  473. network_async(EN_TIMER);
  474. }
  475. void network_async_start() {
  476. network_async(EN_START);
  477. }
  478. void network_async_scan() {
  479. network_async(EN_SCAN);
  480. }
  481. void network_async_update_status() {
  482. network_async(EN_UPDATE_STATUS);
  483. }
  484. void network_async_delete() {
  485. network_async(EN_DELETE);
  486. }
  487. void network_async_scan_done() {
  488. network_async(EN_SCAN_DONE);
  489. }
  490. void network_async_connect(const char * ssid, const char * password) {
  491. queue_message msg;
  492. memset(&msg,0x00,sizeof(msg));
  493. msg.trigger = EN_CONNECT_NEW;
  494. msg.ssid = strdup_psram(ssid);
  495. if(password && strlen(password) >0){
  496. msg.password = strdup_psram(password);
  497. }
  498. ESP_LOGD(TAG, "Posting event %s", event_to_string(msg.trigger));
  499. xQueueSendToBack(network_queue, &msg, portMAX_DELAY);
  500. }
  501. void network_async_lost_connection(wifi_event_sta_disconnected_t* disconnected_event) {
  502. queue_message msg;
  503. memset(&msg,0x00,sizeof(msg));
  504. msg.trigger = EN_LOST_CONNECTION;
  505. ESP_LOGD(TAG, "Posting event %s", event_to_string(msg.trigger));
  506. msg.disconnected_event = clone_obj_psram(disconnected_event,sizeof(wifi_event_sta_disconnected_t));
  507. if(msg.disconnected_event){
  508. xQueueSendToBack(network_queue, &msg, portMAX_DELAY);
  509. }
  510. else {
  511. ESP_LOGE(TAG,"Unable to post lost connection event.");
  512. }
  513. }
  514. void network_async_reboot(reboot_type_t rtype) {
  515. queue_message msg;
  516. memset(&msg,0x00,sizeof(msg));
  517. msg.trigger = EN_REBOOT;
  518. msg.rtype = rtype;
  519. ESP_LOGD(TAG, "Posting event %s - type %d", event_to_string(msg.trigger),rtype);
  520. xQueueSendToBack(network_queue, &msg, portMAX_DELAY);
  521. }
  522. void network_reboot_ota(char* url) {
  523. queue_message msg;
  524. memset(&msg,0x00,sizeof(msg));
  525. if (url == NULL) {
  526. msg.trigger = EN_REBOOT;
  527. msg.rtype = OTA;
  528. ESP_LOGD(TAG, "Posting event %s - type %d", event_to_string(msg.trigger),msg.rtype);
  529. } else {
  530. msg.trigger = EN_REBOOT_URL;
  531. ESP_LOGD(TAG, "Posting event %s - type reboot URL", event_to_string(msg.trigger));
  532. msg.strval = strdup_psram(url);
  533. }
  534. xQueueSendToBack(network_queue, &msg, portMAX_DELAY);
  535. }
  536. network_t* network_get_state_machine() {
  537. return &NM;
  538. }
  539. static void network_timer_cb(void* timer_id) {
  540. network_async_timer();
  541. }
  542. esp_netif_t* network_get_active_interface() {
  543. if (NM.wifi_ap_netif && (network_wifi_is_ap_mode() || network_wifi_is_ap_sta_mode())) {
  544. return NM.wifi_ap_netif;
  545. } else if (NM.wifi_netif && network_wifi_is_sta_mode()) {
  546. return NM.wifi_netif;
  547. }
  548. return NM.eth_netif;
  549. }
  550. bool network_is_interface_connected(esp_netif_t* interface) {
  551. esp_err_t err = ESP_OK;
  552. tcpip_adapter_ip_info_t ipInfo;
  553. if(!interface){
  554. return false;
  555. }
  556. err = network_get_ip_info_for_netif(interface, &ipInfo);
  557. if(err != ESP_OK){
  558. ESP_LOGD(TAG,"network_get_ip_info_for_netif returned %s", esp_err_to_name(err));
  559. }
  560. return ((err == ESP_OK) && (ipInfo.ip.addr != IPADDR_ANY));
  561. }
  562. static esp_netif_t* get_connected_interface() {
  563. esp_netif_t* interface = NULL;
  564. for (int i = 0; i < 4; i++) {
  565. switch (i) {
  566. case 0:
  567. // try the active interface
  568. interface = network_get_active_interface();
  569. break;
  570. case 1:
  571. interface = NM.wifi_ap_netif;
  572. break;
  573. case 2:
  574. interface = NM.wifi_netif;
  575. break;
  576. case 3:
  577. interface = NM.eth_netif;
  578. break;
  579. default:
  580. break;
  581. }
  582. if (interface && network_is_interface_connected(interface)) {
  583. ESP_LOGD(TAG,"Found connected interface in iteration #%d",i);
  584. return interface;
  585. }
  586. }
  587. ESP_LOGD(TAG,"No connected interface found");
  588. return NULL;
  589. }
  590. esp_err_t network_get_ip_info_for_netif(esp_netif_t* netif, tcpip_adapter_ip_info_t* ipInfo) {
  591. esp_netif_ip_info_t loc_ip_info;
  592. if (!ipInfo ) {
  593. ESP_LOGE(TAG, "Invalid pointer for ipInfo");
  594. return ESP_ERR_INVALID_ARG;
  595. }
  596. if (!netif) {
  597. ESP_LOGE(TAG, "Invalid pointer for netif");
  598. return ESP_ERR_INVALID_ARG;
  599. }
  600. memset(ipInfo,0x00,sizeof(tcpip_adapter_ip_info_t));
  601. esp_err_t err= esp_netif_get_ip_info(netif, &loc_ip_info);
  602. if(err==ESP_OK){
  603. ip4_addr_set(&(ipInfo->ip),&loc_ip_info.ip);
  604. ip4_addr_set(&(ipInfo->gw),&loc_ip_info.gw);
  605. ip4_addr_set(&(ipInfo->netmask),&loc_ip_info.netmask);
  606. }
  607. return err;
  608. }
  609. esp_err_t network_get_ip_info(tcpip_adapter_ip_info_t* ipInfo) {
  610. esp_netif_t* netif= get_connected_interface();
  611. if(netif){
  612. return network_get_ip_info_for_netif(netif,ipInfo);
  613. }
  614. return ESP_FAIL;
  615. }
  616. esp_err_t network_get_hostname(const char** hostname) {
  617. return esp_netif_get_hostname(get_connected_interface(), hostname);
  618. }
  619. void network_set_timer(uint16_t duration, const char * tag) {
  620. if (duration > 0) {
  621. if(tag){
  622. ESP_LOGD(TAG, "Setting timer tag to %s", tag);
  623. NM.timer_tag = strdup_psram(tag);
  624. }
  625. if (!NM.state_timer) {
  626. ESP_LOGD(TAG, "Starting %s timer with period of %u ms.", STR_OR_ALT(NM.timer_tag,"anonymous"), duration);
  627. NM.state_timer = xTimerCreate("background STA", pdMS_TO_TICKS(duration), pdFALSE, NULL, network_timer_cb);
  628. } else {
  629. ESP_LOGD(TAG, "Changing %s timer period to %u ms.", STR_OR_ALT(NM.timer_tag,"anonymous"),duration);
  630. xTimerChangePeriod(NM.state_timer, pdMS_TO_TICKS(duration), portMAX_DELAY);
  631. }
  632. xTimerStart(NM.state_timer, portMAX_DELAY);
  633. } else if (NM.state_timer) {
  634. ESP_LOGD(TAG,"Stopping timer %s",STR_OR_ALT(NM.timer_tag,"anonymous"));
  635. xTimerStop(NM.state_timer, portMAX_DELAY);
  636. FREE_AND_NULL(NM.timer_tag);
  637. }
  638. }
  639. void network_ip_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
  640. ip_event_got_ip_t* s = NULL;
  641. esp_netif_ip_info_t* ip_info = NULL;
  642. if (event_base != IP_EVENT)
  643. return;
  644. switch (event_id) {
  645. case IP_EVENT_ETH_GOT_IP:
  646. case IP_EVENT_STA_GOT_IP:
  647. s = (ip_event_got_ip_t*)event_data;
  648. ip_info = &s->ip_info;
  649. ESP_LOGI(TAG, "Got an IP address from interface %s. IP=" IPSTR ", Gateway=" IPSTR ", NetMask=" IPSTR ", %s",
  650. event_id == IP_EVENT_ETH_GOT_IP ? "Eth" : event_id == IP_EVENT_STA_GOT_IP ? "Wifi"
  651. : "Unknown",
  652. IP2STR(&ip_info->ip),
  653. IP2STR(&ip_info->gw),
  654. IP2STR(&ip_info->netmask),
  655. s->ip_changed ? "Address was changed" : "Address unchanged");
  656. network_async(event_id == IP_EVENT_ETH_GOT_IP ? EN_ETH_GOT_IP : EN_GOT_IP);
  657. break;
  658. case IP_EVENT_STA_LOST_IP:
  659. ESP_LOGD(TAG, "IP_EVENT_STA_LOST_IP");
  660. break;
  661. case IP_EVENT_AP_STAIPASSIGNED:
  662. ESP_LOGD(TAG, "IP_EVENT_AP_STAIPASSIGNED");
  663. break;
  664. case IP_EVENT_GOT_IP6:
  665. ESP_LOGD(TAG, "IP_EVENT_GOT_IP6");
  666. break;
  667. default:
  668. break;
  669. }
  670. }
  671. void network_set_hostname(esp_netif_t* interface) {
  672. esp_err_t err;
  673. ESP_LOGD(TAG, "Retrieving host name from nvs");
  674. char* host_name = (char*)config_alloc_get(NVS_TYPE_STR, "host_name");
  675. if (host_name == NULL) {
  676. ESP_LOGE(TAG, "Could not retrieve host name from nvs");
  677. } else {
  678. ESP_LOGD(TAG, "Setting host name to : %s", host_name);
  679. if ((err = esp_netif_set_hostname(interface, host_name)) != ESP_OK) {
  680. ESP_LOGE(TAG, "Unable to set host name. Error: %s", esp_err_to_name(err));
  681. }
  682. free(host_name);
  683. }
  684. }
  685. #define LOCAL_MAC_SIZE 20
  686. char* network_manager_alloc_get_mac_string(uint8_t mac[6]) {
  687. char* macStr = malloc_init_external(LOCAL_MAC_SIZE);
  688. if(macStr){
  689. snprintf(macStr, LOCAL_MAC_SIZE, MACSTR, MAC2STR(mac));
  690. }
  691. return macStr;
  692. }