#include "backlight.h"


static btstack_timer_source_t backlight_timer;
static bool backlight_timer_registered_flag = false;
static uint8_t backlight_count = 0;

static void stop_backlight_task(void)
{
    btstack_run_loop_remove_timer(&backlight_timer);
    backlight_timer_registered_flag = true;
    backlight_count = 0;
}

static void backlight_timer_handler(btstack_timer_source_t *ts)
{
    static bool backlight_open_flag = FALSE;
    if (backlight_count < (BACKLIGHT_MS / BACKLIGHT_LIGHT_MS))
    {
        // 背光
        omw_gpio_set_output(BACKLIGHT_PIN, backlight_open_flag);
        backlight_open_flag = !backlight_open_flag;
        // 设置下一个定时器
        btstack_run_loop_set_timer(ts, BACKLIGHT_LIGHT_MS);
        btstack_run_loop_add_timer(ts);
        backlight_count++;
    }
    else
    {
        backlight_count = 0;
        // 关闭背光
        omw_gpio_set_output(BACKLIGHT_PIN, 1);
        // 设置下一个定时器
        stop_backlight_task();
    }
}

void start_backlight_task(void)
{
    // 如果之前添加过定时器则先移除
    if (backlight_timer_registered_flag)
    {
        stop_backlight_task();
    }
    // set one-shot timer
    backlight_timer.process = &backlight_timer_handler;
    btstack_run_loop_set_timer(&backlight_timer, BACKLIGHT_LIGHT_MS);
    btstack_run_loop_add_timer(&backlight_timer);
    backlight_timer_registered_flag = true;
}

void backlight_init(void)
{
    // 关闭背光
    omw_gpio_set_func(BACKLIGHT_PIN, OMW_GPIO_CFG_VAL(OMW_GPIO_DRIVE_STRENTH3, OMW_GPIO3_GPIO));
    omw_gpio_set_output_en(BACKLIGHT_PIN, 1);
    omw_gpio_set_output(BACKLIGHT_PIN, 1);
}
