我正在使用 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既不提供非阻塞同步读取,也不提供超时读取。因此,替代选择是使用异步读取。 Boost.Asio提供this例子。虽然该示例是针对 TCP 的,但它应该举例说明带超时的异步读取的总体概念和方法。
此外,根据发布的逻辑,数据被读取直到回车或 NULL,可能值得考虑使用 line-based operation ,如boost::asio::async_read_until
.
关于c++ - boost asio - 检查是否有任何内容可以从串行端口读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14518353/