refactor(console/advanced): Merge console advanced and advanced_usb_cdc examples

- removed examples/system/console/advanced_usb_cdc
    - refactor resulting console/advanced example
    - enabled advanced console for all peripherals (UART, USB_OTG, USB_JTAG)
    - added pytest to check UART console output
    - update docs
This commit is contained in:
Peter Marcisovsky 2024-04-05 12:30:17 +02:00
parent 997512ace2
commit 82a4c12817
20 changed files with 352 additions and 524 deletions

View File

@ -191,11 +191,7 @@ Application Examples
- :example:`system/console/basic` demonstrates how to use the REPL (Read-Eval-Print Loop) APIs of the Console Component to create an interactive shell on {IDF_TARGET_NAME}, which can be controlled over a serial interface, supporting UART and USB interfaces, and can serve as a basis for applications requiring a command-line interface.
- :example:`system/console/advanced` demonstrates how to use the Console Component to create an interactive shell on {IDF_TARGET_NAME}, which can be controlled over a serial port, providing a basis for applications that require a command-line interface.
.. only:: esp32s3
- :example:`system/console/advanced_usb_cdc` demonstrates how to create and interact with an interactive shell with a command-line interface, over the {IDF_TARGET_NAME}'s USB_OTG peripheral.
- :example:`system/console/advanced` demonstrates how to use the Console Component to create an interactive shell on {IDF_TARGET_NAME}, which can be controlled over a serial interface, supporting UART and USB interfaces, providing a basis for applications that require a command-line interface.
API Reference
-------------

View File

@ -191,11 +191,7 @@ Linenoise 库不需要显式地初始化,但是在调用行编辑函数之前
- :example:`system/console/basic` 演示了如何使用控制台组件的 REPL读-评估-打印循环API 在 {IDF_TARGET_NAME} 上创建一个交互式 Shell该 Shell 可以通过串行接口控制,支持 UART 和 USB 接口,并可以作为需要命令行接口的应用程序的基础。
- :example:`system/console/advanced` 演示了如何使用控制台组件在 {IDF_TARGET_NAME} 上创建一个交互式 Shell该 Shell 可以通过串行端口控制,为需要命令行接口的应用程序提供基础。
.. only:: esp32s3
- :example:`system/console/advanced_usb_cdc` 演示了如何通过 {IDF_TARGET_NAME} 的 USB_OTG 外设创建并与具有命令行接口的交互式 Shell 进行交互。
- :example:`system/console/advanced` 演示了如何使用控制台组件在 {IDF_TARGET_NAME} 上创建一个交互式 Shell该 Shell 可以通过串行接口控制,支持 UART 和 USB 接口,可作为需要命令行接口的应用程序的基础。
API 参考
--------

View File

@ -12,19 +12,12 @@ examples/system/base_mac_address:
examples/system/console/advanced:
disable_test:
- if: IDF_TARGET not in ["esp32", "esp32c3"]
- if: IDF_TARGET not in ["esp32", "esp32c3"] # IDF-9120 and IDF-9133
reason: Sufficient to run this app on one chip with each architecture
depends_components:
- console
- vfs
examples/system/console/advanced_usb_cdc:
disable:
- if: SOC_USB_OTG_SUPPORTED != 1 or IDF_TARGET == "esp32p4" # TODO: IDF-8078, IDF-9120 and IDF-9133
depends_components:
- console
- vfs
examples/system/console/basic:
disable_test:
- if: IDF_TARGET not in ["esp32", "esp32c3"]

View File

