/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * File Name          : freertos.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2022 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under Ultimate Liberty license
  * SLA0044, the "License"; You may not use this file except in compliance with
  * the License. You may obtain a copy of the License at:
  *                             www.st.com/SLA0044
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "main.h"
#include "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "esp8266.h"
#include "onenet.h"
#include "net_time.h"
#include "touch.h"
#include "LCD.h"
#include "key.h"
#include "main.h"
#include "cmsis_os.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include "fsmc.h"
#include "syn6288.h"
#include "as608.h"
#include "SIM900A.h"
#include "sr04.h"
#include "GY906.h"
#include "i2c.h"
#include <stdio.h>
#include <string.h>
#include "xpt2046.h"
#include "TOUCH.h"
#include "math.h"
#include "lvgl.h"
#include "lv_port_disp.h"
#include "lv_port_indev.h"
#include "gui_guider.h"
#include "events_init.h"

lv_ui guider_ui;

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

void vApplicationTickHook()
{
    // 告诉lvgl已经过去了1毫秒
    lv_tick_inc(1);
}
//configUSE_TICK_HOOK 记得设为1

uint8_t Gate_STATE;//箱门状态
uint8_t drug_STATE;//药品状态
uint8_t beep_STATE;//报警器状态
extern float distant;      //测量距离
float ObjectTemperature;//目标温度
float AmbientTemperature;//环境温度
int tempe[4];//设置温度上限
float tempepe[6];//求温度平均值
int key_t=0,key_x=0,key_y=0,temp_x;//用于定位按键位置，方便设置温度上限
u8 key;

u8 alarmFlag = 0;//是否报警的标志
u8 alarm_is_free = 10;//报警器是否被手动操作，如果被手动操作即设置为0
char PUB_BUF[256];//上传数据的buf
const char *devSubTopic[] = {"/AIthrough/sub"};
const char devPubTopic[] = "/AIthrough/pub";
u8 ESP8266_INIT_OK = 0;//esp8266初始化完成标志
u8 lvgl_screen1_cotrol=1;//控制
u8 as608_cotrol=0;//切换指纹功能，0为识别指纹，1为录指纹，3为删除指纹
u8 press_FR_data=3;

u8 last_drug_STATE=1,last_aRxBuffer6;//保存上一次
float last_tempep;
u8 processnum=0;

char temp_data[10] = { 0 };//转换数据缓存
extern SearchResult seach;;//指纹ID，医生为1，病人为2
u8 face_id=0;//控制人脸修改,1医生，2病人
u8 face_control=0;//控制人脸修改
extern u8 aTxBuffer6[3],at_state;//串口发送,防止一直发送信息

u8 normal_temp=0;//1温度正常，0温度异常

typedef struct   //储存药品
{
	  int  drug_sum;//一种药品的总数
    int  day_time;//一天多少次
    int  one_amount;//一次多少包

}drug;
drug drug_1;//药品1
drug drug_2;//药品2
u8 drug1_save_state=0;
u8 drug2_save_state=0;
u8 drug1_put_state=0;
u8 drug2_put_state=0;
extern present_time time_now;
extern uint8_t number_control;//电话号码转录
u8 person_state=0;//保存识别信息，1医生，2病人
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */

/* USER CODE END Variables */
osThreadId Task_KEYHandle;
osThreadId Task_NFCHandle;
osThreadId Task_LCDHandle;
osThreadId Task_fingerprinHandle;
osThreadId Task_controlHandle;
osThreadId Task_menuHandle;
osThreadId Task_tempHandle;
osThreadId Task_pushtipHandle;
osThreadId Task_lvglHandle;

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FunctionPrototypes */
void publish_tip(void);//发布主题
void mqtt_init(void);//初始化

/* USER CODE END FunctionPrototypes */

void StartDefaultTask_KEY(void const * argument);
void StartTask_NFC(void const * argument);
void StartTask_LCD(void const * argument);
void StartTaskTask_fingerprint(void const * argument);
void StartTask_control(void const * argument);
void StartTask_menu(void const * argument);
void StartTask_temp(void const * argument);
void StartTask_pushtip(void const * argument);
void StartTask_lvgl(void const * argument);

