raspberry boost lib串口异步读取

时间:2015-09-25 14:31:19

标签: c++ boost raspberry-pi

我尝试使用库boost实现串行。 问题是第一次,也是第一次,当我尝试异步读取程序时,程序仍然被阻止。我看过几个例子,但找不到问题。 如果我打开串口,然后关闭它,然后重新打开它,一切都是第一次。为什么呢?

我使用boost 1.50,g ++ 4.7,这是功能代码

class SIM900
{
    boost::asio::io_service io;
    boost::asio::serial_port port;
    boost::asio::deadline_timer timer;
    size_t read_timeout;        // Timeout lettura in ms
    bool read_error;
    void init_module();
    void read_complete(const boost::system::error_code& error, size_t bytes_transferred);
    void time_out(const boost::system::error_code& error);
public:
    SIM900(std::string port_name="/dev/ttyAMA0", unsigned int speed=115200, size_t timeout=500);
    SIM900(const SIM900& p) = delete;
    SIM900(const SIM900&& p) = delete;
    SIM900& operator=(const SIM900& p) = delete;
    SIM900& operator=(const SIM900&& p) = delete;
    //std::string read();
    bool read(std::string &cmd);
    void write(const std::string text);
    void sendcommand(std::string text);
    ~SIM900();
};

void SIM900::read_complete(const boost::system::error_code& error, size_t bytes_transferred)
{
    read_error = (error || bytes_transferred == 0);
    timer.cancel();
}

void SIM900::time_out(const boost::system::error_code& error)
{
    //o timeout
    if(error)
    {
        return;
    }
    // In caso di timeout cancello la lettura
    port.cancel();
}

bool SIM900::read(std::string &cmd)
{
    char c;
    cmd = "";

    // Reset port
    port.get_io_service().reset();

    for(;;)
        {
        timer.expires_from_now(boost::posix_time::milliseconds(read_timeout));
                timer.async_wait(boost::bind(&SIM900::time_out, this, boost::asio::placeholders::error));
        boost::asio::async_read(port, boost::asio::buffer(&c, 1), boost::bind(&SIM900::read_complete, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));


        // Leggo
        port.get_io_service().run();
        if(read_error)
        {
            cmd = "";
            return false;
        }

        switch(c)
        {
            case '\r':
            break;
            case '\n':
                return true;
            default:
                cmd+=c;
        }
    }
    return true;
}

0 个答案:

没有答案