1
This commit is contained in:
82
armor/include/CSerialPort/SerialPort.h
Normal file
82
armor/include/CSerialPort/SerialPort.h
Normal file
@@ -0,0 +1,82 @@
|
||||
#ifndef CSERIALPORT_SERIALPORT_H
|
||||
#define CSERIALPORT_SERIALPORT_H
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
namespace itas109 {
|
||||
|
||||
enum class Parity {
|
||||
ParityNone = 0,
|
||||
ParityOdd = 1,
|
||||
ParityEven = 2,
|
||||
};
|
||||
|
||||
enum class DataBits {
|
||||
DataBits5 = 5,
|
||||
DataBits6 = 6,
|
||||
DataBits7 = 7,
|
||||
DataBits8 = 8,
|
||||
};
|
||||
|
||||
enum class StopBits {
|
||||
StopOne = 1,
|
||||
StopOneAndHalf = 3,
|
||||
StopTwo = 2,
|
||||
};
|
||||
|
||||
enum class FlowControl {
|
||||
FlowNone = 0,
|
||||
FlowHardware = 1,
|
||||
FlowSoftware = 2,
|
||||
};
|
||||
|
||||
class CSerialPort {
|
||||
public:
|
||||
CSerialPort();
|
||||
~CSerialPort();
|
||||
|
||||
// 初始化串口参数(不打开)
|
||||
void init(const char* portName,
|
||||
int baudRate = 115200,
|
||||
Parity parity = Parity::ParityNone,
|
||||
DataBits dataBits = DataBits::DataBits8,
|
||||
StopBits stopBits = StopBits::StopOne,
|
||||
FlowControl flowControl = FlowControl::FlowNone,
|
||||
int readTimeoutMs = 1000);
|
||||
|
||||
// 打开串口,成功返回 true
|
||||
bool open();
|
||||
|
||||
// 关闭串口
|
||||
void close();
|
||||
|
||||
// 写数据,返回实际写入字节数(失败返回 -1)
|
||||
int writeData(const uint8_t* data, size_t length);
|
||||
|
||||
// 读数据,返回实际读取字节数(失败返回 -1)
|
||||
int readData(uint8_t* buffer, size_t maxLength);
|
||||
|
||||
// 返回最近一次错误码
|
||||
int getLastError() const { return m_lastError; }
|
||||
|
||||
private:
|
||||
char m_portName[256];
|
||||
int m_baudRate;
|
||||
Parity m_parity;
|
||||
DataBits m_dataBits;
|
||||
StopBits m_stopBits;
|
||||
FlowControl m_flowControl;
|
||||
int m_readTimeoutMs;
|
||||
|
||||
int m_fd; // 文件描述符
|
||||
int m_lastError;
|
||||
bool m_isOpen;
|
||||
|
||||
// termios 波特率映射
|
||||
static int toBaudRate(int baud);
|
||||
};
|
||||
|
||||
} // namespace itas109
|
||||
|
||||
#endif // CSERIALPORT_SERIALPORT_H
|
||||
Reference in New Issue
Block a user