//------------------------------------------------------------------
// qfixI2CMaster.h
//
// This is a convenience class for writing I2C master classes
// (like SlaveBoard).
// This class supports the qfix I2C protocol.
//
// Copyright 2005 by KTB mechatronics GmbH
// Author: Stefan Enderle
//------------------------------------------------------------------


#ifndef qfixI2CMaster_h
#define qfixI2CMaster_h

#include "qfixI2C.h"
#include "qfixI2CDefs.h"

const uint8_t CMD_PARAMS   = 255;  // the same for all boards


//---------------------------------------------------------------

class I2CMaster
{
  I2C i2c;

  uint8_t brdID;  // board ID (what board)
  uint8_t logID;  // logical ID (which one of these boards)

public:
  /** boardID denotes the board (BobbyBoard, LCD, ...) that 
  *   shall be used. The logical ID is set to 0.
  */
  I2CMaster(uint8_t boardID);

  /** boardID denotes the board (BobbyBoard, LCD, ...) that 
  *   shall be used. logicalID is the sub-ID (e.g. which LCD).
  */
  I2CMaster(uint8_t boardID, uint8_t logicalID);

  void command(uint8_t cmd);
  void command(uint8_t cmd, uint8_t param);
  void command(uint8_t cmd, uint8_t param, uint8_t param2);
  void command(uint8_t cmd, uint8_t param, uint8_t param2, uint8_t param3);
  uint8_t request(uint8_t cmd, uint8_t param);
};


I2CMaster::I2CMaster(uint8_t boardID)
: i2c(), brdID(boardID), logID(0)
{
}


I2CMaster::I2CMaster(uint8_t boardID, uint8_t logicalID)
: i2c(), brdID(boardID), logID(logicalID)
{
}



void I2CMaster::command(uint8_t cmd)
{
  uint8_t buf[2];

  buf[0] = logID;
  buf[1] = cmd;
  i2c.send(brdID, buf, 2);
}

void I2CMaster::command(uint8_t cmd, uint8_t param)
{
  uint8_t buf[3];

  buf[0] = logID;
  buf[1] = cmd;
  buf[2] = param;
  i2c.send(brdID, buf, 3);
}

void I2CMaster::command(uint8_t cmd, uint8_t param, uint8_t param2)
{
  uint8_t buf[4];

  buf[0] = logID;
  buf[1] = cmd;
  buf[2] = param;
  buf[3] = param2;
  i2c.send(brdID, buf, 4);
}

void I2CMaster::command(uint8_t cmd, uint8_t param, uint8_t param2, uint8_t param3)
{
  uint8_t buf[5];

  buf[0] = logID;
  buf[1] = cmd;
  buf[2] = param;
  buf[3] = param2;
  buf[4] = param3;
  i2c.send(brdID, buf, 5);
}


uint8_t I2CMaster::request(uint8_t cmd, uint8_t param)
{
  // send command and params first //
  command(CMD_PARAMS, cmd, param);

  // get return value //
  uint8_t buf[10];
  i2c.get(brdID, buf, 1);
  return(buf[0]);
}


#endif

