#include "hdl_encoder.h"

static volatile uint8_t a_level = 0;
static volatile int16_t encoder_cnt = 0;

static void hdl_encoder_a_callback(void)
{
	if (SET == EXTINT_GetExtIntStatus(ENCODER_A_EX_CH)) {
        if(RESET == ENCODER_A_GET)
		{
			a_level = 0;
			if(SET == ENCODER_B_GET)
				a_level = 1;
		}
		if(SET == ENCODER_A_GET)
		{
			if((a_level == 1) && (RESET == ENCODER_B_GET))
			{
				encoder_cnt++;
			}
			if((a_level == 0) && (SET == ENCODER_B_GET))
			{
				encoder_cnt--;
			}
		}

        EXTINT_ClearExtIntStatus(ENCODER_A_EX_CH);
    }
}

static void hdl_encoder_b_callback(void)
{
	if (SET == EXTINT_GetExtIntStatus(ENCODER_B_EX_CH)) {
        
//        while (PIN_RESET == GPIO_ReadInputPins(KEY10_PORT, KEY10_PIN)) {
//            ;
//        }
        EXTINT_ClearExtIntStatus(ENCODER_B_EX_CH);
    }
}

void hdl_encoder_init(void)
{
	stc_gpio_init_t stcGpioInit;
	stc_extint_init_t stcExtIntInit;
	stc_irq_signin_config_t stcIrqSignConfig;
	
	LL_PERIPH_WE(LL_PERIPH_GPIO);
	
	/* 配置引脚 */
	(void)GPIO_StructInit(&stcGpioInit);
	stcGpioInit.u16PullUp = PIN_PU_ON;		//上拉输入
	stcGpioInit.u16ExtInt = PIN_EXTINT_ON;	//外部中断
	(void)GPIO_Init(ENCODER_SW_PORT, ENCODER_SW_PIN, &stcGpioInit);
	(void)GPIO_Init(ENCODER_A_PORT, ENCODER_A_PIN, &stcGpioInit);
	(void)GPIO_Init(ENCODER_B_PORT, ENCODER_B_PIN, &stcGpioInit);
	
	/* 配置中断 */
	(void)EXTINT_StructInit(&stcExtIntInit);
    stcExtIntInit.u32Filter      = EXTINT_FILTER_ON;
    stcExtIntInit.u32FilterClock = EXTINT_FCLK_DIV8;
    stcExtIntInit.u32Edge = EXTINT_TRIG_BOTH;	//双边沿中断
    (void)EXTINT_Init(ENCODER_A_EX_CH, &stcExtIntInit);
	(void)EXTINT_Init(ENCODER_B_EX_CH, &stcExtIntInit);
	
	/* 配置中断源 */
	stcIrqSignConfig.enIntSrc = ENCODER_A_INT_SRC;
    stcIrqSignConfig.enIRQn   = ENCODER_A_INT_IRQn;
    stcIrqSignConfig.pfnCallback = &hdl_encoder_a_callback;
    (void)INTC_IrqSignIn(&stcIrqSignConfig);	
	NVIC_ClearPendingIRQ(stcIrqSignConfig.enIRQn);
    NVIC_SetPriority(stcIrqSignConfig.enIRQn, DDL_IRQ_PRIO_DEFAULT);
    NVIC_EnableIRQ(stcIrqSignConfig.enIRQn);
	
	stcIrqSignConfig.enIntSrc = ENCODER_B_INT_SRC;
    stcIrqSignConfig.enIRQn   = ENCODER_B_INT_IRQn;
    stcIrqSignConfig.pfnCallback = &hdl_encoder_b_callback;
    (void)INTC_IrqSignIn(&stcIrqSignConfig);
	NVIC_ClearPendingIRQ(stcIrqSignConfig.enIRQn);
    NVIC_SetPriority(stcIrqSignConfig.enIRQn, DDL_IRQ_PRIO_DEFAULT);
    NVIC_EnableIRQ(stcIrqSignConfig.enIRQn);
}

int16_t hdl_encoder_cnt_get(void)
{
	return encoder_cnt;
}

