MIRA
Communication and Networking

Contents

The communication module provides wrappers and additional functionality to the boost::asio library.

IOService - a wrapper for boost::asio::io_service

For asynchronous I/O operations, boost asio provides the io_service class. Therefore, the run() or one of the run_one(), poll() or poll_one() functions must be called. The run() function will block the calling thread until all async I/O operations are finished. More than one thread can call the run() method to join the list of worker threads used to process the io operations. For that purpose, the IOService class provides functionality to start and stop multiple threads on an io_service class. The object can be casted to an io_service object for compatibility reasons to the boost::asio functions.

IOService io;
// start running 3 threads on the wrapped io_service object and continue
io.runThreads(3, false);

SerialPort - a wrapper for boost::asio::serial_port

The mira::SerialPort class enables the use of non-standard baud rates such as 345600.

For reading data from a serial port, the mira::Buffer class can be used as a data container. The communication module also provides a function for reading data from serial port using a timeout. This boost::asio::read_some() method is located in the boost::asio namespace for compatibility.

IOService io;
SerialPort port(io, "/dev/ttyUSB0", 500000);
Buffer<uint8> packet;
// reserve some bytes
packet.reserve(4000);
// read data with timeout of 5 seconds and add it to the buffer's end
std::size_t bytesReceived = boost::asio::read_some(port, boost::asio::buffer(packet.data()+packet.sizeInBytes(),
packet.capacity()-packet.size()), Duration::seconds(5));
// resize the packet to its right size
packet.resize(packet.size()+bytesReceived);
// find 0x00 0x00 0x00 sequence in the packet
while((packet.size() > 2) &&
(packet[0]!=0x00 || packet[1]!=0x00 || packet[2]!=0x00))
{
std::size_t i;
// search for 0x00
for(i = 1; (i < packet.size()) && (packet[i] != 0x00); i++);
// drop all bytes before first 0x00
packet.pop_front(i);
}