修改uapi_uart_read,出现empty的时候如果超时就退出。如果一直有数据,可以一直读。
author孙春阳 <snickersun@163.com>
Sat, 20 Sep 2025 13:35:41 +0000 (21:35 +0800)
committer孙春阳 <snickersun@163.com>
Sat, 20 Sep 2025 13:35:41 +0000 (21:35 +0800)
code/sdk/drivers/drivers/driver/uart/uart.c

index 214942b..1854436 100644 (file)
@@ -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);
         }
     }