//-----------------------------------------------------------------------------
///
/// \brief  BU21026MUV Rohm touch controller
///
///         I2C connected
///
/// \date   20200229
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


//---Includes------------------------------------------------------------------


//---General--------------------------

//#include <string.h>     // strlen

//---Own------------------------------

#include <biwak/bu21026muv.h>
#include <lepto/log.h>

//---Defines-------------------------------------------------------------------



CBu21026muv::CBu21026muv(CI2c &i2c, EGpioPeripheral periphery, EGpioPin pin)
   :CI2cSlave(i2c, addr)
   ,m_interrupt(periphery, pin)
   //,m_i2c(i2c)
{
   int data;
   i2cWriteData(OperationO2::softwareReset , &data, 0);
   i2cWriteData(OperationO0::setPower | Operand0::defaultValue, &data, 0);
   i2cWriteData(OperationO1::setup | Operand1::mafEnabled, &data, 0 );
   i2cWriteData(OperationO0::driveX | Operand0::defaultValue, &data, 0 );
   i2cWriteData(OperationO0::driveY | Operand0::defaultValue, &data, 0 );
   i2cWriteData(OperationO0::driveZ | Operand0::defaultValue, &data, 0 );

   m_interrupt.interruptSignal.connect(this, &CBu21026muv::interrupt);
}

void CBu21026muv::calibrate(int xOffset, int xVpp, int xSize,
                            int yOffset, int yVpp, int ySize )
{
   m_xOffset=xOffset;
   m_xVpp=xVpp;
   m_xSize=xSize;

   m_yOffset=yOffset;
   m_yVpp=yVpp;
   m_ySize=ySize;
}

bool CBu21026muv::readCoordinates(int &x, int &y, bool raw)
{
   int sta;

   if( m_interrupt.getValue() )
   {
      return(false);
   }

   uint16_t xraw=0;
   uint16_t yraw=0;

   sta = i2cReadData(OperationO0::measureX | Operand0::defaultValue, &xraw, 2);
   sta = i2cReadData(OperationO0::measureY | Operand0::defaultValue, &yraw, 2);

   if (sta)
   {
      return(false);
   }

   // resolution12Bit is zero, so invert logic
   if( ! ( Operand0::defaultValue & Operand0::resolution12Bit ) )
   {
      // When doin this in 8Bit resolution, the range would be the same like
      // 12Bit resolution . But in 8Bit resolution the lower nibble is zero.
      // Does not help at all
      xraw=( __builtin_bswap16(xraw) >> 4 );
      yraw=( __builtin_bswap16(yraw) >> 4 );
   }

   if(raw)
   {
      x=xraw;
      y=yraw;
   }
   else
   {
      x=m_xSize - ( ( ( xraw * 0x100 )-m_xOffset) / m_xVpp );
      y=m_ySize - ( ( ( yraw * 0x100 )-m_yOffset) / m_yVpp );
   }

   return(true);
}

void CBu21026muv::interrupt(bool)
{
   lHint << "Pressed!";
}

#if 0
int CBu21026muv::transformX(int xraw)
{
   return( m_xSize - ( (xraw-m_xOffset) / m_xVpp ) );
}


int CBu21026muv::transformY(int yraw)
{
   return( m_ySize - ( (yraw-m_yOffset) / m_yVpp ) );
}
#endif


//---fin-----------------------------------------------------------------------
