#include "gd32f10x.h"
#include "key.h"
#include "systick.h"
#include "device_message.h"
static uint32_t KEY_PORT[KEYn] = {SYS_RECOVERY_KEY_GPIO_PORT};
static uint32_t KEY_PIN[KEYn] = {SYS_RECOVERY_KEY_PIN};
static rcu_periph_enum KEY_CLK[KEYn] = {SYS_RECOVERY_KEY_GPIO_CLK};
static exti_line_enum KEY_EXTI_LINE[KEYn] = {SYS_RECOVERY_KEY_EXTI_LINE};
static uint8_t KEY_PORT_SOURCE[KEYn] = {SYS_RECOVERY_KEY_EXTI_PORT_SOURCE};
static uint8_t KEY_PIN_SOURCE[KEYn] = {SYS_RECOVERY_KEY_EXTI_PORT_SOURCE};
static uint8_t KEY_IRQn[KEYn] = {SYS_RECOVERY_KEY_EXTI_IRQn};

void gd_eval_key_init(key_typedef_enum key_num, keymode_typedef_enum key_mode)
{
    /* enable the key clock */
    rcu_periph_clock_enable(KEY_CLK[key_num]);
    rcu_periph_clock_enable(RCU_AF);

    /* configure button pin as input */
    gpio_init(KEY_PORT[key_num], GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, KEY_PIN[key_num]);

    if (key_mode == KEY_MODE_EXTI) {
        /* enable and set key EXTI interrupt to the lowest priority */
        nvic_irq_enable(KEY_IRQn[key_num], 2U, 2U);

        /* connect key EXTI line to key GPIO pin */
        gpio_exti_source_select(KEY_PORT_SOURCE[key_num], KEY_PIN_SOURCE[key_num]);

        /* configure key EXTI line */
        exti_init(KEY_EXTI_LINE[key_num], EXTI_INTERRUPT, EXTI_TRIG_FALLING);
        exti_interrupt_flag_clear(KEY_EXTI_LINE[key_num]);
    }
}

void EXTI1_IRQHandler(void){
	if (exti_interrupt_flag_get(EXTI_1) != RESET) {
        /* 延时1秒钟 */
        delay_1ms(1000);

        /* 判断按键是否仍然被按下 */
        if (gpio_input_bit_get(KEY_PORT[0], KEY_PIN[0]) == RESET) {
            /* 执行数据清除操作 */
//            clear_gateway_config_block();
        }

        /* 清除EXTI1中断标志 */
        exti_interrupt_flag_clear(EXTI_1);
				NVIC_SystemReset();               //设备重启
    }
}

