#include "battery.h"

extern MyUART_Struct_Typedef uartCool;
extern int actualMinutes;
extern uint32_t oldAdc;

void battery(uint32_t data)
{
	MyRTC_Struct_TypeDef rtcBattery;
	MyRTC_GetTime(&rtcBattery);

	if((actualMinutes == rtcBattery.minutes) && isClose(oldAdc,data,100))	//pas de precision/10 %
	{
		return;
	}
	float percentBattery = ((float)data)/MAX_BAT;
	if(percentBattery > 1)
	{
		return;
	}
	
	oldAdc = data;
	actualMinutes = rtcBattery.minutes;
	char batteryBar[13]="[__________]";
	char testChar[25];
	
	getGauge(batteryBar, percentBattery);
	sprintf(testChar,"[%.2d:%.2d] %s %.3d%%",rtcBattery.hours,rtcBattery.minutes,batteryBar,(int)(percentBattery*100));
	MyUART_SendArray(&uartCool, (uint8_t *)testChar, 25);
	MyUART_Send(&uartCool, '\n');
}

void getGauge(char gauge[], float percent)
{
	int i;
	percent=percent*10;
	for(i=(10-percent)+1; i<11; i++)
	{
		gauge[i]='#';
	}
	gauge[12]='\0';
}

char isClose(uint32_t data, uint32_t compare, int precision)
{
	if(data < precision)
	{
		return !(data >= compare+precision);
	}
	return !((data >= compare+precision) || (data <= compare-precision));
}

void initBattery(void)
{
	MyADC_Init_Periph(battery);
	MyADC_Struct_TypeDef adcBattery = {ADC1,10,cycles239d5};
	MyADC_Init(&adcBattery);
	MyGPIO_Struct_TypeDef gpioBattery = {GPIOC,0,In_Analog};
	MyGPIO_Init(&gpioBattery);
}
