[ create a new paste ] login | about

Link: http://codepad.org/XnLwybDl    [ raw code | fork ]

C++, pasted on Jun 10:
#include <iostream>

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/function.hpp>
#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>

void cancel_reading(boost::asio::serial_port* port, bool* timeout, boost::system::error_code e)
{
    std::cout << "cancel_reading: port(" << port << ") timeout(" << timeout << ") error_code(" << std::dec << e << ")" << std::endl;
    if(e != boost::asio::error::operation_aborted)
    {
        port->cancel();
        *timeout = true;
    }
}

void read_finished(boost::asio::deadline_timer* timer, boost::system::error_code e, std::size_t bytes_transferred)
{
    std::cout << "read_finished: timer(" << timer << ") error_code(" << e << ") bytes_transferred(" << bytes_transferred << ")" << std::endl;
    timer->cancel();
    if(e && e != boost::asio::error::operation_aborted)
        throw boost::system::system_error(e);
}

void timed_read(boost::asio::serial_port& port, std::vector<char>& buf, unsigned ms)
{
    bool timeout = false;
    boost::asio::deadline_timer timer(port.io_service());

    std::cout << "timed_read: port(" << &port << ") timer(" << &timer << ") timeout(" << &timeout << ")" << std::endl;

    timer.expires_from_now(boost::posix_time::milliseconds(ms));
    timer.async_wait(boost::bind(cancel_reading, &port, &timeout, _1));

    boost::asio::async_read(port, boost::asio::buffer(buf), boost::bind(read_finished, &timer, _1, _2));
 
    port.io_service().reset();
    port.io_service().run();

    std::cout << "read " << (timeout ? "with" : "without") << " timeout" << std::endl;
}

int main()
{
    std::string com = "COM4";

    boost::asio::io_service io;
    boost::asio::serial_port serial(io);

    boost::system::error_code ec;
    if(serial.open(com, ec))
    {
        std::cout << "cannot open " << com << std::endl;
        return EXIT_FAILURE;
    }

    typedef boost::asio::serial_port options;

    serial.set_option(options::baud_rate(115200));
    serial.set_option(options::flow_control(options::flow_control::none));
    serial.set_option(options::parity(options::parity::none));
    serial.set_option(options::stop_bits(options::stop_bits::one));
    serial.set_option(options::character_size(CHAR_BIT));

    serial.write_some(boost::asio::buffer("zzzzzz"));

    std::vector<char> buf(100);
    timed_read(serial, buf, 3000);
    serial.close();

    return EXIT_SUCCESS;
}


Create a new paste based on this one


Comments: