esp_app_main.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /*
  2. * Squeezelite for esp32
  3. *
  4. * (c) Sebastien 2019
  5. * Philippe G. 2019, philippe_44@outlook.com
  6. *
  7. * This software is released under the MIT License.
  8. * https://opensource.org/licenses/MIT
  9. *
  10. */
  11. #include "platform_esp32.h"
  12. #include "led.h"
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include "freertos/FreeRTOS.h"
  16. #include "driver/gpio.h"
  17. #include "driver/spi_master.h"
  18. #include "freertos/task.h"
  19. #include "esp_spi_flash.h"
  20. #include "esp_wifi.h"
  21. #include <esp_event.h>
  22. #include "esp_log.h"
  23. #include "freertos/event_groups.h"
  24. #include "mdns.h"
  25. #include "lwip/api.h"
  26. #include "lwip/err.h"
  27. #include "lwip/netdb.h"
  28. #include "trace.h"
  29. #include "network_manager.h"
  30. #include "squeezelite-ota.h"
  31. #include <math.h>
  32. #include "audio_controls.h"
  33. #include "Configurator.h"
  34. #include "telnet.h"
  35. #include "messaging.h"
  36. #include "gds.h"
  37. #include "gds_default_if.h"
  38. #include "gds_draw.h"
  39. #include "gds_text.h"
  40. #include "gds_font.h"
  41. #include "led_vu.h"
  42. #include "display.h"
  43. #include "accessors.h"
  44. #include "cmd_system.h"
  45. #include "tools.h"
  46. #if defined(CONFIG_WITH_METRICS)
  47. #include "Metrics.h"
  48. #endif
  49. const char unknown_string_placeholder[] = "unknown";
  50. const char null_string_placeholder[] = "null";
  51. EventGroupHandle_t network_event_group;
  52. bool bypass_network_manager=false;
  53. const int CONNECTED_BIT = BIT0;
  54. #define JOIN_TIMEOUT_MS (10000)
  55. #define LOCAL_MAC_SIZE 20
  56. static const char TAG[] = "esp_app_main";
  57. #define DEFAULT_HOST_NAME "squeezelite"
  58. RTC_NOINIT_ATTR uint32_t RebootCounter ;
  59. RTC_NOINIT_ATTR uint32_t RecoveryRebootCounter ;
  60. RTC_NOINIT_ATTR uint16_t ColdBootIndicatorFlag;
  61. bool cold_boot=true;
  62. #ifdef CONFIG_IDF_TARGET_ESP32S3
  63. extern const char _ctype_[];
  64. const char* __ctype_ptr__ = _ctype_;
  65. #endif
  66. static bool bNetworkConnected=false;
  67. // as an exception _init function don't need include
  68. extern void services_init(void);
  69. extern void services_sleep_init(void);
  70. extern void display_init(char *welcome);
  71. extern void led_vu_init(void);
  72. extern void target_init(char *target);
  73. extern void start_squeezelite();
  74. const char * str_or_unknown(const char * str) { return (str?str:unknown_string_placeholder); }
  75. const char * str_or_null(const char * str) { return (str?str:null_string_placeholder); }
  76. bool is_recovery_running;
  77. bool is_network_connected(){
  78. return bNetworkConnected;
  79. }
  80. void cb_connection_got_ip(nm_state_t new_state, int sub_state){
  81. const char *hostname;
  82. static ip4_addr_t ip;
  83. tcpip_adapter_ip_info_t ipInfo;
  84. network_get_ip_info(&ipInfo);
  85. if (ip.addr && ipInfo.ip.addr != ip.addr) {
  86. ESP_LOGW(TAG, "IP change, need to reboot");
  87. if(!configurator_waitcommit()){
  88. ESP_LOGW(TAG,"Unable to commit configuration. ");
  89. }
  90. esp_restart();
  91. }
  92. // initializing mDNS
  93. network_get_hostname(&hostname);
  94. mdns_init();
  95. mdns_hostname_set(hostname);
  96. ESP_LOGI(TAG, "Network connected and mDNS initialized with %s", hostname);
  97. messaging_post_message(MESSAGING_INFO,MESSAGING_CLASS_SYSTEM,"Network connected");
  98. xEventGroupSetBits(network_event_group, CONNECTED_BIT);
  99. bNetworkConnected=true;
  100. led_unpush(LED_GREEN);
  101. if(is_recovery_running){
  102. // when running in recovery, send a LMS discovery message
  103. // to find a running instance. This is to enable using
  104. // the plugin's proxy mode for FW download and avoid
  105. // expired certificate issues.
  106. discover_ota_server(5);
  107. }
  108. }
  109. void cb_connection_sta_disconnected(nm_state_t new_state, int sub_state){
  110. led_blink_pushed(LED_GREEN, 250, 250);
  111. messaging_post_message(MESSAGING_WARNING,MESSAGING_CLASS_SYSTEM,"Wifi disconnected");
  112. bNetworkConnected=false;
  113. xEventGroupClearBits(network_event_group, CONNECTED_BIT);
  114. }
  115. bool wait_for_wifi(){
  116. bool connected=(xEventGroupGetBits(network_event_group) & CONNECTED_BIT)!=0;
  117. if(!connected){
  118. ESP_LOGD(TAG,"Waiting for Network...");
  119. connected = (xEventGroupWaitBits(network_event_group, CONNECTED_BIT,
  120. pdFALSE, pdTRUE, JOIN_TIMEOUT_MS / portTICK_PERIOD_MS)& CONNECTED_BIT)!=0;
  121. if(!connected){
  122. ESP_LOGW(TAG,"Network timeout.");
  123. }
  124. else
  125. {
  126. ESP_LOGI(TAG,"Network Connected!");
  127. }
  128. }
  129. return connected;
  130. }
  131. esp_log_level_t get_log_level_from_char(char * level){
  132. if(!strcasecmp(level, "NONE" )) { return ESP_LOG_NONE ;}
  133. if(!strcasecmp(level, "ERROR" )) { return ESP_LOG_ERROR ;}
  134. if(!strcasecmp(level, "WARN" )) { return ESP_LOG_WARN ;}
  135. if(!strcasecmp(level, "INFO" )) { return ESP_LOG_INFO ;}
  136. if(!strcasecmp(level, "DEBUG" )) { return ESP_LOG_DEBUG ;}
  137. if(!strcasecmp(level, "VERBOSE" )) { return ESP_LOG_VERBOSE;}
  138. return ESP_LOG_WARN;
  139. }
  140. void set_log_level(char * tag, char * level){
  141. esp_log_level_set(tag, get_log_level_from_char(level));
  142. }
  143. uint32_t halSTORAGE_RebootCounterRead(void) { return RebootCounter ; }
  144. uint32_t halSTORAGE_RebootCounterUpdate(int32_t xValue) {
  145. if(RebootCounter >100) {
  146. RebootCounter = 0;
  147. RecoveryRebootCounter = 0;
  148. }
  149. RebootCounter = (xValue != 0) ? (RebootCounter + xValue) : 0;
  150. RecoveryRebootCounter = (xValue != 0) && is_recovery_running ? (RecoveryRebootCounter + xValue) : 0;
  151. return RebootCounter ;
  152. }
  153. void handle_ap_connect(nm_state_t new_state, int sub_state){
  154. start_telnet(NULL);
  155. }
  156. void handle_network_up(nm_state_t new_state, int sub_state){
  157. halSTORAGE_RebootCounterUpdate(0);
  158. }
  159. esp_reset_reason_t xReason=ESP_RST_UNKNOWN;
  160. void app_main()
  161. {
  162. if(ColdBootIndicatorFlag != 0xFACE ){
  163. ESP_LOGI(TAG, "System is booting from power on.");
  164. cold_boot = true;
  165. ColdBootIndicatorFlag = 0xFACE;
  166. }
  167. else {
  168. cold_boot = false;
  169. }
  170. const esp_partition_t *running = esp_ota_get_running_partition();
  171. is_recovery_running = (running->subtype == ESP_PARTITION_SUBTYPE_APP_FACTORY);
  172. xReason = esp_reset_reason();
  173. ESP_LOGI(TAG,"Reset reason is: %u. Running from partition %s type %s ",
  174. xReason,
  175. running->label,
  176. running->subtype == ESP_PARTITION_SUBTYPE_APP_FACTORY?"Factory":"Application");
  177. if(!is_recovery_running ) {
  178. /* unscheduled restart (HW, Watchdog or similar) thus increment dynamic
  179. * counter then log current boot statistics as a warning */
  180. uint32_t Counter = halSTORAGE_RebootCounterUpdate(1) ; // increment counter
  181. ESP_LOGI(TAG,"Reboot counter=%u\n", Counter) ;
  182. if (Counter == 5) {
  183. guided_factory();
  184. }
  185. }
  186. else {
  187. uint32_t Counter = halSTORAGE_RebootCounterUpdate(1) ; // increment counter
  188. if(RecoveryRebootCounter==1 && Counter>=5){
  189. // First time we are rebooting in recovery after crashing
  190. messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"System was forced into recovery mode after crash likely caused by some bad configuration\n");
  191. }
  192. ESP_LOGI(TAG,"Recovery Reboot counter=%u\n", Counter) ;
  193. if (RecoveryRebootCounter == 5) {
  194. ESP_LOGW(TAG,"System rebooted too many times. This could be an indication that configuration is corrupted. Erasing config.");
  195. // TODO: Add support for the commented code
  196. // erase_settings_partition();
  197. // reboot one more time
  198. #pragma message("Add support for erasing the configuration")
  199. guided_factory();
  200. }
  201. if (RecoveryRebootCounter >5){
  202. messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"System was forced into recovery mode after crash likely caused by some bad configuration. Configuration was reset to factory.\n");
  203. }
  204. }
  205. MEMTRACE_PRINT_DELTA();
  206. ESP_LOGI(TAG,"Starting app_main");
  207. init_spiffs();
  208. listFiles("/");
  209. ESP_LOGI(TAG,"Setting up config subsystem.");
  210. configurator_load();
  211. MEMTRACE_PRINT_DELTA();
  212. #if defined(CONFIG_WITH_METRICS)
  213. ESP_LOGI(TAG,"Setting up metrics.");
  214. metrics_init();
  215. MEMTRACE_PRINT_DELTA();
  216. #endif
  217. ESP_LOGI(TAG,"Setting up telnet.");
  218. init_telnet(); // align on 32 bits boundaries
  219. MEMTRACE_PRINT_DELTA();
  220. ESP_LOGD(TAG,"Creating event group for wifi");
  221. network_event_group = xEventGroupCreate();
  222. ESP_LOGD(TAG,"Clearing CONNECTED_BIT from wifi group");
  223. xEventGroupClearBits(network_event_group, CONNECTED_BIT);
  224. MEMTRACE_PRINT_DELTA();
  225. ESP_LOGI(TAG,"Configuring services");
  226. services_init();
  227. MEMTRACE_PRINT_DELTA();
  228. ESP_LOGI(TAG,"Initializing display");
  229. display_init("SqueezeESP32");
  230. MEMTRACE_PRINT_DELTA();
  231. if(strlen(platform->target)>0){
  232. target_init(platform->target);
  233. }
  234. ESP_LOGI(TAG,"Initializing led_vu");
  235. led_vu_init();
  236. if(is_recovery_running) {
  237. ESP_LOGI(TAG,"Turning on display");
  238. if (display) {
  239. GDS_ClearExt(display, true);
  240. GDS_SetFont(display, Font_line_2 );
  241. GDS_TextPos(display, GDS_FONT_DEFAULT, GDS_TEXT_CENTERED, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "RECOVERY");
  242. }
  243. if(led_display) {
  244. led_vu_color_yellow(LED_VU_BRIGHT);
  245. }
  246. }
  247. #if defined(CONFIG_WITH_METRICS)
  248. metrics_event_boot(is_recovery_running?"recovery":"ota");
  249. #endif
  250. if(!is_recovery_running){
  251. #pragma message("Add audio controls support")
  252. // ESP_LOGD(TAG,"Getting audio control mapping ");
  253. // if(platform->has_dev && platform->dev.buttons_count >0){
  254. // ESP_LOGD(TAG,"Initializing audio control buttons");
  255. // }
  256. // char *actrls_config = config_alloc_get_default(NVS_TYPE_STR, "actrls_config", "", 0);
  257. // if (actrls_init(actrls_config) == ESP_OK) {
  258. // } else {
  259. // ESP_LOGD(TAG,"No audio control buttons");
  260. // }
  261. // if (actrls_config) free(actrls_config);
  262. // TODO: Add support for the commented code
  263. }
  264. /* start the wifi manager */
  265. ESP_LOGD(TAG,"Blinking led");
  266. led_blink_pushed(LED_GREEN, 250, 250);
  267. MEMTRACE_PRINT_DELTA();
  268. if(bypass_network_manager){
  269. ESP_LOGW(TAG,"Network manager is disabled. Use command line for wifi control.");
  270. }
  271. else {
  272. ESP_LOGI(TAG,"Starting Network Manager");
  273. network_start();
  274. MEMTRACE_PRINT_DELTA();
  275. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_CONNECTED_STATE, "cb_connection_got_ip", &cb_connection_got_ip);
  276. network_register_state_callback(NETWORK_ETH_ACTIVE_STATE,ETH_ACTIVE_CONNECTED_STATE, "cb_connection_got_ip",&cb_connection_got_ip);
  277. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_LOST_CONNECTION_STATE, "cb_connection_sta_disconnected",&cb_connection_sta_disconnected);
  278. /* Start the telnet service after we are certain that the network stack has been properly initialized.
  279. * This can be either after we're started the AP mode, or after we've started the STA mode */
  280. network_register_state_callback(NETWORK_INITIALIZING_STATE,-1, "handle_ap_connect", &handle_ap_connect);
  281. network_register_state_callback(NETWORK_ETH_ACTIVE_STATE,ETH_ACTIVE_LINKDOWN_STATE, "handle_network_up", &handle_network_up);
  282. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_INITIALIZING_STATE, "handle_network_up", &handle_network_up);
  283. MEMTRACE_PRINT_DELTA();
  284. }
  285. if(!is_recovery_running){
  286. MEMTRACE_PRINT_DELTA_MESSAGE("Launching Squeezelite");
  287. start_squeezelite();
  288. MEMTRACE_PRINT_DELTA_MESSAGE("Squeezelite Started");
  289. }
  290. MEMTRACE_PRINT_DELTA_MESSAGE("Starting Console");
  291. console_start();
  292. MEMTRACE_PRINT_DELTA_MESSAGE("Console started");
  293. if(sys_state && sys_state->ota_url && strlen(sys_state->ota_url)){
  294. ESP_LOGD(TAG,"Found OTA URL %s",sys_state->ota_url);
  295. if(is_recovery_running){
  296. while(!bNetworkConnected){
  297. wait_for_wifi();
  298. taskYIELD();
  299. }
  300. ESP_LOGI(TAG,"Updating firmware from link: %s",sys_state->ota_url);
  301. #if defined(CONFIG_WITH_METRICS)
  302. metrics_event("fw_update");
  303. #endif
  304. start_ota(sys_state->ota_url, NULL, 0);
  305. }
  306. else {
  307. ESP_LOGE(TAG,"Restarted to application partition. We're not going to perform OTA!");
  308. }
  309. }
  310. services_sleep_init();
  311. messaging_post_message(MESSAGING_INFO,MESSAGING_CLASS_SYSTEM,"System started");
  312. }