/* * UARTBase.h */ #ifndef BASE_SERIAL_H_ #define BASE_SERIAL_H_ #include "base/Interface.h" #include "type/Tint.h" #include "util/Util.h" #include #include #include #ifdef __arm__ #include #include #include #include #include #include #include #endif class UserPort { public: int PortreadAll(unsigned char* ReadBuf) { int offset = 0; int TargetSize = 256; auto start_time = std::chrono::steady_clock::now(); while (1) { int ReadByteSize = this->PortRead(ReadBuf + offset, TargetSize - offset); offset += ReadByteSize; if (offset >= 255) { break; } auto current_time = std::chrono::steady_clock::now(); if (std::chrono::duration_cast(current_time - start_time).count() >= timeoutlimit) { break; } } return offset; } int PortOpen(std::string ComPort){ #ifdef __arm__ if (ComPort == "COM1"){ handle = stt::util::Util::openComPort("/dev/ttyS1", 9600, 8, 0, 1);//RS485 }else if(ComPort == "COM2"){ // com2 485做翻转方向角处理 handle = stt::util::Util::openComPort("/dev/ttyS3", 9600, 8, 0, 1);//RS485 struct serial_rs485 rs485conf; memset(&rs485conf,0,sizeof(rs485conf)); ioctl(handle, TIOCGRS485, &rs485conf); rs485conf.padding[0] = 56; rs485conf.delay_rts_after_send = 1000; rs485conf.flags|=SER_RS485_RTS_ON_SEND; rs485conf.flags|=SER_RS485_ENABLED; ioctl(handle , TIOCSRS485, &rs485conf); tcflush(handle, TCIOFLUSH); }else if (ComPort == "COM3"){ handle = stt::util::Util::openComPort("/dev/ttyS2", 9600, 8, 0, 1);//RS485 } #else handle = stt::util::Util::openComPort(ComPort.c_str(), 9600, 8, 0, 1);//RS232 #endif return handle; } int PortWrite(const std::vector& cmd) { std::unique_lock lock(mtx); // 检查是否为空 if (cmd.empty()) { return 0; // 空向量时返回0字节写入 } // 直接传递 vector 的数据指针和大小 return stt::util::Util::uartWrite(handle, const_cast(cmd.data()), 0, cmd.size()); } int PortRead(unsigned char *buf, int len) { std::unique_lock lock(mtx); return stt::util::Util::uartRead(handle, buf, 0, len); } int64_t handle; int timeoutlimit; std::mutex mtx; }; #endif /* BASE_UARTBASE_H_ */