network_manager.h 14 KB

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