#include "user_upgrade.h"
#include "peripheral.h"
#include "ota.h"
#include "led.h"

static tmosTaskID user_upgrade_task_id = INVALID_TASK_ID;

static bool ota_timeout_check = false;
static uint16_t ota_timeout_delay_count = 60;

static void user_upgrade_time_pro(void)
{
    if(ota_timeout_check == true)
    {
	if(ota_timeout_delay_count > 0)
	{
	    ota_timeout_delay_count--;
	    if(ota_timeout_delay_count == 1)
	    {
		    Set_User_Upgrade_Queue(USER_UPGRADE_QUEUE_ENTER_APP);
	    }
	}
    }
}

void Set_User_Upgrade_Queue(USER_UPGRADE_QUEUE_TYPE type)
{
    bStatus_t stat = tmos_start_task(user_upgrade_task_id, (1 << type), MS1_TO_SYSTEM_TIME(10));
}

//task的event处理回调函数,需要在注册task时候,传进去
static uint16_t user_upgrade_task_process_event(uint8_t task_id, uint16_t events)
{
    //event 处理
    if(events & (1 << USER_UPGRADE_QUEUE_TIME))
    {
        user_upgrade_time_pro();
        return (events ^ (1 << USER_UPGRADE_QUEUE_TIME)); //异或的方式清除该事件运行标志，并返回未运行的事件标志
    }
    //event 处理
    if(events & (1 << USER_UPGRADE_QUEUE_ENTER_APP))
    {
        /* Close all the current use interrupt, or it is convenient to directly close */
        __disable_irq();
        PRINT("ota timeout jump App \n");
        Delay_Ms(10);
        app_start();
    	return (events ^ (1 << USER_UPGRADE_QUEUE_ENTER_APP)); //异或的方式清除该事件运行标志，并返回未运行的事件标志
    }

    return 0;
}

void ota_timeout_task_start(bool stat)
{
  ota_timeout_check = stat;
  ota_timeout_delay_count = 30;
}

void user_upgrade_start(void)
{
    user_upgrade_task_id  = TMOS_ProcessEventRegister(user_upgrade_task_process_event);
    bStatus_t stat = tmos_start_reload_task(user_upgrade_task_id, (1 << USER_UPGRADE_QUEUE_TIME), MS1_TO_SYSTEM_TIME(1000));
}
