title: Binary communications protocol parser design for serial data
body: <p>I'm revisiting a communications protocol parser design for a stream of bytes (serial data, received 1 byte at a time).</p>
  
  <p>The packet structure (can't be changed) is:</p>
  
  <pre><code>|| Start Delimiter (1 byte) | Message ID (1 byte) | Length (1 byte) | Payload (n bytes) | Checksum (1 byte) ||
  </code></pre>
  
  <p>In the past I have implemented such systems in a procedural state-machine approach.  As each byte of data arrives, the state machine is driven to see where/if the incoming data fits into a valid packet a byte at a time, and once a whole packet has been assembled, a switch statement based on the Message ID executes the appropriate handler for the message.  In some implementations, the parser/state machine/message handler loop sits in its own thread so as not to burden the serial data received event handler, and is triggered by a semaphore indicating bytes have been read.</p>
  
  <p>I'm wondering if there is a more elegant solution to this common problem, exploiting some of the more modern language features of C# and OO design.  Any design patterns that would solve this problem?  Event-driven vs polled vs combination?</p>
  
  <p>I'm interested to hear your ideas.  Thanks.</p>
  
  <p>Prembo. </p>