3

我正在尝试从串行端口异步读取几个字节。目前我正在使用的代码(来源是How do I perform a nonblocking read using asio?),只允许我读取 1 个字节然后退出。如何获取它以使代码继续读取,直到串行端口中没有更多传入数据?谢谢 :)

    void foo()
{
    boost::asio::io_service io_svc;
    boost::asio::serial_port ser_port(io_svc, "/dev/ttyS0");
    boost::asio::deadline_timer timeout(io_svc);
    unsigned char my_buffer[2];
    bool data_available = false;

    ser_port.async_read_some(boost::asio::buffer(my_buffer),
            boost::bind(&read_callback, boost::ref(data_available),
                    boost::ref(timeout),boost::asio::placeholders::error(),
                    boost::asio::placeholders::bytes_transferred()));
    timeout.expires_from_now(boost::posix_time::seconds(30));
    timeout.async_wait(boost::bind(&wait_callback, boost::ref(ser_port),boost::asio::placeholders::error()));

    io_svc.run();

    io_svc.

    if(!data_available)
    {
        ser_port.close();
        cout << "ser_port was closed";
    }

}

void read_callback(bool& data_available, boost::asio::deadline_timer& timeout, const boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (error || !bytes_transferred)
    {
        // No data was read!
        data_available = false;
        return;
    }

    timeout.cancel();
    data_available = true;
}

void wait_callback(boost::asio::serial_port& ser_port, const boost::system::error_code& error)
{
    if (error)
    {
        // Data was read and this timeout was cancelled

        return;
    }

    ser_port.cancel();
}
4

1 回答 1

3

在你的read_callback你取消你的计时器,不要开始新的阅读。
那么您希望 ASIO 做什么。您刚刚取消了所有处理程序,并且像文档状态一样,run 方法将在没有处理程序时返回。

因此,如果您想获得比接收到的一个字节更多的数据,您可以做两件事:
首先只需发出另一个调用 asio 以从端口读取更多数据。

void read_callback(bool& data_available, boost::asio::deadline_timer& timeout, const  boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (error || !bytes_transferred)
    {
        // No data was read!
        data_available = false;
        return;
    }
    // do something with the data you just read
    ser_port.async_read_some(boost::asio::buffer(my_buffer),
        boost::bind(&read_callback, boost::ref(data_available),
                boost::ref(timeout),boost::asio::placeholders::error(),
                boost::asio::placeholders::bytes_transferred()));
    //restart your timer
    data_available = true;
}

或者您可以添加使用transfer_at_least以至少获得所需的数据量。

于 2013-07-09T15:25:03.927 回答