Using Bost asio to read from serial port?

May 10, 2010 at 10:14pm
Hi, we are programming a robot in a project at the university, and I thought you might be able to answer a question about boost asio's read function.

We are going to communicate from a laptop with the robot, over bluetooth, via a firefly connected to the computers serial port. So long, I think I have managed the outgoing data correctly, using boost::asio::write. However, now I think I need some help with the incoming data (the boost asio documentation is, well ... limited).

All messages starts with a header at one byte. The header specifies which message type has been sent. Each message has a unique length which I store in an array called message_lengths.

I had imagined the code to loke something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void user_interface::check_for_incoming_messages()
{
    boost::asio::streambuf response;
    boost::system::error_code error;
    std::string s1, s2;
    if (boost::asio::read(port, response, boost::asio::transfer_at_least(0), error)) {
        convert_streambuf_to_string(response, s1);
        int msg_code = s1[0];
        if (msg_code < 0 || msg_code >= NUM_MESSAGES) {
            // Handle error, invalid message header
        }
        if (boost::asio::read(port, response, boost::asio::transfer_at_least(message_lengths[msg_code]-s1.length()), error)) {
            response >> s2;
            // Handle the content of s1 and s2
        }
        else if (error != boost::asio::error::eof) {
            throw boost::system::system_error(error);
        }
    }
    else if (error != boost::asio::error::eof) {
        throw boost::system::system_error(error);
    }
}


Right now the code will just ignore a second message, if there will happen to be one. And I don't know what convert_streambuf_to_string will look like. Now I have just assumed that response will be reset each time read is called, but maybe that's wrong.

Can someone who knows how to do this please help me? I would be really grateful.

P.S. I hope I will get an email notification now (I didn't see anywhere to choose it), otherwise I will probably not remember to look at the answers!
Topic archived. No new replies allowed.