#include "drv_light.h"


static struct light_drv_cfg g_light_drv_cfg;

/**
 * @brief 初始化LIGHT驱动
 * 
 * @return rt_err_t 错误码，RT_EOK表示成功，-RT_ERROR表示失败
 */
rt_err_t light_drv_init(void)
{
    struct light_drv_cfg *cfg = &g_light_drv_cfg;
    
    if (cfg->is_initlized) {
        rt_kprintf("func: %s, light driver is initialized.\r\n", __func__);
        return -RT_ERROR;
    }

    cfg->dev = (struct rt_device *)rt_device_find(LIGHT_DRV_NAME);
    if (cfg->dev == RT_NULL) {
        rt_kprintf("func: %s, light driver find fail.\r\n", __func__, LIGHT_DRV_NAME);
        return -RT_ERROR;
    }

    cfg->is_initlized = true;

    rt_kprintf("func: %s, light driver init success.\r\n", __func__);

    return RT_EOK;
}

/**
 * @brief 设置LIGHT驱动占空比百分比
 * 
 * @param[in] percentage PWM占空比百分比，范围0-100
 * @return rt_err_t 错误码，RT_EOK表示成功，-RT_ERROR表示失败
 */ 
rt_err_t light_drv_set_percentage(uint8_t percentage)
{
    struct light_drv_cfg *cfg = &g_light_drv_cfg;
        
    if (!cfg->is_initlized) {
        rt_kprintf("func: %s, light driver is not initialized.\r\n", __func__);
        return -RT_ERROR;
    }

    cfg->cfg.percentage = percentage > LIGHT_DRV_PERCENTAGE ? LIGHT_DRV_PERCENTAGE : percentage;

    rt_err_t err = rt_device_control(cfg->dev, 0, &cfg->cfg);
    if (err != RT_EOK) {
        rt_kprintf("func: %s, light driver set percentage %d fail.\r\n", __func__, cfg->cfg.percentage);    
        return -RT_ERROR;
    }
    
    return RT_EOK;
}