void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */

/* GetIdleTaskMemory prototype (linked to static allocation support) */
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize );

/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */
static StaticTask_t xIdleTaskTCBBuffer;
static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];
  
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize )
{
  *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;
  *ppxIdleTaskStackBuffer = &xIdleStack[0];
  *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
  /* place for user code */
}                   
/* USER CODE END GET_IDLE_TASK_MEMORY */

/**
  * @brief  FreeRTOS initialization
  * @param  None
  * @retval None
  */
void MX_FREERTOS_Init(void) {
  /* USER CODE BEGIN Init */
       
  /* USER CODE END Init */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* definition and creation of Task_KEY */
  osThreadDef(Task_KEY, StartDefaultTask_KEY, osPriorityNormal, 0, 128);
  Task_KEYHandle = osThreadCreate(osThread(Task_KEY), NULL);

  /* definition and creation of Task_NFC */
  osThreadDef(Task_NFC, StartTask_NFC, osPriorityNormal, 0, 128);
  Task_NFCHandle = osThreadCreate(osThread(Task_NFC), NULL);

  /* definition and creation of Task_LCD */
  osThreadDef(Task_LCD, StartTask_LCD, osPriorityNormal, 0, 128);
  Task_LCDHandle = osThreadCreate(osThread(Task_LCD), NULL);

  /* definition and creation of Task_fingerprin */
  osThreadDef(Task_fingerprin, StartTaskTask_fingerprint, osPriorityNormal, 0, 128);
  Task_fingerprinHandle = osThreadCreate(osThread(Task_fingerprin), NULL);

  /* definition and creation of Task_control */
  osThreadDef(Task_control, StartTask_control, osPriorityNormal, 0, 128);
  Task_controlHandle = osThreadCreate(osThread(Task_control), NULL);

  /* definition and creation of Task_menu */
  osThreadDef(Task_menu, StartTask_menu, osPriorityNormal, 0, 128);
  Task_menuHandle = osThreadCreate(osThread(Task_menu), NULL);

  /* definition and creation of Task_temp */
  osThreadDef(Task_temp, StartTask_temp, osPriorityAboveNormal, 0, 128);
  Task_tempHandle = osThreadCreate(osThread(Task_temp), NULL);

  /* definition and creation of Task_pushtip */
  osThreadDef(Task_pushtip, StartTask_pushtip, osPriorityRealtime, 0, 128);
  Task_pushtipHandle = osThreadCreate(osThread(Task_pushtip), NULL);

  /* definition and creation of Task_lvgl */
  osThreadDef(Task_lvgl, StartTask_lvgl, osPriorityHigh, 0, 512);
  Task_lvglHandle = osThreadCreate(osThread(Task_lvgl), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

}

/* USER CODE BEGIN Header_StartDefaultTask_KEY */
/**
  * @brief  Function implementing the Task_KEY thread.
  * @param  argument: Not used 
  * @retval None
  */
/* USER CODE END Header_StartDefaultTask_KEY */
void StartDefaultTask_KEY(void const * argument)
{

  /* USER CODE BEGIN StartDefaultTask_KEY */
  /* Infinite loop */
u8 temp_up=0,temp_down=0,temp_fan=0,temp_spray=0,gate_date=0;
  for(;;)
  {
  key=KEY_Scan(0);		//得到键值
		/***处理小程序发来的门数据****/
		if((HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_14)==GPIO_PIN_RESET))//开门
		{
			if(gate_date==0)//防止key一直等于某个数
			{
			key=K0_PRES;
			}
			gate_date=1;
		}
		if((HAL_GPIO_ReadPin(GPIOG, GPIO_PIN_14)==GPIO_PIN_SET))//关门
		{
			if(gate_date==1)
			{
			key=K1_PRES;
			}
			gate_date=0;
		}
		/*****         **/
	  if(key)
		{						   
			switch(key)
			{				 
				case K0_PRES:	//按键K0按下
					
		HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_0);//LED状态翻转
		if(temp_up<1)
		{
	__HAL_TIM_SET_COMPARE(&htim14,TIM_CHANNEL_1,22);// 开门
	osDelay(790);
	__HAL_TIM_SET_COMPARE(&htim14,TIM_CHANNEL_1,15);//
   ++temp_up;
		temp_down=0;
		Gate_STATE=1;
		}
					break;

				case K1_PRES:	//按键K1按下

				HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_0);//LED状态翻转
				if(temp_down<1)
				{
	__HAL_TIM_SET_COMPARE(&htim14,TIM_CHANNEL_1,12);//关门
	osDelay(600);
	__HAL_TIM_SET_COMPARE(&htim14,TIM_CHANNEL_1,15);
					++temp_down;
					temp_up=0;
					Gate_STATE=0;
				}
					break;
				case K2_PRES:	//按键K2按下
				if(temp_fan==0)
				{					
				HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_0);//LED状态翻转
				HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_RESET);//开风扇
				}
				else
				{
					HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_0);//LED状态翻转
					HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_SET);//关风扇
				}
				++temp_fan;
				temp_fan%=2;
					break;
				case K3_PRES:	//按键K3按下
					if(temp_spray==0)
					{
						HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_RESET);//开喷雾
					}
					else
					{
						HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_SET);//关喷雾
					}
				HAL_GPIO_TogglePin(GPIOE,GPIO_PIN_0);//LED状态翻转
				++temp_spray;
				temp_spray%=2;
					break;
			}
		 }
		  osDelay(5);
	 }
    
  /* USER CODE END StartDefaultTask_KEY */
}

