2

I want to write an application that reads packets off of a serial port. I've poked around at different questions on Stack Overflow and it looks like using boost::asio is the way to go.

However, I've never really worked with serial ports or boost::asio before, and I'm looking for some high-level guidance on how to "find" a packet within a byte stream.

Each packet coming off the serial port is composed of 13 bytes. Unfortunately, the packet doesn't contain any sort of header flag, but the last byte contains a checksum of the previous 12 bytes.

I'm assuming that if I start reading off the serial port, the first byte that I get is not necessarily going to be the first byte of the packet. In fact, the first byte I read might be somewhere in the middle of a packet.

  • I'm planning to have the main thread periodically read a bunch of packets off the serial port and store them into a buffer.

  • A second thread periodically scans the buffer and looks for a valid checksum. Assuming it finds a valid checksum, it means that the checksum byte plus the 12 bytes previous form a valid packet.

Is this a valid approach?

Is there a better way to approach this problem?

Community
  • 1
  • 1
Runcible
  • 7,006
  • 12
  • 42
  • 62
  • 1
    See http://stackoverflow.com/questions/9336010/how-to-read-a-fix-sized-packet-using-boost-asio – Mihai8 Jan 26 '13 at 21:53

1 Answers1

3

Real-world serial protocols solve this by using lead-in sequences to allow synchronization -- bytes or byte sequences that unambiguously identify the boundaries. You have to read until you see one, discarding what comes before. Just looking for 12+1 with valid checksum would work, I suppose.

bmargulies
  • 97,814
  • 39
  • 186
  • 310