views:

43

answers:

1

Is there a way to specify a packet-based protocol in XML, so (de)serialization can happen automatically?

The context is as follows. I have a device that communicates through a serial port. It sends and receives a byte stream consisting of 'packets'. A packet is a collection of elementary data types and (sometimes) other packets. Some elements of packets are conditional; their inclusion depends on earlier elements.

I have a C# application that communicates with this device. Naturally, I don't want to work on a byte-level throughout my application; I want to separate the protocol from my application code. Therefore I need to translate the byte stream to structures (classes).

Currently I have implemented the protocol in C# by defining a class for each packet. These classes define the order and type of elements for each packet. Making class members conditional is difficult, so protocol information ends up in functions.

I imagine XML that looks like this (note that my experience designing XML is limited):

<packet>
  <field name="Author" type="int32" />
  <field name="Nickname" type="bytes" size="4">
    <condition type="range">
      <field>Author</field>
      <min>3</min>
      <max>6</min>
    </condition>
  </field>
</packet>

.NET has something called a 'binary serializer', but I don't think that's what I'm looking for.

Is there a way to separate protocol and code, even if packets 'include' other packets and have conditional elements?

A: 

Maybe a partial answer will help you understand where I'm trying to get.

If there's no "protocol library" available yet, I could implement this myself. I'd probably have to use (something like) these four steps:

  1. Design XML to store rules from which packets can be constructed.
  2. Use the 'Abstract Factory Pattern', which creates objects with a common theme.
  3. Parse a byte array into intermediate classes created at run-time.
  4. Use reflection to map these intermediate classes to classes defined at design time.

This is not a definite answer. And obviously, I don't want to reinvent the wheel; if there's a solution readily available, I'll take it.

Mathijs