加速 ASIO - 检查是否有任何内容可以从串行端口读取

boost asio - check whether there is anything to read from a serial port

本文关键字:串行端口 读取 任何内 ASIO 检查 是否 加速      更新时间:2023-10-16

我正在使用boost::asio库来控制具有串行连接的电机。问题是,如果设备不发送任何内容供我读取,boost::asio::serial_port::read() 函数会让程序冻结。

如何检查设备是否有通过端口告诉我的内容?

如果我向设备发送命令,我可以毫无问题地得到答案。但是有没有办法知道它是否在没有我发送命令的情况下发送了任何东西?或者这在串行连接中没有任何意义,其中命令仅作为对已发送命令的响应接收?

请检查我的代码

try
{
    port = new boost::asio::serial_port(io_serial, comPort.c_str());
}
char rcvd;
std::string res;
while(1)
{
    boost::asio::read(*port,boost::asio::buffer(&rcvd, 1)); //here it freezes till something is read
    std::cout<<rcvd<<std::endl; //I know it froze in the last line because nothing was written from here
    if(rcvd == 'r' || rcvd == '')
    {
        break;
    }
    res.push_back(rcvd);
}
return res;

感谢您的任何努力。

对于串行端口,Boost.Asio 既不提供非阻塞同步读取,也不提供超时读取。 因此,替代选项是使用异步读取。 Boost.Asio提供了这个例子。 虽然该示例适用于 TCP,但它应举例说明超时异步读取的整体概念和方法。

此外,根据已发布的逻辑(其中读取数据直到回车或 NULL),可能值得考虑使用基于行的操作,例如 boost::asio::async_read_until