在Windows中使用VMIN和VTIME

Using VMIN and VTIME with Windows

本文关键字:VMIN VTIME Windows      更新时间:2023-10-16

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

我目前的问题是VMIN和VTIME(在struct termios中)的使用。在Linux上,我使用它们来强制读取特定数量的字符,但如果没有收到它们,就会超时并出现错误。但是,Windows建议使用BuildCommDCB函数,而不是直接为其DCB(设备控制块)结构设置参数。该函数不支持任何类似VMIN或VTIME的东西,DCB结构本身也没有好到哪里去。

有没有什么方法可以在不亲自实现的情况下在Windows中获得此功能?如果可以避免的话,我宁愿不为库中的一个平台管理串行中断和回调。

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

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

在类的构造函数中,初始化并应用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: %lun", GetLastError());
    throw std::runtime_error("serial initialization failed");
}

完整的串行类在Github上可用,作为一个更大项目的一部分:serial.hserial.cpp