/* USER CODE BEGIN Header_StartTask_NFC */
/**
* @brief Function implementing the Task_NFC thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_NFC */
void StartTask_NFC(void const * argument)
{
  /* USER CODE BEGIN StartTask_NFC */
  /* Infinite loop */
  for(;;)
  {
		if(face_control)
		{
	vTaskSuspend(Task_KEYHandle);
	vTaskSuspend(Task_fingerprinHandle);
	vTaskSuspend(Task_controlHandle);
	vTaskSuspend(Task_tempHandle);
	vTaskSuspend(Task_pushtipHandle);
	vTaskSuspend(Task_menuHandle);
	vTaskSuspend(Task_menuHandle);

			if(face_id==1)//医生
			{
				SYN_FrameInfo(2, "[v10][m0][t5]请看着屏幕");
				osDelay(5000);
				aTxBuffer6[0]='B';
				HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
				osDelay(1000);
				aTxBuffer6[0]='A';
				HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
				beep_one(200);
				osDelay(5000);
				SYN_FrameInfo(2, "[v10][m0][t5]录入成功");
				osDelay(2000);
			}
			if(face_id==2)//病人
			{
				SYN_FrameInfo(2, "[v10][m0][t5]请看着屏幕");
				osDelay(5000);
				aTxBuffer6[0]='D';
				HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
				osDelay(1000);
				aTxBuffer6[0]='C';
				HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
				beep_one(200);
				osDelay(5000);
				SYN_FrameInfo(2, "[v10][m0][t5]录入成功");
				osDelay(2000);
			}
	vTaskResume(Task_KEYHandle);
	vTaskResume(Task_fingerprinHandle);
	vTaskResume(Task_tempHandle);
	vTaskResume(Task_pushtipHandle);
	vTaskResume(Task_menuHandle);
	face_control=0;
		}
		HAL_GPIO_TogglePin(GPIOE,LED_R_Pin);//LED状态翻转
	 osDelay(500);
		

  }
  /* USER CODE END StartTask_NFC */
}

/* USER CODE BEGIN Header_StartTask_LCD */
/**
* @brief Function implementing the Task_LCD thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_LCD */
void StartTask_LCD(void const * argument)
{
  /* USER CODE BEGIN StartTask_LCD */
  /* Infinite loop */

  for(;;)
  {	
		if(alarmFlag==1)
		{
		 	HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_RESET);//蜂鸣器
		}
		if(alarmFlag==0)
		{
		  HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_SET);//蜂鸣器
		}
		if(HAL_GPIO_ReadPin(GPIOA, drug_state_Pin)==GPIO_PIN_SET)
		{
			 drug_STATE=0;
		}
		if(HAL_GPIO_ReadPin(GPIOA, drug_state_Pin)==GPIO_PIN_RESET)
		{
			 drug_STATE=1;
		}
