2
0

esp_app_main.c 16 KB

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