Note that there are some explanatory texts on larger screens.

plurals
  1. POReading messages from a serial port with Boost Asio
    text
    copied!<p>I would like to use <a href="http://en.wikipedia.org/wiki/Asio_C++_library" rel="nofollow">Boost Asio</a> to read variable length messages from the serial port. I would like to read and wait long enough to be sure that the line is idle, but I do not want to block completely.</p> <p>The following code is what I have so far, and I am in the process of testing it:</p> <pre><code>long readData(void *_pData, unsigned long _uSize, size_t millis) { size_t n = 0; // n will return the message size. if (millis &gt; 0) // millis is the acceptable idle time, 0 is invalid in my case. { size_t uBytesTransferred = 0; boost::asio::deadline_timer timeout(m_ioService); ReadCallback readCallback(uBytesTransferred, timeout); WaitCallback waitCallback(m_port); while (_uSize - (unsigned long)n &gt; 0) { // Setup asynchronous read with timeout m_ioService.reset(); m_port.async_read_some(boost::asio::buffer((char*)_pData + n, _uSize - (unsigned long)n), readCallback); timeout.expires_from_now(boost::posix_time::milliseconds(millis)); timeout.async_wait(waitCallback); // Block until asynchronous callbacks are finished m_ioService.run(); // Continue if any bytes were received, stop otherwise if (uBytesTransferred &gt; 0) { n += uBytesTransferred; m_uBytesReceived += uBytesTransferred; } else { break; } } } return n; } </code></pre> <p>I would like to know if this is the correct way of doing this (that is, reading until the line is idle) with Boost Asio?</p> <p>Here are my callback handlers:</p> <pre><code>struct ReadCallback { ReadCallback(std::size_t &amp;_uBytesTransferred, boost::asio::deadline_timer &amp;_timeout) :m_uBytesTransferred(_uBytesTransferred), m_timeout(_timeout) {} void operator()(const boost::system::error_code &amp;_error, std::size_t _uBytesTransferred) { m_uBytesTransferred = _uBytesTransferred; if (!_error &amp;&amp; (_uBytesTransferred &gt; 0) ) { m_timeout.cancel(); } } std::size_t &amp;m_uBytesTransferred; boost::asio::deadline_timer &amp;m_timeout; private: ReadCallback(); ReadCallback &amp;operator=(const ReadCallback&amp;); }; struct WaitCallback { WaitCallback(boost::asio::serial_port &amp;_port) :m_port(_port) {} void operator()(const boost::system::error_code &amp;_error) { if (!_error) { m_port.cancel(); } } boost::asio::serial_port &amp;m_port; private: WaitCallback(); WaitCallback &amp;operator=(const WaitCallback&amp;); }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload