esp_app_main.c 16 KB

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