esp_app_main.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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_system.h"
  20. #include "esp_spi_flash.h"
  21. #include "esp_wifi.h"
  22. #include <esp_event.h>
  23. #include "nvs_flash.h"
  24. #include "esp_log.h"
  25. #include "freertos/event_groups.h"
  26. #include "mdns.h"
  27. #include "lwip/api.h"
  28. #include "lwip/err.h"
  29. #include "lwip/netdb.h"
  30. #include "nvs_utilities.h"
  31. #include "trace.h"
  32. #include "network_manager.h"
  33. #include "squeezelite-ota.h"
  34. #include <math.h>
  35. #include "audio_controls.h"
  36. #include "platform_config.h"
  37. #include "telnet.h"
  38. #include "messaging.h"
  39. #include "gds.h"
  40. #include "gds_default_if.h"
  41. #include "gds_draw.h"
  42. #include "gds_text.h"
  43. #include "gds_font.h"
  44. #include "display.h"
  45. #include "accessors.h"
  46. #include "cmd_system.h"
  47. #include "tools.h"
  48. const char unknown_string_placeholder[] = "unknown";
  49. const char null_string_placeholder[] = "null";
  50. EventGroupHandle_t network_event_group;
  51. bool bypass_network_manager=false;
  52. const int CONNECTED_BIT = BIT0;
  53. #define JOIN_TIMEOUT_MS (10000)
  54. #define LOCAL_MAC_SIZE 20
  55. static const char TAG[] = "esp_app_main";
  56. #define DEFAULT_HOST_NAME "squeezelite"
  57. char * fwurl = NULL;
  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 display_init(char *welcome);
  70. extern void target_init(char *target);
  71. const char * str_or_unknown(const char * str) { return (str?str:unknown_string_placeholder); }
  72. const char * str_or_null(const char * str) { return (str?str:null_string_placeholder); }
  73. bool is_recovery_running;
  74. void cb_connection_got_ip(nm_state_t new_state, int sub_state){
  75. const char *hostname;
  76. static ip4_addr_t ip;
  77. tcpip_adapter_ip_info_t ipInfo;
  78. network_get_ip_info(&ipInfo);
  79. if (ip.addr && ipInfo.ip.addr != ip.addr) {
  80. ESP_LOGW(TAG, "IP change, need to reboot");
  81. if(!wait_for_commit()){
  82. ESP_LOGW(TAG,"Unable to commit configuration. ");
  83. }
  84. esp_restart();
  85. }
  86. // initializing mDNS
  87. network_get_hostname(&hostname);
  88. mdns_init();
  89. mdns_hostname_set(hostname);
  90. ESP_LOGI(TAG, "Network connected and mDNS initialized with %s", hostname);
  91. messaging_post_message(MESSAGING_INFO,MESSAGING_CLASS_SYSTEM,"Network connected");
  92. xEventGroupSetBits(network_event_group, CONNECTED_BIT);
  93. bNetworkConnected=true;
  94. led_unpush(LED_GREEN);
  95. if(is_recovery_running){
  96. // when running in recovery, send a LMS discovery message
  97. // to find a running instance. This is to enable using
  98. // the plugin's proxy mode for FW download and avoid
  99. // expired certificate issues.
  100. discover_ota_server(5);
  101. }
  102. }
  103. void cb_connection_sta_disconnected(nm_state_t new_state, int sub_state){
  104. led_blink_pushed(LED_GREEN, 250, 250);
  105. messaging_post_message(MESSAGING_WARNING,MESSAGING_CLASS_SYSTEM,"Wifi disconnected");
  106. bNetworkConnected=false;
  107. xEventGroupClearBits(network_event_group, CONNECTED_BIT);
  108. }
  109. bool wait_for_wifi(){
  110. bool connected=(xEventGroupGetBits(network_event_group) & CONNECTED_BIT)!=0;
  111. if(!connected){
  112. ESP_LOGD(TAG,"Waiting for Network...");
  113. connected = (xEventGroupWaitBits(network_event_group, CONNECTED_BIT,
  114. pdFALSE, pdTRUE, JOIN_TIMEOUT_MS / portTICK_PERIOD_MS)& CONNECTED_BIT)!=0;
  115. if(!connected){
  116. ESP_LOGW(TAG,"Network timeout.");
  117. }
  118. else
  119. {
  120. ESP_LOGI(TAG,"Network Connected!");
  121. }
  122. }
  123. return connected;
  124. }
  125. char * process_ota_url(){
  126. ESP_LOGI(TAG,"Checking for update url");
  127. char * fwurl=config_alloc_get(NVS_TYPE_STR, "fwurl");
  128. if(fwurl!=NULL)
  129. {
  130. ESP_LOGD(TAG,"Deleting nvs entry for Firmware URL %s", fwurl);
  131. config_delete_key("fwurl");
  132. }
  133. return fwurl;
  134. }
  135. esp_log_level_t get_log_level_from_char(char * level){
  136. if(!strcasecmp(level, "NONE" )) { return ESP_LOG_NONE ;}
  137. if(!strcasecmp(level, "ERROR" )) { return ESP_LOG_ERROR ;}
  138. if(!strcasecmp(level, "WARN" )) { return ESP_LOG_WARN ;}
  139. if(!strcasecmp(level, "INFO" )) { return ESP_LOG_INFO ;}
  140. if(!strcasecmp(level, "DEBUG" )) { return ESP_LOG_DEBUG ;}
  141. if(!strcasecmp(level, "VERBOSE" )) { return ESP_LOG_VERBOSE;}
  142. return ESP_LOG_WARN;
  143. }
  144. void set_log_level(char * tag, char * level){
  145. esp_log_level_set(tag, get_log_level_from_char(level));
  146. }
  147. #define DEFAULT_NAME_WITH_MAC(var,defval) char var[strlen(defval)+sizeof(macStr)]; strcpy(var,defval); strcat(var,macStr)
  148. void register_default_string_val(const char * key, char * value){
  149. char * existing =(char *)config_alloc_get(NVS_TYPE_STR,key );
  150. ESP_LOGD(TAG,"Register default called with: %s= %s",key,value );
  151. if(!existing) {
  152. ESP_LOGI(TAG,"Registering default value for key %s, value %s",key,value );
  153. config_set_default(NVS_TYPE_STR, key,value, 0);
  154. }
  155. else {
  156. ESP_LOGD(TAG,"Value found for %s: %s",key,existing );
  157. }
  158. FREE_AND_NULL(existing);
  159. }
  160. char * alloc_get_string_with_mac(const char * val) {
  161. uint8_t mac[6];
  162. char macStr[LOCAL_MAC_SIZE + 1];
  163. char* fullvalue = NULL;
  164. esp_read_mac((uint8_t*)&mac, ESP_MAC_WIFI_STA);
  165. snprintf(macStr, LOCAL_MAC_SIZE - 1, "-%x%x%x", mac[3], mac[4], mac[5]);
  166. fullvalue = malloc_init_external(strlen(val)+sizeof(macStr)+1);
  167. if(fullvalue){
  168. strcpy(fullvalue, val);
  169. strcat(fullvalue, macStr);
  170. }
  171. else {
  172. ESP_LOGE(TAG,"Memory allocation failed when getting mac value for %s", val);
  173. }
  174. return fullvalue;
  175. }
  176. void register_default_with_mac(const char* key, char* defval) {
  177. char * fullvalue=alloc_get_string_with_mac(defval);
  178. if(fullvalue){
  179. register_default_string_val(key,fullvalue);
  180. FREE_AND_NULL(fullvalue);
  181. }
  182. else {
  183. ESP_LOGE(TAG,"Memory allocation failed when registering default value for %s", key);
  184. }
  185. }
  186. void register_default_nvs(){
  187. #ifdef CONFIG_CSPOT_SINK
  188. register_default_string_val("enable_cspot", STR(CONFIG_CSPOT_SINK));
  189. cJSON * cspot_config=config_alloc_get_cjson("cspot_config");
  190. if(!cspot_config){
  191. char * name = alloc_get_string_with_mac(DEFAULT_HOST_NAME);
  192. if(name){
  193. cjson_update_string(&cspot_config,"deviceName",name);
  194. cjson_update_number(&cspot_config,"bitrate",160);
  195. // the call below saves the config and frees the json pointer
  196. config_set_cjson_str_and_free("cspot_config",cspot_config);
  197. FREE_AND_NULL(name);
  198. }
  199. else {
  200. register_default_string_val("cspot_config", "");
  201. }
  202. }
  203. #endif
  204. #ifdef CONFIG_AIRPLAY_SINK
  205. register_default_with_mac("airplay_name", CONFIG_AIRPLAY_NAME);
  206. register_default_string_val("airplay_port", CONFIG_AIRPLAY_PORT);
  207. register_default_string_val( "enable_airplay", STR(CONFIG_AIRPLAY_SINK));
  208. #endif
  209. #ifdef CONFIG_BT_SINK
  210. register_default_string_val( "bt_sink_pin", STR(CONFIG_BT_SINK_PIN));
  211. register_default_string_val( "bt_sink_volume", "127");
  212. register_default_with_mac("bt_name", CONFIG_BT_NAME);
  213. register_default_string_val( "enable_bt_sink", STR(CONFIG_BT_SINK));
  214. register_default_string_val("a2dp_dev_name", CONFIG_A2DP_DEV_NAME);
  215. register_default_string_val("a2dp_ctmt", STR(CONFIG_A2DP_CONNECT_TIMEOUT_MS));
  216. register_default_string_val("a2dp_ctrld", STR(CONFIG_A2DP_CONTROL_DELAY_MS));
  217. register_default_string_val("a2dp_sink_name", CONFIG_A2DP_SINK_NAME);
  218. #endif
  219. register_default_with_mac("host_name", DEFAULT_HOST_NAME);
  220. register_default_with_mac("ap_ssid", CONFIG_DEFAULT_AP_SSID);
  221. register_default_string_val("autoexec","1");
  222. register_default_with_mac("autoexec1",CONFIG_DEFAULT_COMMAND_LINE " -n " DEFAULT_HOST_NAME);
  223. register_default_string_val("release_url", CONFIG_SQUEEZELITE_ESP32_RELEASE_URL);
  224. register_default_string_val("ap_ip_address",CONFIG_DEFAULT_AP_IP);
  225. register_default_string_val("ap_ip_gateway",CONFIG_DEFAULT_AP_GATEWAY );
  226. register_default_string_val("ap_ip_netmask",CONFIG_DEFAULT_AP_NETMASK);
  227. register_default_string_val("ap_channel",STR(CONFIG_DEFAULT_AP_CHANNEL));
  228. register_default_string_val("ap_pwd", CONFIG_DEFAULT_AP_PASSWORD);
  229. register_default_string_val("bypass_wm", "0");
  230. register_default_string_val("equalizer", "");
  231. register_default_string_val("actrls_config", "");
  232. register_default_string_val("lms_ctrls_raw", "n");
  233. register_default_string_val("rotary_config", CONFIG_ROTARY_ENCODER);
  234. char number_buffer[101] = {};
  235. snprintf(number_buffer,sizeof(number_buffer)-1,"%u",OTA_FLASH_ERASE_BLOCK);
  236. register_default_string_val( "ota_erase_blk", number_buffer);
  237. snprintf(number_buffer,sizeof(number_buffer)-1,"%u",OTA_STACK_SIZE);
  238. register_default_string_val( "ota_stack", number_buffer);
  239. snprintf(number_buffer,sizeof(number_buffer)-1,"%d",OTA_TASK_PRIOTITY);
  240. register_default_string_val( "ota_prio", number_buffer);
  241. register_default_string_val( "display_config", CONFIG_DISPLAY_CONFIG);
  242. register_default_string_val( "eth_config", CONFIG_ETH_CONFIG);
  243. register_default_string_val( "i2c_config", CONFIG_I2C_CONFIG);
  244. register_default_string_val( "spi_config", CONFIG_SPI_CONFIG);
  245. register_default_string_val( "set_GPIO", CONFIG_SET_GPIO);
  246. register_default_string_val( "led_brightness", "");
  247. register_default_string_val( "spdif_config", "");
  248. register_default_string_val( "dac_config", "");
  249. register_default_string_val( "dac_controlset", "");
  250. register_default_string_val( "jack_mutes_amp", "n");
  251. register_default_string_val("gpio_exp_config", CONFIG_GPIO_EXP_CONFIG);
  252. register_default_string_val( "bat_config", "");
  253. register_default_string_val( "metadata_config", "");
  254. register_default_string_val( "telnet_enable", "");
  255. register_default_string_val( "telnet_buffer", "40000");
  256. register_default_string_val( "telnet_block", "500");
  257. register_default_string_val( "stats", "n");
  258. register_default_string_val( "rel_api", CONFIG_RELEASE_API);
  259. register_default_string_val("pollmx","600");
  260. register_default_string_val("pollmin","15");
  261. register_default_string_val("ethtmout","8");
  262. register_default_string_val("dhcp_tmout","8");
  263. register_default_string_val("target", CONFIG_TARGET);
  264. wait_for_commit();
  265. ESP_LOGD(TAG,"Done setting default values in nvs.");
  266. }
  267. uint32_t halSTORAGE_RebootCounterRead(void) { return RebootCounter ; }
  268. uint32_t halSTORAGE_RebootCounterUpdate(int32_t xValue) {
  269. if(RebootCounter >100) {
  270. RebootCounter = 0;
  271. RecoveryRebootCounter = 0;
  272. }
  273. RebootCounter = (xValue != 0) ? (RebootCounter + xValue) : 0;
  274. RecoveryRebootCounter = (xValue != 0) && is_recovery_running ? (RecoveryRebootCounter + xValue) : 0;
  275. return (RebootCounter) ;
  276. }
  277. void handle_ap_connect(nm_state_t new_state, int sub_state){
  278. start_telnet(NULL);
  279. }
  280. void handle_network_up(nm_state_t new_state, int sub_state){
  281. halSTORAGE_RebootCounterUpdate(0);
  282. }
  283. esp_reset_reason_t xReason=ESP_RST_UNKNOWN;
  284. void app_main()
  285. {
  286. if(ColdBootIndicatorFlag != 0xFACE ){
  287. ESP_LOGI(TAG, "System is booting from power on.");
  288. cold_boot = true;
  289. ColdBootIndicatorFlag = 0xFACE;
  290. }
  291. else {
  292. cold_boot = false;
  293. }
  294. const esp_partition_t *running = esp_ota_get_running_partition();
  295. is_recovery_running = (running->subtype == ESP_PARTITION_SUBTYPE_APP_FACTORY);
  296. xReason = esp_reset_reason();
  297. ESP_LOGI(TAG,"Reset reason is: %u", xReason);
  298. if(!is_recovery_running ) {
  299. /* unscheduled restart (HW, Watchdog or similar) thus increment dynamic
  300. * counter then log current boot statistics as a warning */
  301. uint32_t Counter = halSTORAGE_RebootCounterUpdate(1) ; // increment counter
  302. ESP_LOGI(TAG,"Reboot counter=%u\n", Counter) ;
  303. if (Counter == 5) {
  304. guided_factory();
  305. }
  306. }
  307. else {
  308. uint32_t Counter = halSTORAGE_RebootCounterUpdate(1) ; // increment counter
  309. if(RecoveryRebootCounter==1 && Counter>=5){
  310. // First time we are rebooting in recovery after crashing
  311. messaging_post_message(MESSAGING_ERROR,MESSAGING_CLASS_SYSTEM,"System was forced into recovery mode after crash likely caused by some bad configuration\n");
  312. }
  313. ESP_LOGI(TAG,"Recovery Reboot counter=%u\n", Counter) ;
  314. if (RecoveryRebootCounter == 5) {
  315. ESP_LOGW(TAG,"System rebooted too many times. This could be an indication that configuration is corrupted. Erasing config.");
  316. erase_settings_partition();
  317. // reboot one more time
  318. guided_factory();
  319. }
  320. if (RecoveryRebootCounter >5){
  321. 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");
  322. }
  323. }
  324. char * fwurl = NULL;
  325. MEMTRACE_PRINT_DELTA();
  326. ESP_LOGI(TAG,"Starting app_main");
  327. initialize_nvs();
  328. MEMTRACE_PRINT_DELTA();
  329. ESP_LOGI(TAG,"Setting up telnet.");
  330. init_telnet(); // align on 32 bits boundaries
  331. MEMTRACE_PRINT_DELTA();
  332. ESP_LOGI(TAG,"Setting up config subsystem.");
  333. config_init();
  334. MEMTRACE_PRINT_DELTA();
  335. ESP_LOGD(TAG,"Creating event group for wifi");
  336. network_event_group = xEventGroupCreate();
  337. ESP_LOGD(TAG,"Clearing CONNECTED_BIT from wifi group");
  338. xEventGroupClearBits(network_event_group, CONNECTED_BIT);
  339. ESP_LOGI(TAG,"Registering default values");
  340. register_default_nvs();
  341. MEMTRACE_PRINT_DELTA();
  342. ESP_LOGI(TAG,"Configuring services");
  343. services_init();
  344. MEMTRACE_PRINT_DELTA();
  345. ESP_LOGI(TAG,"Initializing display");
  346. display_init("SqueezeESP32");
  347. MEMTRACE_PRINT_DELTA();
  348. char *target = config_alloc_get_str("target", CONFIG_TARGET, NULL);
  349. if (target) {
  350. target_init(target);
  351. free(target);
  352. }
  353. if(is_recovery_running && display){
  354. GDS_ClearExt(display, true);
  355. GDS_SetFont(display, &Font_line_2 );
  356. GDS_TextPos(display, GDS_FONT_DEFAULT, GDS_TEXT_CENTERED, GDS_TEXT_CLEAR | GDS_TEXT_UPDATE, "RECOVERY");
  357. }
  358. ESP_LOGD(TAG,"Getting firmware OTA URL (if any)");
  359. fwurl = process_ota_url();
  360. ESP_LOGD(TAG,"Getting value for WM bypass, nvs 'bypass_wm'");
  361. char * bypass_wm = config_alloc_get_default(NVS_TYPE_STR, "bypass_wm", "0", 0);
  362. if(bypass_wm==NULL)
  363. {
  364. ESP_LOGE(TAG, "Unable to retrieve the Wifi Manager bypass flag");
  365. bypass_network_manager = false;
  366. }
  367. else {
  368. bypass_network_manager=(strcmp(bypass_wm,"1")==0 ||strcasecmp(bypass_wm,"y")==0);
  369. }
  370. if(!is_recovery_running){
  371. ESP_LOGD(TAG,"Getting audio control mapping ");
  372. char *actrls_config = config_alloc_get_default(NVS_TYPE_STR, "actrls_config", "", 0);
  373. if (actrls_init(actrls_config) == ESP_OK) {
  374. ESP_LOGD(TAG,"Initializing audio control buttons type %s", actrls_config);
  375. } else {
  376. ESP_LOGD(TAG,"No audio control buttons");
  377. }
  378. if (actrls_config) free(actrls_config);
  379. }
  380. /* start the wifi manager */
  381. ESP_LOGD(TAG,"Blinking led");
  382. led_blink_pushed(LED_GREEN, 250, 250);
  383. MEMTRACE_PRINT_DELTA();
  384. if(bypass_network_manager){
  385. ESP_LOGW(TAG,"Network manager is disabled. Use command line for wifi control.");
  386. }
  387. else {
  388. ESP_LOGI(TAG,"Starting Network Manager");
  389. network_start();
  390. MEMTRACE_PRINT_DELTA();
  391. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_CONNECTED_STATE, "cb_connection_got_ip", &cb_connection_got_ip);
  392. network_register_state_callback(NETWORK_ETH_ACTIVE_STATE,ETH_ACTIVE_CONNECTED_STATE, "cb_connection_got_ip",&cb_connection_got_ip);
  393. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_LOST_CONNECTION_STATE, "cb_connection_sta_disconnected",&cb_connection_sta_disconnected);
  394. /* Start the telnet service after we are certain that the network stack has been properly initialized.
  395. * This can be either after we're started the AP mode, or after we've started the STA mode */
  396. network_register_state_callback(NETWORK_INITIALIZING_STATE,-1, "handle_ap_connect", &handle_ap_connect);
  397. network_register_state_callback(NETWORK_ETH_ACTIVE_STATE,ETH_ACTIVE_LINKDOWN_STATE, "handle_network_up", &handle_network_up);
  398. network_register_state_callback(NETWORK_WIFI_ACTIVE_STATE,WIFI_INITIALIZING_STATE, "handle_network_up", &handle_network_up);
  399. MEMTRACE_PRINT_DELTA();
  400. }
  401. MEMTRACE_PRINT_DELTA_MESSAGE("Starting Console");
  402. console_start();
  403. MEMTRACE_PRINT_DELTA_MESSAGE("Console started");
  404. if(fwurl && strlen(fwurl)>0){
  405. if(is_recovery_running){
  406. while(!bNetworkConnected){
  407. wait_for_wifi();
  408. taskYIELD();
  409. }
  410. ESP_LOGI(TAG,"Updating firmware from link: %s",fwurl);
  411. start_ota(fwurl, NULL, 0);
  412. }
  413. else {
  414. ESP_LOGE(TAG,"Restarted to application partition. We're not going to perform OTA!");
  415. }
  416. free(fwurl);
  417. }
  418. messaging_post_message(MESSAGING_INFO,MESSAGING_CLASS_SYSTEM,"System started");
  419. }