#include "stm32f3xx_hal.h"
#include "stm32f3xx_ll_tim.h"
#include "stm32f3xx_ll_adc.h"
#include "stm32f3xx_ll_exti.h"
#include "libs/types.h"

__weak void foc_brake_handler(void) {}
__weak void foc_pwm_up_handler(void) {}
__weak void system_tick_handler(void){}
__weak void current_sample_handler(void){}
__weak void hall_sensor_handler(void){}
__weak void uart2_irq_handler(void) {}
__weak void foc_slow_task_handler(void){}
__weak void start_stop_handler(void) {}

void TIM1_BRK_TIM15_IRQHandler(void){
	if (LL_TIM_IsActiveFlag_BRK2(TIM1))
	{
	  	LL_TIM_ClearFlag_BRK2(TIM1);
	  	TIM1->BDTR |= LL_TIM_OSSI_ENABLE;
		foc_brake_handler();
	}
}

void TIM1_UP_TIM16_IRQHandler(void){
	if (LL_TIM_IsActiveFlag_UPDATE(TIM1))
	{
		LL_TIM_ClearFlag_UPDATE(TIM1);
		foc_pwm_up_handler();
	}
}


void ADC1_IRQHandler(void) {
	LL_ADC_ClearFlag_JEOS( ADC1 );
	current_sample_handler();
}

void TIM6_DAC_IRQHandler(void) {
	if (LL_TIM_IsActiveFlag_UPDATE(TIM6))
	{
		LL_TIM_ClearFlag_UPDATE(TIM6);
		foc_slow_task_handler();
	}
}

void SysTick_Handler(void)
{
	system_tick_handler();
}

void EXTI3_IRQHandler(void) {
  	if ( LL_EXTI_ReadFlag_0_31(LL_EXTI_LINE_3) )
  	{
    	LL_EXTI_ClearFlag_0_31 (LL_EXTI_LINE_3);
  		hall_sensor_handler();
  	}
}

void EXTI15_10_IRQHandler(void) {
  	if ( LL_EXTI_ReadFlag_0_31(LL_EXTI_LINE_10) )
  	{
    	LL_EXTI_ClearFlag_0_31 (LL_EXTI_LINE_10);
    	hall_sensor_handler();
  	}
  	if ( LL_EXTI_ReadFlag_0_31(LL_EXTI_LINE_13) )
  	{
    	LL_EXTI_ClearFlag_0_31 (LL_EXTI_LINE_13);
    	start_stop_handler();
  	}
   	if ( LL_EXTI_ReadFlag_0_31(LL_EXTI_LINE_15) )
  	{
    	LL_EXTI_ClearFlag_0_31 (LL_EXTI_LINE_15);
    	hall_sensor_handler();
  	}
}

void USART2_IRQHandler(void) {
	uart2_irq_handler();
}