@ -18,10 +18,4 @@ This example illustrates lower-level APIs for line editing and autocompletion (`
These APIs allow for a lot of flexibility when building a console application, but require more code to be written.
While these APIs allow for a console to be implemented over various interfaces (UART, USB, TCP), this example works with UART only.
## advanced_usb_cdc example
This example is similar to the one above, except it works over USB CDC provided by USB_OTG peripheral.
Currently it can be used on ESP32-S2.
While these APIs allow for a console to be implemented over various interfaces (UART, USB, TCP), this example can be used with UART, USB_OTG or USB_SERIAL_JTAG peripherals.

View File

@ -5,15 +5,49 @@
(See the README.md file in the upper level 'examples' directory for more information about examples.)
This example illustrates the usage of the [Console Component](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/console.html#console) to create an interactive shell on the ESP32. The interactive shell running on the ESP32 can then be controlled/interacted with over a serial port (UART).
This example illustrates the usage of the [Console Component](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/console.html#console) to create an interactive shell on a ESP chip. The interactive shell running on the ESP chip can then be controlled/interacted with over a serial interface. This example supports UART and USB interfaces.
The interactive shell implemented in this example contains a wide variety of commands, and can act as a basis for applications that require a command-line interface (CLI).
## How to use example
### Hardware Required
This example can be used on boards with UART and USB interfaces. The sections below explain how to set up the board and configure the example.
This example should be able to run on any commonly available ESP32 development board.
### Using with UART
When UART interface is used, this example can run on any commonly available Espressif development board. UART interface is enabled by default (`CONFIG_ESP_CONSOLE_UART_DEFAULT` option in menuconfig). No extra configuration is required.
### Using with USB_SERIAL_JTAG
*NOTE: We recommend to disable the secondary console output on chips with USB_SERIAL_JTAG since the secondary serial is output-only and would not be very useful when using a console application. This is why the secondary console output is deactivated per default (CONFIG_ESP_CONSOLE_SECONDARY_NONE=y)*
On chips with USB_SERIAL_JTAG peripheral, console example can be used over the USB serial port.
* First, connect the USB cable to the USB_SERIAL_JTAG interface.
* Second, run `idf.py menuconfig` and enable `CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG` option.
For more details about connecting and configuring USB_SERIAL_JTAG (including pin numbers), see the IDF Programming Guide:
* [ESP32-C3 USB_SERIAL_JTAG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32c3/api-guides/usb-serial-jtag-console.html)
* [ESP32-C6 USB_SERIAL_JTAG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32c6/api-guides/usb-serial-jtag-console.html)
* [ESP32-S3 USB_SERIAL_JTAG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32s3/api-guides/usb-serial-jtag-console.html)
* [ESP32-H2 USB_SERIAL_JTAG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32h2/api-guides/usb-serial-jtag-console.html)
### Using with USB CDC (USB_OTG peripheral)
USB_OTG peripheral can also provide a USB serial port which works with this example.
* First, connect the USB cable to the USB_OTG peripheral interface.
* Second, run `idf.py menuconfig` and enable `CONFIG_ESP_CONSOLE_USB_CDC` option.
For more details about connecting and configuring USB_OTG (including pin numbers), see the IDF Programming Guide:
* [ESP32-S2 USB_OTG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32s2/api-guides/usb-otg-console.html)
* [ESP32-S3 USB_OTG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32s3/api-guides/usb-otg-console.html)
### Other configuration options
This example has an option to store the command history in Flash. This option is enabled by default.
To disable this, run `idf.py menuconfig` and disable `CONFIG_CONSOLE_STORE_HISTORY` option.
### Configure the project
@ -21,7 +55,12 @@ This example should be able to run on any commonly available ESP32 development b
idf.py menuconfig
```
* Enable/disable `Example Configuration > Store command history in flash` as necessary
* Enable/Disable storing command history in flash and load the history in a next example run. Linenoise line editing library provides functions to save and load
command history. If this option is enabled, initializes a FAT filesystem and uses it to store command history.
* `Example Configuration > Store command history in flash`
* Accept/Ignore empty lines inserted into the console. If an empty line is inserted to the console, the Console can either ignore empty lines (the example would continue), or break on emplty lines (the example would stop after an empty line).
* `Example Configuration > Ignore empty lines inserted into the console`
### Build and Flash
@ -46,33 +85,34 @@ This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
[esp32]> help
Ctrl+C will terminate the console environment.
esp32> help
help
Print the list of registered commands
help [<string>]
Print the summary of all registered commands if no arguments are given,
otherwise print summary of given command.
<string> Name of command
free
Get the total size of heap memory available
free
Get the current size of free heap memory
restart
Restart the program
heap
Get minimum size of free heap memory that was available during program
execution
deep_sleep [-t <t>] [--io=<n>] [--io_level=<0|1>]
Enter deep sleep mode. Two wakeup modes are supported: timer and GPIO. If no
wakeup option is specified, will sleep indefinitely.
-t, --time=<t> Wake up time, ms
--io=<n> If specified, wakeup using GPIO with given number
--io_level=<0|1> GPIO level to trigger wakeup
version
Get version of chip and SDK
join [--timeout=<t>] <ssid> [<pass>]
Join WiFi AP as a station
--timeout=<t> Connection timeout, ms
<ssid> SSID of AP
<pass> PSK of AP
restart
Software reset of the chip
[esp32]> free
...
...
esp32> free
257200
[esp32]> deep_sleep -t 1000
I (146929) deep_sleep: Enabling timer wakeup, timeout=1000000us
esp32> deep_sleep -t 1000
I (146929) cmd_system_sleep: Enabling timer wakeup, timeout=1000000us
I (619) heap_init: Initializing. RAM available for dynamic allocation:
I (620) heap_init: At 3FFAE2A0 len 00001D60 (7 KiB): DRAM
I (626) heap_init: At 3FFB7EA0 len 00028160 (160 KiB): DRAM
@ -84,13 +124,13 @@ This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
[esp32]> join --timeout 10000 test_ap test_password
esp32> join --timeout 10000 test_ap test_password
I (182639) connect: Connecting to 'test_ap'
I (184619) connect: Connected
[esp32]> free
esp32> free
212328
[esp32]> restart
I (205639) restart: Restarting
esp32> restart
I (205639) cmd_system_common: Restarting
I (616) heap_init: Initializing. RAM available for dynamic allocation:
I (617) heap_init: At 3FFAE2A0 len 00001D60 (7 KiB): DRAM
I (623) heap_init: At 3FFB7EA0 len 00028160 (160 KiB): DRAM
@ -102,7 +142,8 @@ This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
[esp32]>
Ctrl+C will terminate the console environment.
esp32>
```
@ -110,7 +151,7 @@ Press TAB when typing command name to auto-complete.
### Line Endings
The line endings in the Console Example are configured to match particular serial monitors. Therefore, if the following log output appears, consider using a different serial monitor (e.g. Putty for Windows) or modify the example's [UART configuration](#Configuring-UART-and-VFS).
The line endings in the Console Example are configured to match particular serial monitors. Therefore, if the following log output appears, consider using a different serial monitor (e.g. Putty for Windows) or modify the example's [UART configuration](#Configuring-UART).
```
This is an example of ESP-IDF console component.
@ -123,11 +164,26 @@ On Windows, try using Putty instead.
esp32>
```
### No USB port appears
On Windows 10, macOS, Linux, USB CDC devices do not require additional drivers to be installed.
If the USB serial port doesn't appear in the system after flashing the example, check the following:
* Check that the USB device is detected by the OS.
VID/PID pair for ESP32-S2 is 303a:0002.
- On Windows, check the Device Manager
- On macOS, check USB section in the System Information utility
- On Linux, check `lsusb` output
* If the device is not detected, check the USB cable connection (D+, D-, and ground should be connected)
## Example Breakdown
### Configuring UART
The ``initialize_console()`` function in the example configures some aspects of UART relevant to the operation of the console.
The ``initialize_console_library()`` function in the example configures some aspects of UART relevant to the operation of the console.
- **Line Endings**: The default line endings are configured to match those expected/generated by common serial monitor programs, such as `screen`, `minicom`, and the `esp-idf-monitor` included in the SDK. The default behavior for these commands are:
- When 'enter' key is pressed on the keyboard, `CR` (0x13) code is sent to the serial device.

View File

@ -1,2 +1,2 @@
idf_component_register(SRCS "console_example_main.c"
idf_component_register(SRCS "console_example_main.c" "console_settings.c"
INCLUDE_DIRS ".")

View File

@ -1,11 +1,19 @@
menu "Example Configuration"
config STORE_HISTORY
config CONSOLE_STORE_HISTORY
bool "Store command history in flash"
default y
help
Linenoise line editing library provides functions to save and load
command history. If this option is enabled, initalizes a FAT filesystem
command history. If this option is enabled, initializes a FAT filesystem
and uses it to store command history.
config CONSOLE_IGNORE_EMPTY_LINES
bool "Ignore empty lines inserted into the console"
default y
help
If an empty line is inserted to the console, the Console can either
ignore empty lines (the example would continue), or break on empty lines
(the example would stop after an empty line).
endmenu

View File

@ -1,11 +1,8 @@
/* Console example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <stdio.h>
#include <string.h>
@ -13,8 +10,6 @@
#include "esp_system.h"
#include "esp_log.h"
#include "esp_console.h"
#include "driver/uart_vfs.h"
#include "driver/uart.h"
#include "linenoise/linenoise.h"
#include "argtable3/argtable3.h"
#include "esp_vfs_fat.h"
@ -24,6 +19,7 @@
#include "cmd_system.h"
#include "cmd_wifi.h"
#include "cmd_nvs.h"
#include "console_settings.h"
/*
* We warn if a secondary serial console is enabled. A secondary serial console is always output-only and
@ -36,14 +32,6 @@
#endif
#endif
#ifdef CONFIG_ESP_CONSOLE_USB_CDC
#error This example is incompatible with USB CDC console. Please try "console_usb" example instead.
#endif // CONFIG_ESP_CONSOLE_USB_CDC
#ifdef CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG
#error This example is incompatible with USB serial JTAG console.
#endif // CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG
static const char* TAG = "example";
#define PROMPT_STR CONFIG_IDF_TARGET
@ -51,7 +39,7 @@ static const char* TAG = "example";
* The easiest way to do this is to use FATFS filesystem on top of
* wear_levelling library.
*/
#if CONFIG_STORE_HISTORY
#if CONFIG_CONSOLE_STORE_HISTORY
#define MOUNT_PATH "/data"
#define HISTORY_PATH MOUNT_PATH "/history.txt"
@ -69,7 +57,9 @@ static void initialize_filesystem(void)
return;
}
}
#endif // CONFIG_STORE_HISTORY
#else
#define HISTORY_PATH NULL
#endif // CONFIG_CONSOLE_STORE_HISTORY
static void initialize_nvs(void)
{
@ -81,89 +71,27 @@ static void initialize_nvs(void)
ESP_ERROR_CHECK(err);
}
static void initialize_console(void)
{
/* Drain stdout before reconfiguring it */
fflush(stdout);
fsync(fileno(stdout));
/* Disable buffering on stdin */
setvbuf(stdin, NULL, _IONBF, 0);
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
uart_vfs_dev_port_set_rx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CR);
/* Move the caret to the beginning of the next line on '\n' */
uart_vfs_dev_port_set_tx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CRLF);
/* Configure UART. Note that REF_TICK is used so that the baud rate remains
* correct while APB frequency is changing in light sleep mode.
*/
const uart_config_t uart_config = {
.baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
#if SOC_UART_SUPPORT_REF_TICK
.source_clk = UART_SCLK_REF_TICK,
#elif SOC_UART_SUPPORT_XTAL_CLK
.source_clk = UART_SCLK_XTAL,
#endif
};
/* Install UART driver for interrupt-driven reads and writes */
ESP_ERROR_CHECK( uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM,
256, 0, 0, NULL, 0) );
ESP_ERROR_CHECK( uart_param_config(CONFIG_ESP_CONSOLE_UART_NUM, &uart_config) );
/* Tell VFS to use UART driver */
uart_vfs_dev_use_driver(CONFIG_ESP_CONSOLE_UART_NUM);
/* Initialize the console */
esp_console_config_t console_config = {
.max_cmdline_args = 8,
.max_cmdline_length = 256,
#if CONFIG_LOG_COLORS
.hint_color = atoi(LOG_COLOR_CYAN)
#endif
};
ESP_ERROR_CHECK( esp_console_init(&console_config) );
/* Configure linenoise line completion library */
/* Enable multiline editing. If not set, long commands will scroll within
* single line.
*/
linenoiseSetMultiLine(1);
/* Tell linenoise where to get command completions and hints */
linenoiseSetCompletionCallback(&esp_console_get_completion);
linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
/* Set command history size */
linenoiseHistorySetMaxLen(100);
/* Set command maximum length */
linenoiseSetMaxLineLen(console_config.max_cmdline_length);
/* Don't return empty lines */
linenoiseAllowEmpty(false);
#if CONFIG_STORE_HISTORY
/* Load command history from filesystem */
linenoiseHistoryLoad(HISTORY_PATH);
#endif
}
void app_main(void)
{
initialize_nvs();
#if CONFIG_STORE_HISTORY
#if CONFIG_CONSOLE_STORE_HISTORY
initialize_filesystem();
ESP_LOGI(TAG, "Command history enabled");
#else
ESP_LOGI(TAG, "Command history disabled");
#endif
initialize_console();
/* Initialize console output periheral (UART, USB_OTG, USB_JTAG) */
initialize_console_peripheral();
/* Initialize linenoise library and esp_console*/
initialize_console_library(HISTORY_PATH);
/* Prompt to be printed before each line.
* This can be customized, made dynamic, etc.
*/
const char *prompt = setup_prompt(PROMPT_STR ">");
/* Register commands */
esp_console_register_help_command();
@ -179,32 +107,18 @@ void app_main(void)
#endif
register_nvs();
/* Prompt to be printed before each line.
* This can be customized, made dynamic, etc.
*/
const char* prompt = LOG_COLOR_I PROMPT_STR "> " LOG_RESET_COLOR;
printf("\n"
"This is an example of ESP-IDF console component.\n"
"Type 'help' to get the list of commands.\n"
"Use UP/DOWN arrows to navigate through command history.\n"
"Press TAB when typing command name to auto-complete.\n"
"Press Enter or Ctrl+C will terminate the console environment.\n");
"Ctrl+C will terminate the console environment.\n");
/* Figure out if the terminal supports escape sequences */
int probe_status = linenoiseProbe();
if (probe_status) { /* zero indicates success */
if (linenoiseIsDumbMode()) {
printf("\n"
"Your terminal application does not support escape sequences.\n"
"Line editing and history features are disabled.\n"
"On Windows, try using Putty instead.\n");
linenoiseSetDumbMode(1);
#if CONFIG_LOG_COLORS
/* Since the terminal doesn't support escape sequences,
* don't use color codes in the prompt.
*/
prompt = PROMPT_STR "> ";
#endif //CONFIG_LOG_COLORS
}
/* Main loop */
@ -213,16 +127,24 @@ void app_main(void)
* The line is returned when ENTER is pressed.
*/
char* line = linenoise(prompt);
#if CONFIG_CONSOLE_IGNORE_EMPTY_LINES
if (line == NULL) { /* Ignore empty lines */
continue;;
}
#else
if (line == NULL) { /* Break on EOF or error */
break;
}
#endif // CONFIG_CONSOLE_IGNORE_EMPTY_LINES
/* Add the command to the history if not empty*/
if (strlen(line) > 0) {
linenoiseHistoryAdd(line);
#if CONFIG_STORE_HISTORY
#if CONFIG_CONSOLE_STORE_HISTORY
/* Save command history to filesystem */
linenoiseHistorySave(HISTORY_PATH);
#endif
#endif // CONFIG_CONSOLE_STORE_HISTORY
}
/* Try to run the command */

View File

@ -0,0 +1,163 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_console.h"
#include "sdkconfig.h"
#include "soc/soc_caps.h"
#include "driver/uart_vfs.h"
#include "driver/uart.h"
#include "driver/usb_serial_jtag.h"
#include "driver/usb_serial_jtag_vfs.h"
#include "esp_vfs_cdcacm.h"
#include "linenoise/linenoise.h"
#include "argtable3/argtable3.h"
#define CONSOLE_MAX_CMDLINE_ARGS 8
#define CONSOLE_MAX_CMDLINE_LENGTH 256
#define CONSOLE_PROMPT_MAX_LEN (32)
char prompt[CONSOLE_PROMPT_MAX_LEN]; // Prompt to be printed before each line
void initialize_console_peripheral(void)
{
/* Drain stdout before reconfiguring it */
fflush(stdout);
fsync(fileno(stdout));
#if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) || defined(CONFIG_ESP_CONSOLE_UART_CUSTOM)
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
uart_vfs_dev_port_set_rx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CR);
/* Move the caret to the beginning of the next line on '\n' */
uart_vfs_dev_port_set_tx_line_endings(CONFIG_ESP_CONSOLE_UART_NUM, ESP_LINE_ENDINGS_CRLF);
/* Configure UART. Note that REF_TICK is used so that the baud rate remains
* correct while APB frequency is changing in light sleep mode.
*/
const uart_config_t uart_config = {
.baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
#if SOC_UART_SUPPORT_REF_TICK
.source_clk = UART_SCLK_REF_TICK,
#elif SOC_UART_SUPPORT_XTAL_CLK
.source_clk = UART_SCLK_XTAL,
#endif
};
/* Install UART driver for interrupt-driven reads and writes */
ESP_ERROR_CHECK( uart_driver_install(CONFIG_ESP_CONSOLE_UART_NUM, 256, 0, 0, NULL, 0) );
ESP_ERROR_CHECK( uart_param_config(CONFIG_ESP_CONSOLE_UART_NUM, &uart_config) );
/* Tell VFS to use UART driver */
uart_vfs_dev_use_driver(CONFIG_ESP_CONSOLE_UART_NUM);
#elif defined(CONFIG_ESP_CONSOLE_USB_CDC)
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
esp_vfs_dev_cdcacm_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
/* Move the caret to the beginning of the next line on '\n' */
esp_vfs_dev_cdcacm_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
/* Enable blocking mode on stdin and stdout */
fcntl(fileno(stdout), F_SETFL, 0);
fcntl(fileno(stdin), F_SETFL, 0);
#elif defined(CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG)
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
usb_serial_jtag_vfs_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
/* Move the caret to the beginning of the next line on '\n' */
usb_serial_jtag_vfs_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
/* Enable blocking mode on stdin and stdout */
fcntl(fileno(stdout), F_SETFL, 0);
fcntl(fileno(stdin), F_SETFL, 0);
usb_serial_jtag_driver_config_t jtag_config = {
.tx_buffer_size = 256,
.rx_buffer_size = 256,
};
/* Install USB-SERIAL-JTAG driver for interrupt-driven reads and writes */
ESP_ERROR_CHECK( usb_serial_jtag_driver_install(&jtag_config));
/* Tell vfs to use usb-serial-jtag driver */
usb_serial_jtag_vfs_use_driver();
#else
#error Unsupported console type
#endif
/* Disable buffering on stdin */
setvbuf(stdin, NULL, _IONBF, 0);
}
void initialize_console_library(const char *history_path)
{
/* Initialize the console */
esp_console_config_t console_config = {
.max_cmdline_args = CONSOLE_MAX_CMDLINE_ARGS,
.max_cmdline_length = CONSOLE_MAX_CMDLINE_LENGTH,
#if CONFIG_LOG_COLORS
.hint_color = atoi(LOG_COLOR_CYAN)
#endif
};
ESP_ERROR_CHECK( esp_console_init(&console_config) );
/* Configure linenoise line completion library */
/* Enable multiline editing. If not set, long commands will scroll within
* single line.
*/
linenoiseSetMultiLine(1);
/* Tell linenoise where to get command completions and hints */
linenoiseSetCompletionCallback(&esp_console_get_completion);
linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
/* Set command history size */
linenoiseHistorySetMaxLen(100);
/* Set command maximum length */
linenoiseSetMaxLineLen(console_config.max_cmdline_length);
/* Don't return empty lines */
linenoiseAllowEmpty(false);
#if CONFIG_CONSOLE_STORE_HISTORY
/* Load command history from filesystem */
linenoiseHistoryLoad(history_path);
#endif // CONFIG_CONSOLE_STORE_HISTORY
/* Figure out if the terminal supports escape sequences */
const int probe_status = linenoiseProbe();
if (probe_status) { /* zero indicates success */
linenoiseSetDumbMode(1);
}
}
char *setup_prompt(const char *prompt_str)
{
/* set command line prompt */
const char *prompt_temp = "esp>";
if (prompt_str) {
prompt_temp = prompt_str;
}
snprintf(prompt, CONSOLE_PROMPT_MAX_LEN - 1, LOG_COLOR_I "%s " LOG_RESET_COLOR, prompt_temp);
if (linenoiseIsDumbMode()) {
#if CONFIG_LOG_COLORS
/* Since the terminal doesn't support escape sequences,
* don't use color codes in the s_prompt.
*/
snprintf(prompt, CONSOLE_PROMPT_MAX_LEN - 1, "%s ", prompt_temp);
#endif //CONFIG_LOG_COLORS
}
return prompt;
}

View File

@ -0,0 +1,39 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @brief Initialize console peripheral type
*
* Console peripheral is based on sdkconfig settings
*
* UART CONFIG_ESP_CONSOLE_UART_DEFAULT
* USB_OTG CONFIG_ESP_CONSOLE_USB_CDC
* USB_SERIAL_JTAG CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG
*/
void initialize_console_peripheral(void);
/**
* @brief Initialize linenoise and esp console
*
* This function initialize linenoise library and esp_console component,
* also checks if the terminal supports escape sequences
*
* @param history_path Path to store command history
*/
void initialize_console_library(const char *history_path);
/**
* @brief Initialize console prompt
*
* This function adds color code to the prompt (if the console supports escape sequences)
*
* @param prompt_str Prompt in form of string eg esp32s3>
*
* @return
* - pointer to initialized prompt
*/
char *setup_prompt(const char *prompt_str);

View File

@ -1,5 +1,6 @@
# SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
# SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: CC0-1.0
from time import sleep
import pytest
from pytest_embedded import Dut
@ -8,12 +9,16 @@ from pytest_embedded import Dut
@pytest.mark.esp32
@pytest.mark.esp32c3
@pytest.mark.generic
@pytest.mark.parametrize('config', [
'history',
'nohistory',
], indirect=True)
def test_console_advanced(config: str, dut: Dut) -> None:
if config == 'history':
dut.expect('Command history enabled')
elif config == 'nohistory':
dut.expect('Command history disabled')
def test_console_advanced(dut: Dut) -> None:
sleep(2) # Some time for the OS to enumerate our USB device
# Wait until the console prompt appears
dut.expect(dut.target + '> ')
# Write CLI command "version"
dut.write('version')
sleep(0.5)
# Check if following strings are present in the "version" command output
dut.expect('IDF Version')
dut.expect('Chip info')

View File

@ -1 +0,0 @@
CONFIG_STORE_HISTORY=y

View File

@ -1 +0,0 @@
CONFIG_STORE_HISTORY=n

View File

@ -1,6 +0,0 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(console_usb)

View File

@ -1,150 +0,0 @@
| Supported Targets | ESP32-S2 | ESP32-S3 |
| ----------------- | -------- | -------- |
# USB_OTG CDC Console Example
(See the README.md file in the upper level 'examples' directory for more information about examples.)
This example is similar to the [advanced console example](../advanced/README.md), but instead of the UART it uses the USB CDC port provided by USB_OTG peripheral for console output.
The example uses the [Console Component](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/console.html#console) to create an interactive shell.
The interactive shell implemented in this example contains a wide variety of commands, and can act as a basis for applications that require a command-line interface (CLI).
## How to use example
### Hardware Required
This example can run on an ESP32-S2 or ESP32-S3 development board with USB port attached to the built-in USB_OTG controller.
For more details about connecting and configuring USB_OTG (including pin numbers), see the IDF Programming Guide:
* [ESP32-S2 USB_OTG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32s2/api-guides/usb-otg-console.html)
* [ESP32-S3 USB_OTG](https://docs.espressif.com/projects/esp-idf/en/stable/esp32s3/api-guides/usb-otg-console.html)
### Build and Flash
Build the project, by running:
```
idf.py build
```
First time flashing can be done over USB or over UART.
#### Flashing the project for the first time using UART
This is the same procedure described in the Getting Started Guide. Flashing is done using a USB-Serial adapter included on the development board. Determine the device name of the serial port (`PORT`) and run:
```
idf.py -p PORT flash
```
#### Flashing the project for the first time using USB
We can also use the built-in USB bootloader in the ESP chip to flash the program for the first time.
1. Connect the development board using a USB breakout cable to the computer.
2. Put the chip into bootloader (download) mode, by holding "Boot" button (connected to GPIO0) and pressing "Reset" button.
3. A USB serial port device will appear in the system:
- On Windows, it will be one of COM ports
- On Linux, it will by /dev/ttyACMn (n is some number)
- On macOS, it will be /dev/tty.usbmodemN (N is some number)
If the port doesn't appear, check that the board has entered the bootloader mode, and that the USB cable is connected correctly.
4. Flash the board:
```
idf.py -p PORT flash
```
### View the console output over USB
Once the board is flashed for the first time, a USB serial port will appear in the system.
**Note: if you have used the step above to flash the board over USB, note that the port name may change after flashing!**
To start the monitor, run:
```
idf.py -p PORT monitor
```
To exit the serial monitor, type ``Ctrl-]``.
See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects.
## Example Output
Enter the `help` command get a full list of all available commands. The following is a sample session of the Console Example where a variety of commands provided by the Console Example are used. Note that GPIO15 is connected to GND to remove the boot log output.
```
This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
esp32s2> help
help
Print the list of registered commands
free
Get the current size of free heap memory
heap
Get minimum size of free heap memory that was available during program execution
version
Get version of chip and SDK
restart
Software reset of the chip
tasks
Get information about running tasks
(remaining output of the help command skipped here)
esp32s2> free
237824
I (39864) cmd_system: Restarting
I (185) spi_flash: detected chip: generic
I (186) spi_flash: flash io: dio
I (186) cpu_start: Starting scheduler on PRO CPU.
This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
esp32s2>
```
## Troubleshooting
### Line Endings
The line endings in the Console Example are configured to match particular serial monitors. Therefore, if the following log output appears, consider using a different serial monitor (e.g. Putty for Windows).
```
This is an example of ESP-IDF console component.
Type 'help' to get the list of commands.
Use UP/DOWN arrows to navigate through command history.
Press TAB when typing command name to auto-complete.
Your terminal application does not support escape sequences.
Line editing and history features are disabled.
On Windows, try using Putty instead.
esp32s2>
```
### No USB port appears
On Windows 10, macOS, Linux, USB CDC devices do not require additional drivers to be installed.
If the USB serial port doesn't appear in the system after flashing the example, check the following:
* Check that the USB device is detected by the OS.
VID/PID pair for ESP32-S2 is 303a:0002.
- On Windows, check the Device Manager
- On macOS, check USB section in the System Information utility
- On Linux, check `lsusb` output
* If the device is not detected, check the USB cable connection (D+, D-, and ground should be connected)

View File

@ -1,2 +0,0 @@
idf_component_register(SRCS "console_usb_example_main.c"
INCLUDE_DIRS ".")

View File

@ -1,163 +0,0 @@
/*
* SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
/* USB console example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_console.h"
#include "linenoise/linenoise.h"
#include "argtable3/argtable3.h"
#include "esp_vfs_cdcacm.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "cmd_nvs.h"
#include "cmd_system.h"
#include "cmd_wifi.h"
/*
* We warn if a secondary serial console is enabled. A secondary serial console is always output-only and
* hence not very useful for interactive console applications. If you encounter this warning, consider disabling
* the secondary serial console in menuconfig unless you know what you are doing.
*/
#if SOC_USB_SERIAL_JTAG_SUPPORTED
#if !CONFIG_ESP_CONSOLE_SECONDARY_NONE
#warning "A secondary serial console is not useful when using the console component. Please disable it in menuconfig."
#endif
#endif
static void initialize_nvs(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK( nvs_flash_erase() );
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
}
static void initialize_console(void)
{
/* Disable buffering on stdin */
setvbuf(stdin, NULL, _IONBF, 0);
/* Minicom, screen, idf_monitor send CR when ENTER key is pressed */
esp_vfs_dev_cdcacm_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
/* Move the caret to the beginning of the next line on '\n' */
esp_vfs_dev_cdcacm_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
/* Enable non-blocking mode on stdin and stdout */
fcntl(fileno(stdout), F_SETFL, 0);
fcntl(fileno(stdin), F_SETFL, 0);
/* Initialize the console */
esp_console_config_t console_config = {
.max_cmdline_args = 8,
.max_cmdline_length = 256,
#if CONFIG_LOG_COLORS
.hint_color = atoi(LOG_COLOR_CYAN)
#endif
};
ESP_ERROR_CHECK( esp_console_init(&console_config) );
/* Configure linenoise line completion library */
/* Enable multiline editing. If not set, long commands will scroll within
* single line.
*/
linenoiseSetMultiLine(1);
/* Tell linenoise where to get command completions and hints */
linenoiseSetCompletionCallback(&esp_console_get_completion);
linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint);
/* Set command history size */
linenoiseHistorySetMaxLen(10);
}
void app_main(void)
{
initialize_nvs();
initialize_console();
/* Register commands */
esp_console_register_help_command();
register_system_common();
#if SOC_LIGHT_SLEEP_SUPPORTED
register_system_light_sleep();
#endif
#if SOC_DEEP_SLEEP_SUPPORTED
register_system_deep_sleep();
#endif
#if SOC_WIFI_SUPPORTED
register_wifi();
#endif
register_nvs();
/* Prompt to be printed before each line.
* This can be customized, made dynamic, etc.
*/
const char* prompt = LOG_COLOR_I CONFIG_IDF_TARGET "> " LOG_RESET_COLOR;
printf("\n"
"This is an example of ESP-IDF console component.\n"
"Type 'help' to get the list of commands.\n"
"Use UP/DOWN arrows to navigate through command history.\n"
"Press TAB when typing command name to auto-complete.\n");
/* Figure out if the terminal supports escape sequences */
int probe_status = linenoiseProbe();
if (probe_status) { /* zero indicates success */
printf("\n"
"Your terminal application does not support escape sequences.\n"
"Line editing and history features are disabled.\n"
"On Windows, try using Putty instead.\n");
linenoiseSetDumbMode(1);
#if CONFIG_LOG_COLORS
/* Since the terminal doesn't support escape sequences,
* don't use color codes in the prompt.
*/
prompt = CONFIG_IDF_TARGET "> ";
#endif //CONFIG_LOG_COLORS
}
/* Main loop */
while(true) {
/* Get a line using linenoise.
* The line is returned when ENTER is pressed.
*/
char* line = linenoise(prompt);
if (line == NULL) { /* Ignore empty lines */
continue;
}
/* Add the command to the history */
linenoiseHistoryAdd(line);
/* Try to run the command */
int ret;
esp_err_t err = esp_console_run(line, &ret);
if (err == ESP_ERR_NOT_FOUND) {
printf("Unrecognized command\n");
} else if (err == ESP_ERR_INVALID_ARG) {
// command was empty
} else if (err == ESP_OK && ret != ESP_OK) {
printf("Command returned non-zero error code: 0x%x (%s)\n", ret, esp_err_to_name(ret));
} else if (err != ESP_OK) {
printf("Internal error: %s\n", esp_err_to_name(err));
}
/* linenoise allocates line buffer on the heap, so need to free it */
linenoiseFree(line);
}
}

View File

@ -1,7 +0,0 @@
dependencies:
cmd_system:
path: ${IDF_PATH}/examples/system/console/advanced/components/cmd_system
cmd_nvs:
path: ${IDF_PATH}/examples/system/console/advanced/components/cmd_nvs
cmd_wifi:
path: ${IDF_PATH}/examples/system/console/advanced/components/cmd_wifi

View File

@ -1,13 +0,0 @@
# Enable USB console
CONFIG_ESP_CONSOLE_USB_CDC=y
# On chips with USB serial, disable secondary console which does not make sense when using console component
CONFIG_ESP_CONSOLE_SECONDARY_NONE=y
# Reduce bootloader log verbosity
CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y
CONFIG_BOOTLOADER_LOG_LEVEL=2
# Enable FreeRTOS stats formatting functions, needed for 'tasks' command
CONFIG_FREERTOS_USE_TRACE_FACILITY=y
CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS=y

View File

@ -1102,7 +1102,6 @@ examples/system/console/advanced/components/cmd_nvs/cmd_nvs.c
examples/system/console/advanced/components/cmd_nvs/cmd_nvs.h
examples/system/console/advanced/components/cmd_system/cmd_system.c
examples/system/console/advanced/components/cmd_system/cmd_system.h
examples/system/console/advanced/main/console_example_main.c
examples/system/console/basic/main/console_example_main.c
examples/system/efuse/main/efuse_main.c
examples/system/esp_event/default_event_loop/main/event_source.h