Search code examples
c++winapieventsserial-portuart

Windows WaitCommEvent to wait for n characters


I'm trying to set up a uart/serial port in windows. The device I am interfacing to will send me 10 characters and then I need to parse and respond with 30 characters. I need to try and respond in under 2 millseconds.

I plan to use the CreateFile in a synchronous fashion.

I plan to use the following calls

 SetCommMask (hPort, EV_RXCHAR | EV_ERR); //receive character event
 WaitCommEvent (hPort, &dwCommModemStatus, 0); //wait for character 
  1. Is there a way to set WaitCommEvent to wait for n characters?
  2. Also, do I need to call SetCommMask before every time I call WaitCommEvent? If so, what is the characters come in before I make the call to SetCommMask?
  3. One possible solution I'm floating is a combination of event driven with polling until I get the number of characters I need. Is this a good compromise?

Solution

  • The answer is to not use SetCommMask and WaitCommEvent.

    I can use SetCommTimeouts, request 10 bytes and set ReadTotalTimeoutConstant to x milliseconds so the call doesn't block forever.

    https://learn.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