//
#include <RtcDS3231.h>
//
//-------------------------------------
// CRtcDS3231 - Constructor
//-------------------------------------
CRtcDS3231::CRtcDS3231(TwoWire* pwire, byte i2caddress)
{
    FI2CAddress = i2caddress;
    FPWire = pwire;
}
//-------------------------------------
// CRtcDS3231 - Helper
//-------------------------------------
byte CRtcDS3231::DecBcd(byte value) 
{
  return ((value / 10 * 16) + (value % 10));
}

byte CRtcDS3231::BcdDec(byte value) 
{
  return ((value / 16 * 10) + (value % 16));
}
//-------------------------------------
// CRtcDS3231 - Read/Write
//-------------------------------------
// [year, month, day, hours, minutes, seconds, dayofweek]
void CRtcDS3231::WriteDateTime(byte year, byte month, byte day, 
                               byte hours, byte minutes, byte seconds, 
                               byte dayofweek) 
{
  FPWire->beginTransmission(I2CADDRESS_RTCDS3231);
  FPWire->write(0x00);
  FPWire->write(DecBcd(seconds));
  FPWire->write(DecBcd(minutes));
  FPWire->write(DecBcd(hours));       // 24h-mode
  FPWire->write(DecBcd(dayofweek));   // 1 = sunday, 2 = monday,  ...
  FPWire->write(DecBcd(day));
  FPWire->write(DecBcd(month));
  FPWire->write(DecBcd(year));       
  FPWire->endTransmission();
}
// [year, month, day, hours, minutes, seconds, dayofweek]
void CRtcDS3231::ReadDateTime(byte &year, byte &month, byte &day, 
                              byte &hours, byte &minutes, byte &seconds, 
                              byte &dayofweek) 
{
  FPWire->beginTransmission(I2CADDRESS_RTCDS3231);
  FPWire->write(0x00);
  FPWire->endTransmission();
  //
  FPWire->requestFrom(I2CADDRESS_RTCDS3231, 7);
  seconds    = BcdDec(FPWire->read() & 0x7F);
  minutes    = BcdDec(FPWire->read());
  hours      = BcdDec(FPWire->read() & 0x3F);
  dayofweek  = BcdDec(FPWire->read());
  day        = BcdDec(FPWire->read());
  month      = BcdDec(FPWire->read() & 0x1F);
  year       = BcdDec(FPWire->read());
}
//
float CRtcDS3231::ReadTemperatureC(void) 
{
  FPWire->beginTransmission(I2CADDRESS_RTCDS3231);
  FPWire->write(0x11);
  FPWire->endTransmission();
  FPWire->requestFrom(I2CADDRESS_RTCDS3231, 2);
  int8_t msb = FPWire->read();
  byte lsb = FPWire->read();
  return (float)(msb + ((lsb >> 6) * 0.25));
}
