#include "main.h"
#include "FreeRTOS.h"
#include "semphr.h"
#include "timers.h"
#include "task.h"
#include "shell.h"
#include "shell_port.h"

static TaskHandle_t AppTaskCreate_Handle = NULL;	// 创建任务句柄
static TaskHandle_t Main_Task_Handle = NULL;			// Main任务句柄
static TaskHandle_t Key_Task_Handle = NULL;				// Key任务句柄
static TaskHandle_t Wdog_Task_Handle = NULL;			// Wdog任务句柄
static TaskHandle_t Bat_Task_Handle = NULL;				// 电池任务句柄
static TimerHandle_t xTimeHandle = NULL;          //软件定时器句柄
	
static void AppTaskCreate(void);									// 用于创建任务 
static void Main_Task(void *pvParameters);				// Main_Task任务实现
static void Key_Task(void *pvParameters);	   			// KEY_Task任务实现
static void Wdog_Task(void *pvParameters); 				// Wdog发送任务实现
static void Bat_Task(void *pvParameters);	   			// 电池检测任务实现
static void timeCallBackTask(void);               // 定时锁机任务实现


uint8_t lora_sendbuf[255]; //Lora数据构造数组

void BSP_Init(void);

int main(void)
{

	BaseType_t xReturn = pdPASS;

	BSP_Init();

	xReturn = xTaskCreate((TaskFunction_t)AppTaskCreate,
						  (const char *)"AppTaskCreate",
						  (uint16_t)512,
						  (void *)NULL,
						  (UBaseType_t)1,
						  (TaskHandle_t *)&AppTaskCreate_Handle);

	if (pdPASS == xReturn)
		vTaskStartScheduler();
	else
		return -1;

	while (1)
		;
}

static void AppTaskCreate(void)
{
	BaseType_t xReturn = pdPASS;

	taskENTER_CRITICAL(); //临界保护
	/*创建线程*/
	xReturn = xTaskCreate((TaskFunction_t)Main_Task,
						  (const char *)"Main_Task",
						  (uint16_t)512,
						  (void *)NULL,
						  (UBaseType_t)2,
						  (TaskHandle_t *)&Main_Task_Handle);
	if (pdPASS != xReturn)
		printf("创建Main_Task任务失败!\r\n");

	xReturn = xTaskCreate((TaskFunction_t)Key_Task,
						  (const char *)"Key_Task",
						  (uint16_t)64,
						  (void *)NULL,
						  (UBaseType_t)2,
						  (TaskHandle_t *)&Key_Task_Handle);
	if (pdPASS != xReturn)
		printf("创建Key_Task任务失败!\r\n");

	xReturn = xTaskCreate((TaskFunction_t)Wdog_Task,
						  (const char *)"Wdog_Task",
						  (uint16_t)512,
						  (void *)NULL,
						  (UBaseType_t)2, Wdog_Task_Handle);
	if (pdPASS != xReturn)
		printf("创建Wdog_Task任务失败!\r\n");

	xReturn = xTaskCreate((TaskFunction_t)Bat_Task,
						  (const char *)"Bat_Task",
						  (uint16_t)64,
						  (void *)NULL,
						  (UBaseType_t)2, Bat_Task_Handle);
	if (pdPASS != xReturn)
		printf("创建Bat_Task任务失败!\r\n");
	

	/*注册超时模块软件定时器*/
	xTimeHandle = xTimerCreate(
		(const char *)"time_lock",		// 定时器名字
		(TickType_t)1000,							// 定时器的周期
		pdTRUE,												// 定时器周期执行
		(void *)1,									  // 给定时器分配的唯一ID
		(TimerCallbackFunction_t)timeCallBackTask // 定时器回调函数
	);
	if (xTimeHandle)
	{
		xTimerStart(xTimeHandle, 0); // 开启定时器
	}

	vTaskDelete(AppTaskCreate_Handle);
	taskEXIT_CRITICAL();
}

/*软件定时器回调*/
void timeCallBackTask(void)
{
	if (rc_data()->Lock_state == UNLOCK)
	{
		rc_data()->Lock_time_tick++;
	}
	
	if (rc_data()->Lock_time_tick >= rc_data()->Kv_get.lock_time)
	{
		rc_data()->Asr_state = LOCK;	
		rc_data()->Lock_state = LOCK;
		rc_data()->Lock_time_tick = 0;
		ASR_Power_OFF;
		LEDClass.Set(BLACK);
	}
}

