network_manager.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #pragma once
  2. #include "esp_system.h"
  3. #include "esp_wifi.h"
  4. #include "esp_wifi_types.h"
  5. #include "squeezelite-ota.h"
  6. #include "cJSON.h"
  7. #include "esp_eth.h"
  8. #include "freertos/event_groups.h"
  9. #include "hsm.h"
  10. #include "esp_log.h"
  11. #include "network_services.h"
  12. #ifdef __cplusplus
  13. extern "C" {
  14. #endif
  15. //! List of oven events
  16. #define ALL_NM_EVENTS \
  17. ADD_FIRST_EVENT(EN_LINK_UP) \
  18. ADD_EVENT(EN_LINK_DOWN)\
  19. ADD_EVENT(EN_CONFIGURE)\
  20. ADD_EVENT(EN_GOT_IP)\
  21. ADD_EVENT(EN_ETH_GOT_IP)\
  22. ADD_EVENT(EN_DELETE)\
  23. ADD_EVENT(EN_TIMER)\
  24. ADD_EVENT(EN_START)\
  25. ADD_EVENT(EN_SCAN)\
  26. ADD_EVENT(EN_FAIL)\
  27. ADD_EVENT(EN_SUCCESS)\
  28. ADD_EVENT(EN_SCAN_DONE)\
  29. ADD_EVENT(EN_CONNECT)\
  30. ADD_EVENT(EN_CONNECT_NEW)\
  31. ADD_EVENT(EN_REBOOT)\
  32. ADD_EVENT(EN_REBOOT_URL)\
  33. ADD_EVENT(EN_LOST_CONNECTION)\
  34. ADD_EVENT(EN_ETHERNET_FALLBACK)\
  35. ADD_EVENT(EN_UPDATE_STATUS)\
  36. ADD_EVENT(EN_CONNECTED)
  37. #define ADD_EVENT(name) name,
  38. #define ADD_FIRST_EVENT(name) name=1,
  39. typedef enum {
  40. ALL_NM_EVENTS
  41. } network_event_t;
  42. #undef ADD_EVENT
  43. #undef ADD_FIRST_EVENT
  44. typedef enum {
  45. OTA,
  46. RECOVERY,
  47. RESTART,
  48. } reboot_type_t;
  49. typedef struct {
  50. network_event_t trigger;
  51. char * ssid;
  52. char * password;
  53. reboot_type_t rtype;
  54. char* strval;
  55. wifi_event_sta_disconnected_t* disconnected_event;
  56. esp_netif_t *netif;
  57. } queue_message;
  58. typedef struct
  59. {
  60. state_machine_t Machine; //!< Abstract state machine
  61. const state_t* source_state;
  62. bool ethernet_connected;
  63. TimerHandle_t state_timer;
  64. uint32_t STA_duration;
  65. int32_t total_connected_time;
  66. int64_t last_connected;
  67. uint16_t num_disconnect;
  68. uint16_t retries;
  69. bool wifi_connected;
  70. esp_netif_t *wifi_netif;
  71. esp_netif_t *eth_netif;
  72. esp_netif_t *wifi_ap_netif;
  73. uint16_t sta_polling_min_ms;
  74. uint16_t sta_polling_max_ms;
  75. uint16_t ap_duration_ms;
  76. uint16_t eth_link_down_reboot_ms;
  77. uint16_t dhcp_timeout;
  78. uint16_t wifi_dhcp_fail_ms;
  79. queue_message * event_parameters;
  80. char * timer_tag;
  81. } network_t;
  82. /*
  83. * --------------------- External function prototype ---------------------
  84. */
  85. void network_start();
  86. network_t * network_get_state_machine();
  87. void network_event_simple(network_event_t trigger);
  88. void network_event(network_event_t trigger, void* param);
  89. void network_async_event(network_event_t trigger, void* param);
  90. void network_async(network_event_t trigger);
  91. void network_async_fail();
  92. void network_async_success();
  93. void network_async_link_up();
  94. void network_async_link_down();
  95. void network_async_configure();
  96. void network_async_got_ip();
  97. void network_async_timer();
  98. void network_async_start();
  99. void network_async_scan();
  100. void network_async_scan_done();
  101. void network_async_connect(const char * ssid, const char * password);
  102. void network_async_lost_connection(wifi_event_sta_disconnected_t * disconnected_event);
  103. void network_async_reboot(reboot_type_t rtype);
  104. void network_reboot_ota(char* url);
  105. void network_async_delete();
  106. void network_async_update_status();
  107. void network_async_eth_got_ip();
  108. void network_ip_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data);
  109. bool network_is_interface_connected(esp_netif_t * interface);
  110. /*
  111. * --------------------- Inline functions ---------------------
  112. */
  113. /**
  114. * @brief Defines the maximum size of a SSID name. 32 is IEEE standard.
  115. * @warning limit is also hard coded in wifi_config_t. Never extend this value.
  116. */
  117. #define MAX_SSID_SIZE 32
  118. /**
  119. * @brief Defines the maximum size of a WPA2 passkey. 64 is IEEE standard.
  120. * @warning limit is also hard coded in wifi_config_t. Never extend this value.
  121. */
  122. #define MAX_PASSWORD_SIZE 64
  123. #define MAX_COMMAND_LINE_SIZE 201
  124. /**
  125. * @brief Defines the maximum number of access points that can be scanned.
  126. *
  127. * To save memory and avoid nasty out of memory errors,
  128. * we can limit the number of APs detected in a wifi scan.
  129. */
  130. #define MAX_AP_NUM 15
  131. /**
  132. * @brief Defines when a connection is lost/attempt to connect is made, how many retries should be made before giving up.
  133. * Setting it to 2 for instance means there will be 3 attempts in total (original request + 2 retries)
  134. */
  135. #define WIFI_MANAGER_MAX_RETRY CONFIG_WIFI_MANAGER_MAX_RETRY
  136. /** @brief Defines the task priority of the wifi_manager.
  137. *
  138. * Tasks spawn by the manager will have a priority of WIFI_MANAGER_TASK_PRIORITY-1.
  139. * For this particular reason, minimum task priority is 1. It it highly not recommended to set
  140. * it to 1 though as the sub-tasks will now have a priority of 0 which is the priority
  141. * of freeRTOS' idle task.
  142. */
  143. #define WIFI_MANAGER_TASK_PRIORITY CONFIG_WIFI_MANAGER_TASK_PRIORITY
  144. /** @brief Defines the auth mode as an access point
  145. * Value must be of type wifi_auth_mode_t
  146. * @see esp_wifi_types.h
  147. * @warning if set to WIFI_AUTH_OPEN, passowrd me be empty. See DEFAULT_AP_PASSWORD.
  148. */
  149. #define AP_AUTHMODE WIFI_AUTH_WPA2_PSK
  150. /** @brief Defines visibility of the access point. 0: visible AP. 1: hidden */
  151. #define DEFAULT_AP_SSID_HIDDEN 0
  152. /** @brief Defines access point's name. Default value: esp32. Run 'make menuconfig' to setup your own value or replace here by a string */
  153. #define DEFAULT_AP_SSID CONFIG_DEFAULT_AP_SSID
  154. /** @brief Defines access point's password.
  155. * @warning In the case of an open access point, the password must be a null string "" or "\0" if you want to be verbose but waste one byte.
  156. * In addition, the AP_AUTHMODE must be WIFI_AUTH_OPEN
  157. */
  158. #define DEFAULT_AP_PASSWORD CONFIG_DEFAULT_AP_PASSWORD
  159. /** @brief Defines access point's bandwidth.
  160. * Value: WIFI_BW_HT20 for 20 MHz or WIFI_BW_HT40 for 40 MHz
  161. * 20 MHz minimize channel interference but is not suitable for
  162. * applications with high data speeds
  163. */
  164. #define DEFAULT_AP_BANDWIDTH WIFI_BW_HT20
  165. /** @brief Defines access point's channel.
  166. * Channel selection is only effective when not connected to another AP.
  167. * Good practice for minimal channel interference to use
  168. * For 20 MHz: 1, 6 or 11 in USA and 1, 5, 9 or 13 in most parts of the world
  169. * For 40 MHz: 3 in USA and 3 or 11 in most parts of the world
  170. */
  171. #define DEFAULT_AP_CHANNEL CONFIG_DEFAULT_AP_CHANNEL
  172. /** @brief Defines the access point's default IP address. Default: "10.10.0.1 */
  173. #define DEFAULT_AP_IP CONFIG_DEFAULT_AP_IP
  174. /** @brief Defines the access point's gateway. This should be the same as your IP. Default: "10.10.0.1" */
  175. #define DEFAULT_AP_GATEWAY CONFIG_DEFAULT_AP_GATEWAY
  176. /** @brief Defines the access point's netmask. Default: "255.255.255.0" */
  177. #define DEFAULT_AP_NETMASK CONFIG_DEFAULT_AP_NETMASK
  178. /** @brief Defines access point's maximum number of clients. Default: 4 */
  179. #define DEFAULT_AP_MAX_CONNECTIONS CONFIG_DEFAULT_AP_MAX_CONNECTIONS
  180. /** @brief Defines access point's beacon interval. 100ms is the recommended default. */
  181. #define DEFAULT_AP_BEACON_INTERVAL CONFIG_DEFAULT_AP_BEACON_INTERVAL
  182. /** @brief Defines if esp32 shall run both AP + STA when connected to another AP.
  183. * Value: 0 will have the own AP always on (APSTA mode)
  184. * Value: 1 will turn off own AP when connected to another AP (STA only mode when connected)
  185. * Turning off own AP when connected to another AP minimize channel interference and increase throughput
  186. */
  187. #define DEFAULT_STA_ONLY 1
  188. /** @brief Defines if wifi power save shall be enabled.
  189. * Value: WIFI_PS_NONE for full power (wifi modem always on)
  190. * Value: WIFI_PS_MODEM for power save (wifi modem sleep periodically)
  191. * Note: Power save is only effective when in STA only mode
  192. */
  193. #define DEFAULT_STA_POWER_SAVE WIFI_PS_MIN_MODEM
  194. void network_reboot_ota(char * url);
  195. /**
  196. * @brief simplified reason codes for a lost connection.
  197. *
  198. * esp-idf maintains a big list of reason codes which in practice are useless for most typical application.
  199. * UPDATE_CONNECTION_OK - Web UI expects this when attempting to connect to a new access point succeeds
  200. * UPDATE_FAILED_ATTEMPT - Web UI expects this when attempting to connect to a new access point fails
  201. * UPDATE_USER_DISCONNECT = 2,
  202. * UPDATE_LOST_CONNECTION = 3,
  203. * UPDATE_FAILED_ATTEMPT_AND_RESTORE - Web UI expects this when attempting to connect to a new access point fails and previous connection is restored
  204. * UPDATE_ETHERNET_CONNECTED = 5
  205. */
  206. typedef enum update_reason_code_t {
  207. UPDATE_CONNECTION_OK = 0, // expected when
  208. UPDATE_FAILED_ATTEMPT = 1,
  209. UPDATE_USER_DISCONNECT = 2,
  210. UPDATE_LOST_CONNECTION = 3,
  211. UPDATE_FAILED_ATTEMPT_AND_RESTORE = 4,
  212. UPDATE_ETHERNET_CONNECTED = 5
  213. }update_reason_code_t;
  214. /**
  215. * Frees up all memory allocated by the wifi_manager and kill the task.
  216. */
  217. void network_destroy();
  218. /**
  219. * Filters the AP scan list to unique SSIDs
  220. */
  221. void filter_unique( wifi_ap_record_t * aplist, uint16_t * ap_num);
  222. char* network_status_alloc_get_ap_list_json();
  223. cJSON * network_manager_clear_ap_list_json(cJSON **old);
  224. /**
  225. * @brief A standard wifi event handler as recommended by Espressif
  226. */
  227. esp_err_t network_manager_event_handler(void *ctx, system_event_t *event);
  228. /**
  229. * @brief Clears the connection status json.
  230. * @note This is not thread-safe and should be called only if network_status_lock_json_buffer call is successful.
  231. */
  232. cJSON * network_status_clear_ip_info_json(cJSON **old);
  233. cJSON * network_status_get_new_json(cJSON **old);
  234. /**
  235. * @brief Start the mDNS service
  236. */
  237. void network_manager_initialise_mdns();
  238. /**
  239. * @brief Register a callback to a custom function when specific network manager states are reached.
  240. */
  241. bool network_is_wifi_prioritized();
  242. void network_set_timer(uint16_t duration, const char * tag);
  243. void network_set_hostname(esp_netif_t * netif);
  244. esp_err_t network_get_ip_info_for_netif(esp_netif_t* netif, tcpip_adapter_ip_info_t* ipInfo);
  245. void network_start_stop_dhcp_client(esp_netif_t* netif, bool start);
  246. void network_start_stop_dhcps(esp_netif_t* netif, bool start);
  247. void network_prioritize_wifi(bool activate);
  248. #define ADD_ROOT_FORWARD_DECLARATION(name, ...) ADD_STATE_FORWARD_DECLARATION_(name)
  249. #define ADD_ROOT_LEAF_FORWARD_DECLARATION(name, ...) ADD_STATE_FORWARD_DECLARATION_(name)
  250. #define ADD_LEAF_FORWARD_DECLARATION(name, ...) ADD_STATE_FORWARD_DECLARATION_(name)
  251. #define ADD_STATE_FORWARD_DECLARATION_(name) \
  252. static state_machine_result_t name##_handler(state_machine_t* const State_Machine); \
  253. static state_machine_result_t name##_entry_handler(state_machine_t* const State_Machine); \
  254. static state_machine_result_t name##_exit_handler(state_machine_t* const State_Machine);
  255. void initialize_network_handlers(state_machine_t* state_machine);
  256. void network_manager_format_from_to_states(esp_log_level_t level, const char* prefix, state_t const * from_state, state_t const* current_state, network_event_t event,bool show_source, const char * caller );
  257. 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) ;
  258. char* network_manager_alloc_get_mac_string(uint8_t mac[6]);
  259. #if defined(LOG_LOCAL_LEVEL)
  260. #if LOG_LOCAL_LEVEL >=5
  261. #define NETWORK_PRINT_TRANSITION(begin, prefix, source,target, event, print_source,caller ) network_manager_format_from_to_states(ESP_LOG_VERBOSE, prefix, source,target, event, print_source,caller )
  262. #define NETWORK_DEBUG_STATE_MACHINE(begin, cb_prefix,state_machine,print_from,caller) network_manager_format_state_machine(ESP_LOG_DEBUG,cb_prefix,state_machine,print_from,caller)
  263. #define NETWORK_EXECUTE_CB(mch) network_execute_cb(mch,__FUNCTION__);
  264. #define network_handler_entry_print(State_Machine, begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"ENTRY START":"ENTRY END",State_Machine,false,__FUNCTION__)
  265. #define network_exit_handler_print(State_Machine, begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"EXIT START":"END END",State_Machine,false,__FUNCTION__)
  266. #define network_handler_print(State_Machine, begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"HANDLER START":"HANDLER END",State_Machine,false,__FUNCTION__)
  267. #elif LOG_LOCAL_LEVEL >= 4
  268. #define network_handler_entry_print(State_Machine, begin) if(begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"BEGIN ENTRY":"END ENTRY",State_Machine,false,"")
  269. #define network_exit_handler_print(State_Machine, begin) if(begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"BEGIN EXIT":"END EXIT",State_Machine,false,"")
  270. #define network_handler_print(State_Machine, begin) if(begin) network_manager_format_state_machine(ESP_LOG_DEBUG,begin?"HANDLER START":"HANDLER END",State_Machine,false,"")
  271. #define NETWORK_PRINT_TRANSITION(begin, prefix, source,target, event, print_source,caller ) if(begin) network_manager_format_from_to_states(ESP_LOG_DEBUG, prefix, source,target, event, print_source,caller )#define NETWORK_EXECUTE_CB(mch) network_execute_cb(mch,__FUNCTION__);
  272. #define NETWORK_DEBUG_STATE_MACHINE(begin, cb_prefix,state_machine,print_from,caller) if(begin) network_manager_format_state_machine(ESP_LOG_DEBUG,cb_prefix,state_machine,print_from,caller)
  273. #endif
  274. #endif
  275. #ifndef NETWORK_PRINT_TRANSITION
  276. #define network_exit_handler_print(nm, begin)
  277. #define network_handler_entry_print(State_Machine, begin)
  278. #define network_handler_print(State_Machine, begin)
  279. #define NETWORK_EXECUTE_CB(mch) network_execute_cb(mch,NULL)
  280. #define NETWORK_PRINT_TRANSITION(begin, prefix, source,target, event, print_source,caller )
  281. #define NETWORK_DEBUG_STATE_MACHINE(begin, cb_prefix,state_machine,print_from,caller)
  282. #endif
  283. #ifdef __cplusplus
  284. }
  285. #endif