/*
 * RTC.c
 *
 *  Created on: 15 janv. 2019
 *      Author: e_rcluze
 */

#include "RTC.h"
#include "RTC_ADD.h"
#include "i2c.h"

void readRTC(uint8_t add, uint8_t *tab, int len){
	uint8_t ad[1];
	ad[0]=add;
	HAL_StatusTypeDef res;
	res = HAL_I2C_Master_Transmit(&hi2c3,RTC_ADD,ad,1,1000);
	res = HAL_I2C_Master_Receive(&hi2c3,RTC_ADD,tab,len,1000);
}

void writeRTC(uint8_t add, uint8_t *tab, int len){
	uint8_t ad[len+1];
	ad[0]=add;
	for (int i = 0; i< len;i++){
		ad[i+1]=tab[i];
	}
	HAL_StatusTypeDef res;
	res = HAL_I2C_Master_Transmit(&hi2c3,RTC_ADD,ad,len+1,1000);
}

uint8_t readMinute(){
	uint8_t tab[1];
	readRTC(MINUTES,tab,1);
	return ((tab[0]>>4)*10)+tab[0]&&0X0F;
}

uint8_t readHeure(){
	uint8_t tab[1];
	readRTC(HOURS,tab,1);
	return (((tab[0]&&0XC0)>>4)*10)+tab[0]&&0X0F;
}

void readDate(Date *date){
	uint8_t tab[7];
	readRTC(SECOND,tab,7);
	date->second=(((tab[0]&&0X80)>>4)*10)+tab[0]&&0X0F;
	date->minute=((tab[1]>>4)*10)+tab[1]&&0X0F;
	date->heure=(((tab[2]&&0XC0)>>4)*10)+tab[2]&&0X0F;
	date->jour=(((tab[4]&&0XC0)>>4)*10)+tab[4]&&0X0F;
	date->mois=(((tab[5]&&0XE0)>>4)*10)+tab[5]&&0X0F;
	date->annee=((tab[6]>>4)*10)+tab[6]&&0X0F;
}

void redemareRTC(){
	uint8_t pt[1]={0X40};
	writeRTC(ALARM_HOURS,pt,1);
}
