#include "bsp_led.h"
#include "rtthread.h"
#include "pin.h"
#include "bsp_nt26k.h"   
#include "user_sys.h"


#define LOG_TAG "bsp.led"
#define LOG_LVL LOG_LVL_DBG
#include <ulog.h>

//用到了atoi
#include <stdlib.h>

agile_led_t *led_r = RT_NULL;
agile_led_t *led_g = RT_NULL;
agile_led_t *led_y = RT_NULL;

ALIGN(4)
static char user_led_thread_stack[512];
static struct rt_thread user_led_thread;


static void BSP_Led_thread_entry(void *param)
{
    while (1)
    {  
        if (SysControl.status == kNormalDetectionEvents)
        {
          if ((nt26k_conncet_tcp_flag))
           {
              LED_G_NORMAL;
           }
           else if ((!nt26k_conncet_tcp_flag))
           {
                LED_G_INTERNET;
           }
        }
        else if (SysControl.status == KMuteEvent)
        {
            if (SysControl.last_status == kNormalDetectionEvents)
            {
                if ((nt26k_conncet_tcp_flag))
                {
                    LED_G_NORMAL;
                }
                else
                {
                    LED_G_INTERNET;
                }
            }
        }
        rt_thread_mdelay(1500);
    }
}

int BSP_LED_Init(void)
{
    led_r = agile_led_create(LED_R_PIN, PIN_HIGH, "100,0", 0);
    led_g = agile_led_create(LED_G_PIN, PIN_HIGH, "100,0", 0);
    led_y = agile_led_create(LED_Y_PIN, PIN_HIGH, "100,0", 0);

 rt_err_t ret = rt_thread_init(&user_led_thread,
                                  "user_led_thread",
                                  BSP_Led_thread_entry,
                                  RT_NULL,
                                  &user_led_thread_stack[0],
                                  sizeof(user_led_thread_stack),
                                  20, 5);

    if (ret == RT_EOK)
    {
        rt_thread_startup(&user_led_thread);
    }

    LOG_D("BSP_LED_Init");

    return RT_EOK;
}
// INIT_DEVICE_EXPORT(BSP_LED_Init);

#ifdef TEST_ENABLE
static void TEST_LED(int argc, char **argv)
{
    if (argc == 4)
    {
        char led_name = argv[1][0];
        // strcmp(led_name, "r")
        int loop_cnt = atoi(argv[3]);
        switch (led_name)
        {
            case 'r':
                agile_led_dynamic_change_light_mode(led_r, argv[2], loop_cnt);
                agile_led_start(led_r);
                break;
            case 'g':
                agile_led_dynamic_change_light_mode(led_g, argv[2], loop_cnt);
                agile_led_start(led_g);
                break;
            case 'y':
                agile_led_dynamic_change_light_mode(led_y, argv[2], loop_cnt);
                agile_led_start(led_y);
                break;
        }
    }
    else
    {
        LOG_E("TEST_LED      --use _cmd_ [r/g/y][mode][loop_cnt]");
    }
}
MSH_CMD_EXPORT(TEST_LED, "TEST_LED");
#endif
