将 VMIN 和 VTIME 与 Windows 一起使用

Using VMIN and VTIME with Windows

我正在改编我为跨平台兼容性而编写的简单 Linux 串行库。大多数东西都保留了下来(尽管微软坚持要重命名所有东西),但有一些我没能找到的功能。

我目前的问题是 VMIN 和 VTIME 的使用(在 struct termios 中)。在 Linux 上,我使用它们强制读取一定数量的字符而阻塞,但如果未收到它们则会超时并出现错误。但是,Windows 建议使用 BuildCommDCB function be used instead of directly setting parameters for its DCB(设备控制块)结构。该函数不支持任何类似 VMIN 或 VTIME 的东西,而且 DCB 结构本身也好不了多少。

有没有办法在 Windows 中获得此功能而无需自己实现?如果完全可以避免的话,我宁愿不为我的库中的一个平台管理串行中断和回调。

编辑:SetCommTimeouts 函数似乎模仿了 VTIME 的功能,但我仍然没有找到 VMIN 的任何内容。

您可以尝试查看 source code for cygwin。我认为他们在使 windows 串行 i/o 基于 Unix API.

正常运行方面做得很好

我无法完美模拟 VMIN=0 和 VTIME=0 的情况,但我能够准确地重新创建其他所有内容。

在class的构造函数中,初始化并应用DCB后(timeoutCOMMTIMEOUTSreadTimeoutreadMinCharsunsigned chars):

//Set read timeouts
if(readTimeout > 0) {
    if(readMinChars > 0) {  //Intercharacter timeout
        timeout.ReadIntervalTimeout = readTimeout * 100;    //Deciseconds to milliseconds
    } else {                //Total timeout
        timeout.ReadTotalTimeoutConstant = readTimeout * 100;   //Deciseconds to milliseconds
    }
} else {
    if(readMinChars > 0) {  //Counted read
        //Handled by length parameter of serialRead(); timeouts remain 0 (unused)
    } else {                //"Nonblocking" read
        timeout.ReadTotalTimeoutConstant = 1;   //Wait as little as possible for a blocking read (1 millisecond)
    }
}
if(!SetCommTimeouts(handle, &timeout)) {
    printf("Error setting serial port timeout: %lu\n", GetLastError());
    throw std::runtime_error("serial initialization failed");
}

完整的系列 class 可在 Github 上获得,作为更大项目的一部分:serial.h serial.cpp