#include "RFInput.h"
#include "stm32f1xx_ll_gpio.h" 
#include "stm32f1xx_ll_bus.h"
#include "stm32f1xx_ll_tim.h"


// timer 4 channel 1 for pb6 channel 2 for pb7

void RF_INPUT_Init(void)
{
	// GPIO setup
	LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_GPIOB);
	LL_GPIO_InitTypeDef  pb6_init_conf, pb7_init_conf;
	
	pb6_init_conf.Mode = LL_GPIO_MODE_FLOATING;
	pb6_init_conf.Pin = LL_GPIO_PIN_6;
	pb6_init_conf.Pull = LL_GPIO_PULL_DOWN;
	LL_GPIO_Init(GPIOB, &pb6_init_conf);
	
	pb7_init_conf.Mode = LL_GPIO_MODE_FLOATING;
	pb7_init_conf.Pin = LL_GPIO_PIN_7;
	pb7_init_conf.Pull = LL_GPIO_PULL_DOWN;
	LL_GPIO_Init(GPIOB, &pb7_init_conf);
	
	// timer setup to
	LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM4);
	LL_TIM_InitTypeDef tim4_init_struct;
	
	tim4_init_struct.Autoreload= 0xFFFF; // ??
	tim4_init_struct.Prescaler=71;
	tim4_init_struct.ClockDivision=LL_TIM_CLOCKDIVISION_DIV1;
	tim4_init_struct.CounterMode=LL_TIM_COUNTERMODE_UP;
	tim4_init_struct.RepetitionCounter=0;
	
	LL_TIM_Init(TIM4, &tim4_init_struct);
	
	
	// setup channel 1 to capture period of pwm
	LL_TIM_IC_InitTypeDef tim4_ic_conf;
	tim4_ic_conf.ICPolarity= LL_TIM_IC_POLARITY_RISING;
	tim4_ic_conf.ICActiveInput = LL_TIM_ACTIVEINPUT_DIRECTTI;
	tim4_ic_conf.ICFilter = LL_TIM_IC_FILTER_FDIV1;
	tim4_ic_conf.ICPrescaler = LL_TIM_ICPSC_DIV1;
	
	LL_TIM_IC_Init(TIM4, LL_TIM_CHANNEL_CH1, &tim4_ic_conf);
	
	// setup channel 2 to capture duty time of pwm
	LL_TIM_IC_InitTypeDef tim4_ic_conf_2;
	tim4_ic_conf_2.ICPolarity= LL_TIM_IC_POLARITY_FALLING;
	tim4_ic_conf_2.ICActiveInput = LL_TIM_ACTIVEINPUT_INDIRECTTI;
	tim4_ic_conf_2.ICFilter = LL_TIM_IC_FILTER_FDIV1;
	tim4_ic_conf_2.ICPrescaler = LL_TIM_ICPSC_DIV1;
	
	LL_TIM_IC_Init(TIM4, LL_TIM_CHANNEL_CH2, &tim4_ic_conf_2);
	
	// setup reset of clock at rising edge
	LL_TIM_SetSlaveMode(TIM4, LL_TIM_SLAVEMODE_RESET);
	LL_TIM_SetTriggerInput(TIM4, LL_TIM_TS_TI1FP1);
	
	LL_TIM_EnableCounter(TIM4);
}

int RF_INPUT_GetPeriodUs(void)
{
	return LL_TIM_ReadReg(TIM4, CCR1);
}

int RF_INPUT_GetDutyTimeUs(void)
{
	return LL_TIM_ReadReg(TIM4, CCR2);
}

int RF_INPUT_GetDutyTimeRelative(void)
{
	int d = RF_INPUT_GetDutyTimeUs();
	return (d - 1500) / 5;
}
