//-----------------------------------------------------------------------------
///
/// \brief  Si705x temperature sensor
///
///         I2C connected
///
///   https://www.silabs.com/documents/public/data-sheets/Si7050-1-3-4-5-A20-1.pdf
///   https://www.silabs.com/documents/public/application-notes/AN607.pdf
///
///   The I2C address is 0x40:7Bit. There are no address pins that change the
///   address.
///   Devices with address 0x70:7Bit can be ordered. They will have an part
///   numbers with "-A21".
///
/// \date   20210210
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


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


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


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

//#define LEPTO_LOG_DEBUG
//#undef LEPTO_LOG_DEBUG

#include <biwak/si705x.hpp>
#include <lepto/log.h>
#include <arpa/inet.h>


//---Documentation-------------------------------------------------------------


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


CSi705x::CSi705x(CI2c &i2c, int addr)
   :CI2cSlave(i2c, addr)
{
   probe();
}


bool CSi705x::probe()
{
   // Serial number is 8 Bytes with CRC for each byte.
   // SNB3 is the devices ID;
   // 50 = 0x32 = Si7050   ...   55 = 0x37 = Si7055
   uint8_t first;
   int sta;
   setAddressWidth(EAddressSize::_16Bits);
   sta=i2cReadData( REG_ID2, &first, 1);
   if(sta!=0)
   {
      lCaution(LDS("DSBL Dev s=%d", "Disabling device. sta=%d"), sta);
   }
   else
   {
      if( ( first >= 0x32 ) && ( first <= 0x37 ) )
      {
         #if IS_ENABLED( CONFIG_BIWAK_I2C_NODE_ABSENT )
            setPresent(true);
         #endif
      }
      else
      {
         lCaution(LDS("DSBL Dev id=%d", "Disabling device. id=0x%x"), first);
      }
   }

   setAddressWidth(EAddressSize::_8Bits);
   return( false );
}

uint16_t CSi705x::readRaw()
{
   uint32_t raw=0;

   //int sta=
   i2cReadData( REG_MEASURE_HOLD, &raw, 3);
   // MSB - LSB - CRC - --(0x00)
   raw=ntohl(raw);
   raw>>=16;
   lDebug("Raw: 0x%X", raw);

   return( (uint16_t)raw );
}

#if defined ( SI705X_FLOAT )

float CSi705x::convertTemperature(uint32_t raw) const
{
   return (  ( ( 175.72 * raw ) / 65536.0 ) - 46.85 );
}

float CSi705x::getTemperature()
{
   return( convertTemperature( readRaw() ) );
}

#else

int CSi705x::convertTemperature(uint32_t raw) const
{
   return ( (  ( ( 17572 * raw ) / 65536 ) - 4685 ) / 1 );
}

int CSi705x::getTemperature()
{
   return( convertTemperature( readRaw() ) );
}

#endif

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