From 96aaeb0460246e4ee589a6deb54f991489aa994f Mon Sep 17 00:00:00 2001 From: lyf <169361657@qq.com> Date: Sat, 28 Mar 2026 05:03:21 +0800 Subject: [PATCH] =?UTF-8?q?=C2=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- others/src/serial.cpp | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/others/src/serial.cpp b/others/src/serial.cpp index d2b599f..7eb360a 100644 --- a/others/src/serial.cpp +++ b/others/src/serial.cpp @@ -177,6 +177,8 @@ bool Serial::ReadData(unsigned char *buffer, unsigned int length) { #elif defined(Linux) || defined(Darwin) #include +#include +#include using namespace std; @@ -189,17 +191,10 @@ string get_uart_dev_name() { Serial::Serial(int nSpeed, char nEvent, int nBits, int nStop) : nSpeed(nSpeed), nEvent(nEvent), nBits(nBits), nStop(nStop) { - if (wait_uart) { - LOGM("Wait for serial be ready!"); - while (!InitPort(nSpeed, nEvent, nBits, nStop)); - LOGM("Port set successfully!"); - } else { - if (InitPort(nSpeed, nEvent, nBits, nStop)) { - LOGM("Port set successfully!"); - } else { - LOGE("Port set fail!"); - } - } + LOGM("Waiting for serial port..."); + while (!InitPort(nSpeed, nEvent, nBits, nStop)) + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + LOGM("Port set successfully!"); } Serial::~Serial() { @@ -227,19 +222,19 @@ bool Serial::InitPort(int nSpeed, char nEvent, int nBits, int nStop) { bool Serial::WriteData(const unsigned char *pData, unsigned int length) { int cnt = 0, curr = 0; - if (fd <= 0){ - if(wait_uart){ - InitPort(nSpeed, nEvent, nBits, nStop); - } + if (fd <= 0) { + LOGE("Serial offline! Reconnecting..."); + while (!InitPort(nSpeed, nEvent, nBits, nStop)) + std::this_thread::sleep_for(std::chrono::milliseconds(500)); return false; } while ((curr = write(fd, pData + cnt, length - cnt)) > 0 && (cnt += curr) < length); if (curr < 0) { - LOGE("Serial offline!"); + LOGE("Serial write error! Reconnecting..."); close(fd); - if (wait_uart) { - InitPort(nSpeed, nEvent, nBits, nStop); - } + fd = -1; + while (!InitPort(nSpeed, nEvent, nBits, nStop)) + std::this_thread::sleep_for(std::chrono::milliseconds(500)); return false; } return true; @@ -249,11 +244,11 @@ bool Serial::ReadData(unsigned char *buffer, unsigned int length) { int cnt = 0, curr = 0; while ((curr = read(fd, buffer + cnt, length - cnt)) > 0 && (cnt += curr) < length); if (curr < 0) { - LOGE("Serial offline!"); + LOGE("Serial read error! Reconnecting..."); close(fd); - if (wait_uart) { - InitPort(nSpeed, nEvent, nBits, nStop); - } + fd = -1; + while (!InitPort(nSpeed, nEvent, nBits, nStop)) + std::this_thread::sleep_for(std::chrono::milliseconds(500)); return false; } return true;