1

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

sehe
  • 374,641
  • 47
  • 450
  • 633
Ryan Lee
  • 361
  • 1
  • 3
  • 10

2 Answers2

0

First off, error 125 is operation aborted: so that would mean (probably) a cancel() call (or the destructor of the io object causing cancellation).

That's just normal.

I've painstakenly completed your incomplete code¹ and don't readily see your problem:

Live On Coliru

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>

struct myclass {
    struct timeout_exception : std::runtime_error {
        timeout_exception(std::string const &msg) : std::runtime_error(msg) {}
    };

    enum {
        resultInProgress,
        resultTimeoutExpired,
        resultSuccess,
        resultError,
    } result = resultInProgress;

    std::string readStringUntil(std::string const &);
    struct ReadSetupParameters {
        ReadSetupParameters(std::string const &d = "") : delim{ d } {}
        std::string delim;
        bool fixedSize = false;
        char mutable data[1024];
        size_t size = sizeof(data);
    };

    void performReadSetup(const ReadSetupParameters &param);

    ReadSetupParameters setupParameters;
    boost::posix_time::time_duration timeout{ boost::posix_time::seconds(3) };
    boost::asio::io_service io;
    boost::asio::deadline_timer timer{ io };

    // more likely a serial port, but I'm not gonna bother mocking that:
    boost::asio::ip::tcp::socket port{ io };
    boost::asio::streambuf readData;
    size_t bytesTransferred;

    myclass() { port.connect({ {}, 6767 }); }

    void timeoutExpired(boost::system::error_code const &ec);
    void readCompleted(boost::system::error_code const &ec, size_t bytesTransferred);
};

std::string myclass::readStringUntil(const std::string &delim) {
    using namespace boost;

    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;
    for (;;) {
        io.run_one();
        switch (result) {
        case resultSuccess: {
            timer.cancel();
            bytesTransferred -= delim.size(); // Don't count delim
            std::istream is(&readData);
            std::string result(bytesTransferred, '\0'); // Alloc string
            is.read(&result[0], bytesTransferred);      // Fill values
            is.ignore(delim.size());                    // Remove delimiter from stream
            return result;
        } break;
        case resultTimeoutExpired:
            port.cancel();
            std::cout << "timeout on readuntill" << std::endl;
            throw(timeout_exception("Timeout expired"));
            break;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(), "Error while reading"));
        }
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters &param) {
    using namespace boost;
    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;
}

int main() {
    myclass absent;
    std::cout << "Ok: '" << absent.readStringUntil("Transferred") << "'\n";
}

Notes:

  • it looks as if you're basically trying really hard to avoid asynch calls at all. This is making things clumsy. If all you need is the timeout, see Boost::Asio synchronous client with timeout and boost::asio + std::future - Access violation after closing socket
  • you seem unaware that *read_until can read beyond the delimiter (it will read at least up to and including the first time it sees the delimiter). You should really account for it
  • You never check the return value for run_one(). If it returns 0 the loop should exit. Running it again without performing a reset() will never do anything.

¹ why?

sehe
  • 374,641
  • 47
  • 450
  • 633
  • Hey! Thanks for keeping track and helping me out! My apologies if I passed you incomplete set of code. It's a snippet from the original. I get "Error while reading" on my console. In this case, what did io.run_one() execute? How did result = resultInProgress change its value? For those who are following in the future, it's a continuation from this [question](https://stackoverflow.com/questions/44429978/how-to-use-boostasioio-servicerun-one/44430221#44430221) – Ryan Lee Jun 08 '17 at 15:06
  • Have you tried just debugging? Or adding some tracing inside the `readCompleted` or `timeoutExpired` handlers? As you can see, I'm [not getting the specific behaviour](http://coliru.stacked-crooked.com/a/04ed1dcf723ff2b5). Be sure to heed all the notes below my answer code. – sehe Jun 08 '17 at 15:06
  • I will try debugging it. Setting up SublimeGDB and the project file/settings really is very confusing, but I'll persevere. Thanks a lot for your help – Ryan Lee Jun 08 '17 at 16:18
  • Those are tools that you will cherish a lifetime. Good luck – sehe Jun 08 '17 at 16:24
  • Have the same issue (the same code for RS232 from google). For reproducing need call readStringUntil (or other reads) multiple times from one object 'myclass'. On the second call io.run_one(); will appear timeoutExpired event from deadline_timer even if on the second call timer was not added to async_wait() Don't know where is bug... – Dmitry Ivanov Jun 07 '23 at 06:57
  • @DmitryIvanov I'm happy to help. If you can post **complete** self-contained program in a new question, I'll look at it again. The problem is that in my answer I had to make up important parts of the code that probably hide the problem that you and others run into. – sehe Jun 07 '23 at 07:55
  • @DmitryIvanov Regardless of anything, here's a modernized and simplified version of the code that might help you: http://coliru.stacked-crooked.com/a/0d1ec5691cd243be – sehe Jun 07 '23 at 09:52
  • @sehe Hi. Finally, I decided to use native WIN RS232. Because after solving spurious I faced a new issue)) asio::async_read(m_port, asio::buffer(data, 1), After for example 5 timeouts wait for 5 bytes instead of 1. Looks like use m_io.run_one(); multiple times wrong idea. Solved) – Dmitry Ivanov Jun 07 '23 at 17:57
0

My workaround is:

    case resultSuccess:
        m_timer.cancel();
        m_io.reset();
        break;//go to finalize timer spirious event
        //return;
Dmitry Ivanov
  • 508
  • 7
  • 9