【问题标题】:boost asio - check whether there is anything to read from a serial portboost asio - 检查是否有任何东西可以从串口读取
【发布时间】:2013-01-09 05:06:48
【问题描述】:

我正在使用 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 == '\0')
    {
        break;
    }
    res.push_back(rcvd);
}
return res;

感谢您的努力。

【问题讨论】:

  • 为什么不使用 boost::asio::async_read_* 的异步读取?
  • 感谢您的回复。我不知道实际上会有什么不同。你能解释一下区别吗?
  • 它不能告诉你,端口中有数据......但它不会阻止执行(直到你调用 ios.run())并且你可以设置超时(如果超时发生 - 那里是端口中没有数据)...我认为在asio中,没有可以说你的功能,该端口有任何要发送的数据。
  • 其实我也没找到什么超时方法。您能否指出如何使用超时?

标签: c++ boost serial-port boost-asio


【解决方案1】:

对于串口,Boost.Asio 既不提供非阻塞同步读取也不提供超时读取。因此,另一种选择是使用异步读取。 Boost.Asio 提供了this 的例子。虽然该示例是针对 TCP 的,但它应该举例说明具有超时的异步读取的总体概念和方法。

此外,根据发布的逻辑,在回车或 NULL 之前读取数据时,可能值得考虑使用 line-based operation,例如 boost::asio::async_read_until

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    相关资源
    最近更新 更多