#include "main.h"

extern int8_t user_i2c_read(uint8_t id, uint8_t reg_addr, uint8_t *data, uint16_t len);
extern int8_t user_i2c_write(uint8_t id, uint8_t reg_addr, uint8_t *data, uint16_t len);

/**
 * @brief Инициализация RTC
 */
void RTC_Init(void) {
  uint8_t buf[3] = {0};

  /* Clear flags */
  Flag.I2C_TX_End = 0;

  buf[0] = DS3231_1HZ; // set 1 Hz output squware
  buf[1] = 0x0; // disable 32 kHz output

  user_i2c_write(DS3231_I2C_ADDR, DS3231_ADDR_CONTROL, buf, 2);
}

/**
 * @brief Чтение всех регистров DS3231
 */
void RTC_ReadAll(rtc_t * data) {
  Flag.I2C_RX_End = 0;
  Flag.I2C_TX_End = 0;

  user_i2c_read(DS3231_I2C_ADDR, DS3231_ADDR_TIME, (uint8_t *)data, DS3231_SIZE_ALL);
}

/**
 * @brief Запись времени и календаря "SS:MM:HH wd dd/mm/yy"
 */
void RTC_WriteTimeCalendar(rtc_t * data) {
  Flag.I2C_TX_End = 0;

  user_i2c_write(DS3231_I2C_ADDR, DS3231_ADDR_TIME, &(data->Sec), (DS3231_SIZE_TIME + DS3231_SIZE_CALENDAR));
}

/**
 * @brief Запись времени "SS:MM:HH"
 */
void RTC_WriteTime(rtc_t * data) {
  Flag.I2C_TX_End = 0;

  user_i2c_write(DS3231_I2C_ADDR, DS3231_ADDR_TIME, &(data->Sec), DS3231_SIZE_TIME);
}

/**
 * @brief Запись часов "HH"
 */
void RTC_WriteHH(rtc_t * data) {
  Flag.I2C_TX_End = 0;

  user_i2c_write(DS3231_I2C_ADDR, (DS3231_ADDR_TIME + 2), &(data->Hr), 1);
}

/**
 * @brief Запись часов и минут "MM:HH"
 */
void RTC_WriteHHMM(rtc_t * data) {
  Flag.I2C_TX_End = 0;

  user_i2c_write(DS3231_I2C_ADDR, (DS3231_ADDR_TIME + 1), &(data->Min), 2);
}

/**
 * @brief Запись календаря "wd dd/mm/yy"
 */
void RTC_WriteCalendar(rtc_t * data) {
  Flag.I2C_TX_End = 0;

  user_i2c_write(DS3231_I2C_ADDR, DS3231_ADDR_CALENDAR, &(data->WD), DS3231_SIZE_CALENDAR);
}

/**
 * @brief Convert BCD value to Binary
 */
uint8_t bcd2bin(uint8_t bcd)
{
  return (10 * (bcd >> 4) + (bcd & 0x0f));
}

/**
 * @brief Convert Binary value to BCD
 */
uint8_t bin2bcd(uint8_t bin)
{
  return (((bin / 10 ) << 4) | (bin % 10));
}
