#ifndef _I2C_RTC_H_
#define _I2C_RTC_H_
//----------------------------------------------------------------------------
///
/// \brief support for I2C-RTC MCP7940N
///
/// https://www.mouser.de/datasheet/2/268/25010A-71550.pdf
///
/// \author Maximilian Seesslen
///
//----------------------------------------------------------------------------


//#include <time.h>       // time.h, localtime, strftime

#ifdef STM32
   //#include <arena/platform.h>
   
#endif
#include <biwak/rtc.hpp>
#include <biwak/i2c_slave.h>
#include <lepto/log.h>


class CI2cRtc
{
   private:
      CI2cSlave m_slave;

   public:
      CI2cRtc(CI2c &i2c)
         :m_slave(i2c, 0x6F)
      {
         char start;
         int sta;
         sta=m_slave.i2cReadData(0, &start, 1);
         lAssert( sta == 0);

         if( ! (start&0x80) )
         {
            printf("Warnung: RTC was stopped.\n");
         }
      }
      void enable() const;
      //virtual int exec(int argc, const char *argv[]) const;
      void modifyBit(int reg, char value, char bit) const
      {
         char data;
         int sta;
         sta=m_slave.i2cReadData(reg, &data, 1);
         lAssert( sta == 0);
         if(value)
         {
            data|=(1<<bit);
         }else
         {
            data&=~(1<<bit);
         }
         sta=m_slave.i2cWriteData(reg,  &data, 1);
      }
      int getDate() const;
      static int bcd2dec(int val)
      {
         return( ( ( val >> 4) * 10) + (val & 0xF) );
      }
      static int dec2bcd(int val)
      {
         return( ( ( val / 10 ) << 4) + ( val % 10 ) );
      }

      int getTime(int &hour, int &minute, int &sec) const;
      int getDate(int &year, int &month, int &day) const;
      int setTime(int hour, int minute, int sec) const;
      int setDate(int year, int month, int day) const;
      void hwToRtc(CRtc &rtc) const;
      void rtcToHw(CRtc &rtc) const;
      int dump() const;
};


//---fin----------------------------------------------------------------------
#endif // ? ! _I2C_RTC_H_
