1、设置超时时间,超时重传;
2、重传超过3次返回失败,否则返回成功;
3、设置需要读取的数据长度,如果此长度参数没传,则表示读取超时时间内读取到的所有数据;
3、发完清空接收缓冲区;tcflush(m_fd, TCIFLUSH);
4、使用标准485modbus通信协议:地址码+功能码+数据长度+数据+校验码;
5、通信速率选择:115200(485通信不易受干扰)
6、在收发接口处添加智能锁,避免多线程调用时出现通信错乱问题,一个智能锁管一个总线资源;
#include <iostream>
#include <string>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/select.h>
#include <mutex>
// 定义错误码宏
#define ERROR_WRITE_TIMEOUT -100
#define ERROR_READ_TIMEOUT -101
#define ERROR_WRITE_FAILED -102
#define ERROR_READ_FAILED -103
#define ERROR_LENGTH_MISMATCH -104
class SerialPort {
public:
SerialPort(const std::string& portName, int baudRate) : portName(portName), baudRate(baudRate) {
openPort();
configurePort();
}
~SerialPort() {
close(fd);
}
// 封装的读写函数
ssize_t readAndWrite(const std::string& dataToWrite, std::string& readBuffer, int timeout_ms, ssize_t expectedLength = -1) {
std::lock_guard<std::mutex> guard(mutex_);
// 清空输入和输出缓冲区
tcflush(fd, TCIOFLUSH);
// 写操作
fd_set writefds;
FD_ZERO(&writefds);
FD_SET(fd, &writefds);
struct timeval timeout;
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
int ret = select(fd + 1, nullptr, &writefds, nullptr, &timeout);
if (ret == -1) {
return ERROR_WRITE_FAILED;
} else if (ret == 0) {
return ERROR_WRITE_TIMEOUT;
} else {
if (FD_ISSET(fd, &writefds)) {
::write(fd, dataToWrite.data(), dataToWrite.length());
}
}
// 读操作
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
ret = select(fd + 1, &readfds, nullptr, nullptr, &timeout);
if (ret == -1) {
return ERROR_READ_FAILED;
} else if (ret == 0) {
return ERROR_READ_TIMEOUT;
} else {
if (FD_ISSET(fd, &readfds)) {
char tempBuffer[BUFFER_SIZE];
ssize_t totalBytesRead = 0;
while (true) {
ssize_t bytesRead = ::read(fd, tempBuffer + totalBytesRead, BUFFER_SIZE - totalBytesRead);
if (bytesRead <= 0) {
break;
}
totalBytesRead += bytesRead;
if (expectedLength!= -1 && totalBytesRead >= expectedLength) {
break;
}
}
readBuffer.assign(tempBuffer, totalBytesRead);
if (expectedLength!= -1 && totalBytesRead == expectedLength) {
return expectedLength;
} else {
return totalBytesRead;
}
}
}
return ERROR_READ_FAILED;
}
private:
std::string portName;
int baudRate;
int fd;
const int BUFFER_SIZE = 256;
std::mutex mutex_;
void openPort() {
fd = ::open(portName.c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
std::cerr << "Error opening serial port: " << portName << std::endl;
exit(EXIT_FAILURE);
}
fcntl(fd, F_SETFL, 0);
}
void configurePort() {
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, baudRate);
cfsetospeed(&options, baudRate);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
}
};
int main() {
std::string portName = "/dev/ttyS0";
int baudRate = B9600;
SerialPort serialPort(portName, baudRate);
std::string readBuffer;
std::string dataToWrite = "Hello from C++ via serial port!";
ssize_t result;
int timeout_ms = 5000;
ssize_t expectedLength = 100;
// 指定长度读取,最多尝试三次
int attempts = 0;
std::string failureReason;
while (attempts < 3) {
result = serialPort.readAndWrite(dataToWrite, readBuffer, timeout_ms, expectedLength);
if (result >= 0) {
if (result == expectedLength) {
std::cout << "Received expected length of data." << std::endl;
break;
} else {
failureReason = "Did not receive expected length. Received " + std::to_string(result) + " bytes.";
}
} else {
switch (result) {
case ERROR_WRITE_TIMEOUT:
failureReason = "Write timeout.";
break;
case ERROR_READ_TIMEOUT:
failureReason = "Read timeout.";
break;
case ERROR_WRITE_FAILED:
failureReason = "Write failed.";
break;
case ERROR_READ_FAILED:
failureReason = "Read failed.";
break;
case ERROR_LENGTH_MISMATCH:
failureReason = "Length mismatch.";
break;
default:
failureReason = "Unknown error.";
}
}
attempts++;
}
if (attempts == 3) {
std::cerr << "Failed to read with specified length after three attempts. Reason: " << failureReason << std::endl;
}
// 不指定长度读取,最多尝试三次
attempts = 0;
failureReason = "";
while (attempts < 3) {
result = serialPort.readAndWrite(dataToWrite, readBuffer, timeout_ms);
if (result >= 0) {
std::cout << "Received: " << readBuffer << std::endl;
break;
} else {
switch (result) {
case ERROR_WRITE_TIMEOUT:
failureReason = "Write timeout.";
break;
case ERROR_READ_TIMEOUT:
failureReason = "Read timeout.";
break;
case ERROR_WRITE_FAILED:
failureReason = "Write failed.";
break;
case ERROR_READ_FAILED:
failureReason = "Read failed.";
break;
default:
failureReason = "Unknown error.";
}
}
attempts++;
}
if (attempts == 3) {
std::cerr << "Failed to read without specified length after three attempts. Reason: " << failureReason << std::endl;
}
return 0;
}