如何使用COMMTIMEOUTS等待字节可用,但读取多个字节? [英] How do I use COMMTIMEOUTS to wait until bytes are available but read more than one byte?

查看:158
本文介绍了如何使用COMMTIMEOUTS等待字节可用,但读取多个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++串行端口类,具有无阻塞和阻塞模式的读操作。对于阻止模式:

I have a C++ serial port class that has a none blocking and a blocking mode for read operations. For blocking mode:

COMMTIMEOUTS cto;
GetCommTimeouts(m_hFile,&cto);
// Set the new timeouts
cto.ReadIntervalTimeout = 0;
cto.ReadTotalTimeoutConstant = 0;
cto.ReadTotalTimeoutMultiplier = 0;
SetCommTimeouts(m_hFile,&cto)

对于非阻塞模式:

COMMTIMEOUTS cto;
GetCommTimeouts(m_hFile,&cto);
// Set the new timeouts
cto.ReadIntervalTimeout = MAXDWORD;
cto.ReadTotalTimeoutConstant = 0;
cto.ReadTotalTimeoutMultiplier = 0;
SetCommTimeouts(m_hFile,&cto)

我想添加另一种模式,

I would like to add another mode that waits for any number of bytes and read them.

从MSDN COMMTIMEOUTS结构

如果应用程序设置 ReadIntervalTimeout < ReadTotalTimeoutMultiplier 更改为 MAXDWORD ,并将 ReadTotalTimeoutConstant 设置为大于零且小于 MAXDWORD 的值,当调用ReadFile函数时:

If an application sets ReadIntervalTimeout and ReadTotalTimeoutMultiplier to MAXDWORD and sets ReadTotalTimeoutConstant to a value greater than zero and less than MAXDWORD, one of the following occurs when the ReadFile function is called:


  • 如果输入缓冲区中有任何字节,ReadFile会立即返回缓冲区中的字节。 / li>
  • 如果输入缓冲区中没有字节,则ReadFile等待直到
    字节到达,然后立即返回。


  • ReadTotalTimeoutConstant指定的时间内,ReadFile超时。

这样看起来像这样:

COMMTIMEOUTS cto;
GetCommTimeouts(m_hFile,&cto);
// Set the new timeouts
cto.ReadIntervalTimeout = 100;
cto.ReadTotalTimeoutConstant = MAXDWORD;
cto.ReadTotalTimeoutMultiplier = MAXDWORD;
SetCommTimeouts(m_hFile,&cto)

但是这将立即返回第一个字节。这是一个问题,因为我在一个循环读取端口,并且一个字节的处理是如此之快,以致下次我读取端口,只有另一个字节可用。最终结果是,我在循环中一次读取一个字节,并使用运行该线程的内核的100%。

But this returns emidiately on the first byte. This is a problem since I am reading the port in a loop and the handling of a byte is so fast that the next time I read the port, only another byte is available. The end result is that I am reading one byte at a time in a loop and using 100% of the core running that thread.

我想使用 cto.ReadIntervalTimeout 就像在MSDN文档中,但仍然等到至少一个字节可用。有人有想法吗?

I would like to use the cto.ReadIntervalTimeout like in the MSDN documentation but still wait until at least one byte is available. Does anyone have an idea?

感谢。

推荐答案

你想要来自:

cto.ReadIntervalTimeout = 10;
cto.ReadTotalTimeoutConstant = 0;
cto.ReadTotalTimeoutMultiplier = 0;

它对第一个字节阻塞任意长度(通过将后两个字段设置为零来禁用总超时,根据文档),然后读取到缓冲区大小,只要数据流入。如果数据中有10ms的间隙,它将返回到目前为止已经收到的内容。

It blocks arbitrarily long for the first byte (total timeout is disabled by setting the latter two fields to zero, per the documentation), then reads up to the buffer size as long as data is streaming in. If there's a 10ms gap in the data, it will return with what has been received so far.

这篇关于如何使用COMMTIMEOUTS等待字节可用,但读取多个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