//		/***k210信息处理**/
if(aRxBuffer6[0]=='0'||seach.pageID==1||person_state==1)//识别到是医生
{
	person_state=1;
	switch (aRxBuffer6[0])
	{
	    case '2':drug_1.drug_sum=12,drug_1.day_time=2,drug_1.one_amount=1,drug1_put_state=1,aRxBuffer6[0]=0,beep_one(200);//一共12包,一天三次，一次1包
		break;
			case '3':drug_2.drug_sum=20,drug_2.day_time=3,drug_2.one_amount=2,drug2_put_state=1;aRxBuffer6[0]=0,beep_one(200);//一共20包,一天两次，一次2包
		break;
	default:
		break;
	}
	
}
			if(aRxBuffer6[0]=='2')
		{
	vTaskSuspend(Task_KEYHandle);
	vTaskSuspend(Task_NFCHandle);
	vTaskSuspend(Task_fingerprinHandle);
	vTaskSuspend(Task_controlHandle);
	vTaskSuspend(Task_tempHandle);
	vTaskSuspend(Task_pushtipHandle);
	vTaskSuspend(Task_menuHandle);
	SYN_FrameInfo(2, "[v10][m0][t5]氯雷他定一天三次一次一包饭后吃");
	osDelay(5000);
	vTaskResume(Task_KEYHandle);
	vTaskResume(Task_NFCHandle);
	vTaskResume(Task_fingerprinHandle);
	vTaskResume(Task_controlHandle);
	vTaskResume(Task_tempHandle);
	vTaskResume(Task_pushtipHandle);
	vTaskResume(Task_menuHandle);
		aRxBuffer6[0]=0;
		}	
		if(aRxBuffer6[0]=='3')
		{

	vTaskSuspend(Task_KEYHandle);
	vTaskSuspend(Task_NFCHandle);
	vTaskSuspend(Task_fingerprinHandle);
	vTaskSuspend(Task_controlHandle);
	vTaskSuspend(Task_tempHandle);
	vTaskSuspend(Task_pushtipHandle);
	vTaskSuspend(Task_menuHandle);
	SYN_FrameInfo(2, "[v10][m0][t5]西替利嗪一天两次一次两包饭后吃");
	osDelay(5000);
	vTaskResume(Task_KEYHandle);
	vTaskResume(Task_NFCHandle);
	vTaskResume(Task_fingerprinHandle);
	vTaskResume(Task_controlHandle);
	vTaskResume(Task_tempHandle);
	vTaskResume(Task_pushtipHandle);
	vTaskResume(Task_menuHandle);
		aRxBuffer6[0]=0;
		}	
	   osDelay(500);
  }
  /* USER CODE END StartTask_LCD */
}

/* USER CODE BEGIN Header_StartTaskTask_fingerprint */
/**
* @brief Function implementing the Task_fingerprin thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTaskTask_fingerprint */
void StartTaskTask_fingerprint(void const * argument)
{
  /* USER CODE BEGIN StartTaskTask_fingerprint */
  /* Infinite loop */
	uint8_t res = 1;
	res = as608_init();
	if(res == 0)
	{
		printf("AS608指纹模块初始化成功\r\n");
	}
	else
		printf("AS608指纹模块初始化失败\r\n");
  for(;;)
  {
		switch (as608_cotrol)
	{
	    case 0:press_FR();//刷指纹测试
		break;
			case 1:Add_FR();//录指纹测试
		break;
			case 2:Del_FR();//删除指纹测试
		break;
	default:
		break;
	}

    osDelay(100);
  }
  /* USER CODE END StartTaskTask_fingerprint */
}

