我正在尝试使用超时实现同步写入。我使用截止时间计时器和async_write
代码:
size_t SerialBus::timeout_write(std::vector<byte>& buf)
{
isWriteTimeOut_=false;
bytes_writen_=0;
// After a timeout & cancel it seems we need
// to do a reset for subsequent reads to work.
port_.get_io_service().reset();
// Asynchronously read 1 character.
boost::asio::async_write(port_, boost::asio::buffer(buf),
boost::bind(&PLT::SerialBus::write_complete,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
// Setup a deadline time to implement our timeout.
timerWrite_.expires_from_now(boost::posix_time::milliseconds(timeout_));
timerWrite_.async_wait(boost::bind(&PLT::SerialBus::timeOutWriteHandler,
this, boost::asio::placeholders::error));
port_.get_io_service().run();
return bytes_writen_;
}
void SerialBus::timeOutWriteHandler(const boost::system::error_code& error)
{
// Was the timeout was cancelled?
if (error) {
// yes
isWriteTimeOut_=false;
return;
}
// no, we have timed out, so kill
// the read operation
// The read callback will be called
// with an error
isWriteTimeOut_=true;
port_.cancel();
}
void SerialBus::write_complete(const boost::system::error_code& error,
size_t bytes_transferred)
{
bytes_writen_=bytes_transferred;
errorCode_=error;
timerWrite_.cancel();
}
我有相同的阅读功能
当我使用具有足够长缓冲区的timeout_write并且计时器到期时。当这发生async_write处理程序write_complete得到995错误,bytes_transfered为0,buf变为空(实际上它是同一个类的成员,它的生命周期足够长)但数据被转移。当我调用timeout_read时,我从我的设备(FTDI)获得正确的答案。当缓冲区长度减少并且写入完成时,在计时器之前调用一切都是正常的(缓冲区已经完全放入了我放入的内容)。 。当我使用同步版本写入时,它会阻止COM,直到我用usb cable replug重新启动它。
在这种情况下,我不知道如何确定真正发送到设备的内容或更正取消传输。或者我需要使用本机函数而不是boost?
我使用boost 1.58 Win7 x64和ftdi 2.12.00和vs2010