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

#include "serialportlogger.h"

SerialPortLogger:: SerialPortLogger(SerialPort *_stream, const char *filename, bool append)
: stream(_stream), toclose(true) , was_write(false)
{
  fp = append ? fopen(filename, "a") : fopen(filename, "w");
}

SerialPortLogger::SerialPortLogger(SerialPort *_stream, FILE *_fp)
: fp(_fp), stream(_stream), toclose(false), was_write(false)
{
}

int SerialPortLogger:: readByte(unsigned char * byte){
  if( was_write == true ){ 
    was_write = !was_write; 
    fprintf(fp, "\nread:  ");
  }
  
  int ret = stream->readByte(byte);
  ret > 0 ? fprintf(fp, "0x%x ", *byte) : fprintf(fp, "     ");
  fflush(fp);
  return ret;
}

int SerialPortLogger::writeByte(unsigned char byte){
  if( was_write == false ){ 
    was_write = !was_write; 
    fprintf(fp, "\nwrite: ");
  }  
  
  int ret = stream->writeByte(byte);
  fprintf(fp, "0x%x ", byte);
  fflush(fp);
  return ret;
}

int SerialPortLogger::writeData(unsigned char TxBuff[], unsigned int TxBytes){
  if( was_write == false ){ 
    was_write = !was_write; 
    fprintf(fp, "\nwrite: ");
  }  
  
  for(int i=0; i<TxBytes; i++){
    fprintf(fp, "0x%x ", TxBuff[i]);
  }
  
  fflush(fp);  
  return stream->writeData(TxBuff,TxBytes);
}

int SerialPortLogger::readData(unsigned char RxBuff[], unsigned int RxBytes){
  if( was_write == true ){ 
    was_write = !was_write; 
    fprintf(fp, "\nread:  ");
  }
  
  int ret = stream->readData(RxBuff,RxBytes);
  if( ret < 1 ){
     fprintf(fp, "     ");
     fflush(fp);
     return ret;
  }
  
  for(int i=0; i<RxBytes; i++){
    fprintf(fp, "0x%x ", RxBuff[i]);
  }  
  
  fflush(fp);
  return ret; 
}

int SerialPortLogger::setTimeout(unsigned int msec){
  return stream->setTimeout(msec);
}

SerialPortLogger::~SerialPortLogger(){
  if( toclose == true ){
    fclose(fp);
  }
}