/* USER CODE BEGIN Header_StartTask_control */
/**
* @brief Function implementing the Task_control thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_control */
void StartTask_control(void const * argument)
{
  /* USER CODE BEGIN StartTask_control */
  /* Infinite loop */
  for(;;)
  {
		while(HAL_UART_GetState(&huart4) == HAL_UART_STATE_BUSY_RX);//忙等待
		if((aRxBuffer6[0]=='0'||seach.pageID==1)&&(normal_temp==1))//医生端
		{
		if(drug_STATE==1)//有药品
		{
				SYN_FrameInfo(2, "[v10][m0][t5]已有药品");
			  osDelay(5000);
		}
		else
		{
			vTaskSuspend(Task_tempHandle);
			osDelay(2000);
			SYN_FrameInfo(2, "[v10][m0][t5]请洗手消毒");
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14,GPIO_PIN_RESET);//打开门
			osDelay(500);
			SYN_FrameInfo(2, "[v10][m0][t5]请扫描药品放入药箱");
			aTxBuffer6[0]='1';
			HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
			osDelay(2000);
		  while(__HAL_UART_GET_FLAG(&huart6,UART_FLAG_IDLE) != RESET)
			{
				osDelay(4000);
			}
			while(drug_STATE==0);//等待药品放入
			osDelay(1000);
			aTxBuffer6[0]='0';
			HAL_UART_Transmit(&huart6,aTxBuffer6,1,100);
			if(drug_STATE==1)//药品放完
			{
				HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14,GPIO_PIN_SET);//关门
			}
			Sim900A_SendMsg2("8BF7524D5F80003153F7836F7BB153D6836F");
			osDelay(500);
			HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_RESET);//开喷雾
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_SET);//关喷雾
			HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_RESET);//开风扇
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_SET);//关风扇
			aRxBuffer6[0]=0;
		  normal_temp=0;//执行一次
			seach.pageID=0;
			person_state=0;
			
			printf("请取药\r\n");
			
			vTaskResume(Task_tempHandle);
		 }
		}
		if(((aRxBuffer6[0]=='1'||seach.pageID==2))&&(normal_temp==1))//病人端
		{
		if(drug_STATE==0)//没有药品
		{
				SYN_FrameInfo(2, "[v10][m0][t5]没有药品");
			  osDelay(5000);
		}
		else
		{
				vTaskSuspend(Task_tempHandle);
			osDelay(2000);
			SYN_FrameInfo(2, "[v10][m0][t5]请洗手消毒");
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14,GPIO_PIN_RESET);//打开门
			osDelay(500);
			SYN_FrameInfo(2, "[v10][m0][t5]请取走药品");
			while(drug_STATE==1);//等待药品取走
			osDelay(3000);
			if(drug_STATE==0)//药品取走
			{
				HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14,GPIO_PIN_SET);//关门
				osDelay(500);
			}
			osDelay(500);
	    HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_RESET);//开喷雾
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOG,spray_Pin,GPIO_PIN_SET);//关喷雾
			HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_RESET);//开风扇
			osDelay(5000);
			HAL_GPIO_WritePin(GPIOE,FAN_Pin,GPIO_PIN_SET);//关风扇
				if(drug1_put_state==1)
			{
				drug1_save_state=1;
				drug1_put_state=0;
			}
	
				if(drug2_put_state==1)
			{
				drug2_save_state=1;
				drug2_put_state=0;
			}
			aRxBuffer6[0]=0;
			seach.pageID=0;
		  normal_temp=0;//执行一次
			vTaskResume(Task_tempHandle);
		}

		}
    osDelay(1);
  }
  /* USER CODE END StartTask_control */
}

