From 204586f2817f29cc7c5f94525473aec158c78eba Mon Sep 17 00:00:00 2001 From: Yu-886 <2860280851@qq.com> Date: Thu, 27 Mar 2025 12:59:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AF=B9=E8=99=9A=E6=8B=9F?= =?UTF-8?q?=E4=B8=B2=E5=8F=A3=E6=8E=A5=E6=94=B6=E7=9A=84=E6=B5=81=E6=8E=A7?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE=EF=BC=8C=E5=B0=86=E6=A8=A1=E5=9D=97=E6=BA=90?= =?UTF-8?q?=E7=A0=81=E6=94=BE=E5=9C=A8=E5=B7=A5=E7=A8=8B=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../esp_driver_usb_serial_jtag/CMakeLists.txt | 25 + components/esp_driver_usb_serial_jtag/Kconfig | 28 + .../driver/esp_private/usb_serial_jtag_vfs.h | 27 + .../include/driver/usb_serial_jtag.h | 101 ++++ .../include/driver/usb_serial_jtag_vfs.h | 72 +++ .../src/usb_serial_jtag.c | 279 ++++++++++ .../src/usb_serial_jtag_connection_monitor.c | 95 ++++ .../src/usb_serial_jtag_vfs.c | 480 ++++++++++++++++++ .../test_apps/.build-test-rules.yml | 13 + .../test_apps/usb_serial_jtag/CMakeLists.txt | 8 + .../test_apps/usb_serial_jtag/README.md | 2 + .../usb_serial_jtag/main/CMakeLists.txt | 7 + .../usb_serial_jtag/main/test_app_main.c | 50 ++ .../main/test_usb_serial_jtag.c | 65 +++ .../usb_serial_jtag/pytest_usb_serial_jtag.py | 23 + .../usb_serial_jtag/sdkconfig.ci.release | 6 + .../usb_serial_jtag/sdkconfig.defaults | 3 + 17 files changed, 1284 insertions(+) create mode 100644 components/esp_driver_usb_serial_jtag/CMakeLists.txt create mode 100644 components/esp_driver_usb_serial_jtag/Kconfig create mode 100644 components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h create mode 100644 components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h create mode 100644 components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h create mode 100644 components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c create mode 100644 components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c create mode 100644 components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/.build-test-rules.yml create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/CMakeLists.txt create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/README.md create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/CMakeLists.txt create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_app_main.c create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_usb_serial_jtag.c create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/pytest_usb_serial_jtag.py create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.ci.release create mode 100644 components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.defaults diff --git a/components/esp_driver_usb_serial_jtag/CMakeLists.txt b/components/esp_driver_usb_serial_jtag/CMakeLists.txt new file mode 100644 index 0000000..48856a7 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/CMakeLists.txt @@ -0,0 +1,25 @@ +set(srcs) +set(include "include") + +# USB Serial JTAG related source files +if(CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED) + list(APPEND srcs "src/usb_serial_jtag.c" + "src/usb_serial_jtag_connection_monitor.c") +endif() + +idf_component_register(SRCS ${srcs} + INCLUDE_DIRS ${include} + PRIV_REQUIRES esp_driver_gpio esp_ringbuf esp_pm esp_timer + ) + +if(CONFIG_VFS_SUPPORT_IO AND CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED) + target_link_libraries(${COMPONENT_LIB} PUBLIC idf::vfs) + target_sources(${COMPONENT_LIB} PRIVATE "src/usb_serial_jtag_vfs.c") + target_link_libraries(${COMPONENT_LIB} INTERFACE "-u usb_serial_jtag_vfs_include_dev_init") +endif() + +# If system needs to monitor USJ connection status, then usb_serial_jtag_connection_monitor object file has to be linked +# to the binary, to allow tick hook to be registered +if(CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION OR CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED) + target_link_libraries(${COMPONENT_LIB} INTERFACE "-u usb_serial_jtag_connection_monitor_include") +endif() diff --git a/components/esp_driver_usb_serial_jtag/Kconfig b/components/esp_driver_usb_serial_jtag/Kconfig new file mode 100644 index 0000000..48bb15b --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/Kconfig @@ -0,0 +1,28 @@ +menu "ESP-Driver:USB Serial/JTAG Configuration" + depends on SOC_USB_SERIAL_JTAG_SUPPORTED + + config USJ_ENABLE_USB_SERIAL_JTAG + bool "Enable USB-Serial-JTAG Module" + default y + help + The USB-Serial-JTAG module on ESP chips is turned on by default after power-on. + If your application does not need it and not rely on it to be used as system + console or use the built-in JTAG for debugging, you can disable this option, + then the clock of this module will be disabled at startup, which will save + some power consumption. + + config USJ_NO_AUTO_LS_ON_CONNECTION + bool "Don't enter the automatic light sleep when USB Serial/JTAG port is connected" + depends on PM_ENABLE && ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED && !SOC_USB_SERIAL_JTAG_SUPPORT_LIGHT_SLEEP \ + && USJ_ENABLE_USB_SERIAL_JTAG + default n + help + If enabled, the chip will constantly monitor the connection status of the USB Serial/JTAG port. As long + as the USB Serial/JTAG is connected, a ESP_PM_NO_LIGHT_SLEEP power management lock will be acquired to + prevent the system from entering light sleep. + This option can be useful if serial monitoring is needed via USB Serial/JTAG while power management is + enabled, as the USB Serial/JTAG cannot work under light sleep and after waking up from light sleep. + Note. This option can only control the automatic Light-Sleep behavior. If esp_light_sleep_start() is + called manually from the program, enabling this option will not prevent light sleep entry even if the + USB Serial/JTAG is in use. +endmenu # USB Serial/JTAG Configuration diff --git a/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h b/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h new file mode 100644 index 0000000..7a94728 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/include/driver/esp_private/usb_serial_jtag_vfs.h @@ -0,0 +1,27 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "esp_vfs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief get pointer of usb_serial_jtag vfs. + * + * This function is called in vfs_console in order to get the vfs implementation + * of usb_serial_jtag. + * + * @return pointer to structure esp_vfs_t + */ +const esp_vfs_t *esp_vfs_usb_serial_jtag_get_vfs(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h b/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h new file mode 100644 index 0000000..93aec7a --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag.h @@ -0,0 +1,101 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "esp_err.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Configuration structure for the usb-serial-jtag-driver. Can be expanded in the future + * + * @note tx_buffer_size and rx_buffer_size must be > 0 + */ +typedef struct { + uint32_t tx_buffer_size; /* Size of the buffer (in bytes) for the TX direction */ + uint32_t rx_buffer_size; /* Size of the buffer (in bytes) for the RX direction */ +} usb_serial_jtag_driver_config_t; + +#define USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT() (usb_serial_jtag_driver_config_t) {\ + .tx_buffer_size = 256,\ + .rx_buffer_size = 256,\ +} + +/** + * @brief Install USB-SERIAL-JTAG driver and set the USB-SERIAL-JTAG to the default configuration. + * + * USB-SERIAL-JTAG driver's ISR will be attached to the same CPU core that calls this function. Thus, users + * should ensure that the same core is used when calling `usb_serial_jtag_driver_uninstall()`. + * + * @note Blocking mode will result in usb_serial_jtag_write_bytes() blocking for a + * short period if the TX FIFO if full. It will not block again until the buffer + * has some space available again. + * + * @param usb_serial_jtag_driver_config_t Configuration for usb_serial_jtag driver. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Failed for some reason. + */ +esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *usb_serial_jtag_config); + +/** + * @brief USB_SERIAL_JTAG read bytes from USB_SERIAL_JTAG buffer + * + * @param buf pointer to the buffer. + * @param length data length + * @param ticks_to_wait Timeout in RTOS ticks + * + * @return + * - The number of bytes read from USB_SERIAL FIFO + */ +int usb_serial_jtag_read_bytes(void* buf, uint32_t length, TickType_t ticks_to_wait); + +/** + * @brief Send data to the USB-UART port from a given buffer and length, + * + * Please ensure the `tx_buffer_size is larger than 0`, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, + * USB_SERIAL_JTAG ISR will then move data from the ring buffer to TX FIFO gradually. + * + * @param src data buffer address + * @param size data length to send + * @param ticks_to_wait Maximum timeout in RTOS ticks + * + * @return + * - The number of bytes pushed to the TX FIFO + */ +int usb_serial_jtag_write_bytes(const void* src, size_t size, TickType_t ticks_to_wait); + +/** + * @brief Uninstall USB-SERIAL-JTAG driver. + * + * @return + * - ESP_OK Success + */ +esp_err_t usb_serial_jtag_driver_uninstall(void); + +/** + * @brief Check if the USB Serial/JTAG port is connected to the host + * + * This function checks whether the USB Serial/JTAG (USJ) port is currently connected. USJ is considered "connected" + * so long as it is receiving SOF packets from the host, even if there is no serial communications occurring (i.e., the + * USJ is connected to the PC, but the serial port is not opened). Having the USB port connected to a power bank will + * never be considered as connected (due to the lack of SOF packets). + * + * @note If your application needs this function, it will add some extra overhead time to every freertos tick. + * + * @return True if USJ is connected, false otherwise + */ +bool usb_serial_jtag_is_connected(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h b/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h new file mode 100644 index 0000000..c5a790e --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/include/driver/usb_serial_jtag_vfs.h @@ -0,0 +1,72 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "esp_err.h" +#include "esp_vfs.h" +#include "esp_vfs_common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief add /dev/usbserjtag virtual filesystem driver + * + * This function is called from startup code to enable console output + */ +esp_err_t usb_serial_jtag_vfs_register(void); + +/** + * @brief Set the line endings expected to be received + * + * This specifies the conversion between line endings received and + * newlines ('\n', LF) passed into stdin: + * + * - ESP_LINE_ENDINGS_CRLF: convert CRLF to LF + * - ESP_LINE_ENDINGS_CR: convert CR to LF + * - ESP_LINE_ENDINGS_LF: no modification + * + * @note this function is not thread safe w.r.t. reading + * + * @param mode line endings expected + */ +void usb_serial_jtag_vfs_set_rx_line_endings(esp_line_endings_t mode); + +/** + * @brief Set the line endings to sent + * + * This specifies the conversion between newlines ('\n', LF) on stdout and line + * endings sent: + * + * - ESP_LINE_ENDINGS_CRLF: convert LF to CRLF + * - ESP_LINE_ENDINGS_CR: convert LF to CR + * - ESP_LINE_ENDINGS_LF: no modification + * + * @note this function is not thread safe w.r.t. writing + * + * @param mode line endings to send + */ +void usb_serial_jtag_vfs_set_tx_line_endings(esp_line_endings_t mode); + +/** + * @brief set VFS to use USB-SERIAL-JTAG driver for reading and writing + * @note application must configure USB-SERIAL-JTAG driver before calling these functions + * With these functions, read and write are blocking and interrupt-driven. + */ +void usb_serial_jtag_vfs_use_driver(void); + +/** + * @brief set VFS to use simple functions for reading and writing UART + * Read is non-blocking, write is busy waiting until TX FIFO has enough space. + * These functions are used by default. + */ +void usb_serial_jtag_vfs_use_nonblocking(void); + +#ifdef __cplusplus +} +#endif diff --git a/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c new file mode 100644 index 0000000..a2b7d12 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag.c @@ -0,0 +1,279 @@ +/* + * SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include "esp_log.h" +#include "hal/usb_serial_jtag_ll.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/ringbuf.h" +#include "esp_intr_alloc.h" +#include "driver/usb_serial_jtag.h" +#include "soc/periph_defs.h" +#include "soc/soc_caps.h" +#include "esp_check.h" +#include "esp_private/periph_ctrl.h" + +/* + Note: Before you add a workaround for an issue in this driver, please please try + to figure out the actual root cause first. The USB-serial-JTAG is a simple device, + it shouldn't need anything more than a simple, straightforward driver. +*/ + +#if !SOC_RCC_IS_INDEPENDENT +#define USJ_RCC_ATOMIC() PERIPH_RCC_ATOMIC() +#else +#define USJ_RCC_ATOMIC() +#endif + +// The hardware buffer max size is 64, both for RX and TX. +#define USB_SER_JTAG_ENDP_SIZE (64) +#define USB_SER_JTAG_RX_MAX_SIZE (USB_SER_JTAG_ENDP_SIZE) + +typedef struct { + intr_handle_t intr_handle; /*!< USB-SERIAL-JTAG interrupt handler */ + + // RX parameters + RingbufHandle_t rx_ring_buf; /*!< RX ring buffer handler */ + + // TX parameters + RingbufHandle_t tx_ring_buf; /*!< TX ring buffer handler */ + uint8_t tx_stash_buf[USB_SER_JTAG_ENDP_SIZE]; /*!< Data buffer to stash TX FIFO data */ + size_t tx_stash_cnt; /*!< Number of stashed TX FIFO bytes */ +} usb_serial_jtag_obj_t; + +static usb_serial_jtag_obj_t *p_usb_serial_jtag_obj = NULL; + +static const char* USB_SERIAL_JTAG_TAG = "usb_serial_jtag"; + +static uint16_t flow_control = 0; + +static void usb_serial_jtag_isr_handler_default(void *arg) +{ + + BaseType_t xTaskWoken = 0; + uint32_t usbjtag_intr_status = 0; + usbjtag_intr_status = usb_serial_jtag_ll_get_intsts_mask(); + + if (usbjtag_intr_status & USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY) { + //Clear interrupt so we won't be called until the next transfer finishes. + usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY); + + // Interrupt tells us the host picked up the data we sent. + // If we have more data, we can put it in the buffer and the host will pick that up next. + // We expect the TX FIFO to be writable for this. If it's not, somehow someone else + // (ROM print routines?) have snuck in a full buffer before we got here. In that case, + // we simply ignore the interrupt, a new one will come if the buffer is empty again. + if (usb_serial_jtag_ll_txfifo_writable() == 1) { + // Retrieve data from either the stash buffer or, if that's empty, from the ring buffer. + size_t queued_size; + uint8_t *queued_buf = NULL; + if (p_usb_serial_jtag_obj->tx_stash_cnt != 0) { + // Send stashed tx bytes before reading bytes from ring buffer + queued_buf = p_usb_serial_jtag_obj->tx_stash_buf; + queued_size = p_usb_serial_jtag_obj->tx_stash_cnt; + } else { + // Max 64 data payload size in a single EndPoint + queued_buf = (uint8_t *)xRingbufferReceiveUpToFromISR(p_usb_serial_jtag_obj->tx_ring_buf, &queued_size, USB_SER_JTAG_ENDP_SIZE); + } + + if (queued_buf != NULL && queued_size > 0) { + // We have some data to send. Send it. + uint32_t sent_size = usb_serial_jtag_ll_write_txfifo(queued_buf, queued_size); + usb_serial_jtag_ll_txfifo_flush(); + + // Check if we were able to send everything. + if (sent_size < queued_size) { + // Not all bytes could be sent at once; stash the unwritten bytes in a buffer + // This will happen if e.g. the rom output functions manage to sneak a few bytes into the + // TX FIFO before this interrupt triggers. Note stash_size will not larger than + // USB_SER_JTAG_ENDP_SIZE because queued_size is obtained from xRingbufferReceiveUpToFromISR. + size_t stash_size = queued_size - sent_size; + memcpy(p_usb_serial_jtag_obj->tx_stash_buf, &queued_buf[sent_size], stash_size); + p_usb_serial_jtag_obj->tx_stash_cnt = stash_size; + } else { + p_usb_serial_jtag_obj->tx_stash_cnt = 0; + } + // Return the buffer if we got it from the ring buffer. + if (queued_buf != p_usb_serial_jtag_obj->tx_stash_buf) { + vRingbufferReturnItemFromISR(p_usb_serial_jtag_obj->tx_ring_buf, queued_buf, &xTaskWoken); + } + } else { + // No data to send. + // The last transmit may have sent a full EP worth of data. The host will interpret + // this as a transaction that hasn't finished yet and keep the data in its internal + // buffers rather than releasing it to the program listening on the CDC serial port. + // We need to flush again in order to send a 0-byte packet that ends the transaction. + usb_serial_jtag_ll_txfifo_flush(); + + // We will also disable the interrupt as for now there's no need to handle the + // TX interrupt again. We'll re-enable this externally if we need data sent. + usb_serial_jtag_ll_disable_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY); + } + } + } + + if (usbjtag_intr_status & USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT) { + // Acknowledge interrupt + // usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + + // 获取环形缓冲区剩余空间 + size_t free_size = xRingbufferGetCurFreeSize(p_usb_serial_jtag_obj->rx_ring_buf); + + if ( free_size > 128) { + usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + // Read RX FIFO and send available data to ringbuffer. + uint8_t buf[USB_SER_JTAG_RX_MAX_SIZE]; + uint32_t rx_fifo_len = usb_serial_jtag_ll_read_rxfifo(buf, USB_SER_JTAG_RX_MAX_SIZE); + xRingbufferSendFromISR(p_usb_serial_jtag_obj->rx_ring_buf, buf, rx_fifo_len, &xTaskWoken); + }else{ + flow_control = 1; + usb_serial_jtag_ll_disable_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + } + + } + + if (xTaskWoken == pdTRUE) { + portYIELD_FROM_ISR(); + } +} + +esp_err_t usb_serial_jtag_driver_install(usb_serial_jtag_driver_config_t *usb_serial_jtag_config) +{ + esp_err_t err = ESP_OK; + ESP_RETURN_ON_FALSE((p_usb_serial_jtag_obj == NULL), ESP_ERR_INVALID_STATE, USB_SERIAL_JTAG_TAG, "Driver already installed"); + ESP_RETURN_ON_FALSE((usb_serial_jtag_config->rx_buffer_size > 0), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "RX buffer is not prepared"); + ESP_RETURN_ON_FALSE((usb_serial_jtag_config->rx_buffer_size > USB_SER_JTAG_RX_MAX_SIZE), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "RX buffer prepared is so small, should larger than 64"); + ESP_RETURN_ON_FALSE((usb_serial_jtag_config->tx_buffer_size > 0), ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "TX buffer is not prepared"); + p_usb_serial_jtag_obj = (usb_serial_jtag_obj_t*) heap_caps_calloc(1, sizeof(usb_serial_jtag_obj_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + p_usb_serial_jtag_obj->tx_stash_cnt = 0; + if (p_usb_serial_jtag_obj == NULL) { + ESP_LOGE(USB_SERIAL_JTAG_TAG, "memory allocate error"); + // no `goto _exit` here as there's nothing to clean up and that would make the uninstall + // routine unhappy. + return ESP_ERR_NO_MEM; + } + + p_usb_serial_jtag_obj->rx_ring_buf = xRingbufferCreate(usb_serial_jtag_config->rx_buffer_size, RINGBUF_TYPE_BYTEBUF); + if (p_usb_serial_jtag_obj->rx_ring_buf == NULL) { + ESP_LOGE(USB_SERIAL_JTAG_TAG, "ringbuffer create error"); + err = ESP_ERR_NO_MEM; + goto _exit; + } + + p_usb_serial_jtag_obj->tx_ring_buf = xRingbufferCreate(usb_serial_jtag_config->tx_buffer_size, RINGBUF_TYPE_BYTEBUF); + if (p_usb_serial_jtag_obj->rx_ring_buf == NULL) { + ESP_LOGE(USB_SERIAL_JTAG_TAG, "ringbuffer create error"); + err = ESP_ERR_NO_MEM; + goto _exit; + } + + // Enable USB-Serial-JTAG peripheral module clock + USJ_RCC_ATOMIC() { + usb_serial_jtag_ll_enable_bus_clock(true); + } + + // Configure PHY +#if USB_SERIAL_JTAG_LL_EXT_PHY_SUPPORTED + usb_serial_jtag_ll_phy_enable_external(false); // Use internal PHY + usb_serial_jtag_ll_phy_enable_pad(true); // Enable USB PHY pads +#else // USB_SERIAL_JTAG_LL_EXT_PHY_SUPPORTED + usb_serial_jtag_ll_phy_set_defaults(); // External PHY not supported. Set default values. +#endif // USB_WRAP_LL_EXT_PHY_SUPPORTED + + // Note: DO NOT clear the interrupt status bits here. The output routine needs + // USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY set because it needs the ISR to trigger + // as soon as data is sent; the input routine needs the status to retrieve any + // data that is still in the FIFOs. + + // We only enable the RX interrupt; we'll enable the TX one when we actually + // have anything to send. + usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + + err = esp_intr_alloc(ETS_USB_SERIAL_JTAG_INTR_SOURCE, 0, usb_serial_jtag_isr_handler_default, NULL, &p_usb_serial_jtag_obj->intr_handle); + if (err != ESP_OK) { + goto _exit; + } + return ESP_OK; + +_exit: + usb_serial_jtag_driver_uninstall(); + return err; +} + +int usb_serial_jtag_read_bytes(void* buf, uint32_t length, TickType_t ticks_to_wait) +{ + uint8_t *data = NULL; + size_t data_read_len = 0; + + // 获取环形缓冲区剩余空间 + size_t free_size = xRingbufferGetCurFreeSize(p_usb_serial_jtag_obj->rx_ring_buf); + if (free_size > 128 && flow_control == 1) + { + usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + } + + if (length == 0) { + return 0; + } + // Receive new data from ISR + data = (uint8_t*) xRingbufferReceiveUpTo(p_usb_serial_jtag_obj->rx_ring_buf, &data_read_len, (TickType_t) ticks_to_wait, length); + if (data == NULL) { + // If there is no data received from ringbuffer, return 0 directly. + return 0; + } + + memcpy((uint8_t*)buf, data, data_read_len); + vRingbufferReturnItem(p_usb_serial_jtag_obj->rx_ring_buf, data); + data = NULL; + + return data_read_len; +} + +int usb_serial_jtag_write_bytes(const void* src, size_t size, TickType_t ticks_to_wait) +{ + ESP_RETURN_ON_FALSE(size != 0, ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "size should be larger than 0"); + ESP_RETURN_ON_FALSE(src != NULL, ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "Invalid buffer pointer."); + ESP_RETURN_ON_FALSE(p_usb_serial_jtag_obj != NULL, ESP_ERR_INVALID_ARG, USB_SERIAL_JTAG_TAG, "The driver hasn't been initialized"); + + BaseType_t result = pdTRUE; + result = xRingbufferSend(p_usb_serial_jtag_obj->tx_ring_buf, (void*)src, size, ticks_to_wait); + // Re-enable the TX interrupt. If this was disabled, this will immediately trigger the ISR + // and send the things we just put in the ringbuffer. + usb_serial_jtag_ll_ena_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY); + return (result == pdFALSE) ? 0 : size; +} + +//Note that this is also called when usb_serial_jtag_driver_install errors out and as such should +//work on a half-initialized driver as well. +esp_err_t usb_serial_jtag_driver_uninstall(void) +{ + if (p_usb_serial_jtag_obj == NULL) { + ESP_LOGE(USB_SERIAL_JTAG_TAG, "uninstall without install called"); + return ESP_OK; + } + + /* Don't disable the module clock and usb_pad_enable here since the USJ stdout might still depends on it. */ + + usb_serial_jtag_ll_disable_intr_mask(USB_SERIAL_JTAG_INTR_SERIAL_IN_EMPTY | USB_SERIAL_JTAG_INTR_SERIAL_OUT_RECV_PKT); + if (p_usb_serial_jtag_obj->intr_handle) { + esp_intr_free(p_usb_serial_jtag_obj->intr_handle); + } + + if (p_usb_serial_jtag_obj->rx_ring_buf) { + vRingbufferDelete(p_usb_serial_jtag_obj->rx_ring_buf); + p_usb_serial_jtag_obj->rx_ring_buf = NULL; + } + if (p_usb_serial_jtag_obj->tx_ring_buf) { + vRingbufferDelete(p_usb_serial_jtag_obj->tx_ring_buf); + p_usb_serial_jtag_obj->tx_ring_buf = NULL; + } + heap_caps_free(p_usb_serial_jtag_obj); + p_usb_serial_jtag_obj = NULL; + return ESP_OK; +} diff --git a/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c new file mode 100644 index 0000000..a730a63 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_connection_monitor.c @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "driver/usb_serial_jtag.h" +#include "hal/usb_serial_jtag_ll.h" +#include "esp_private/startup_internal.h" +#include "esp_freertos_hooks.h" +#include "esp_pm.h" +#include "esp_private/rtc_clk.h" +#include "esp_check.h" +#include "sdkconfig.h" + +static volatile bool s_usb_serial_jtag_conn_status; +#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION +static esp_pm_lock_handle_t s_usb_serial_jtag_pm_lock; +#endif + +// FreeRTOS tick interrupt may get delayed in handling, which could lead to no SOF coming in within the period from +// a delayed tick to the following tick. Therefore, when FREERTOS_HZ is comparable to SOF packet frequency, a NO_SOF +// tolerance needs to be given to avoid a false disconnection detection. +#define USJ_DISCONNECT_CONFIRM_PERIOD_MS 3 +#define ALLOWED_NO_SOF_TICKS pdMS_TO_TICKS(USJ_DISCONNECT_CONFIRM_PERIOD_MS) + +static uint32_t remaining_allowed_no_sof_ticks; + +static __attribute__((unused)) const char *USB_SERIAL_JTAG_CONN_MONITOR_TAG = "usb_serial_jtag"; + +bool usb_serial_jtag_is_connected(void) +{ + return s_usb_serial_jtag_conn_status; +} + +static void IRAM_ATTR usb_serial_jtag_sof_tick_hook(void) +{ + // SOF packet is sent by the HOST every 1ms on a full speed bus + // Between two consecutive tick hooks, there will be at least 1ms (selectable tick rate range is 1 - 1000Hz) + // Therefore, SOF intr bit must have be raised at every tick hook if it is connected to a HOST + // Here, the strategy is: Always assume USB Serial/JTAG is connected until we are sure it is not connected + // Consider it is disconnected only if SOF intr bit is not raised within (ALLOWED_NO_SOF_TICKS + 1) tick periods + bool sof_received = (usb_serial_jtag_ll_get_intraw_mask() & USB_SERIAL_JTAG_INTR_SOF); + usb_serial_jtag_ll_clr_intsts_mask(USB_SERIAL_JTAG_INTR_SOF); + if (s_usb_serial_jtag_conn_status != sof_received) { + if (!sof_received) { + if (remaining_allowed_no_sof_ticks > 0) { + remaining_allowed_no_sof_ticks--; + } else { + // Tolerance credit used up, considered as USJ disconnected +#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION + esp_pm_lock_release(s_usb_serial_jtag_pm_lock); +#endif +#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL + rtc_clk_bbpll_remove_consumer(); +#endif + s_usb_serial_jtag_conn_status = false; + } + } else { + // USJ re-connected +#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION + esp_pm_lock_acquire(s_usb_serial_jtag_pm_lock); +#endif +#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL + rtc_clk_bbpll_add_consumer(); +#endif + s_usb_serial_jtag_conn_status = true; + remaining_allowed_no_sof_ticks = ALLOWED_NO_SOF_TICKS; + } + } +} + +ESP_SYSTEM_INIT_FN(usb_serial_jtag_conn_status_init, SECONDARY, BIT(0), 230) +{ +#if CONFIG_USJ_NO_AUTO_LS_ON_CONNECTION + ESP_RETURN_ON_ERROR(esp_pm_lock_create(ESP_PM_NO_LIGHT_SLEEP, 0, "usb_serial_jtag", &s_usb_serial_jtag_pm_lock), + USB_SERIAL_JTAG_CONN_MONITOR_TAG, "create NO_LIGHT_SLEEP lock failed"); + // We always assume it is connected at first, so acquires the lock to avoid auto light sleep + esp_pm_lock_acquire(s_usb_serial_jtag_pm_lock); +#endif +#if USB_SERIAL_JTAG_LL_PHY_DEPENDS_ON_BBPLL +// TODO: esp32p4 USJ rely on SPLL, if it will also be disabled during sleep, we need to call spll_add_consumer? IDF-9947 + rtc_clk_bbpll_add_consumer(); +#endif + s_usb_serial_jtag_conn_status = true; + remaining_allowed_no_sof_ticks = ALLOWED_NO_SOF_TICKS; + + return esp_register_freertos_tick_hook(usb_serial_jtag_sof_tick_hook); +} + +void usb_serial_jtag_connection_monitor_include(void) +{ + // Linker hook function, exists to make the linker examine this file +} diff --git a/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c new file mode 100644 index 0000000..ea400bb --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/src/usb_serial_jtag_vfs.c @@ -0,0 +1,480 @@ +/* + * SPDX-FileCopyrightText: 2015-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +//This is a simple non-blocking (well, tx may spin for a bit if the buffer +//is full) USB-serial-jtag driver. Select etc is not supported yet. + +#include +#include +#include +#include +#include +#include +#include +#include "esp_timer.h" +#include "esp_vfs.h" +#include "esp_vfs_dev.h" // Old headers for the aliasing functions +#include "esp_vfs_usb_serial_jtag.h" // Old headers for the aliasing functions +#include "esp_attr.h" +#include "esp_log.h" +#include "sdkconfig.h" +#include "soc/soc_caps.h" +#include "hal/usb_serial_jtag_ll.h" +#include "driver/usb_serial_jtag_vfs.h" +#include "driver/usb_serial_jtag.h" +#include "esp_private/startup_internal.h" + +// Token signifying that no character is available +#define NONE -1 + +#if CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF +# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_CRLF +#elif CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR +# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_CR +#else +# define DEFAULT_TX_MODE ESP_LINE_ENDINGS_LF +#endif + +#if CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF +# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_CRLF +#elif CONFIG_NEWLIB_STDIN_LINE_ENDING_CR +# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_CR +#else +# define DEFAULT_RX_MODE ESP_LINE_ENDINGS_LF +#endif + +// write bytes function type +typedef void (*tx_func_t)(int, int); +// read bytes function type +typedef int (*rx_func_t)(int); + +// Basic functions for sending and receiving bytes +static void usb_serial_jtag_tx_char(int fd, int c); +static int usb_serial_jtag_rx_char(int fd); + +//If no host is listening to the CDCACM port, the TX buffer +//will never be able to flush to the host. Instead of the Tx +//routines waiting forever, if the buffer hasn't been flushed +//to the host the tx routine will fail fast. (Note that as +//soon as something starts listening, the CDCACM port will +//start working as normal again.) +#define TX_FLUSH_TIMEOUT_US (50*1000LL) +//(As a reference, you'd expect an unloaded usb bus to try to +//pick up tx data once every USB frame, aka every 1ms. We take a +//longer timeout to allow for a loaded bus.) + +typedef struct { + // One-character buffer used for newline conversion code + int peek_char; + // Read and write locks, lazily initialized + _lock_t read_lock; + _lock_t write_lock; + // Non-blocking flag. + // The default implementation does not honor this flag, all reads + // are non-blocking. + // When the driver is used (via esp_vfs_usb_serial_jtag_use_driver), + // reads are either blocking or non-blocking depending on this flag. + bool non_blocking; + // TX has already tried a blocking send. + bool tx_tried_blocking; + // Newline conversion mode when transmitting + esp_line_endings_t tx_mode; + // Newline conversion mode when receiving + esp_line_endings_t rx_mode; + // Functions used to write bytes to port. Default to "basic" functions. + tx_func_t tx_func; + // Functions used to read bytes from port. Default to "basic" functions. + rx_func_t rx_func; + // Timestamp of last time we managed to write something to the tx buffer + int64_t last_tx_ts; +} usb_serial_jtag_vfs_context_t; + +//If the context should be dynamically initialized, remove this structure +//and point s_ctx to allocated data. +static usb_serial_jtag_vfs_context_t s_ctx = { + .peek_char = NONE, + .tx_mode = DEFAULT_TX_MODE, + .rx_mode = DEFAULT_RX_MODE, + .tx_func = usb_serial_jtag_tx_char, + .rx_func = usb_serial_jtag_rx_char +}; + +static int usb_serial_jtag_open(const char * path, int flags, int mode) +{ + s_ctx.non_blocking = ((flags & O_NONBLOCK) == O_NONBLOCK); + return 0; +} + +static void usb_serial_jtag_tx_char(int fd, int c) +{ + uint8_t cc = (uint8_t)c; + // Try to write to the buffer as long as we still expect the buffer to have + // a chance of being emptied by an active host. Just drop the data if there's + // no chance anymore. + // When we first try to send a character and the buffer is not accessible yet, + // we wait until the time has been more than TX_FLUSH_TIMEOUT_US since we successfully + // sent the last byte. If it takes longer than TX_FLUSH_TIMEOUT_US, we drop every + // byte until the buffer can be accessible again. + do { + if (usb_serial_jtag_ll_txfifo_writable()) { + usb_serial_jtag_ll_write_txfifo(&cc, 1); + if (c == '\n') { + //Make sure line doesn't linger in fifo + usb_serial_jtag_ll_txfifo_flush(); + } + //update time of last successful tx to now. + s_ctx.last_tx_ts = esp_timer_get_time(); + break; + } + } while ((esp_timer_get_time() - s_ctx.last_tx_ts) < TX_FLUSH_TIMEOUT_US); + +} + +static int usb_serial_jtag_rx_char(int fd) +{ + uint8_t c; + int l = usb_serial_jtag_ll_read_rxfifo(&c, 1); + if (l == 0) { + return NONE; + } + return c; +} + +static ssize_t usb_serial_jtag_write(int fd, const void * data, size_t size) +{ + const char *data_c = (const char *)data; + /* Even though newlib does stream locking on each individual stream, we need + * a dedicated lock if two streams (stdout and stderr) point to the + * same port. + */ + _lock_acquire_recursive(&s_ctx.write_lock); + for (size_t i = 0; i < size; i++) { + int c = data_c[i]; + if (c == '\n' && s_ctx.tx_mode != ESP_LINE_ENDINGS_LF) { + s_ctx.tx_func(fd, '\r'); + if (s_ctx.tx_mode == ESP_LINE_ENDINGS_CR) { + continue; + } + } + s_ctx.tx_func(fd, c); + } + _lock_release_recursive(&s_ctx.write_lock); + return size; +} + +/* Helper function which returns a previous character or reads a new one from + * the port. Previous character can be returned ("pushed back") using + * usb_serial_jtag_return_char function. + */ +static int usb_serial_jtag_read_char(int fd) +{ + /* return character from peek buffer, if it is there */ + if (s_ctx.peek_char != NONE) { + int c = s_ctx.peek_char; + s_ctx.peek_char = NONE; + return c; + } + return s_ctx.rx_func(fd); +} + +/* Push back a character; it will be returned by next call to usb_serial_jtag_read_char */ +static void usb_serial_jtag_return_char(int fd, int c) +{ + assert(s_ctx.peek_char == NONE); + s_ctx.peek_char = c; +} + +static ssize_t usb_serial_jtag_read(int fd, void* data, size_t size) +{ + char *data_c = (char *) data; + size_t received = 0; + _lock_acquire_recursive(&s_ctx.read_lock); + while (received < size) { + int c = usb_serial_jtag_read_char(fd); + if (c == '\r') { + if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CR) { + c = '\n'; + } else if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CRLF) { + /* look ahead */ + int c2 = usb_serial_jtag_read_char(fd); + if (c2 == NONE) { + /* could not look ahead, put the current character back */ + usb_serial_jtag_return_char(fd, c); + break; + } + if (c2 == '\n') { + /* this was \r\n sequence. discard \r, return \n */ + c = '\n'; + } else { + /* \r followed by something else. put the second char back, + * it will be processed on next iteration. return \r now. + */ + usb_serial_jtag_return_char(fd, c2); + } + } + } else if (c == NONE) { + break; + } + data_c[received] = (char) c; + ++received; + if (c == '\n') { + break; + } + } + _lock_release_recursive(&s_ctx.read_lock); + if (received > 0) { + return received; + } + errno = EWOULDBLOCK; + return -1; +} + +static int usb_serial_jtag_fstat(int fd, struct stat * st) +{ + memset(st, 0, sizeof(*st)); + st->st_mode = S_IFCHR; + return 0; +} + +static int usb_serial_jtag_close(int fd) +{ + return 0; +} + +static int usb_serial_jtag_fcntl(int fd, int cmd, int arg) +{ + int result = 0; + if (cmd == F_GETFL) { + result |= O_RDWR; + if (s_ctx.non_blocking) { + result |= O_NONBLOCK; + } + } else if (cmd == F_SETFL) { + s_ctx.non_blocking = (arg & O_NONBLOCK) != 0; + } else { + // unsupported operation + result = -1; + errno = ENOSYS; + } + return result; +} + +static int usb_serial_jtag_fsync(int fd) +{ + _lock_acquire_recursive(&s_ctx.write_lock); + usb_serial_jtag_ll_txfifo_flush(); + //Wait for the host to have picked up the buffer, but honour the timeout in + //case the host is not listening. + while ((esp_timer_get_time() - s_ctx.last_tx_ts) < TX_FLUSH_TIMEOUT_US) { + if (usb_serial_jtag_ll_txfifo_writable()) { + s_ctx.last_tx_ts = esp_timer_get_time(); + //The last transfer may have been a 64-byte one. Flush again in order to + //send a 0-byte packet to indicate the end of the USB transfer, otherwise + //those 64 bytes will get stuck in the hosts buffer. + usb_serial_jtag_ll_txfifo_flush(); + break; + } + } + _lock_release_recursive(&s_ctx.write_lock); + return 0; +} + +#ifdef CONFIG_VFS_SUPPORT_TERMIOS +static int usb_serial_jtag_tcsetattr(int fd, int optional_actions, const struct termios *p) +{ + if (p == NULL) { + errno = EINVAL; + return -1; + } + + switch (optional_actions) { + case TCSANOW: + // nothing to do + break; + case TCSADRAIN: + usb_serial_jtag_fsync(fd); + break; + case TCSAFLUSH: + // Not applicable. + break; + default: + errno = EINVAL; + return -1; + } + + if (p->c_iflag & IGNCR) { + s_ctx.rx_mode = ESP_LINE_ENDINGS_CRLF; + } else if (p->c_iflag & ICRNL) { + s_ctx.rx_mode = ESP_LINE_ENDINGS_CR; + } else { + s_ctx.rx_mode = ESP_LINE_ENDINGS_LF; + } + return 0; +} + +static int usb_serial_jtag_tcgetattr(int fd, struct termios *p) +{ + if (p == NULL) { + errno = EINVAL; + return -1; + } + + memset(p, 0, sizeof(struct termios)); + + if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CRLF) { + p->c_iflag |= IGNCR; + } else if (s_ctx.rx_mode == ESP_LINE_ENDINGS_CR) { + p->c_iflag |= ICRNL; + } + + //Dummy values that vaguely make sense on a not-actually-rs232 port. + //Should be good enough to keep software that expects an actual + //serial port happy. + p->c_cflag &= (~CSIZE); + p->c_cflag |= CS8; + p->c_ispeed = p->c_ospeed = 1000000; + + return 0; +} + +static int usb_serial_jtag_tcdrain(int fd) +{ + usb_serial_jtag_fsync(fd); + return 0; +} + +static int usb_serial_jtag_tcflush(int fd, int select) +{ + //Flushing is not supported. + errno = EINVAL; + return -1; +} +#endif // CONFIG_VFS_SUPPORT_TERMIOS + +void usb_serial_jtag_vfs_set_tx_line_endings(esp_line_endings_t mode) +{ + s_ctx.tx_mode = mode; +} + +void usb_serial_jtag_vfs_set_rx_line_endings(esp_line_endings_t mode) +{ + s_ctx.rx_mode = mode; +} + +static const esp_vfs_t usj_vfs = { + .flags = ESP_VFS_FLAG_DEFAULT, + .write = &usb_serial_jtag_write, + .open = &usb_serial_jtag_open, + .fstat = &usb_serial_jtag_fstat, + .close = &usb_serial_jtag_close, + .read = &usb_serial_jtag_read, + .fcntl = &usb_serial_jtag_fcntl, + .fsync = &usb_serial_jtag_fsync, +#ifdef CONFIG_VFS_SUPPORT_TERMIOS + .tcsetattr = &usb_serial_jtag_tcsetattr, + .tcgetattr = &usb_serial_jtag_tcgetattr, + .tcdrain = &usb_serial_jtag_tcdrain, + .tcflush = &usb_serial_jtag_tcflush, +#endif // CONFIG_VFS_SUPPORT_TERMIOS +}; + +const esp_vfs_t* esp_vfs_usb_serial_jtag_get_vfs(void) +{ + return &usj_vfs; +} + +esp_err_t usb_serial_jtag_vfs_register(void) +{ + // "/dev/usb_serial_jtag" unfortunately is too long for vfs + return esp_vfs_register("/dev/usbserjtag", &usj_vfs, NULL); +} + +#if CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG +ESP_SYSTEM_INIT_FN(init_vfs_usj, CORE, BIT(0), 111) +{ + usb_serial_jtag_vfs_register(); + return ESP_OK; +} +#endif + +#if CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG +ESP_SYSTEM_INIT_FN(init_vfs_usj_sec, CORE, BIT(0), 112) +{ + // "/dev/seccondary_usb_serial_jtag" unfortunately is too long for vfs + esp_vfs_register("/dev/secondary", &usj_vfs, NULL); + return ESP_OK; +} +#endif + +/*********************************************************** + * VFS uses USB-SERIAL-JTAG driver part. + **********************************************************/ + +static int usbjtag_rx_char_via_driver(int fd) +{ + uint8_t c; + TickType_t timeout = s_ctx.non_blocking ? 0 : portMAX_DELAY; + int n = usb_serial_jtag_read_bytes(&c, 1, timeout); + if (n <= 0) { + return NONE; + } + return c; +} + +static void usbjtag_tx_char_via_driver(int fd, int c) +{ + char ch = (char) c; + TickType_t ticks = (TX_FLUSH_TIMEOUT_US / 1000) / portTICK_PERIOD_MS; + if (usb_serial_jtag_write_bytes(&ch, 1, 0) != 0) { + s_ctx.tx_tried_blocking = false; + return; + } + + if (s_ctx.tx_tried_blocking == false) { + if (usb_serial_jtag_write_bytes(&ch, 1, ticks) != 0) { + return; + } else { + s_ctx.tx_tried_blocking = true; + } + } +} + +void usb_serial_jtag_vfs_use_nonblocking(void) +{ + _lock_acquire_recursive(&s_ctx.read_lock); + _lock_acquire_recursive(&s_ctx.write_lock); + s_ctx.tx_func = usb_serial_jtag_tx_char; + s_ctx.rx_func = usb_serial_jtag_rx_char; + _lock_release_recursive(&s_ctx.write_lock); + _lock_release_recursive(&s_ctx.read_lock); +} + +void usb_serial_jtag_vfs_use_driver(void) +{ + _lock_acquire_recursive(&s_ctx.read_lock); + _lock_acquire_recursive(&s_ctx.write_lock); + s_ctx.tx_func = usbjtag_tx_char_via_driver; + s_ctx.rx_func = usbjtag_rx_char_via_driver; + _lock_release_recursive(&s_ctx.write_lock); + _lock_release_recursive(&s_ctx.read_lock); +} + +void usb_serial_jtag_vfs_include_dev_init(void) +{ + // Linker hook function, exists to make the linker examine this file +} + +// -------------------------- esp_vfs_usb_serial_jtag_xxx ALIAS (deprecated) ---------------------------- + +esp_err_t esp_vfs_dev_usb_serial_jtag_register(void) __attribute__((alias("usb_serial_jtag_vfs_register"))); + +void esp_vfs_dev_usb_serial_jtag_set_rx_line_endings(esp_line_endings_t mode) __attribute__((alias("usb_serial_jtag_vfs_set_rx_line_endings"))); + +void esp_vfs_dev_usb_serial_jtag_set_tx_line_endings(esp_line_endings_t mode) __attribute__((alias("usb_serial_jtag_vfs_set_tx_line_endings"))); + +void esp_vfs_usb_serial_jtag_use_nonblocking(void) __attribute__((alias("usb_serial_jtag_vfs_use_nonblocking"))); + +void esp_vfs_usb_serial_jtag_use_driver(void) __attribute__((alias("usb_serial_jtag_vfs_use_driver"))); diff --git a/components/esp_driver_usb_serial_jtag/test_apps/.build-test-rules.yml b/components/esp_driver_usb_serial_jtag/test_apps/.build-test-rules.yml new file mode 100644 index 0000000..18ab2db --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/.build-test-rules.yml @@ -0,0 +1,13 @@ +# Documentation: .gitlab/ci/README.md#manifest-file-to-control-the-buildtest-apps + +components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag: + disable: + - if: SOC_USB_SERIAL_JTAG_SUPPORTED != 1 + disable_test: + - if: IDF_TARGET in ["esp32p4"] + temporary: true + reason: No runners. + depends_components: + - vfs + - esp_driver_gpio + - esp_driver_usb_serial_jtag diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/CMakeLists.txt b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/CMakeLists.txt new file mode 100644 index 0000000..0881e00 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/CMakeLists.txt @@ -0,0 +1,8 @@ +# This is the project CMakeLists.txt file for the test subproject +cmake_minimum_required(VERSION 3.16) + +# "Trim" the build. Include the minimal set of components, main, and anything it depends on. +set(COMPONENTS main) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(usb_serial_test) diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/README.md b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/README.md new file mode 100644 index 0000000..ad95e41 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/README.md @@ -0,0 +1,2 @@ +| Supported Targets | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-P4 | ESP32-S3 | +| ----------------- | -------- | -------- | -------- | -------- | -------- | diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/CMakeLists.txt b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/CMakeLists.txt new file mode 100644 index 0000000..f1b9135 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/CMakeLists.txt @@ -0,0 +1,7 @@ +# In order for the cases defined by `TEST_CASE` to be linked into the final elf, +# the component can be registered as WHOLE_ARCHIVE +idf_component_register( + SRCS "test_app_main.c" "test_usb_serial_jtag.c" + REQUIRES driver unity vfs + WHOLE_ARCHIVE +) diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_app_main.c b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_app_main.c new file mode 100644 index 0000000..dead56b --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_app_main.c @@ -0,0 +1,50 @@ +/* + * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "unity.h" +#include "unity_test_utils.h" +#include "esp_heap_caps.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#define TEST_MEMORY_LEAK_THRESHOLD (200) + +static size_t before_free_8bit; +static size_t before_free_32bit; + +void setUp(void) +{ + before_free_8bit = heap_caps_get_free_size(MALLOC_CAP_8BIT); + before_free_32bit = heap_caps_get_free_size(MALLOC_CAP_32BIT); +} + +void tearDown(void) +{ + size_t after_free_8bit = heap_caps_get_free_size(MALLOC_CAP_8BIT); + size_t after_free_32bit = heap_caps_get_free_size(MALLOC_CAP_32BIT); + printf("\n"); + unity_utils_check_leak(before_free_8bit, after_free_8bit, "8BIT", TEST_MEMORY_LEAK_THRESHOLD); + unity_utils_check_leak(before_free_32bit, after_free_32bit, "32BIT", TEST_MEMORY_LEAK_THRESHOLD); +} + +void app_main(void) +{ + // _ _ _____ ____ _____ ______ _____ _____ _ + // | | | |/ ____| _ \ / ____| ____| __ \|_ _| /\ | | + // | | | | (___ | |_) || (___ | |__ | |__) | | | / \ | | + // | | | |\___ \| _ < \___ \| __| | _ / | | / /\ \ | | + // | |__| |____) | |_) | ____) | |____| | \ \ _| |_ / ____ \| |____ + // \____/|_____/|____/ |_____/|______|_| \_\_____/_/ \_\______| + printf("\n"); + printf(" _ _ _____ ____ _____ ______ _____ _____ _ \n"); + printf("| | | |/ ____| _ \\ / ____| ____| __ \\|_ _| /\\ | | \n"); + printf("| | | | (___ | |_) || (___ | |__ | |__) | | | / \\ | | \n"); + printf("| | | |\\___ \\| _ < \\___ \\| __| | _ / | | / /\\ \\ | | \n"); + printf("| |__| |____) | |_) | ____) | |____| | \\ \\ _| |_ / ____ \\| |____ \n"); + printf(" \\____/|_____/|____/ |_____/|______|_| \\_\\_____/_/ \\_\\______|\n"); + + unity_run_menu(); +} diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_usb_serial_jtag.c b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_usb_serial_jtag.c new file mode 100644 index 0000000..b1bdb9c --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/main/test_usb_serial_jtag.c @@ -0,0 +1,65 @@ +/* + * SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include "unity.h" +#include "driver/usb_serial_jtag.h" +#include "esp_log.h" +#include "esp_vfs_dev.h" +#include "driver/usb_serial_jtag_vfs.h" +#include "driver/usb_serial_jtag.h" +#include +#include +#include + +#define PRINT_TIMES (300) +static const char TAG[] = "usb_serial_test"; + +static void test_task_driver1(void *pvParameters) +{ + SemaphoreHandle_t sem = (SemaphoreHandle_t)pvParameters; + for (int i = 0; i < PRINT_TIMES; i++) { + ESP_LOGI(TAG, "Oh, hello world 1, this test is for testing message and parse in python, time %d", i); + vTaskDelay(11); + } + xSemaphoreGive(sem); + vTaskDelete(NULL); +} + +static void test_task_driver2(void *pvParameters) +{ + SemaphoreHandle_t sem = (SemaphoreHandle_t)pvParameters; + for (int i = 0; i < PRINT_TIMES; i++) { + ESP_LOGI(TAG, "Oh, hello world 2, this test is for testing message and parse in python, time %d", i); + vTaskDelay(10); + } + xSemaphoreGive(sem); + vTaskDelete(NULL); +} + +TEST_CASE("test print via usb_serial_jtag driver multiple times in different tasks", "[usb_serial_jtag]") +{ + usb_serial_jtag_driver_config_t cfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT(); + SemaphoreHandle_t sem = xSemaphoreCreateCounting(2, 0); + + TEST_ESP_OK(usb_serial_jtag_driver_install(&cfg)); + + // Tell vfs to use usb-serial-jtag driver + usb_serial_jtag_vfs_use_driver(); + + xTaskCreate(test_task_driver2, "usj_print_1", 4096, sem, 10, NULL); + xTaskCreate(test_task_driver1, "usj_print_2", 4096, sem, 10, NULL); + for (int i = 0; i < 2; i++) { + xSemaphoreTake(sem, portMAX_DELAY); + } + + vSemaphoreDelete(sem); + vTaskDelay(5); + + usb_serial_jtag_vfs_use_nonblocking(); + usb_serial_jtag_driver_uninstall(); +} diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/pytest_usb_serial_jtag.py b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/pytest_usb_serial_jtag.py new file mode 100644 index 0000000..6b10e90 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/pytest_usb_serial_jtag.py @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: CC0-1.0 +import pytest +from pytest_embedded import Dut + + +@pytest.mark.esp32s3 +@pytest.mark.esp32c3 +@pytest.mark.esp32c6 +@pytest.mark.esp32h2 +@pytest.mark.usb_serial_jtag +@pytest.mark.parametrize( + 'port, config', + [ + pytest.param('/dev/serial_ports/ttyACM-esp32', 'release'), + ], + indirect=True, +) +def test_usb_serial_jtag_dev(dut: Dut) -> None: # type: ignore + dut.expect_exact('Press ENTER to see the list of tests') + dut.write('\"test print via usb_serial_jtag driver multiple times in different tasks\"') + for i in range(300 * 2): + dut.expect(r'Oh, hello world (\d), this test is for testing message and parse in python, time (\d+)', timeout=10) diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.ci.release b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.ci.release new file mode 100644 index 0000000..673b6f8 --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.ci.release @@ -0,0 +1,6 @@ +CONFIG_PM_ENABLE=y +CONFIG_FREERTOS_USE_TICKLESS_IDLE=y +CONFIG_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y +CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT=y +CONFIG_COMPILER_OPTIMIZATION_NONE=y diff --git a/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.defaults b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.defaults new file mode 100644 index 0000000..7c1a0ce --- /dev/null +++ b/components/esp_driver_usb_serial_jtag/test_apps/usb_serial_jtag/sdkconfig.defaults @@ -0,0 +1,3 @@ +CONFIG_FREERTOS_HZ=1000 +CONFIG_ESP_TASK_WDT_INIT=n +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y