/*
 *  packetparser.h
 *
 * $Id: packetparser.h 2 2008-07-30 09:28:03Z mschneider $
 * $URL: svn://localhost/Bioloid/trunk/packetparser.h $
 
 * \version   $Rev: 2 $
 * \author    Markus Schneider
 * \date      17.07.08
 *
 */

#ifndef PACKETPARSER_H
#define PACKETPARSER_H

#include "bytestream.h"
#include "packet.h"

/***********************************************************************
 * PACKET_PARSER
 ***********************************************************************/

/*
 * this class could parse packets from a given
 * bytestream.
 */

class PacketParser
{
public:

  // constructor
  // @param stream - the bytestream to read from
  PacketParser(ByteStream *stream);
  
  // try to parse a packet from bytestream
  // @param pkt - memory for the packet
  // @return -1 on timeout
  //          0 no error
  int parse(Packet *pkt);
  
  // try to parse a packet from bytestream
  // @return NULL on timeout
  Packet *parse();
  
  // reset the parser. all already parsed bytes will be ignored
  void reset();
  
  // get the timeout
  unsigned int getTimeout();
  
  // set the timeout
  void setTimeout(unsigned int millisec);
  
private:
  static const int MAX_PACKELEN = 255;
  
  enum statetype{
    STATE_IDLE, 
    STATE_1ST_FF_RCVD,
    STATE_2ND_FF_RCVD,   
    STATE_ID_RCVD,
    STATE_LENGTH_RCVD,
    STATE_COMMAND_RCVD,
    STATE_PARAM_RCVD,
    STATE_PKT_COMPLETE
  };
  
  // process the next byte to the statemachine
  void nextByte(unsigned char);
  
  ByteStream *stream;
  Packet *pkt;
  statetype state;
  unsigned int timeout;  
};


#endif
