This commit is contained in:
2026-03-28 05:03:21 +08:00
parent 99226caf2f
commit 96aaeb0460

View File

@@ -177,6 +177,8 @@ bool Serial::ReadData(unsigned char *buffer, unsigned int length) {
#elif defined(Linux) || defined(Darwin) #elif defined(Linux) || defined(Darwin)
#include <string.h> #include <string.h>
#include <thread>
#include <chrono>
using namespace std; using namespace std;
@@ -189,17 +191,10 @@ string get_uart_dev_name() {
Serial::Serial(int nSpeed, char nEvent, int nBits, int nStop) : Serial::Serial(int nSpeed, char nEvent, int nBits, int nStop) :
nSpeed(nSpeed), nEvent(nEvent), nBits(nBits), nStop(nStop) { nSpeed(nSpeed), nEvent(nEvent), nBits(nBits), nStop(nStop) {
if (wait_uart) { LOGM("Waiting for serial port...");
LOGM("Wait for serial be ready!"); while (!InitPort(nSpeed, nEvent, nBits, nStop))
while (!InitPort(nSpeed, nEvent, nBits, nStop)); std::this_thread::sleep_for(std::chrono::milliseconds(500));
LOGM("Port set successfully!"); LOGM("Port set successfully!");
} else {
if (InitPort(nSpeed, nEvent, nBits, nStop)) {
LOGM("Port set successfully!");
} else {
LOGE("Port set fail!");
}
}
} }
Serial::~Serial() { 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) { bool Serial::WriteData(const unsigned char *pData, unsigned int length) {
int cnt = 0, curr = 0; int cnt = 0, curr = 0;
if (fd <= 0){ if (fd <= 0) {
if(wait_uart){ LOGE("Serial offline! Reconnecting...");
InitPort(nSpeed, nEvent, nBits, nStop); while (!InitPort(nSpeed, nEvent, nBits, nStop))
} std::this_thread::sleep_for(std::chrono::milliseconds(500));
return false; return false;
} }
while ((curr = write(fd, pData + cnt, length - cnt)) > 0 && (cnt += curr) < length); while ((curr = write(fd, pData + cnt, length - cnt)) > 0 && (cnt += curr) < length);
if (curr < 0) { if (curr < 0) {
LOGE("Serial offline!"); LOGE("Serial write error! Reconnecting...");
close(fd); close(fd);
if (wait_uart) { fd = -1;
InitPort(nSpeed, nEvent, nBits, nStop); while (!InitPort(nSpeed, nEvent, nBits, nStop))
} std::this_thread::sleep_for(std::chrono::milliseconds(500));
return false; return false;
} }
return true; return true;
@@ -249,11 +244,11 @@ bool Serial::ReadData(unsigned char *buffer, unsigned int length) {
int cnt = 0, curr = 0; int cnt = 0, curr = 0;
while ((curr = read(fd, buffer + cnt, length - cnt)) > 0 && (cnt += curr) < length); while ((curr = read(fd, buffer + cnt, length - cnt)) > 0 && (cnt += curr) < length);
if (curr < 0) { if (curr < 0) {
LOGE("Serial offline!"); LOGE("Serial read error! Reconnecting...");
close(fd); close(fd);
if (wait_uart) { fd = -1;
InitPort(nSpeed, nEvent, nBits, nStop); while (!InitPort(nSpeed, nEvent, nBits, nStop))
} std::this_thread::sleep_for(std::chrono::milliseconds(500));
return false; return false;
} }
return true; return true;