From c6d63f7e1526569c80be1fef147c0215fe02e419 Mon Sep 17 00:00:00 2001 From: =?utf8?q?=E5=AD=99=E6=98=A5=E9=98=B3?= Date: Sat, 20 Sep 2025 21:35:41 +0800 Subject: [PATCH] =?utf8?q?=E4=BF=AE=E6=94=B9uapi=5Fuart=5Fread=EF=BC=8C?= =?utf8?q?=E5=87=BA=E7=8E=B0empty=E7=9A=84=E6=97=B6=E5=80=99=E5=A6=82?= =?utf8?q?=E6=9E=9C=E8=B6=85=E6=97=B6=E5=B0=B1=E9=80=80=E5=87=BA=E3=80=82?= =?utf8?q?=E5=A6=82=E6=9E=9C=E4=B8=80=E7=9B=B4=E6=9C=89=E6=95=B0=E6=8D=AE?= =?utf8?q?=EF=BC=8C=E5=8F=AF=E4=BB=A5=E4=B8=80=E7=9B=B4=E8=AF=BB=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- code/sdk/drivers/drivers/driver/uart/uart.c | 42 ++++++++------------- 1 file changed, 15 insertions(+), 27 deletions(-) diff --git a/code/sdk/drivers/drivers/driver/uart/uart.c b/code/sdk/drivers/drivers/driver/uart/uart.c index 214942b1d..185443628 100644 --- a/code/sdk/drivers/drivers/driver/uart/uart.c +++ b/code/sdk/drivers/drivers/driver/uart/uart.c @@ -686,11 +686,6 @@ int32_t uapi_uart_read_by_dma(uart_bus_t bus, const void *buffer, uint32_t lengt #endif /* CONFIG_UART_SUPPORT_TX */ #if defined(CONFIG_UART_SUPPORT_RX) -/* - * timeout的作用:如果在超时时间内一直没有数据到达,则退出; - * 如果有数据到达,则应持续读取,直到没有数据可读(即RX FIFO空), - * 此时才正常返回,不能因为超时而中断正在进行的数据读取。 - */ int32_t uapi_uart_read(uart_bus_t bus, const uint8_t *buffer, uint32_t length, uint32_t timeout) { #ifdef SUPPORT_GNSS @@ -714,10 +709,11 @@ int32_t uapi_uart_read(uart_bus_t bus, const uint8_t *buffer, uint32_t length, u return -1; } - uint32_t time_waited = 0; - bool got_data = false; - - while (len > 0) { + /* Poll until we read the requested length or timeout expires. + If timeout == 0, behave non-blocking and return immediately if no data. */ + uint32_t timeout_tick = osal_get_jiffies() + timeout; + for (;;) { + /* Try to read one byte if available */ uint32_t irq_sts = uart_porting_lock(bus); hal_funcs->ctrl(bus, UART_CTRL_CHECK_RX_FIFO_EMPTY, (uintptr_t)&rx_fifo_empty); if (!rx_fifo_empty) { @@ -725,32 +721,24 @@ int32_t uapi_uart_read(uart_bus_t bus, const uint8_t *buffer, uint32_t length, u data_buffer++; len--; read_count++; - got_data = true; - time_waited = 0; // reset wait time after receiving data } uart_porting_unlock(bus, irq_sts); if (len == 0) { - break; // 已读满length字节 + break; /* finished reading requested bytes */ } if (rx_fifo_empty) { - if (!got_data) { - // 尚未收到任何数据,等待timeout - if (timeout == 0) { - break; // 非阻塞模式 - } - if (time_waited >= timeout) { - break; // 超时未收到任何数据 - } - osal_msleep(1); - if (timeout != 0xFFFFFFFF) { - time_waited++; - } - } else { - // 已经收到过数据,只要RX FIFO空就返回 - break; + /* No data available now */ + if (timeout == 0) { + break; /* non-blocking: return whatever we got */ + } + uint32_t now_tick = osal_get_jiffies(); + if (timeout != 0xFFFFFFFF && now_tick >= timeout_tick) { + break; /* timed out */ } + /* Sleep briefly and try again */ + osal_msleep(1); } } -- 2.17.1