// 文件编码: GB18030
/*
 * button.c
 *
 *  Created on: 2025年4月19日
 *      Author: LHYe200
 */


#include "button.h"

gpio_pin_enum BUTTON_PIN[BUTTON_PIN_NUM] = BUTTON_PINS;
uint8 button_state[BUTTON_PIN_NUM]; // 按键状态
uint16 button_last_time[BUTTON_PIN_NUM]; // 持续按下时间

void Button_Init(void)
{
    for(int i = 0; i < BUTTON_PIN_NUM; i++)
    {
        gpio_init(BUTTON_PIN[i], GPI, GPIO_LOW, GPI_PULL_UP); // 按键引脚初始化为输入模式，默认拉高
    }
    memset(button_state, 0, sizeof(button_state)); // 清除按键状态
    memset(button_last_time, 0, sizeof(button_last_time)); // 清除上一次按键状态
}

void Button_Scan()
{
    for(int i = 0; i < BUTTON_PIN_NUM; i++)
    {
        if(gpio_get_level(BUTTON_PIN[i]) == GPIO_LOW) // 按键按下
        {
            button_last_time[i] += BUTTON_SCAN_TIME; // 持续按下时间增加
        }
        else // 按键松开
        {
            if(button_last_time[i] >= BUTTON_SHORT_PRESS_TIME && button_last_time[i] < BUTTON_LONG_PRESS_TIME) // 短按
            {
                button_state[i] = BUTTON_SHORT_PRESS; // 设置为短按状态
            }
            else // 未按下
            {
                if(button_state[i] == BUTTON_LONG_PRESS || button_state[i] == BUTTON_LONG_PRESS_GOT) // 如果之前是长按状态
                {
                    button_state[i] = BUTTON_RELEASE;
                }
                // button_state[i] = BUTTON_RELEASE; // 设置为未按下状态
            }
            button_last_time[i] = 0; // 持续按下时间清零
        }
        if(button_last_time[i] >= BUTTON_LONG_PRESS_TIME) // 长按
        {
            if(button_state[i] != BUTTON_LONG_PRESS_GOT) // 如果之前不是长按GOT状态
            {
                button_state[i] = BUTTON_LONG_PRESS; // 设置为长按状态
            }
            
        }
        
    }
}

uint8 Button_Get_State(uint8 button_num)
{
    if(button_num >= BUTTON_PIN_NUM) // 按键编号越界
    {
        return -1; // 返回错误
    }
    uint8 tmp_sta = button_state[button_num];
    if(button_state[button_num] == BUTTON_LONG_PRESS)
    {
        button_state[button_num] = BUTTON_LONG_PRESS_GOT;
    }
    return tmp_sta; // 返回按键状态
}


void Button_Reset(uint8 button_num)
{
    if(button_num >= BUTTON_PIN_NUM) // 按键编号越界
    {
        return ; // 返回错误
    }
    button_state[button_num] = BUTTON_RELEASE; // 重置按键状态为未按下
}