/* USER CODE BEGIN Header_StartTask_menu */
/**
* @brief Function implementing the Task_menu thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_menu */
void StartTask_menu(void const * argument)
{
  /* USER CODE BEGIN StartTask_menu */
  /* Infinite loop */
	u8 drug1_note_time;//发送短信的次数
	u8 drug2_note_time;//发送短信的次数	
	u8 stand1_time=0,stand2_time=0,stand3_time=0;
  for(;;)
  {
		if(drug1_save_state==1)
		{
     drug2_save_state=0;
		 drug1_note_time=drug_1.drug_sum/(drug_1.day_time*drug_1.one_amount);
		 drug1_save_state=0;
		}
		if(drug2_save_state==1)
		{

		 drug2_note_time=drug_2.drug_sum/(drug_2.day_time*drug_2.one_amount);
		 drug2_save_state=0;
		}
		if(drug1_note_time!=0)
		{
			if(drug1_note_time==2)
			{
				printf("药品即将吃完，如病情还未好转，请及时联系医生r\n");
				Sim900A_SendMsg2("836F54C153735C0654035B8CFF0C598275C560C58FD8672A597D8F6CFF0C8BF753CA65F680547CFB533B751F");
			}
		switch (time_now.hour)
	 {
	    case 8: if(stand1_time==0){ 
			--drug1_note_time ,stand1_time=1,printf("温馨提醒：该吃药了1（如已吃请忽视此条信息）\r\n");
			Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}
		break;
			case 13: if(stand2_time==0){ 
			--drug1_note_time ,stand2_time=1,printf("温馨提醒：该吃药了2（如已吃请忽视此条信息）\r\n");
		Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}
		break;
			case 18: if(stand3_time==0){ 
			--drug1_note_time ,stand3_time=1,printf("温馨提醒：该吃药了3（如已吃请忽视此条信息）\r\n");
			Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}                
		break;
	default:
		break;
	}
		}
		if(drug2_note_time!=0)
		{
			if(drug2_note_time==2)
			{
				printf("药品即将吃完，如病情还未好转，请及时联系医生\r\n");
				Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}
		switch (time_now.hour)
	{
	    case 8: if(stand1_time==0){ 
			--drug1_note_time ,stand1_time=1,printf("温馨提醒：该吃药了4（如已吃请忽视此条信息）\r\n");
						Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}
		break;
			case 18: if(stand3_time==0){ 
			--drug1_note_time ,stand3_time=1,printf("温馨提醒：该吃药了5（如已吃请忽视此条信息）\r\n");
					Sim900A_SendMsg2("6E2999A863D09192FF1A8BE55403836F4E86FF0859825DF254038BF75FFD89C66B6467614FE1606FFF09");
			}
		break;
	default:
		break;
	}
		}
		if(time_now.hour==23)//回复标志位，下一天调用
		{
			stand1_time=0,stand2_time=0,stand3_time=0;
		}
    //printf("%d-%d-%d %d:%d:%d\r\n",time_now.year,time_now.month,time_now.day,time_now.hour,time_now.min,time_now.sec);
		 osDelay(500);
  }
	
  /* USER CODE END StartTask_menu */
}

/* USER CODE BEGIN Header_StartTask_temp */
/**
* @brief Function implementing the Task_temp thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_temp */
void StartTask_temp(void const * argument)
{
  /* USER CODE BEGIN StartTask_temp */
  /* Infinite loop */
	MLX90614_Init(&hi2c1);
  MLX90614_SetEmissivity(0.985); // Human skin
	tempe[0]=3,tempe[1]=7,tempe[2]=3,tempe[3]=3;
  for(;;)
  {
	//	MLX90614_ReadObjectTemperature(&ObjectTemperature); 
		//printf("温度值为:%.2f\r\n",ObjectTemperature);
		SR04_GetData();
    //printf("距离:%.2f\r\n",distant);

		if(distant<100&&distant>0)//进入测温范围
		{
			 MLX90614_ReadObjectTemperature(&ObjectTemperature); 
			 ++temp_x;
		}
		else
		{
				temp_x=0;
		}
		if(temp_x==1)
		{
				//printf("%d,%d,%d，%d\r\n",tempe[0],tempe[1],tempe[2],tempe[3]);
        tempepe[0]=ObjectTemperature+0.012*distant+0.95;
			//tempepe[0]=ObjectTemperature;
			  beep_one(200);
		}
			if(tempepe[0]<(tempe[0]*10+tempe[1]+tempe[2]*0.1+tempe[3]*0.01)&&tempepe[0]>0)
			{	
				if(temp_x==1)
				{
				  SYN_FrameInfo(2, "[v10][m0][t5]温度正常");
					normal_temp=1;
					osDelay(1000);
				}
				
			}
		if(tempepe[0]>(tempe[0]*10+tempe[1]+tempe[2]*0.1+tempe[3]*0.01))
			{
				if(temp_x==1)
				{
					SYN_FrameInfo(2, "[v10][m0][t5]温度异常");
					normal_temp=0;
					osDelay(1000);
				}				
			}
    osDelay(500);
  }
		
  /* USER CODE END StartTask_temp */
}

