I am using BOOST for asynchronous communication with a serial port. I can't pinpoint the cause of the error I am facing and would appreciate some guidance.
std::string myclass::readStringUntil(const std::string& delim)
{
setupParameters=ReadSetupParameters(delim);
performReadSetup(setupParameters);
if(timeout!=posix_time::seconds(0)) timer.expires_from_now(timeout);
else timer.expires_from_now(posix_time::hours(100000));
timer.async_wait(boost::bind(&myclass::timeoutExpired,this,
asio::placeholders::error));
result=resultInProgress;
bytesTransferred=0;
for(;;)
{
io.run_one();
switch(result)
{
case resultSuccess:
{
timer.cancel();
bytesTransferred-=delim.size();//Don't count delim
istream is(&readData);
string result(bytesTransferred,'\0');//Alloc string
is.read(&result[0],bytesTransferred);//Fill values
is.ignore(delim.size());//Remove delimiter from stream
return result;
}
case resultTimeoutExpired:
port.cancel();
throw(timeout_exception("Timeout expired"));
cout<<"timeout on readuntill"<<endl;
case resultError:
timer.cancel();
port.cancel();
throw(boost::system::system_error(boost::system::error_code(),
"Error while reading"));
}
}
/////////////////////////////////////////////////////////////////////////////
void myclass::performReadSetup(const ReadSetupParameters& param)
{
if(param.fixedSize)
{
asio::async_read(port,asio::buffer(param.data,param.size),boost::bind(
&myclass::readCompleted,this,asio::placeholders::error,
asio::placeholders::bytes_transferred));
} else {
asio::async_read_until(port,readData,param.delim,boost::bind(
&myclass::readCompleted,this,asio::placeholders::error,
asio::placeholders::bytes_transferred));
}
}
/////////////////////////////////////////////////////////////////////////////
void myclass::timeoutExpired(const boost::system::error_code& error)
{
if(!error && result==resultInProgress) result=resultTimeoutExpired;
}
/////////////////////////////////////////////////////////////////////////////
void myclass::readCompleted(const boost::system::error_code& error,
const size_t bytesTransferred)
{
if(!error)
{
result=resultSuccess;
this->bytesTransferred=bytesTransferred;
return;
}
#ifdef _WIN32
if(error.value()==995) return; //Windows spits out error 995
#elif defined(__APPLE__)
if(error.value()==45)
{
//Bug on OS X, it might be necessary to repeat the setup
//http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
performReadSetup(setupParameters);
return;
}
#else //Linux
if(error.value()==125) return; //Linux outputs error 125
#endif
result=resultError;
}
Without io.run_one(), I go into an infinite loop and not entering the switch case.
How could I fixed my code so that it gets out of the indefinite block? I can't confirm, but I think the run_one() is causing an error#125