Files
TS660_DLL/SerialPort.h
T

75 lines
1.8 KiB
C++

// SerialPort.h: 串口通信封装类(异步 Overlapped I/O)
#pragma once
#include <windows.h>
// 导出宏定义
#ifdef TS660_DLL_EXPORTS
#define TS660_DLL_API __declspec(dllexport)
#else
#define TS660_DLL_API __declspec(dllimport)
#endif
// 停止位
enum class StopBits : int {
One = 0, // 1
OnePointFive = 1, // 1.5
Two = 2 // 2
};
// 校验位
enum class Parity : int {
None = 0,
Odd = 1,
Even = 2,
Mark = 3,
Space = 4
};
class TS660_DLL_API SerialPort {
public:
SerialPort();
~SerialPort();
SerialPort(const SerialPort&) = delete;
SerialPort& operator=(const SerialPort&) = delete;
// 打开串口
// comPort: 如 L"COM1"
// 返回 true 成功
bool Open(const wchar_t* comPort,
int baudRate = 9600,
int dataBits = 8,
StopBits stopBits = StopBits::One,
Parity parity = Parity::None);
// 关闭串口
void Close();
// 是否已打开
bool IsOpen() const { return m_hCom != INVALID_HANDLE_VALUE; }
// 直接设置 COMMTIMEOUTS
bool SetTimeouts(const COMMTIMEOUTS& timeouts);
// 简化版: 设置读/写总超时(毫秒)
bool SetTimeout(int readTimeoutMs, int writeTimeoutMs);
// 异步读: 返回读取字节数; 失败/出错返回 -1; 超时返回已读字节数(可能为0)
int Read(unsigned char* buf, int size, int timeoutMs);
// 异步写: 返回写入字节数; 失败返回 -1
int Write(const unsigned char* buf, int size, int timeoutMs);
// 获取底层句柄
HANDLE GetHandle() const { return m_hCom; }
private:
HANDLE m_hCom;
OVERLAPPED m_readOl; // 读 overlapped
OVERLAPPED m_writeOl; // 写 overlapped
bool CreateOverlappedEvents();
void DestroyOverlappedEvents();
};