#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
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) {
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);
}
}