#include "led.h"

static struct led *led_table[LED_MAX_NUM];
static uint32_t p_led_table=0;
/**
 * @brief 注册LED灯
 * 
 * @param led struct led 结构指针
 * @param gpio LED所在的GPIO
 * @param pin LED所在的引脚
 * @param state LED初始状态
 * @param level_on LED点亮时的电平 1:高 0:低
 * @return int 0:成功 非0:失败
 */
int led_register(struct led *led,GPIO_TypeDef *gpio,uint16_t pin,enum led_state state,uint16_t level_on)
{
    if(p_led_table>=LED_MAX_NUM-1){
        return -1;
    }
    led->gpio=gpio;
    led->pin=pin;
    led->state=state;
    led->level_on=level_on;
    led_table[p_led_table++]=led;
    return 0;
}
/**
 * @brief 设置LED状态
 * 
 * @param led struct led 结构指针
 * @param state LED状态
 * @return int 0:成功
 */
int led_set_state(struct led *led,enum led_state state)
{
    led->state=state;
    return 0;
}
/**
 * @brief led回调函数 每100ms调用一次
 * 
 */
void led_callback(void)
{
    int i;
    static uint32_t tick_con=0;
    tick_con++;
    for(i=0;i<p_led_table;i++){
        switch (led_table[i]->state)
        {
        case LED_STATE_OFF:
            HAL_GPIO_WritePin( led_table[i]->gpio,led_table[i]->pin,(~led_table[i]->level_on)&1 );
            // GPIO_WriteBit(led_table[i]->gpio,led_table[i]->pin,(~led_table[i]->level_on)&1);
            break;
        case LED_STATE_ON:
            HAL_GPIO_WritePin( led_table[i]->gpio,led_table[i]->pin,led_table[i]->level_on&1 );
            // GPIO_WriteBit(led_table[i]->gpio,led_table[i]->pin,led_table[i]->level_on&1);
            break;
        case LED_STATE_FLICKER_QUICK:
            HAL_GPIO_TogglePin(  led_table[i]->gpio,led_table[i]->pin);
            // GPIO_WriteBit(led_table[i]->gpio,led_table[i]->pin,!GPIO_ReadOutputDataBit(led_table[i]->gpio,led_table[i]->pin));
            break;
        case LED_STATE_FLICKER_MEDIUM:
            if((tick_con&0x01)==0){
                HAL_GPIO_TogglePin(  led_table[i]->gpio,led_table[i]->pin);
                // GPIO_WriteBit(led_table[i]->gpio,led_table[i]->pin,!GPIO_ReadOutputDataBit(led_table[i]->gpio,led_table[i]->pin));
            }
            break;
        case LED_STATE_FLICKER_SLOW:
            if((tick_con&0x03)==0){
                HAL_GPIO_TogglePin(  led_table[i]->gpio,led_table[i]->pin);
                // GPIO_WriteBit(led_table[i]->gpio,led_table[i]->pin,!GPIO_ReadOutputDataBit(led_table[i]->gpio,led_table[i]->pin));
            }
            break;
        default:
            break;
        }
    }
}