Compare commits

..

No commits in common. "e2df5b29e0c5dd7c0a0e9874844d0b194456a7f3" and "98626cbd47dd109413e20b1f7dcf0a9103de2b43" have entirely different histories.

23 changed files with 111 additions and 1489 deletions

View File

@ -1,25 +0,0 @@
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()

View File

@ -1,28 +0,0 @@
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

View File

@ -1,27 +0,0 @@
/*
* 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

View File

@ -1,101 +0,0 @@
/*
* 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

View File

@ -1,72 +0,0 @@
/*
* 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

View File

@ -1,279 +0,0 @@
/*
* SPDX-FileCopyrightText: 2021-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <stdbool.h>
#include <stdatomic.h>
#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;
}

View File

@ -1,95 +0,0 @@
/*
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdbool.h>
#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
}

View File

@ -1,480 +0,0 @@
/*
* 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 <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <sys/errno.h>
#include <sys/lock.h>
#include <sys/fcntl.h>
#include <sys/param.h>
#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")));

View File

@ -1,13 +0,0 @@
# 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

View File

@ -1,8 +0,0 @@
# 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)

View File

@ -1,2 +0,0 @@
| Supported Targets | ESP32-C3 | ESP32-C6 | ESP32-H2 | ESP32-P4 | ESP32-S3 |
| ----------------- | -------- | -------- | -------- | -------- | -------- |

View File

@ -1,7 +0,0 @@
# 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
)

View File

@ -1,50 +0,0 @@
/*
* 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();
}

View File

@ -1,65 +0,0 @@
/*
* SPDX-FileCopyrightText: 2023-2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#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 <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
#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();
}

View File

@ -1,23 +0,0 @@
# 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)

View File

@ -1,6 +0,0 @@
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

View File

@ -1,3 +0,0 @@
CONFIG_FREERTOS_HZ=1000
CONFIG_ESP_TASK_WDT_INIT=n
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y

View File

@ -3,7 +3,7 @@ file(GLOB PORT_SRCS "wifi/*.c" )
file(GLOB FILE_SYS_SRCS "file_system/spiffs.c" "file_system/file_encryptor.c" )
idf_component_register(SRCS "main.c" "usb_serial_task" "Receiver.c" "flasher_tool.c"
idf_component_register(SRCS "main.c" "usb_serial_task" "Receiver.c"
${PORT_SRCS}
${FILE_SYS_SRCS}
INCLUDE_DIRS "."

View File

@ -73,20 +73,6 @@ uint16_t crc16_modbus(const uint8_t *data, uint16_t len) {
例:0xAA 0x55 + 0x01 + 0x01 + 0x0008 + 数据内容 + CRC校验
*/
void Report_transmission_progress(uint32_t file_size,uint32_t have_load)
{
float tran_schedule = 0;
uint8_t send_buff[512] = {0x55, 0xAA, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00};
uint16_t data_len = 0;
// ESP_LOGI(TAG,"Report_transmission_progress");
tran_schedule = (float)have_load / file_size;
data_len = 1 + 2;
send_buff[4] = data_len & 0xff;
send_buff[5] = (data_len >> 8) & 0xff;
send_buff[6] = (uint8_t)(tran_schedule * 100);
usb_serial_jtag_write_bytes(&send_buff[0],(6 + data_len + 2),20 / portTICK_PERIOD_MS);
// ESP_LOGI(TAG,"buff size:%d %.2f %d",send_buff[6],tran_schedule,data_len);
}
uint8_t Device_SN[12];
@ -108,11 +94,9 @@ void Connection_test(uint8_t *buffer)
if (buffer[0] == 0x01) {
usb_serial_jtag_write_bytes(&send_buff[0],(6 + sizeof(Device_info_t) + 2),20 / portTICK_PERIOD_MS);
}
// ESP_LOGI(TAG,"buff size:%d %d",sizeof(Device_info_t),data_len);
ESP_LOGI(TAG,"buff size:%d %d",sizeof(Device_info_t),data_len);
}
/*
Funcode(0x02)
Cmdcode:(0x01)----文件名
@ -124,8 +108,6 @@ void Transfer_file(uint8_t *buffer)
uint16_t data_len = 0;
uint16_t crc_calc = 0xffff;
uint16_t crc_received = 0;
static uint32_t file_size = 0;
static uint32_t have_load = 0;
static FILE* file;
char* data_buff = NULL;
char file_name[64];
@ -145,15 +127,14 @@ void Transfer_file(uint8_t *buffer)
{
return;
}
file_size = data_buff[0] | data_buff[1] << 8 | data_buff[2] << 16 | data_buff[3] << 24;
sprintf(&file_name[0],"/spiffs/%s",&data_buff[4]);
ESP_LOGI(TAG,"file name:%s file size:%ld",file_name,file_size);
sprintf(&file_name[0],"/spiffs/%s",data_buff);
ESP_LOGI(TAG,"file name:%s",file_name);
file = fopen(file_name, "ab");
if (file == NULL) {
printf("Failed to open file for writing\n");
return;
}
// fclose(file);
}
} else if(buffer[0] == 0x02) {//文件内容
@ -164,35 +145,23 @@ void Transfer_file(uint8_t *buffer)
crc_received = data_buff[data_len-1]<<8 | data_buff[data_len-2];
data_buff[data_len-2] = 0;
data_buff[data_len-1] = 0;
have_load += data_len;
//
size_t written = fwrite(&data_buff[2], 1, (data_len - 4), file);
if (written != (data_len - 4)) {
ESP_LOGE("SPIFFS", "fwrite failed, written=%d", written);
} else {
// ESP_LOGI("SPIFFS", "Write success: %d bytes", written);
ESP_LOGI("SPIFFS", "Write success: %d bytes", written);
}
Report_transmission_progress(file_size,have_load);
if(data_buff[0] == 0xff && data_buff[1] == 0xff)
{
have_load = 0;
fclose(file);
ESP_LOGI(TAG,"data_buff[0]:%X %X",data_buff[0],data_buff[1]);
}
// ESP_LOGI(TAG,"data_buff[0]:%X %X",data_buff[0],data_buff[1]);
ESP_LOGI(TAG,"data_buff[0]:%X %X",data_buff[0],data_buff[1]);
crc_calc = crc16_modbus((uint8_t*)&data_buff[2],data_len-4);
}else{
ESP_LOGE(TAG,"fail:%d",data_len);
}
if(crc_calc != crc_received)
{
ESP_LOG_BUFFER_HEXDUMP("Recv str: ", &data_buff[0], 1024, ESP_LOG_INFO);
while (1)
{
vTaskDelay(100/ portTICK_PERIOD_MS);
}
}
} else if(buffer[0] == 0x03) {//删除所有文件
if (WaitPrnBufBytes(&uart_interface_data,2,0xffff,(uint8_t*)&data_buff[0]) == 2)
{
@ -200,7 +169,7 @@ void Transfer_file(uint8_t *buffer)
}
delete_all_file();
}
// ESP_LOGI(TAG,"crc:%X----%X",crc_calc,crc_received);
ESP_LOGI(TAG,"crc:%X----%X",crc_calc,crc_received);
free(data_buff);
}
@ -218,7 +187,7 @@ void Read_CMD_task(void *pvParameter)
{
frameStreamRead(&uart_interface_data,&ch,1);
// ESP_LOGI(TAG, "Read:%X,%ld,---%ld:%ld",ch,frameStreamRecLen(&uart_interface_data),uart_interface_data.read,uart_interface_data.write);
ESP_LOGI(TAG, "Read:%X,%ld,---%ld:%ld",ch,frameStreamRecLen(&uart_interface_data),uart_interface_data.read,uart_interface_data.write);
if(ch == 0xAA)
{
if (WaitPrnBufBytes(&uart_interface_data,2,0xffff,&data[0]) == 2)

View File

@ -1,124 +0,0 @@
#include "public.h"
#include "esp_log.h"
#include "spiffs.h"
static const char *TAG = "main";
#define WRITE_BLOCK 64
void Flasher_tool_task(void *pvParameter)
{
#if 1
FILE* f;
uint8_t* load_buff = NULL;
const loader_esp32_config_t esp32c3_config = {
.baud_rate = 1152000,
.uart_port = UART_NUM_1,
.uart_rx_pin = GPIO_NUM_20,
.uart_tx_pin = GPIO_NUM_21,
.reset_trigger_pin = GPIO_NUM_9,
.gpio0_trigger_pin = GPIO_NUM_2,
};
if (loader_port_esp32_init(&esp32c3_config) != ESP_LOADER_SUCCESS) {
ESP_LOGE(TAG, "serial initialization failed.");
return;
}
if (connect_to_target(1152000) == ESP_LOADER_SUCCESS) {
ESP_LOGI(TAG, "connect_to_target initialization success.");
if(esp_get_free_heap_size() >(WRITE_BLOCK + 20)*1024)
{
load_buff = malloc(WRITE_BLOCK*1024+24);
if(load_buff == NULL)
{
return;
}
}
if(esp_loader_get_target() == ESP32S3_CHIP)
{
ESP_LOGI(TAG,"Find ESP32S3");
ESP_LOGI(TAG, "Loading bin...");
// flash_binary()
#if 0
uint32_t bin_size = 749504;
uint32_t write_addr = 0;
while (bin_size)
{
if(bin_size > WRITE_BLOCK*1024)
{
if(Read_ESPFlash(0x45,write_addr,&load_buff[0],WRITE_BLOCK*1024) == WRITE_BLOCK*1024)
{
flash_binary(&load_buff[0],WRITE_BLOCK*1024,write_addr);
write_addr+=WRITE_BLOCK*1024;
bin_size -= WRITE_BLOCK*1024;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
}
}else{
Read_ESPFlash(0x45,write_addr,&load_buff[0],bin_size);
flash_binary(&load_buff[0],bin_size,write_addr);
write_addr += bin_size;
bin_size = 0;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
break;
}
}
#else
f = fopen("/spiffs/target_esp32s3.bin", "rb");
if (f == NULL) {
ESP_LOGE(FILE_TAG, "Failed to open file for writing");
return;
}
uint32_t bin_size = off_line_tool.directory[0].size;
uint32_t write_addr = 0;
size_t bytesRead;
while (bin_size)
{
if(bin_size > WRITE_BLOCK*1024)
{
bytesRead = fread(&load_buff[0],1,WRITE_BLOCK*1024,f);
if(bytesRead == WRITE_BLOCK*1024)
// if(Read_ESPFlash(0x45,write_addr,&load_buff[0],WRITE_BLOCK*1024) == WRITE_BLOCK*1024)
{
flash_binary(&load_buff[0],WRITE_BLOCK*1024,write_addr);
write_addr+=WRITE_BLOCK*1024;
bin_size -= WRITE_BLOCK*1024;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
}
}else{
// Read_ESPFlash(0x45,write_addr,&load_buff[0],bin_size);
fread(&load_buff[0],1,bin_size,f);
flash_binary(&load_buff[0],bin_size,write_addr);
write_addr += bin_size;
bin_size = 0;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
break;
}
}
fclose(f);
#endif
ESP_LOGI(TAG, "Loading bin success");
ESP_LOGI(TAG, "Done!");
esp_loader_reset_target();
// Delay for skipping the boot message of the targets
vTaskDelay(500 / portTICK_PERIOD_MS);
// Forward slave's serial output
ESP_LOGI(TAG, "********************************************");
ESP_LOGI(TAG, "*** Logs below are print from slave .... ***");
ESP_LOGI(TAG, "********************************************");
}
}else{
ESP_LOGE(TAG, "connect_to_target initialization failed.");
}
free(load_buff);
loader_port_esp32_deinit();
vTaskDelete(NULL);
#endif
}

View File

@ -40,6 +40,7 @@
#include "public.h"
#include "esp_flash.h"
#define WRITE_BLOCK 64
static const char *TAG = "main";
@ -82,7 +83,7 @@ void app_main(void)
ESP_LOGI(TAG, "Found file: %s, size: %ld bytes", off_line_tool.directory[0].name, off_line_tool.directory[0].size);
ESP_LOGI(TAG, "Found file: %s, size: %ld bytes", off_line_tool.directory[1].name, off_line_tool.directory[1].size);
ESPFlash_Init();
stream_init(&uart_interface_data,1024*50);
stream_init(&uart_interface_data,1024*100);
ESP_LOGI(TAG, "mem free:%ld",esp_get_free_heap_size());
gpio_config_t config = {
@ -93,18 +94,8 @@ void app_main(void)
gpio_config(&config);
gpio_set_level(8,0);
// gpio_set_level(18,1);
// gpio_config_t input_config = {
// .mode = GPIO_MODE_INPUT,
// .pin_bit_mask = 1ULL << 9 | 1ULL << 2,
// .pull_up_en = 1
// };
// gpio_config(&input_config);
usb_serial2Uart(NULL);
xTaskCreate(&Read_CMD_task, "Read_CMD_task", 1024*20, NULL, 14, NULL);
xTaskCreate(&Flasher_tool_task, "Flasher_tool_task", 1024*20, NULL, 10, NULL);
#if 0
home_html.html_data = load_html2Ram(home_html);
wifi_config_html.html_data = load_html2Ram(wifi_config_html);
@ -124,6 +115,19 @@ void app_main(void)
}
#endif
// FILE* f = fopen("/spiffs/hello.txt", "w");
// if (f == NULL) {
// printf("Failed to open file for writing\n");
// return;
// }
// fprintf(f, "Hello World!\n");
// fclose(f);
// f = fopen("/spiffs/hello.txt", "r");
// char line[64];
// fgets(line, sizeof(line), f);
// fclose(f);
// printf("Read from file: '%s'\n", line);
esp_flash_t *chip = esp_flash_default_chip;
esp_err_t ret = esp_flash_read_id(chip, &off_line_tool.flash_id);
@ -154,16 +158,82 @@ void app_main(void)
// start_web_server();
// xTaskCreate(tcp_server_task, "tcp_server", 4096, (void*)AF_INET, 5, NULL);
ESP_LOGI(TAG, "mem free:%ld",esp_get_free_heap_size());
// Document_feeder_test();
#if 0
while (1)
{
// if(gpio_get_level(GPIO_NUM_9) == 0 || gpio_get_level(GPIO_NUM_2) == 0)
// {
// ESP_LOGI(TAG,"BOOT Down");
// }
// ESP_LOGI(TAG, "mem free:%ld",esp_get_free_heap_size());
vTaskDelay(1000/ portTICK_PERIOD_MS);
uint8_t* load_buff = NULL;
const loader_esp32_config_t esp32c3_config = {
.baud_rate = 1152000,
.uart_port = UART_NUM_0,
.uart_rx_pin = GPIO_NUM_20,
.uart_tx_pin = GPIO_NUM_21,
.reset_trigger_pin = GPIO_NUM_9,
.gpio0_trigger_pin = GPIO_NUM_2,
};
if (loader_port_esp32_init(&esp32c3_config) != ESP_LOADER_SUCCESS) {
ESP_LOGE(TAG, "serial initialization failed.");
return;
}
if (connect_to_target(1152000) == ESP_LOADER_SUCCESS) {
ESP_LOGI(TAG, "connect_to_target initialization success.");
if(esp_get_free_heap_size() >200*1024)
{
load_buff = malloc(WRITE_BLOCK*1024+24);
if(load_buff == NULL)
{
return;
}
}
if(esp_loader_get_target() == ESP32S3_CHIP)
{
ESP_LOGI(TAG,"Find ESP32S3");
ESP_LOGI(TAG, "Loading bin...");
// flash_binary()
uint32_t bin_size = 749504;
uint32_t write_addr = 0;
while (bin_size)
{
if(bin_size > WRITE_BLOCK*1024)
{
if(Read_ESPFlash(0x45,write_addr,&load_buff[0],WRITE_BLOCK*1024) == WRITE_BLOCK*1024)
{
flash_binary(&load_buff[0],WRITE_BLOCK*1024,write_addr);
write_addr+=WRITE_BLOCK*1024;
bin_size -= WRITE_BLOCK*1024;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
}
}else{
Read_ESPFlash(0x45,write_addr,&load_buff[0],bin_size);
flash_binary(&load_buff[0],bin_size,write_addr);
write_addr += bin_size;
bin_size = 0;
ESP_LOGI(TAG,"Load : %ld --- %ld",write_addr,bin_size);
break;
}
}
ESP_LOGI(TAG, "Loading bin success");
ESP_LOGI(TAG, "Done!");
esp_loader_reset_target();
// Delay for skipping the boot message of the targets
vTaskDelay(500 / portTICK_PERIOD_MS);
// Forward slave's serial output
ESP_LOGI(TAG, "********************************************");
ESP_LOGI(TAG, "*** Logs below are print from slave .... ***");
ESP_LOGI(TAG, "********************************************");
}
}else{
ESP_LOGE(TAG, "connect_to_target initialization failed.");
}
loader_port_esp32_deinit();
#endif
}

View File

@ -53,6 +53,4 @@ extern stream_data_t uart_interface_data;
extern void usb_serial2Uart(void *pvParameters);
extern void Read_CMD_task(void *pvParameter);
extern void Flasher_tool_task(void *pvParameter);
#endif

View File

@ -4,7 +4,7 @@
#define EX_UART_NUM UART_NUM_1
#define PATTERN_CHR_NUM (3) /*!< Set the number of consecutive and identical characters received by receiver which defines a UART pattern*/
#define BUF_SIZE (4096)
#define BUF_SIZE (1024)
#define ECHO_TASK_STACK_SIZE (4096)
#define RD_BUF_SIZE (BUF_SIZE)
@ -32,33 +32,29 @@ static void echo_task(void *arg)
while (1) {
int len = usb_serial_jtag_read_bytes(data, (BUF_SIZE - 1), 200 / portTICK_PERIOD_MS);
int len = usb_serial_jtag_read_bytes(data, (BUF_SIZE - 1), 2000 / portTICK_PERIOD_MS);
// Write data back to the USB SERIAL JTAG
if (len) {
if(frameStreamRecEmptyLen(&uart_interface_data) < 1024*4)
// usb_serial_jtag_write_bytes((const char *) data, len, 20 / portTICK_PERIOD_MS);
if(frameStreamRecEmptyLen(&uart_interface_data) < 1024*30)
{
// ESP_LOGE(TAG,"frameStream Be almost full:%d",len);
frameStreamWrite(&uart_interface_data,&data[0],len);
ESP_LOGE(TAG,"frameStream Be almost full:%d",len);
while (1)
{
vTaskDelay(10/ portTICK_PERIOD_MS);
len = usb_serial_jtag_read_bytes(data, 0, 200 / portTICK_PERIOD_MS);//刷新流控
if(frameStreamRecEmptyLen(&uart_interface_data) > 1024*6)
if(frameStreamRecEmptyLen(&uart_interface_data) > 1024*32)
{
// ESP_LOGE(TAG,"frameStream: %ld",frameStreamRecEmptyLen(&uart_interface_data));
ESP_LOGE(TAG,"frameStream: %ld",frameStreamRecEmptyLen(&uart_interface_data));
break;
}
}
}else{
frameStreamWrite(&uart_interface_data,&data[0],len);
}
}
frameStreamWrite(&uart_interface_data,&data[0],len);
// uart_write_bytes(EX_UART_NUM, (const char *) data, len);
// data[len] = '\0';
// ESP_LOG_BUFFER_HEXDUMP("Recv str: ", data, 8, ESP_LOG_INFO);
}else{
// ESP_LOG_BUFFER_HEXDUMP("Recv str: ", data, len, ESP_LOG_INFO);
}
}
}
@ -157,11 +153,9 @@ static void uart_event_task(void *pvParameters)
stream_data_t usb_interface_data;
void usb_serial2Uart(void *pvParameters)
{
// stream_init(&usb_interface_data,1024*20);
stream_init(&usb_interface_data,1024*20);
/* Configure parameters of an UART driver,
* communication pins and install the driver */
#if 0
uart_config_t uart_config = {
.baud_rate = 115200,
.data_bits = UART_DATA_8_BITS,
@ -174,9 +168,8 @@ void usb_serial2Uart(void *pvParameters)
//Install UART driver, and get the queue.
uart_driver_install(UART_NUM_1, BUF_SIZE * 2, BUF_SIZE * 2, 20, &uart0_queue, 0);
uart_param_config(UART_NUM_1, &uart_config);
xTaskCreate(echo_task, "USB SERIAL JTAG_echo_task", ECHO_TASK_STACK_SIZE, NULL, 20, NULL);
//Create a task to handler UART event from ISR
xTaskCreate(uart_event_task, "uart_event_task", 2048*10, NULL, 12, NULL);
#endif
xTaskCreate(echo_task, "USB SERIAL JTAG_echo_task", ECHO_TASK_STACK_SIZE, NULL, 20, NULL);
}