/* USER CODE BEGIN Header_StartTask_pushtip */
/**
* @brief Function implementing the Task_pushtip thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_pushtip */
void StartTask_pushtip(void const * argument)
{
  /* USER CODE BEGIN StartTask_pushtip */
  /* Infinite loop */
  	unsigned char *dataPtr = NULL,push_time=0;
	  get_beijing_time();//获取网络时间
	  beep_one(100);
	  mqtt_init();
	  OneNet_Subscribe(devSubTopic, 1);//订阅mqtt主题
	  beep_one(200);
	
  for(;;)
  {
		if(push_time==30)//3s发布一次
		{
		   publish_tip();
		   HAL_GPIO_TogglePin(GPIOG,tip_led_Pin);//LED状态翻转
		}
		dataPtr = ESP8266_GetIPD(3);
		if(dataPtr != NULL)
		OneNet_RevPro(dataPtr);
		osDelay(10);
		++push_time;
		push_time%=31;

		osDelay(100);
  }
	
  /* USER CODE END StartTask_pushtip */
}

/* USER CODE BEGIN Header_StartTask_lvgl */
/**
* @brief Function implementing the Task_lvgl thread.
* @param argument: Not used
* @retval None
*/
/* USER CODE END Header_StartTask_lvgl */
void StartTask_lvgl(void const * argument)
{
  /* USER CODE BEGIN StartTask_lvgl */
  /* Infinite loop */

  lv_init();			  // lvgl系统初始化
	lv_port_disp_init();  // lvgl显示接口初始化,放在lv_init()的后面
	lv_port_indev_init(); // lvgl输入接口初始化,放在lv_init()的后面
  setup_ui(&guider_ui);
  events_init(&guider_ui);
  for(;;)
  {
		XPT2046_Scan(0); 	
		lv_task_handler(); // lvgl的事务处理
		
 if(lvgl_screen1_cotrol)//控制整个画面
 {	
		if((aRxBuffer6[0]=='1'&&aRxBuffer6[0]!=last_aRxBuffer6)||(seach.pageID==2))//人脸识别数据
		{
			  last_aRxBuffer6=aRxBuffer6[0];
  	    lv_obj_set_style_text_color(guider_ui.screen1_label_7, lv_color_hex(0xFF3300), 0);
	      lv_label_set_text(guider_ui.screen1_label_7, "patient");
			if(seach.pageID==2)
			{
				last_aRxBuffer6=0;//防止干扰人脸识别
			}
		}
		if((aRxBuffer6[0]=='0'&&aRxBuffer6[0]!=last_aRxBuffer6)||(seach.pageID==1))
		{
			  last_aRxBuffer6=aRxBuffer6[0];
		    lv_obj_set_style_text_color(guider_ui.screen1_label_7, lv_color_hex(0x33FF33), 0);
	      lv_label_set_text(guider_ui.screen1_label_7, "doctor");
				if(seach.pageID==1)
			{
				last_aRxBuffer6=0;//防止干扰人脸识别
			}
		}
   if(tempepe[0]<(tempe[0]*10+tempe[1]+tempe[2]*0.1+tempe[3]*0.01)&&tempepe[0]!=last_tempep)//温度正常
			{
				 last_tempep=tempepe[0];
	       lv_obj_set_style_text_color(guider_ui.screen1_label_11, lv_color_hex(0x33FF33), 0);
	       sprintf((char*)temp_data, "%.2f", tempepe[0]);//格式化输出 浮点数转成字符串输出
	       lv_label_set_text_fmt(guider_ui.screen1_label_11, "%s", (const char*)temp_data);
			}
		if(tempepe[0]>(tempe[0]*10+tempe[1]+tempe[2]*0.1+tempe[3]*0.01)&&tempepe[0]!=last_tempep)
			{
				
					last_tempep=tempepe[0];
	        lv_obj_set_style_text_color(guider_ui.screen1_label_11, lv_color_hex(0xFF3300), 0);
	        sprintf((char*)temp_data, "%.2f", tempepe[0]);//格式化输出 浮点数转成字符串输出
	        lv_label_set_text_fmt(guider_ui.screen1_label_11, "%s", (const char*)temp_data);
			}
			if(drug_STATE==0&&drug_STATE!=last_drug_STATE)//没药
			{
			 	 last_drug_STATE=drug_STATE;
				 lv_obj_set_style_text_color(guider_ui.screen1_label_12, lv_color_hex(0xFF3300), 0);
	       lv_label_set_text(guider_ui.screen1_label_12, "NO");
			}
			if(drug_STATE==1!=last_drug_STATE)//有药
			{
				  last_drug_STATE=drug_STATE;
					lv_obj_set_style_text_color(guider_ui.screen1_label_12, lv_color_hex(0x33FF33), 0);
	        lv_label_set_text(guider_ui.screen1_label_12, "YES");
			}
		if(press_FR_data==1)
		{
				  lv_obj_set_style_text_color(guider_ui.screen1_label_9, lv_color_hex(0x33FF33), 0);
	        lv_label_set_text(guider_ui.screen1_label_9, "success");
		    	press_FR_data=2;
		}
		if(press_FR_data==0)
		{
					lv_obj_set_style_text_color(guider_ui.screen1_label_9, lv_color_hex(0xFF3300), 0);
	        lv_label_set_text(guider_ui.screen1_label_9, "fail");
		    	press_FR_data=2;
		}

 }			
    osDelay(500);
		HAL_GPIO_TogglePin(GPIOE,LED_Y_Pin);//LED状态翻转
  }
  /* USER CODE END StartTask_lvgl */
}

