platform_console.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 "tools.h"
  26. #include "messaging.h"
  27. #include "config.h"
  28. static pthread_t thread_console;
  29. static void * console_thread();
  30. void console_start();
  31. static const char * TAG = "console";
  32. extern bool bypass_network_manager;
  33. extern void register_squeezelite();
  34. static EXT_RAM_ATTR QueueHandle_t uart_queue;
  35. static EXT_RAM_ATTR struct {
  36. uint8_t _buf[512];
  37. StaticRingbuffer_t _ringbuf;
  38. RingbufHandle_t handle;
  39. QueueSetHandle_t queue_set;
  40. } stdin_redir;
  41. /* Prompt to be printed before each line.
  42. * This can be customized, made dynamic, etc.
  43. */
  44. const char* prompt = LOG_COLOR_I "squeezelite-esp32> " LOG_RESET_COLOR;
  45. const char* recovery_prompt = LOG_COLOR_E "recovery-squeezelite-esp32> " LOG_RESET_COLOR;
  46. /* Console command history can be stored to and loaded from a file.
  47. * The easiest way to do this is to use FATFS filesystem on top of
  48. * wear_levelling library.
  49. */
  50. #define MOUNT_PATH "/data"
  51. #define HISTORY_PATH MOUNT_PATH "/history.txt"
  52. static esp_err_t run_command(char * line);
  53. #define ADD_TO_JSON(o,t,n) if (t->n) cJSON_AddStringToObject(o,QUOTE(n),t->n);
  54. #define ADD_PARMS_TO_CMD(o,t,n) { cJSON * parms = ParmsToJSON(&t.n->hdr); if(parms) cJSON_AddItemToObject(o,QUOTE(n),parms); }
  55. cJSON * cmdList;
  56. cJSON * values_fn_list;
  57. cJSON * get_cmd_list(){
  58. cJSON * element;
  59. cJSON * values=cJSON_CreateObject();
  60. cJSON * list = cJSON_CreateObject();
  61. cJSON_AddItemReferenceToObject(list,"commands",cmdList);
  62. cJSON_AddItemToObject(list,"values",values);
  63. cJSON_ArrayForEach(element,cmdList){
  64. cJSON * name = cJSON_GetObjectItem(element,"name");
  65. cJSON * vals_fn = cJSON_GetObjectItem(values_fn_list,cJSON_GetStringValue(name));
  66. if(vals_fn!=NULL ){
  67. parm_values_fn_t *parm_values_fn = (parm_values_fn_t *)strtoul(cJSON_GetStringValue(vals_fn), NULL, 16);;
  68. if(parm_values_fn){
  69. cJSON_AddItemToObject(values,cJSON_GetStringValue(name),parm_values_fn());
  70. }
  71. }
  72. }
  73. return list;
  74. }
  75. void console_set_bool_parameter(cJSON * root,char * nvs_name, struct arg_lit *arg){
  76. char * p=NULL;
  77. if(!root) {
  78. ESP_LOGE(TAG,"Invalid json parameter. Cannot set %s from %s",arg->hdr.longopts?arg->hdr.longopts:arg->hdr.glossary,nvs_name);
  79. return;
  80. }
  81. if ((p = config_alloc_get(NVS_TYPE_STR, nvs_name)) != NULL) {
  82. cJSON_AddBoolToObject(root,arg->hdr.longopts,strcmp(p,"1") == 0 || strcasecmp(p,"y") == 0);
  83. FREE_AND_NULL(p);
  84. }
  85. }
  86. struct arg_end *getParmsEnd(struct arg_hdr * * argtable){
  87. if(!argtable) return NULL;
  88. struct arg_hdr * *table = (struct arg_hdr * *)argtable;
  89. int tabindex = 0;
  90. while (!(table[tabindex]->flag & ARG_TERMINATOR))
  91. {
  92. tabindex++;
  93. }
  94. return (struct arg_end *)table[tabindex];
  95. }
  96. cJSON * ParmsToJSON(struct arg_hdr * * argtable){
  97. if(!argtable) return NULL;
  98. cJSON * arg_list = cJSON_CreateArray();
  99. struct arg_hdr * *table = (struct arg_hdr * *)argtable;
  100. int tabindex = 0;
  101. while (!(table[tabindex]->flag & ARG_TERMINATOR))
  102. {
  103. cJSON * entry = cJSON_CreateObject();
  104. ADD_TO_JSON(entry,table[tabindex],datatype);
  105. ADD_TO_JSON(entry,table[tabindex],glossary);
  106. ADD_TO_JSON(entry,table[tabindex],longopts);
  107. ADD_TO_JSON(entry,table[tabindex],shortopts);
  108. cJSON_AddBoolToObject(entry, "checkbox", (table[tabindex]->flag & ARG_HASOPTVALUE)==0 && (table[tabindex]->flag & ARG_HASVALUE)==0 && (table[tabindex]->longopts || table[tabindex]->shortopts) );
  109. cJSON_AddBoolToObject(entry, "remark", (table[tabindex]->flag & ARG_HASOPTVALUE)==0 && (table[tabindex]->flag & ARG_HASVALUE)==0 && (!table[tabindex]->longopts && !table[tabindex]->shortopts));
  110. cJSON_AddBoolToObject(entry, "hasvalue", table[tabindex]->flag & ARG_HASVALUE);
  111. cJSON_AddNumberToObject(entry,"mincount",table[tabindex]->mincount);
  112. cJSON_AddNumberToObject(entry,"maxcount",table[tabindex]->maxcount);
  113. cJSON_AddItemToArray(arg_list, entry);
  114. tabindex++;
  115. }
  116. return arg_list;
  117. }
  118. esp_err_t cmd_to_json(const esp_console_cmd_t *cmd){
  119. return cmd_to_json_with_cb(cmd, NULL);
  120. }
  121. esp_err_t cmd_to_json_with_cb(const esp_console_cmd_t *cmd, parm_values_fn_t parm_values_fn){
  122. if(!cmdList){
  123. cmdList=cJSON_CreateArray();
  124. }
  125. if(!values_fn_list){
  126. values_fn_list=cJSON_CreateObject();
  127. }
  128. if (cmd->command == NULL) {
  129. return ESP_ERR_INVALID_ARG;
  130. }
  131. if (strchr(cmd->command, ' ') != NULL) {
  132. return ESP_ERR_INVALID_ARG;
  133. }
  134. cJSON * jsoncmd = cJSON_CreateObject();
  135. ADD_TO_JSON(jsoncmd,cmd,help);
  136. ADD_TO_JSON(jsoncmd,cmd,hint);
  137. if(parm_values_fn){
  138. char addr[11]={0};
  139. snprintf(addr,sizeof(addr),"%lx",(unsigned long)parm_values_fn);
  140. cJSON_AddStringToObject(values_fn_list,cmd->command,addr);
  141. }
  142. cJSON_AddBoolToObject(jsoncmd,"hascb",parm_values_fn!=NULL);
  143. if(cmd->argtable){
  144. cJSON_AddItemToObject(jsoncmd,"argtable",ParmsToJSON(cmd->argtable));
  145. }
  146. if (cmd->hint) {
  147. cJSON_AddStringToObject(jsoncmd, "hint", cmd->hint);
  148. }
  149. else if (cmd->argtable) {
  150. /* Generate hint based on cmd->argtable */
  151. char *buf = NULL;
  152. size_t buf_size = 0;
  153. FILE *f = open_memstream(&buf, &buf_size);
  154. if (f != NULL) {
  155. arg_print_syntax(f, cmd->argtable, NULL);
  156. fflush(f);
  157. fclose(f);
  158. }
  159. cJSON_AddStringToObject(jsoncmd, "hint", buf);
  160. FREE_AND_NULL(buf);
  161. }
  162. cJSON_AddStringToObject(jsoncmd, "name", cmd->command);
  163. char * b=cJSON_Print(jsoncmd);
  164. if(b){
  165. ESP_LOGD(TAG,"Adding command table %s",b);
  166. free(b);
  167. }
  168. cJSON_AddItemToArray(cmdList, jsoncmd);
  169. return ESP_OK;
  170. }
  171. int arg_parse_msg(int argc, char **argv, struct arg_hdr ** args){
  172. int nerrors = arg_parse(argc, argv, (void **)args);
  173. if (nerrors != 0) {
  174. char *buf = NULL;
  175. size_t buf_size = 0;
  176. FILE *f = open_memstream(&buf, &buf_size);
  177. if (f != NULL) {
  178. arg_print_errors(f, getParmsEnd(args), argv[0]);
  179. fflush (f);
  180. cmd_send_messaging(argv[0],MESSAGING_ERROR,"%s", buf);
  181. }
  182. fclose(f);
  183. FREE_AND_NULL(buf);
  184. }
  185. return nerrors;
  186. }
  187. void process_autoexec(){
  188. int i=1;
  189. char autoexec_name[21]={0};
  190. char * autoexec_value=NULL;
  191. uint8_t autoexec_flag=0;
  192. char * str_flag = config_alloc_get(NVS_TYPE_STR, "autoexec");
  193. if(!bypass_network_manager){
  194. ESP_LOGW(TAG, "Processing autoexec commands while network manager active. Wifi related commands will be ignored.");
  195. }
  196. if(is_recovery_running){
  197. ESP_LOGD(TAG, "Processing autoexec commands in recovery mode. Squeezelite commands will be ignored.");
  198. }
  199. if(str_flag !=NULL ){
  200. autoexec_flag=atoi(str_flag);
  201. ESP_LOGI(TAG,"autoexec is set to %s auto-process", autoexec_flag>0?"perform":"skip");
  202. if(autoexec_flag == 1) {
  203. do {
  204. snprintf(autoexec_name,sizeof(autoexec_name)-1,"autoexec%u",i++);
  205. ESP_LOGD(TAG,"Getting command name %s", autoexec_name);
  206. autoexec_value= config_alloc_get(NVS_TYPE_STR, autoexec_name);
  207. if(autoexec_value!=NULL ){
  208. if(!bypass_network_manager && strstr(autoexec_value, "join ")!=NULL ){
  209. ESP_LOGW(TAG,"Ignoring wifi join command.");
  210. }
  211. else if(is_recovery_running && !strstr(autoexec_value, "squeezelite " ) ){
  212. ESP_LOGW(TAG,"Ignoring command. ");
  213. }
  214. else {
  215. ESP_LOGI(TAG,"Running command %s = %s", autoexec_name, autoexec_value);
  216. run_command(autoexec_value);
  217. }
  218. ESP_LOGD(TAG,"Freeing memory for command %s name", autoexec_name);
  219. free(autoexec_value);
  220. }
  221. else {
  222. ESP_LOGD(TAG,"No matching command found for name %s", autoexec_name);
  223. break;
  224. }
  225. } while(1);
  226. }
  227. free(str_flag);
  228. }
  229. else
  230. {
  231. ESP_LOGD(TAG,"No matching command found for name autoexec.");
  232. }
  233. }
  234. static ssize_t stdin_read(int fd, void* data, size_t size) {
  235. size_t bytes = -1;
  236. while (1) {
  237. QueueSetMemberHandle_t activated = xQueueSelectFromSet(stdin_redir.queue_set, portMAX_DELAY);
  238. if (activated == uart_queue) {
  239. uart_event_t event;
  240. xQueueReceive(uart_queue, &event, 0);
  241. if (event.type == UART_DATA) {
  242. bytes = uart_read_bytes(CONFIG_ESP_CONSOLE_UART_NUM, data, size < event.size ? size : event.size, 0);
  243. // we have to do our own line ending translation here
  244. for (int i = 0; i < bytes; i++) if (((char*)data)[i] == '\r') ((char*)data)[i] = '\n';
  245. break;
  246. }
  247. } else if (xRingbufferCanRead(stdin_redir.handle, activated)) {
  248. char *p = xRingbufferReceiveUpTo(stdin_redir.handle, &bytes, 0, size);
  249. // we might receive strings, replace null by \n
  250. for (int i = 0; i < bytes; i++) if (p[i] == '\0' || p[i] == '\r') p[i] = '\n';
  251. memcpy(data, p, bytes);
  252. vRingbufferReturnItem(stdin_redir.handle, p);
  253. break;
  254. }
  255. }
  256. return bytes;
  257. }
  258. static int stdin_dummy(const char * path, int flags, int mode) { return 0; }
  259. void initialize_console() {
  260. /* Minicom, screen, idf_monitor send CR when ENTER key is pressed (unused if we redirect stdin) */
  261. esp_vfs_dev_uart_port_set_rx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CR);
  262. /* Move the caret to the beginning of the next line on '\n' */
  263. esp_vfs_dev_uart_port_set_tx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CRLF);
  264. /* Configure UART. Note that REF_TICK is used so that the baud rate remains
  265. * correct while APB frequency is changing in light sleep mode.
  266. */
  267. const uart_config_t uart_config = { .baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE,
  268. .data_bits = UART_DATA_8_BITS,
  269. .parity = UART_PARITY_DISABLE, .stop_bits = UART_STOP_BITS_1,
  270. };
  271. ESP_ERROR_CHECK(uart_param_config(CONFIG_ESP_CONSOLE_UART_NUM, &uart_config));
  272. /* Install UART driver for interrupt-driven reads and writes */
  273. ESP_ERROR_CHECK( uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM, 256, 0, 3, &uart_queue, 0));
  274. /* Tell VFS to use UART driver */
  275. esp_vfs_dev_uart_use_driver(CONFIG_ESP_CONSOLE_UART_NUM);
  276. /* re-direct stdin to our own driver so we can gather data from various sources */
  277. stdin_redir.queue_set = xQueueCreateSet(2);
  278. stdin_redir.handle = xRingbufferCreateStatic(sizeof(stdin_redir._buf), RINGBUF_TYPE_BYTEBUF, stdin_redir._buf, &stdin_redir._ringbuf);
  279. xRingbufferAddToQueueSetRead(stdin_redir.handle, stdin_redir.queue_set);
  280. xQueueAddToSet(uart_queue, stdin_redir.queue_set);
  281. esp_vfs_t vfs = { };
  282. vfs.flags = ESP_VFS_FLAG_DEFAULT;
  283. vfs.open = stdin_dummy;
  284. vfs.read = stdin_read;
  285. ESP_ERROR_CHECK(esp_vfs_register("/dev/redirect", &vfs, NULL));
  286. freopen("/dev/redirect", "r", stdin);
  287. /* Disable buffering on stdin */
  288. setvbuf(stdin, NULL, _IONBF, 0);
  289. /* Initialize the console */
  290. esp_console_config_t console_config = { .max_cmdline_args = 28,
  291. .max_cmdline_length = 600,
  292. #if CONFIG_LOG_COLORS
  293. .hint_color = atoi(LOG_COLOR_CYAN)
  294. #endif
  295. };
  296. ESP_ERROR_CHECK(esp_console_init(&console_config));
  297. /* Configure linenoise line completion library */
  298. /* Enable multiline editing. If not set, long commands will scroll within
  299. * single line.
  300. */
  301. linenoiseSetMultiLine(1);
  302. /* Tell linenoise where to get command completions and hints */
  303. linenoiseSetCompletionCallback(&esp_console_get_completion);
  304. linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
  305. /* Set command history size */
  306. linenoiseHistorySetMaxLen(100);
  307. /* Load command history from filesystem */
  308. //linenoiseHistoryLoad(HISTORY_PATH);
  309. }
  310. bool console_push(const char *data, size_t size) {
  311. return xRingbufferSend(stdin_redir.handle, data, size, pdMS_TO_TICKS(100)) == pdPASS;
  312. }
  313. void console_start() {
  314. /* we always run console b/c telnet sends commands to stdin */
  315. initialize_console();
  316. /* Register commands */
  317. MEMTRACE_PRINT_DELTA_MESSAGE("Registering help command");
  318. esp_console_register_help_command();
  319. MEMTRACE_PRINT_DELTA_MESSAGE("Registering system commands");
  320. register_system();
  321. MEMTRACE_PRINT_DELTA_MESSAGE("Registering config commands");
  322. register_config_cmd();
  323. MEMTRACE_PRINT_DELTA_MESSAGE("Registering nvs commands");
  324. register_nvs();
  325. MEMTRACE_PRINT_DELTA_MESSAGE("Registering wifi commands");
  326. register_wifi();
  327. if(!is_recovery_running){
  328. MEMTRACE_PRINT_DELTA_MESSAGE("Registering squeezelite commands");
  329. register_squeezelite();
  330. }
  331. else {
  332. MEMTRACE_PRINT_DELTA_MESSAGE("Registering recovery commands");
  333. register_ota_cmd();
  334. }
  335. MEMTRACE_PRINT_DELTA_MESSAGE("Registering i2c commands");
  336. register_i2ctools();
  337. printf("\n");
  338. if(is_recovery_running){
  339. printf("****************************************************************\n"
  340. "RECOVERY APPLICATION\n"
  341. "This mode is used to flash Squeezelite into the OTA partition\n"
  342. "****\n\n");
  343. }
  344. printf("Type 'help' to get the list of commands.\n"
  345. "Use UP/DOWN arrows to navigate through command history.\n"
  346. "Press TAB when typing command name to auto-complete.\n"
  347. "\n");
  348. if(!is_recovery_running){
  349. printf("To automatically execute lines at startup:\n"
  350. "\tSet NVS variable autoexec (U8) = 1 to enable, 0 to disable automatic execution.\n"
  351. "\tSet NVS variable autoexec[1~9] (string)to a command that should be executed automatically\n");
  352. }
  353. printf("\n\n");
  354. /* Figure out if the terminal supports escape sequences */
  355. int probe_status = linenoiseProbe();
  356. if (probe_status) { /* zero indicates success */
  357. printf("\n****************************\n"
  358. "Your terminal application does not support escape sequences.\n"
  359. "Line editing and history features are disabled.\n"
  360. "On Windows, try using Putty instead.\n"
  361. "****************************\n");
  362. linenoiseSetDumbMode(1);
  363. #if CONFIG_LOG_COLORS
  364. /* Since the terminal doesn't support escape sequences,
  365. * don't use color codes in the prompt.
  366. */
  367. if(is_recovery_running){
  368. recovery_prompt= "recovery-squeezelite-esp32>";
  369. }
  370. prompt = "squeezelite-esp32> ";
  371. #endif //CONFIG_LOG_COLORS
  372. }
  373. esp_pthread_cfg_t cfg = esp_pthread_get_default_config();
  374. cfg.thread_name= "console";
  375. cfg.inherit_cfg = true;
  376. cfg.stack_size = 4*1024;
  377. if(is_recovery_running){
  378. prompt = recovery_prompt;
  379. }
  380. MEMTRACE_PRINT_DELTA_MESSAGE("Creating console thread with stack size of 4096 bytes");
  381. esp_pthread_set_cfg(&cfg);
  382. pthread_create(&thread_console, NULL, console_thread, NULL);
  383. MEMTRACE_PRINT_DELTA_MESSAGE("Console thread created");
  384. }
  385. static esp_err_t run_command(char * line){
  386. /* Try to run the command */
  387. int ret;
  388. esp_err_t err = esp_console_run(line, &ret);
  389. if (err == ESP_ERR_NOT_FOUND) {
  390. ESP_LOGE(TAG,"Unrecognized command: %s", line);
  391. } else if (err == ESP_ERR_INVALID_ARG) {
  392. // command was empty
  393. } else if (err != ESP_OK && ret != ESP_OK) {
  394. ESP_LOGW(TAG,"Command returned non-zero error code: 0x%x (%s)", ret,
  395. esp_err_to_name(err));
  396. } else if (err == ESP_OK && ret != ESP_OK) {
  397. ESP_LOGW(TAG,"Command returned in error");
  398. err = ESP_FAIL;
  399. } else if (err != ESP_OK) {
  400. ESP_LOGE(TAG,"Internal error: %s", esp_err_to_name(err));
  401. }
  402. return err;
  403. }
  404. static void * console_thread() {
  405. if(!is_recovery_running){
  406. MEMTRACE_PRINT_DELTA_MESSAGE("Running autoexec");
  407. process_autoexec();
  408. MEMTRACE_PRINT_DELTA_MESSAGE("Autoexec done");
  409. }
  410. /* Main loop */
  411. while (1) {
  412. /* Get a line using linenoise.
  413. * The line is returned when ENTER is pressed.
  414. */
  415. char* line = linenoise(prompt);
  416. if (line == NULL) { /* Ignore empty lines */
  417. continue;
  418. }
  419. /* Add the command to the history */
  420. linenoiseHistoryAdd(line);
  421. /* Save command history to filesystem */
  422. linenoiseHistorySave(HISTORY_PATH);
  423. printf("\n");
  424. run_command(line);
  425. /* linenoise allocates line buffer on the heap, so need to free it */
  426. linenoiseFree(line);
  427. taskYIELD();
  428. }
  429. return NULL;
  430. }