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

#ifndef SERIAL_PORT_H
#define SERIAL_PORT_H

#include "bytestream.h"

class SerialPort : public ByteStream
{
public:
 /**
  * read 1 byte from stream
  * @param byte Buffer to store byte
  * @return Number of bytes read. This is 1 of no error occures.
  */
  virtual int readByte(unsigned char * byte)  = 0;
  
 /**
  * write 1 byte to stream
  * @param byte The byte to write
  * @return Number of bytes written. This is 1 of no error occures.
  */  
  virtual int writeByte(unsigned char byte) = 0;  
  
 /**
  * Set the timeout in msec for the read operation. The read
  * operation will return with an error if no bytes received 
  * during this time.
  * @param msec The timeout in milliseconds
  * @return 0 if no error
  */  
  virtual int setTimeout(unsigned int msec) = 0;
  
  
 /**
  * Perform close operation on serial port
  */
  virtual ~SerialPort() {}
     
 /**
  * This method writes an array of bytes to the serial port.
  * You should override this method if the serial port supports
  * this natively to increase performance
  * @param TxBuff Pointer to the buffer that contains the data to be written to the device.
  * @param TxBytes Number of bytes to write to the device
  * @return Number of bytes written to the device
  */
  virtual int writeData(unsigned char TxBuff[], unsigned int TxBytes){
    int written = 0;
    for(unsigned int i=0; i<TxBytes; i++){
      written += writeByte(TxBuff[i]);
    }
    return written;
  }

 /**
  * This method reads an array of bytes from the serial port.
  * You should override this method if the serial port supports
  * this natively to increase performance
  * @param RxBuff Pointer to the buffer that receives the data from the device.
  * @param RxBytes Number of bytes to be read from the device
  * @return Number of bytes read from the device
  */  
  virtual int readData(unsigned char RxBuff[], unsigned int RxBytes){
    int read = 0;
    for(unsigned int i=0; i<RxBytes; i++){
      read += readByte(&RxBuff[i]);
    }
    return read;
  }  
  
  virtual void operator<<(unsigned char byte){
    writeByte(byte);
  }
  virtual void operator>>(unsigned char &byte){
    readByte(&byte);
  }  
};
#endif