/* Private application code --------------------------------------------------*/
/* USER CODE BEGIN Application */

void publish_tip(void)
{
	u8 sigal;
	if(seach.pageID==1)
	{
		sigal='0';
	}
	if(seach.pageID==2)
	{
		sigal='1';
	}
	if(aRxBuffer6[0]=='0')
	{
			sigal='0';
	}
		if(aRxBuffer6[0]=='1')
	{
			sigal='1';
	}
			printf("============================================================\r\n");
			printf("发布数据 ----- OneNet_Publish\r\n");
			sprintf(PUB_BUF,"{\"Temp\":%5.2f,\"drug\":%d,\"Beep\":%d,\"gate\":%d,\"dotor\":%d}",
	   	tempepe[0],drug_STATE?0:1,alarmFlag,Gate_STATE,sigal);
			OneNet_Publish(devPubTopic, PUB_BUF);
			printf("==============================================================\r\n");
			ESP8266_Clear();

}
void mqtt_init(void)
{
	LCD_Clear(WHITE);//清屏
	if(!ESP8266_INIT_OK){
		LCD_DisplayString_color(0,64,24,"Waiting For",RED,WHITE);
		LCD_DisplayString_color(0,90,24,"Onenet",RED,WHITE);
		LCD_DisplayString_color(0,120,24,"Connection",RED,WHITE);
	}
	ESP8266_Init();					//初始化ESP8266
	LCD_Clear(WHITE);//清屏
			LCD_DisplayString_color(0,64,24,"Waiting For",RED,WHITE);
		LCD_DisplayString_color(0,90,24,"MQTT Server",RED,WHITE);
		LCD_DisplayString_color(0,120,24,"Connection",RED,WHITE);
	
	while(OneNet_DevLink())//接入OneNET
	{
	HAL_Delay(500);
	}	
	LCD_Clear(WHITE);//清屏
}

/* USER CODE END Application */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
