esp_console_repl.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. // Copyright 2016-2020 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdint.h>
  15. #include <stdio.h>
  16. #include <fcntl.h>
  17. #include <sys/cdefs.h>
  18. #include "sdkconfig.h"
  19. #include "esp_err.h"
  20. #include "esp_log.h"
  21. #include "esp_console.h"
  22. #include "esp_vfs_dev.h"
  23. #include "esp_vfs_cdcacm.h"
  24. #include "freertos/FreeRTOS.h"
  25. #include "freertos/task.h"
  26. #include "driver/uart.h"
  27. #include "linenoise/linenoise.h"
  28. static const char *TAG = "console.repl";
  29. #define CONSOLE_PROMPT_MAX_LEN (32)
  30. #define CONSOLE_PATH_MAX_LEN (ESP_VFS_PATH_MAX)
  31. typedef enum {
  32. CONSOLE_REPL_STATE_DEINIT,
  33. CONSOLE_REPL_STATE_INIT,
  34. CONSOLE_REPL_STATE_START,
  35. } repl_state_t;
  36. typedef struct {
  37. esp_console_repl_t repl_core; // base class
  38. char prompt[CONSOLE_PROMPT_MAX_LEN]; // Prompt to be printed before each line
  39. repl_state_t state;
  40. const char *history_save_path;
  41. TaskHandle_t task_hdl; // REPL task handle
  42. } esp_console_repl_com_t;
  43. typedef struct {
  44. esp_console_repl_com_t repl_com; // base class
  45. int uart_channel; // uart channel number
  46. } esp_console_repl_universal_t;
  47. static void esp_console_repl_task(void *args);
  48. static esp_err_t esp_console_repl_uart_delete(esp_console_repl_t *repl);
  49. static esp_err_t esp_console_repl_usb_cdc_delete(esp_console_repl_t *repl);
  50. static esp_err_t esp_console_common_init(esp_console_repl_com_t *repl_com);
  51. static esp_err_t esp_console_setup_prompt(const char *prompt, esp_console_repl_com_t *repl_com);
  52. static esp_err_t esp_console_setup_history(const char *history_path, uint32_t max_history_len, esp_console_repl_com_t *repl_com);
  53. esp_err_t esp_console_new_repl_usb_cdc(const esp_console_dev_usb_cdc_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl)
  54. {
  55. esp_err_t ret = ESP_OK;
  56. esp_console_repl_universal_t *cdc_repl = NULL;
  57. if (!repl_config | !dev_config | !ret_repl) {
  58. ret = ESP_ERR_INVALID_ARG;
  59. goto _exit;
  60. }
  61. // allocate memory for console REPL context
  62. cdc_repl = calloc(1, sizeof(esp_console_repl_universal_t));
  63. if (!cdc_repl) {
  64. ret = ESP_ERR_NO_MEM;
  65. goto _exit;
  66. }
  67. /* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
  68. esp_vfs_dev_cdcacm_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
  69. /* Move the caret to the beginning of the next line on '\n' */
  70. esp_vfs_dev_cdcacm_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
  71. /* Enable non-blocking mode on stdin and stdout */
  72. fcntl(fileno(stdout), F_SETFL, 0);
  73. fcntl(fileno(stdin), F_SETFL, 0);
  74. // initialize console, common part
  75. ret = esp_console_common_init(&cdc_repl->repl_com);
  76. if (ret != ESP_OK) {
  77. goto _exit;
  78. }
  79. // setup history
  80. ret = esp_console_setup_history(repl_config->history_save_path, repl_config->max_history_len, &cdc_repl->repl_com);
  81. if (ret != ESP_OK) {
  82. goto _exit;
  83. }
  84. // setup prompt
  85. esp_console_setup_prompt(repl_config->prompt, &cdc_repl->repl_com);
  86. /* Fill the structure here as it will be used directly by the created task. */
  87. cdc_repl->uart_channel = CONFIG_ESP_CONSOLE_UART_NUM;
  88. cdc_repl->repl_com.state = CONSOLE_REPL_STATE_INIT;
  89. cdc_repl->repl_com.repl_core.del = esp_console_repl_usb_cdc_delete;
  90. /* spawn a single thread to run REPL */
  91. if (xTaskCreate(esp_console_repl_task, "console_repl", repl_config->task_stack_size,
  92. cdc_repl, repl_config->task_priority, &cdc_repl->repl_com.task_hdl) != pdTRUE) {
  93. ret = ESP_FAIL;
  94. goto _exit;
  95. }
  96. *ret_repl = &cdc_repl->repl_com.repl_core;
  97. return ESP_OK;
  98. _exit:
  99. if (cdc_repl) {
  100. esp_console_deinit();
  101. free(cdc_repl);
  102. }
  103. if (ret_repl) {
  104. *ret_repl = NULL;
  105. }
  106. return ret;
  107. }
  108. esp_err_t esp_console_new_repl_uart(const esp_console_dev_uart_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl)
  109. {
  110. esp_err_t ret = ESP_OK;
  111. esp_console_repl_universal_t *uart_repl = NULL;
  112. if (!repl_config | !dev_config | !ret_repl) {
  113. ret = ESP_ERR_INVALID_ARG;
  114. goto _exit;
  115. }
  116. // allocate memory for console REPL context
  117. uart_repl = calloc(1, sizeof(esp_console_repl_universal_t));
  118. if (!uart_repl) {
  119. ret = ESP_ERR_NO_MEM;
  120. goto _exit;
  121. }
  122. /* Drain stdout before reconfiguring it */
  123. fflush(stdout);
  124. fsync(fileno(stdout));
  125. /* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
  126. esp_vfs_dev_uart_port_set_rx_line_endings(dev_config->channel, ESP_LINE_ENDINGS_CR);
  127. /* Move the caret to the beginning of the next line on '\n' */
  128. esp_vfs_dev_uart_port_set_tx_line_endings(dev_config->channel, ESP_LINE_ENDINGS_CRLF);
  129. /* Configure UART. Note that REF_TICK/XTAL is used so that the baud rate remains
  130. * correct while APB frequency is changing in light sleep mode.
  131. */
  132. const uart_config_t uart_config = {
  133. .baud_rate = dev_config->baud_rate,
  134. .data_bits = UART_DATA_8_BITS,
  135. .parity = UART_PARITY_DISABLE,
  136. .stop_bits = UART_STOP_BITS_1,
  137. #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
  138. .source_clk = UART_SCLK_REF_TICK,
  139. #else
  140. .source_clk = UART_SCLK_XTAL,
  141. #endif
  142. };
  143. uart_param_config(dev_config->channel, &uart_config);
  144. uart_set_pin(dev_config->channel, dev_config->tx_gpio_num, dev_config->rx_gpio_num, -1, -1);
  145. /* Install UART driver for interrupt-driven reads and writes */
  146. ret = uart_driver_install(dev_config->channel, 256, 0, 0, NULL, 0);
  147. if (ret != ESP_OK) {
  148. goto _exit;
  149. }
  150. /* Tell VFS to use UART driver */
  151. esp_vfs_dev_uart_use_driver(dev_config->channel);
  152. // initialize console, common part
  153. ret = esp_console_common_init(&uart_repl->repl_com);
  154. if (ret != ESP_OK) {
  155. goto _exit;
  156. }
  157. // setup history
  158. ret = esp_console_setup_history(repl_config->history_save_path, repl_config->max_history_len, &uart_repl->repl_com);
  159. if (ret != ESP_OK) {
  160. goto _exit;
  161. }
  162. // setup prompt
  163. esp_console_setup_prompt(repl_config->prompt, &uart_repl->repl_com);
  164. /* Fill the structure here as it will be used directly by the created task. */
  165. uart_repl->uart_channel = dev_config->channel;
  166. uart_repl->repl_com.state = CONSOLE_REPL_STATE_INIT;
  167. uart_repl->repl_com.repl_core.del = esp_console_repl_uart_delete;
  168. /* Spawn a single thread to run REPL, we need to pass `uart_repl` to it as
  169. * it also requires the uart channel. */
  170. if (xTaskCreate(esp_console_repl_task, "console_repl", repl_config->task_stack_size,
  171. uart_repl, repl_config->task_priority, &uart_repl->repl_com.task_hdl) != pdTRUE) {
  172. ret = ESP_FAIL;
  173. goto _exit;
  174. }
  175. *ret_repl = &uart_repl->repl_com.repl_core;
  176. return ESP_OK;
  177. _exit:
  178. if (uart_repl) {
  179. esp_console_deinit();
  180. uart_driver_delete(dev_config->channel);
  181. free(uart_repl);
  182. }
  183. if (ret_repl) {
  184. *ret_repl = NULL;
  185. }
  186. return ret;
  187. }
  188. esp_err_t esp_console_start_repl(esp_console_repl_t *repl)
  189. {
  190. esp_err_t ret = ESP_OK;
  191. esp_console_repl_com_t *repl_com = __containerof(repl, esp_console_repl_com_t, repl_core);
  192. // check if already initialized
  193. if (repl_com->state != CONSOLE_REPL_STATE_INIT) {
  194. ret = ESP_ERR_INVALID_STATE;
  195. goto _exit;
  196. }
  197. repl_com->state = CONSOLE_REPL_STATE_START;
  198. xTaskNotifyGive(repl_com->task_hdl);
  199. return ESP_OK;
  200. _exit:
  201. return ret;
  202. }
  203. static esp_err_t esp_console_setup_prompt(const char *prompt, esp_console_repl_com_t *repl_com)
  204. {
  205. /* set command line prompt */
  206. const char *prompt_temp = "esp>";
  207. if (prompt) {
  208. prompt_temp = prompt;
  209. }
  210. snprintf(repl_com->prompt, CONSOLE_PROMPT_MAX_LEN - 1, LOG_COLOR_I "%s " LOG_RESET_COLOR, prompt_temp);
  211. /* Figure out if the terminal supports escape sequences */
  212. int probe_status = linenoiseProbe();
  213. if (probe_status) {
  214. /* zero indicates success */
  215. linenoiseSetDumbMode(1);
  216. #if CONFIG_LOG_COLORS
  217. /* Since the terminal doesn't support escape sequences,
  218. * don't use color codes in the s_prompt.
  219. */
  220. snprintf(repl_com->prompt, CONSOLE_PROMPT_MAX_LEN - 1, "%s ", prompt_temp);
  221. #endif //CONFIG_LOG_COLORS
  222. }
  223. return ESP_OK;
  224. }
  225. static esp_err_t esp_console_setup_history(const char *history_path, uint32_t max_history_len, esp_console_repl_com_t *repl_com)
  226. {
  227. esp_err_t ret = ESP_OK;
  228. repl_com->history_save_path = history_path;
  229. if (history_path) {
  230. /* Load command history from filesystem */
  231. linenoiseHistoryLoad(history_path);
  232. }
  233. /* Set command history size */
  234. if (linenoiseHistorySetMaxLen(max_history_len) != 1) {
  235. ESP_LOGE(TAG, "set max history length to %d failed", max_history_len);
  236. ret = ESP_FAIL;
  237. goto _exit;
  238. }
  239. return ESP_OK;
  240. _exit:
  241. return ret;
  242. }
  243. static esp_err_t esp_console_common_init(esp_console_repl_com_t *repl_com)
  244. {
  245. esp_err_t ret = ESP_OK;
  246. /* Initialize the console */
  247. esp_console_config_t console_config = ESP_CONSOLE_CONFIG_DEFAULT();
  248. #if CONFIG_LOG_COLORS
  249. console_config.hint_color = atoi(LOG_COLOR_CYAN);
  250. #endif
  251. ret = esp_console_init(&console_config);
  252. if (ret != ESP_OK) {
  253. goto _exit;
  254. }
  255. ret = esp_console_register_help_command();
  256. if (ret != ESP_OK) {
  257. goto _exit;
  258. }
  259. /* Configure linenoise line completion library */
  260. /* Enable multiline editing. If not set, long commands will scroll within single line */
  261. linenoiseSetMultiLine(1);
  262. /* Tell linenoise where to get command completions and hints */
  263. linenoiseSetCompletionCallback(&esp_console_get_completion);
  264. linenoiseSetHintsCallback((linenoiseHintsCallback *)&esp_console_get_hint);
  265. return ESP_OK;
  266. _exit:
  267. return ret;
  268. }
  269. static esp_err_t esp_console_repl_uart_delete(esp_console_repl_t *repl)
  270. {
  271. esp_err_t ret = ESP_OK;
  272. esp_console_repl_com_t *repl_com = __containerof(repl, esp_console_repl_com_t, repl_core);
  273. esp_console_repl_universal_t *uart_repl = __containerof(repl_com, esp_console_repl_universal_t, repl_com);
  274. // check if already de-initialized
  275. if (repl_com->state == CONSOLE_REPL_STATE_DEINIT) {
  276. ESP_LOGE(TAG, "already de-initialized");
  277. ret = ESP_ERR_INVALID_STATE;
  278. goto _exit;
  279. }
  280. repl_com->state = CONSOLE_REPL_STATE_DEINIT;
  281. esp_console_deinit();
  282. esp_vfs_dev_uart_use_nonblocking(uart_repl->uart_channel);
  283. uart_driver_delete(uart_repl->uart_channel);
  284. free(uart_repl);
  285. _exit:
  286. return ret;
  287. }
  288. static esp_err_t esp_console_repl_usb_cdc_delete(esp_console_repl_t *repl)
  289. {
  290. esp_err_t ret = ESP_OK;
  291. esp_console_repl_com_t *repl_com = __containerof(repl, esp_console_repl_com_t, repl_core);
  292. esp_console_repl_universal_t *cdc_repl = __containerof(repl_com, esp_console_repl_universal_t, repl_com);
  293. // check if already de-initialized
  294. if (repl_com->state == CONSOLE_REPL_STATE_DEINIT) {
  295. ESP_LOGE(TAG, "already de-initialized");
  296. ret = ESP_ERR_INVALID_STATE;
  297. goto _exit;
  298. }
  299. repl_com->state = CONSOLE_REPL_STATE_DEINIT;
  300. esp_console_deinit();
  301. free(cdc_repl);
  302. _exit:
  303. return ret;
  304. }
  305. static void esp_console_repl_task(void *args)
  306. {
  307. esp_console_repl_universal_t *repl_conf = (esp_console_repl_universal_t *) args;
  308. esp_console_repl_com_t *repl_com = &repl_conf->repl_com;
  309. const int uart_channel = repl_conf->uart_channel;
  310. /* Waiting for task notify. This happens when `esp_console_start_repl()`
  311. * function is called. */
  312. ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
  313. /* Change standard input and output of the task if the requested UART is
  314. * NOT the default one. This block will replace stdin, stdout and stderr.
  315. */
  316. if (uart_channel != CONFIG_ESP_CONSOLE_UART_NUM) {
  317. char path[CONSOLE_PATH_MAX_LEN] = { 0 };
  318. snprintf(path, CONSOLE_PATH_MAX_LEN, "/dev/uart/%d", uart_channel);
  319. stdin = fopen(path, "r");
  320. stdout = fopen(path, "w");
  321. stderr = stdout;
  322. }
  323. /* Disable buffering on stdin of the current task.
  324. * If the console is ran on a different UART than the default one,
  325. * buffering shall only be disabled for the current one. */
  326. setvbuf(stdin, NULL, _IONBF, 0);
  327. /* This message shall be printed here and not earlier as the stdout
  328. * has just been set above. */
  329. printf("\r\n"
  330. "Type 'help' to get the list of commands.\r\n"
  331. "Use UP/DOWN arrows to navigate through command history.\r\n"
  332. "Press TAB when typing command name to auto-complete.\r\n");
  333. if (linenoiseIsDumbMode()) {
  334. printf("\r\n"
  335. "Your terminal application does not support escape sequences.\n\n"
  336. "Line editing and history features are disabled.\n\n"
  337. "On Windows, try using Putty instead.\r\n");
  338. }
  339. while (repl_com->state == CONSOLE_REPL_STATE_START) {
  340. char *line = linenoise(repl_com->prompt);
  341. if (line == NULL) {
  342. ESP_LOGD(TAG, "empty line");
  343. /* Ignore empty lines */
  344. continue;
  345. }
  346. /* Add the command to the history */
  347. linenoiseHistoryAdd(line);
  348. /* Save command history to filesystem */
  349. if (repl_com->history_save_path) {
  350. linenoiseHistorySave(repl_com->history_save_path);
  351. }
  352. /* Try to run the command */
  353. int ret;
  354. esp_err_t err = esp_console_run(line, &ret);
  355. if (err == ESP_ERR_NOT_FOUND) {
  356. printf("Unrecognized command\n");
  357. } else if (err == ESP_ERR_INVALID_ARG) {
  358. // command was empty
  359. } else if (err == ESP_OK && ret != ESP_OK) {
  360. printf("Command returned non-zero error code: 0x%x (%s)\n", ret, esp_err_to_name(ret));
  361. } else if (err != ESP_OK) {
  362. printf("Internal error: %s\n", esp_err_to_name(err));
  363. }
  364. /* linenoise allocates line buffer on the heap, so need to free it */
  365. linenoiseFree(line);
  366. }
  367. ESP_LOGD(TAG, "The End");
  368. vTaskDelete(NULL);
  369. }