platform_console.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. /* Console example
  2. This example code is in the Public Domain (or CC0 licensed, at your option.)
  3. Unless required by applicable law or agreed to in writing, this
  4. software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  5. CONDITIONS OF ANY KIND, either express or implied.
  6. */
  7. #include "platform_console.h"
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include "esp_log.h"
  12. #include "esp_console.h"
  13. #include "esp_vfs_dev.h"
  14. #include "driver/uart.h"
  15. #include "linenoise/linenoise.h"
  16. #include "argtable3/argtable3.h"
  17. #include "nvs.h"
  18. #include "nvs_flash.h"
  19. #include "pthread.h"
  20. #include "platform_esp32.h"
  21. #include "cmd_decl.h"
  22. #include "trace.h"
  23. #include "platform_config.h"
  24. #include "telnet.h"
  25. #include "messaging.h"
  26. #include "config.h"
  27. pthread_t thread_console;
  28. static void * console_thread();
  29. void console_start();
  30. static const char * TAG = "console";
  31. extern bool bypass_wifi_manager;
  32. extern void register_squeezelite();
  33. /* Prompt to be printed before each line.
  34. * This can be customized, made dynamic, etc.
  35. */
  36. const char* prompt = LOG_COLOR_I "squeezelite-esp32> " LOG_RESET_COLOR;
  37. const char* recovery_prompt = LOG_COLOR_E "recovery-squeezelite-esp32> " LOG_RESET_COLOR;
  38. /* Console command history can be stored to and loaded from a file.
  39. * The easiest way to do this is to use FATFS filesystem on top of
  40. * wear_levelling library.
  41. */
  42. #define MOUNT_PATH "/data"
  43. #define HISTORY_PATH MOUNT_PATH "/history.txt"
  44. esp_err_t run_command(char * line);
  45. #define ADD_TO_JSON(o,t,n) if (t->n) cJSON_AddStringToObject(o,QUOTE(n),t->n);
  46. #define ADD_PARMS_TO_CMD(o,t,n) { cJSON * parms = ParmsToJSON(&t.n->hdr); if(parms) cJSON_AddItemToObject(o,QUOTE(n),parms); }
  47. cJSON * cmdList;
  48. cJSON * values_fn_list;
  49. cJSON * get_cmd_list(){
  50. cJSON * element;
  51. cJSON * values=cJSON_CreateObject();
  52. cJSON * list = cJSON_CreateObject();
  53. cJSON_AddItemReferenceToObject(list,"commands",cmdList);
  54. cJSON_AddItemToObject(list,"values",values);
  55. cJSON_ArrayForEach(element,cmdList){
  56. cJSON * name = cJSON_GetObjectItem(element,"name");
  57. cJSON * vals_fn = cJSON_GetObjectItem(values_fn_list,cJSON_GetStringValue(name));
  58. if(vals_fn!=NULL ){
  59. parm_values_fn_t *parm_values_fn = (parm_values_fn_t *)strtoul(cJSON_GetStringValue(vals_fn), NULL, 16);;
  60. if(parm_values_fn){
  61. cJSON_AddItemToObject(values,cJSON_GetStringValue(name),parm_values_fn());
  62. }
  63. }
  64. }
  65. return list;
  66. }
  67. struct arg_end *getParmsEnd(struct arg_hdr * * argtable){
  68. if(!argtable) return NULL;
  69. struct arg_hdr * *table = (struct arg_hdr * *)argtable;
  70. int tabindex = 0;
  71. while (!(table[tabindex]->flag & ARG_TERMINATOR))
  72. {
  73. tabindex++;
  74. }
  75. return (struct arg_end *)table[tabindex];
  76. }
  77. cJSON * ParmsToJSON(struct arg_hdr * * argtable){
  78. if(!argtable) return NULL;
  79. cJSON * arg_list = cJSON_CreateArray();
  80. struct arg_hdr * *table = (struct arg_hdr * *)argtable;
  81. int tabindex = 0;
  82. while (!(table[tabindex]->flag & ARG_TERMINATOR))
  83. {
  84. cJSON * entry = cJSON_CreateObject();
  85. ADD_TO_JSON(entry,table[tabindex],datatype);
  86. ADD_TO_JSON(entry,table[tabindex],glossary);
  87. ADD_TO_JSON(entry,table[tabindex],longopts);
  88. ADD_TO_JSON(entry,table[tabindex],shortopts);
  89. cJSON_AddBoolToObject(entry, "checkbox", (table[tabindex]->flag & ARG_HASOPTVALUE)==0 && (table[tabindex]->flag & ARG_HASVALUE)==0 && (table[tabindex]->longopts || table[tabindex]->shortopts) );
  90. cJSON_AddBoolToObject(entry, "remark", (table[tabindex]->flag & ARG_HASOPTVALUE)==0 && (table[tabindex]->flag & ARG_HASVALUE)==0 && (!table[tabindex]->longopts && !table[tabindex]->shortopts));
  91. cJSON_AddBoolToObject(entry, "hasvalue", table[tabindex]->flag & ARG_HASVALUE);
  92. cJSON_AddNumberToObject(entry,"mincount",table[tabindex]->mincount);
  93. cJSON_AddNumberToObject(entry,"maxcount",table[tabindex]->maxcount);
  94. cJSON_AddItemToArray(arg_list, entry);
  95. tabindex++;
  96. }
  97. return arg_list;
  98. }
  99. esp_err_t cmd_to_json(const esp_console_cmd_t *cmd){
  100. return cmd_to_json_with_cb(cmd, NULL);
  101. }
  102. esp_err_t cmd_to_json_with_cb(const esp_console_cmd_t *cmd, parm_values_fn_t parm_values_fn){
  103. if(!cmdList){
  104. cmdList=cJSON_CreateArray();
  105. }
  106. if(!values_fn_list){
  107. values_fn_list=cJSON_CreateObject();
  108. }
  109. if (cmd->command == NULL) {
  110. return ESP_ERR_INVALID_ARG;
  111. }
  112. if (strchr(cmd->command, ' ') != NULL) {
  113. return ESP_ERR_INVALID_ARG;
  114. }
  115. cJSON * jsoncmd = cJSON_CreateObject();
  116. ADD_TO_JSON(jsoncmd,cmd,help);
  117. ADD_TO_JSON(jsoncmd,cmd,hint);
  118. if(parm_values_fn){
  119. char addr[11]={0};
  120. snprintf(addr,sizeof(addr),"%lx",(unsigned long)parm_values_fn);
  121. cJSON_AddStringToObject(values_fn_list,cmd->command,addr);
  122. }
  123. cJSON_AddBoolToObject(jsoncmd,"hascb",parm_values_fn!=NULL);
  124. if(cmd->argtable){
  125. cJSON_AddItemToObject(jsoncmd,"argtable",ParmsToJSON(cmd->argtable));
  126. }
  127. if (cmd->hint) {
  128. cJSON_AddStringToObject(jsoncmd, "hint", cmd->hint);
  129. }
  130. else if (cmd->argtable) {
  131. /* Generate hint based on cmd->argtable */
  132. char *buf = NULL;
  133. size_t buf_size = 0;
  134. FILE *f = open_memstream(&buf, &buf_size);
  135. if (f != NULL) {
  136. arg_print_syntax(f, cmd->argtable, NULL);
  137. fflush(f);
  138. fclose(f);
  139. }
  140. cJSON_AddStringToObject(jsoncmd, "hint", buf);
  141. FREE_AND_NULL(buf);
  142. }
  143. cJSON_AddStringToObject(jsoncmd, "name", cmd->command);
  144. char * b=cJSON_Print(jsoncmd);
  145. if(b){
  146. ESP_LOGD(TAG,"Adding command table %s",b);
  147. free(b);
  148. }
  149. cJSON_AddItemToArray(cmdList, jsoncmd);
  150. return ESP_OK;
  151. }
  152. int arg_parse_msg(int argc, char **argv, struct arg_hdr ** args){
  153. int nerrors = arg_parse(argc, argv, (void **)args);
  154. if (nerrors != 0) {
  155. char *buf = NULL;
  156. size_t buf_size = 0;
  157. FILE *f = open_memstream(&buf, &buf_size);
  158. if (f != NULL) {
  159. arg_print_errors(f, getParmsEnd(args), argv[0]);
  160. fflush (f);
  161. cmd_send_messaging(argv[0],MESSAGING_ERROR,"%s", buf);
  162. }
  163. fclose(f);
  164. FREE_AND_NULL(buf);
  165. }
  166. return nerrors;
  167. }
  168. void process_autoexec(){
  169. int i=1;
  170. char autoexec_name[21]={0};
  171. char * autoexec_value=NULL;
  172. uint8_t autoexec_flag=0;
  173. char * str_flag = config_alloc_get(NVS_TYPE_STR, "autoexec");
  174. if(!bypass_wifi_manager){
  175. ESP_LOGW(TAG, "Processing autoexec commands while wifi_manager active. Wifi related commands will be ignored.");
  176. }
  177. if(is_recovery_running){
  178. ESP_LOGD(TAG, "Processing autoexec commands in recovery mode. Squeezelite commands will be ignored.");
  179. }
  180. if(str_flag !=NULL ){
  181. autoexec_flag=atoi(str_flag);
  182. ESP_LOGI(TAG,"autoexec is set to %s auto-process", autoexec_flag>0?"perform":"skip");
  183. if(autoexec_flag == 1) {
  184. do {
  185. snprintf(autoexec_name,sizeof(autoexec_name)-1,"autoexec%u",i++);
  186. ESP_LOGD(TAG,"Getting command name %s", autoexec_name);
  187. autoexec_value= config_alloc_get(NVS_TYPE_STR, autoexec_name);
  188. if(autoexec_value!=NULL ){
  189. if(!bypass_wifi_manager && strstr(autoexec_value, "join ")!=NULL ){
  190. ESP_LOGW(TAG,"Ignoring wifi join command.");
  191. }
  192. else if(is_recovery_running && !strstr(autoexec_value, "squeezelite " ) ){
  193. ESP_LOGW(TAG,"Ignoring command. ");
  194. }
  195. else {
  196. ESP_LOGI(TAG,"Running command %s = %s", autoexec_name, autoexec_value);
  197. run_command(autoexec_value);
  198. }
  199. ESP_LOGD(TAG,"Freeing memory for command %s name", autoexec_name);
  200. free(autoexec_value);
  201. }
  202. else {
  203. ESP_LOGD(TAG,"No matching command found for name %s", autoexec_name);
  204. break;
  205. }
  206. } while(1);
  207. }
  208. free(str_flag);
  209. }
  210. else
  211. {
  212. ESP_LOGD(TAG,"No matching command found for name autoexec.");
  213. }
  214. }
  215. void initialize_console() {
  216. /* Disable buffering on stdin */
  217. setvbuf(stdin, NULL, _IONBF, 0);
  218. /* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
  219. esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
  220. /* Move the caret to the beginning of the next line on '\n' */
  221. esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
  222. /* Configure UART. Note that REF_TICK is used so that the baud rate remains
  223. * correct while APB frequency is changing in light sleep mode.
  224. */
  225. const uart_config_t uart_config = { .baud_rate =
  226. CONFIG_CONSOLE_UART_BAUDRATE, .data_bits = UART_DATA_8_BITS,
  227. .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1,
  228. .use_ref_tick = true };
  229. ESP_ERROR_CHECK(uart_param_config(CONFIG_ESP_CONSOLE_UART_NUM, &uart_config));
  230. /* Install UART driver for interrupt-driven reads and writes */
  231. ESP_ERROR_CHECK( uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM, 256, 0, 0, NULL, 0));
  232. /* Tell VFS to use UART driver */
  233. esp_vfs_dev_uart_use_driver(CONFIG_ESP_CONSOLE_UART_NUM);
  234. /* Initialize the console */
  235. esp_console_config_t console_config = { .max_cmdline_args = 28,
  236. .max_cmdline_length = 600,
  237. #if CONFIG_LOG_COLORS
  238. .hint_color = atoi(LOG_COLOR_CYAN)
  239. #endif
  240. };
  241. ESP_ERROR_CHECK(esp_console_init(&console_config));
  242. /* Configure linenoise line completion library */
  243. /* Enable multiline editing. If not set, long commands will scroll within
  244. * single line.
  245. */
  246. linenoiseSetMultiLine(1);
  247. /* Tell linenoise where to get command completions and hints */
  248. linenoiseSetCompletionCallback(&esp_console_get_completion);
  249. linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
  250. /* Set command history size */
  251. linenoiseHistorySetMaxLen(100);
  252. /* Load command history from filesystem */
  253. //linenoiseHistoryLoad(HISTORY_PATH);
  254. }
  255. void console_start() {
  256. if(!is_serial_suppressed()){
  257. initialize_console();
  258. }
  259. else {
  260. /* Initialize the console */
  261. esp_console_config_t console_config = { .max_cmdline_args = 28,
  262. .max_cmdline_length = 600,
  263. #if CONFIG_LOG_COLORS
  264. .hint_color = atoi(LOG_COLOR_CYAN)
  265. #endif
  266. };
  267. ESP_ERROR_CHECK(esp_console_init(&console_config));
  268. }
  269. /* Register commands */
  270. esp_console_register_help_command();
  271. register_system();
  272. register_config_cmd();
  273. register_nvs();
  274. register_wifi();
  275. if(!is_recovery_running){
  276. register_squeezelite();
  277. }
  278. else {
  279. register_ota_cmd();
  280. }
  281. register_i2ctools();
  282. if(!is_serial_suppressed()){
  283. printf("\n");
  284. if(is_recovery_running){
  285. printf("****************************************************************\n"
  286. "RECOVERY APPLICATION\n"
  287. "This mode is used to flash Squeezelite into the OTA partition\n"
  288. "****\n\n");
  289. }
  290. printf("Type 'help' to get the list of commands.\n"
  291. "Use UP/DOWN arrows to navigate through command history.\n"
  292. "Press TAB when typing command name to auto-complete.\n"
  293. "\n");
  294. if(!is_recovery_running){
  295. printf("To automatically execute lines at startup:\n"
  296. "\tSet NVS variable autoexec (U8) = 1 to enable, 0 to disable automatic execution.\n"
  297. "\tSet NVS variable autoexec[1~9] (string)to a command that should be executed automatically\n");
  298. }
  299. printf("\n\n");
  300. /* Figure out if the terminal supports escape sequences */
  301. int probe_status = linenoiseProbe();
  302. if (probe_status) { /* zero indicates success */
  303. printf("\n****************************\n"
  304. "Your terminal application does not support escape sequences.\n"
  305. "Line editing and history features are disabled.\n"
  306. "On Windows, try using Putty instead.\n"
  307. "****************************\n");
  308. linenoiseSetDumbMode(1);
  309. #if CONFIG_LOG_COLORS
  310. /* Since the terminal doesn't support escape sequences,
  311. * don't use color codes in the prompt.
  312. */
  313. if(is_recovery_running){
  314. recovery_prompt= "recovery-squeezelite-esp32>";
  315. }
  316. prompt = "squeezelite-esp32> ";
  317. #endif //CONFIG_LOG_COLORS
  318. }
  319. esp_pthread_cfg_t cfg = esp_pthread_get_default_config();
  320. cfg.thread_name= "console";
  321. cfg.inherit_cfg = true;
  322. if(is_recovery_running){
  323. prompt = recovery_prompt;
  324. cfg.stack_size = 4096 ;
  325. }
  326. esp_pthread_set_cfg(&cfg);
  327. pthread_attr_t attr;
  328. pthread_attr_init(&attr);
  329. pthread_create(&thread_console, &attr, console_thread, NULL);
  330. pthread_attr_destroy(&attr);
  331. }
  332. else if(!is_recovery_running){
  333. process_autoexec();
  334. }
  335. }
  336. esp_err_t run_command(char * line){
  337. /* Try to run the command */
  338. int ret;
  339. esp_err_t err = esp_console_run(line, &ret);
  340. if (err == ESP_ERR_NOT_FOUND) {
  341. ESP_LOGE(TAG,"Unrecognized command: %s", line);
  342. } else if (err == ESP_ERR_INVALID_ARG) {
  343. // command was empty
  344. } else if (err != ESP_OK && ret != ESP_OK) {
  345. ESP_LOGW(TAG,"Command returned non-zero error code: 0x%x (%s)", ret,
  346. esp_err_to_name(err));
  347. } else if (err == ESP_OK && ret != ESP_OK) {
  348. ESP_LOGW(TAG,"Command returned in error");
  349. err = ESP_FAIL;
  350. } else if (err != ESP_OK) {
  351. ESP_LOGE(TAG,"Internal error: %s", esp_err_to_name(err));
  352. }
  353. return err;
  354. }
  355. static void * console_thread() {
  356. if(!is_recovery_running){
  357. process_autoexec();
  358. }
  359. /* Main loop */
  360. while (1) {
  361. /* Get a line using linenoise.
  362. * The line is returned when ENTER is pressed.
  363. */
  364. char* line = linenoise(prompt);
  365. if (line == NULL) { /* Ignore empty lines */
  366. continue;
  367. }
  368. /* Add the command to the history */
  369. linenoiseHistoryAdd(line);
  370. /* Save command history to filesystem */
  371. linenoiseHistorySave(HISTORY_PATH);
  372. printf("\n");
  373. run_command(line);
  374. /* linenoise allocates line buffer on the heap, so need to free it */
  375. linenoiseFree(line);
  376. taskYIELD();
  377. }
  378. return NULL;
  379. }