Windows WaitCommEvent 等待 n 个字符

Windows WaitCommEvent to wait for n characters

我正在尝试在 windows 中设置一个 uart/serial 端口。我正在连接的设备将向我发送 10 个字符,然后我需要解析并响应 30 个字符。我需要尝试在 2 毫秒内做出响应。

我打算以同步方式使用 CreateFile。

我打算使用以下调用

 SetCommMask (hPort, EV_RXCHAR | EV_ERR); //receive character event
 WaitCommEvent (hPort, &dwCommModemStatus, 0); //wait for character 
  1. 有没有办法设置 WaitCommEvent 等待 n 个字符?
  2. 还有,每次调用WaitCommEvent之前需要先调用SetCommMask吗?如果是这样,在我调用 SetCommMask 之前输入的字符是什么?
  3. 我正在浮动的一个可能的解决方案是将事件驱动与轮询相结合,直到我获得所需的字符数。这是一个好的折衷方案吗?

答案是不使用SetCommMask和WaitCommEvent。

我可以使用 SetCommTimeouts,请求 10 个字节并将 ReadTotalTimeoutConstant 设置为 x 毫秒,这样调用就不会永远阻塞。

https://docs.microsoft.com/en-us/windows/desktop/api/winbase/ns-winbase-_commtimeouts

if (!::GetCommTimeouts(m_hCommPort, &timeouts))
    std::cout << "error" << std::endl;

timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 5000;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;

if (!::SetCommTimeouts(m_hCommPort, &timeouts))
    std::cout << "error" << std::endl;

BYTE Byte;
DWORD dwBytesTransferred;
DWORD dwCommModemStatus;

ReadFile(m_hCommPort, &Byte, 1, &dwBytesTransferred, 0); //read 1