boost - 串口通信 超时处理


另外一个方法是使用前面说过的异步读写+超时的方式,代码如下:


#include 
#include 
#include 

using namespace std;
using namespace boost::asio;
void handle_read(char *buf,boost::system::error_code ec,
 std::size_t bytes_transferred)
{
         cout.write(buf, bytes_transferred);
}

int main(int argc, char* argv[])
{
         io_service iosev;
         serial_port sp(iosev,  "COM1");
         sp.set_option(serial_port::baud_rate(19200));
         sp.set_option(serial_port::flow_control());
         sp.set_option(serial_port::parity());
         sp.set_option(serial_port::stop_bits());
         sp.set_option(serial_port::character_size(8));

         write(sp, buffer("Hello world", 12));

         // 异步读
         char buf[100];
         async_read(sp, buffer(buf), boost::bind(handle_read, buf, _1, _2));
         // 100ms后超时
         deadline_timer timer(iosev);
         timer.expires_from_now(boost::posix_time::millisec(100));
         // 超时后调用sp的cancel()方法放弃读取更多字符
         timer.async_wait(boost::bind(&serial_port::cancel, boost::ref(sp)));

         iosev.run();
         return 0;
} 


//


    boost::asio::async_read(m_port, boost::asio::buffer(m_cData), boost::bind(&SerialPort::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
        boost::asio::deadline_timer timer(m_ios);
        timer.expires_from_now(boost::posix_time::millisec(1000*20));
        timer.async_wait(boost::bind(&boost::asio::serial_port::cancel, boost::ref(m_port))); //超时后调用cancel()方法放弃读取更多字符

//

boost::asio::async_read() cannot be used with null_buffers()

An attempt to use async_read() with null_buffers() causes the handler to be invoked even when the underlying file descriptor is not yet available for reading.




你可能感兴趣的:(C/C++,串口通信)