Discussion:
raspberry boost lib serial port read asynchronously problem
(too old to reply)
paolo miatto
2015-10-06 07:28:51 UTC
Permalink
I tried to implement the serial with the library boost. The problem is that
the first time, and only the first time, when I try to read asynchronously
the program remains blocked. I have seen several examples, but could not
find the problem. If I open the serial port, then close it and then reopen
it all goes at first time. Why?

I use boost 1.50, g++ 4.7 and this is the function code

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;}

Thanks

Paolo

Loading...