/*主线程函数*/
static void Main_Task(void *parameter)
{

	while (1)
	{
		/*按键控制模式*/
		if((rc_data()->Lock_state ==UNLOCK)&&(rc_data()->Asr_state == LOCK))
		{
				LEDClass.Set(BLACK);
				ADC1Class.GetValue(0) > 170 ? LEDClass.Set(GREEN) : LEDClass.Set(YELLOW);
				
			if(rc_data()->isLEDTog == ENABLE)
			{
				LEDClass.Set(BLACK);
				MODClass.Loop(LEDClass.GREEN_Toggle,vTaskDelay,7,50);
				rc_data()->isLEDTog = 0;
			}
			
			if(rc_data()->isSend == ENABLE )
			{
				rc_data()->isSend  = DISABLE;
				if ((rc_data()->Key_data[0] == 0 && rc_data()->Key_data[1] == 1) || (rc_data()->Key_data[0] != 0))
				{
					sprintf((char *)lora_sendbuf, 
						"AT+LRSEND=85,1,33,\"{\"E\":\"%d\",\"T\":\"%d\",\"R\":\"%d\",\"C\":\"%d\"}\"\r\n",
					   rc_data()->Key_data[0],rc_data()->Key_data[1],
						//(rc_data()->Key_data[0] != 9 && rc_data()->Key_data[0] != 10) ? rc_data()->Key_data[0] : 0,
						//(rc_data()->Key_data[0] != 9 && rc_data()->Key_data[0] != 10) ? rc_data()->Key_data[1] : 0,
						rc_data()->Key_data[2],
						rc_data()->Key_data[3]);
					LEDClass.Set(BLACK);
					USARTClass.USART_SendString1(USART3, lora_sendbuf, 54);
					MODClass.Loop(LEDClass.GREEN_Toggle,vTaskDelay,4,400);
					LEDClass.Set(BLACK);
					rc_data()->Lock_state = LOCK;
				}
				else
				{
					LEDClass.Set(BLACK);
					MODClass.Loop(LEDClass.RED_Toggle,vTaskDelay,4,400);
				}
				memset(rc_data()->Key_data,0x00,4);
			}
		}
		/*语音控制模式*/
		if((rc_data()->Lock_state==UNLOCK)&&rc_data()->Asr_state  == UNLOCK)
		{
			LEDClass.Set(WHITE);
			if (Asr_recbuff[0] == 0x55 && Asr_recbuff[1] == 0xAA)
			{
				rc_data()->Lock_time_tick =0;
				switch (Asr_recbuff[2]) 
				{
					case 1 ... 12:
					{
						const LoraCommandParams *params = &cmd_params[Asr_recbuff[2] - 1];
						sprintf((char *)lora_sendbuf, 
               "AT+LRSEND=85,1,33,\"{\"E\":\"%s\",\"T\":\"%s\",\"R\":\"%s\",\"C\":\"%s\"}\"\r\n",
               params->e_val, params->t_val, params->r_val, params->c_val);
						break;
					}
					default:
						break;
				}
				USARTClass.USART_SendString1(USART3, lora_sendbuf, 54);
				memset(Asr_recbuff, 0x00, 20);
				LEDClass.Set(BLACK);
				MODClass.Loop(LEDClass.GREEN_Toggle,vTaskDelay,4,400);
				LEDClass.Set(BLACK);
				rc_data()->Lock_state  = LOCK;
				rc_data()->Asr_state  = LOCK;
				vTaskDelay(2000);
				ASR_Power_OFF;
			}	
		}
		if(rc_data()->Lock_state ==LOCK)
		{
			BATClass.Read_State();
		}
		vTaskDelay(20);
	}
}

/*看门狗线程函数*/
static void Wdog_Task(void *parameter)
{
	while (1)
	{
		IWDG_ReloadCounter();
		vTaskDelay(30);
	}
}

/*电池检测线程函数*/
static void Bat_Task(void *parameter)
{
	while (1)
	{

	//	printf("bat value:%d\r\n",ADC1Class.GetValue(0));
		vTaskDelay(1000);
	}
}

/*按键检测线程函数*/
static void Key_Task(void *parameter)
{
	while (1)
	{
		flex_button_scan();
		vTaskDelay(10);
	}
}



/*用户密码提取kv函数*/
//static void read_password(void)
//{
//	char *read_password;
//	read_password = ef_get_env("ziit_password");
//	assert_param(read_password);
//	strcpy(shellPasswordDefaultUser, read_password);
//	printf("The ziit password is %s \n\r", shellPasswordDefaultUser);
//}

/*锁定时间提取kv函数*/
static void read_lock_time(void)
{
	char *keys;
	keys = ef_get_env("key_s");
	assert_param(keys);          //检查参数合法性
	rc_data()->Kv_get.lock_time = atol(keys); //str => int
	printf("锁定时间:%d\r\n", rc_data()->Kv_get.lock_time);
}

/* 
 * 按键使能提取函数 - 使用16位变量存储10个按键状态
 * 每个按键占用1位，最低位(bit0)表示第1个按键，bit9表示第10个按键
 * 0表示失能，1表示使能
 */
static void read_key_en_table(void)
{
    char *key_en_table;
    uint16_t key_en_bits = 0;  // 16位存储按键状态
    
    // 从环境变量获取键值
    key_en_table = ef_get_env("key_en_table");
    assert_param(key_en_table);  // 检查参数合法性
    
    // 将字符串转换为16位数值
    key_en_bits = (uint16_t)strtoul(key_en_table, NULL, 0);
    
    // 存储到数据结构中
    rc_data()->Kv_get.key_en_table = key_en_bits;
 
}

/*BSP初始化函数*/
static void BSP_Init(void)
{
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
	delay_init();
	LEDClass.Init();
	ASR_Power_Init();
	USARTClass.USART1_Init(115200);
	USARTClass.USART3_Init(9600);
	USARTClass.USART2_Init(9600);
	USARTClass.USART_SendString1(USART3, (uint8_t *)"start",5);
	BATClass.Init();
	ADC1Class.Init();
	rc_data()->Lock_state = UNLOCK;
	rc_data()->Asr_state = LOCK;
	rc_data()->isSend  = DISABLE;
	rc_data()->isLEDTog = DISABLE;
	ASR_Power_OFF;
	delay_ms(700);
	delay_ms(700);
	BOARD_Power_Init();
	LEDClass.Set(GREEN);
	Power_button_init();
	if (easyflash_init() == EF_NO_ERR)
	{
	//	read_password();
		read_lock_time();
		read_key_en_table();
	}

	while (1)
	{

		if (Check_Power_buttun() == 0)
		{
			break;
		}
	}
	WDOG_Init();
	userShellInit();
	user_button_init();
}

