2
0

network_manager.h 13 KB

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