#include "custom_led.h"
#include "cmsis_os.h"
#include "custom_flags.h"

extern struct flags FLAGS;

uint16_t UNDER_400V = 2500;
void LED_Init(void)
{
	GPIOC->ODR &= ~(1<<13);
	FLAGS.LED_WARNING_POSITION=1;
}

void LED_Check(float R)
{
	if(ADC1->JDR1>=3570) FLAGS.INSUFFICIENT_POWER_LEVEL=0;
	if(!(FLAGS.INSUFFICIENT_POWER_LEVEL)){
	if(R<500.0){ //Аварийный режим
		LED_EMERGENCY(FLAGS);
	}
	else if (toMega(R)<1.0){//Предупредительный режим
		LED_WARNING(FLAGS);
	} 
	else {
		LED_STABLE(FLAGS);
	}}
}
void LED_Power_Less(void)
{
	FLAGS.INSUFFICIENT_POWER_LEVEL=1;
}
uint16_t LED_Mode()
{
	if (FLAGS.INSUFFICIENT_POWER_LEVEL)
	{
		GPIOC->ODR &= ~(1<<13);
		return 1000;
	}
	else if(FLAGS.LED_EMERGENCY_MODE)
	{
		GPIOC->ODR ^= 1<<13;
		FLAGS.LED_WARNING_POSITION=0;
		return 200;
	}
	else if(FLAGS.LED_WARNING_MODE){
			if(FLAGS.LED_WARNING_POSITION){
				GPIOC->ODR |= 1<<13;
				FLAGS.LED_WARNING_POSITION=0;
				return 1000;
			}
			else{
				GPIOC->ODR &= ~(1<<13);
				FLAGS.LED_WARNING_POSITION=1;
				return 1000;
			}
		}
	else{
		GPIOC->ODR |= 1<<13;
		FLAGS.LED_WARNING_POSITION=1;
		return 1000;
	}
}

void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
{
	if(hadc->Instance == ADC1){
		LED_Power_Less();
	  ADC1->LTR=UNDER_400V;
	}
}
