title: Best practice to implement fixed byte serial protocol in C++?
body: <p>I have a device connected via serial interface to a BeagleBone computer. I communicates in a simple binary format like</p>
  
  <pre><code>|MessagID (1 Byte) | Data (n Bytes) | checksum (2 bytes) |
  </code></pre>
  
  <p>The message length is fixed for each command, meaning that it is known how many bytes to read after the First byte of a command was received. After some initial setup communication it sends packets of data every 20 ms.</p>
  
  <p>My approach would be to use either termios or something like serial lib and then start a loop doing like that (a:</p>
  
  <pre><code>while(keepRunning)
  {
      char* buffer[256];
      serial.read(buffer, 1)
      switch(buffer[0])
          {
          case COMMAND1:
              serial.read(&amp;buffer[1], sizeof(MessageHello)+2); //Read data + checksum
              if (calculateChecksum(buffer, sizeof(MessageHello)+3) )
              {
                  extractDatafromCommand(buffer);
              }
              else
              {
                  doSomeErrorHandling(buffer[0]);
              }
              break;
          case COMMAND2:
              serial.read(&amp;buffer[1], sizeof(MessageFoo)+2);
              [...]
      }
  }
  </code></pre>
  
  <p>extractDatafromCommand would then create some structs like:</p>
  
  <pre><code>struct MessageHello
  {
      char name[20];
      int version;
  }
  </code></pre>
  
  <p>Put everything in an own read thread and signal the availability of a new packet to other parts of the program using a semaphore (or a simple flag). </p>
  
  <p>Is this a viable solution or are there better improvements to do (I assume so)?</p>
  
  <p>Maybe make a abstract class Message and derive the other messages?</p>