I'm trying to process a stream of binary data which as it happens is coming in through a serial port. The data takes the form of several types of packets and I want a simple extendable framework for processing and adding more packet types.
For a oversimplified example I made, here is a sample solution...
#include <fstream>
#include <iostream>
using namespace::std;
//packet format 0x33, 0x44, [Packtype] , [data], [data], [data]
//bit of dummy data on front and back
unsigned char data[] = { 0x11, 0x23, 0x34, 0x33, 0x44, 0x01, 0x00, 0x00, 0x00, 0x00, 0x32, 0x45, 0x33, 0x44, 0x02, 0x12, 0x54, 0xA1, 0xBC, 0x11 };
class Pack1
{
public:
char data[3];
};
class Pack2
{
public:
char data[5];
};
void WriteData()
{
ofstream ofs("test.dat", ios::binary);
ofs.write((char *)&data, sizeof(data));
}
int main()
{
char c;
int header = 0;
// WriteData();
ifstream ifs("test.dat", ios::binary);
while(ifs.get(c)) {
if (( header == 0) && (c == 0x33) ) {//got first part of pack header
char d = ifs.peek();
if (d == 0x44) {
ifs.get(); // Get and discard 2ns header byte
header = 1;
//find out which packet
c = ifs.peek();
if ( c == 0x01 ) {
cout << "Got a Pack1" << endl;
Pack1 p1;
ifs.read((char *)&p1, sizeof(p1));
header = 0;
} else if ( c == 0x02) {
cout << "Got a Pack2" << endl;
Pack2 p2;
ifs.read((char *)&p2, sizeof(p2));
header = 0;
}
}
}
}
return 0;
}
Gives....
Got a Pack1
Got a pack2
To me this seems like a very ugly way of doing this. Surely there is some nice encapsulated way of defining packets and checking which we've got. I'm looking for advice on a better mouse trap to do this. Does anyone have some snippets of code, that could help out? How are fundamental systems doing this i.e. processing the TCPIP messages, surely this is refined to nice solution.