#include "stm32f4xx.h"
#include <type-spec.h>
#include "at.h"
#include <string.h>
#include "queue.h"
#include "atair720.h"
#include "flash_if.h"
#include "board-config.h"
#include "usart.h"
#include "WatchDog.h"
#include "sys_tick.h"
#include "sx1276_api.h"
#include "para-config.h"
#include "led.h"

#include "type-spec.h"
#include <stdlib.h>
#include "atoi.h"
#include "main.h"
#include "ota.h"
//#include "usart.h"
#define TEST_TEST_TEST 1

#define UART2_Buffer_Max_LEN 256
#define USART_REC_LEN  			200  	//定义最大接收字节数 200
#define RevOK  1
#define Idle 0
#define Reving 2

uint8_t Air_IMEI[32]={0};
uint8_t Air_ICCID[32]={0};

//TCP连接超时
u16 TcpConnectTimeOut = 0;
uint16_t USART1RxSta = 0;

//TCP连接OK标识
u8 CONNECTISOK = 0;
extern struct UsartRxBuffer Usart2RxBuffer;

/**
  * @brief	向 AIR 模块发送命令后，检测接收到的应答
  * @param	str		期待的应答结果
  * @retval 0		没有得到期待的应答结果
			其他 	期待应答结果的位置
  */
char* air_check_cmd(char *str)
{
	char *strx = 0;
	char *CONNECTOK = "CONNECT OK";

	if(str == NULL)
		return strx;
		/* 添加结束符 */
		strx = strstr((const char*)Usart2RxBuffer.pBuffer, (const char*)str);
		if( NULL != strstr((const char*)Usart2RxBuffer.pBuffer, (const char*)CONNECTOK ) )
		{ 
			CONNECTISOK = 1;
			TcpConnectTimeOut = 0;
			
		}


	return (char*)strx;
}
/**
  * @brief	实现下载
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
uint8_t * air_send_HTTPREADCmd(uint16_t srcadr,uint16_t downcLen, uint16_t waittime)
{
	uint8_t  res,cmdtmp[100],tmp[50],len;
	u8 times = 3;
	uint32_t wait = waittime,readlen,cmdLen,codelen = downcLen;
	 char *cmdTmp;
	 char *AckTmp = "+HTTPACTION:",*pstrx,*pchar,*pres=NULL;

	memset(cmdtmp,0,50);
	cmdLen = strlen("AT+HTTPREAD=");
	memcpy(cmdtmp,"AT+HTTPREAD=",cmdLen);
	memset(tmp,0,50);
	len = myitoa(srcadr,(char *)&tmp[0]);//address
	strcat((char *)&cmdtmp[0],(char *)&tmp);
	cmdLen += len;
	memset(tmp,0,50);
	strcat((char *)&cmdtmp[0],",");//,
	cmdLen += 1;
	memset(tmp,0,50);
	myitoa(codelen,(char *)&tmp[0]);//data len
	strcat((char *)&cmdtmp[0],(char *)&tmp);
	cmdLen += strlen((char *)&tmp[0]);
	
	strcat((char *)&cmdtmp[0],"\r\n");
	cmdLen +=strlen("\r\n");
	times = 10;
	res = 0;
	AT_AIR720_DEBUG_F("%s",cmdtmp);

	USART2_ready_buf_ok = 0;
	while(times)
	{
		times--;
		/* 发送下一条命令之前，清接收状态 */
		
		memset(Usart2RxBuffer.pBuffer , 0 , USART2_BUF_SIZE);
		Usart2RxBuffer.Buffer_Len = 0;
		
    USART2_ready_buf_ok = Idle;
		USART2_SendNByte((uint8_t *)cmdtmp, cmdLen);
	
		wait=waittime;
		if(wait)
		{
			while(--wait)
			{
				delay_ms(100);
				/* 接收到一帧数据 */
				//AT_AIR720_DEBUG_F("%s:wait!!!!","+HTTPREAD:");
				if (USART2_ready_buf_ok == RevOK)
				{
            USART2_ready_buf_ok = Idle;
            AT_AIR720_DEBUG_F("cmd rcv =%s\r\n",Usart2RxBuffer.pBuffer);
						/* 添加结束符 */
						pstrx = strstr((const char*)Usart2RxBuffer.pBuffer, "+HTTPREAD:");
						if(pstrx == NULL)
					  {
							break;
						}
						pstrx += strlen("+HTTPREAD: ");
						pchar = strstr((const char*)pstrx, "\r\n");
						*pchar = '\0';
					
						
						readlen = atoi(pstrx);
						
						if(readlen == downcLen)
						{
							pres = pchar+2;
							res = 1;
							break;
						}
							
						//AT_AIR720_DEBUG_F("%s:send ok!!!!",cmd);
						break;
					}
					USART2_ready_buf_ok = Idle;
			}
      IWDG_Feed();														//喂狗

		}

		return (uint8_t *)pres;
	}
  return NULL;
}

/**
  * @brief	向 AIR 模块发送命令
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
uint8_t  air_send_cmd(char *cmd, char *ack, uint16_t waittime)
{
	uint8_t res = 0;
	u8 times = 3;
	uint16_t wait = waittime;
	//memset(Usart2_RX_BUF , 0 , 64);
	//AT_AIR720_DEBUG_F("%s!!!!",cmd);
	times = 10;
	while(times)
	{
		times--;
		/* 发送下一条命令之前，清接收状态 */
		
		memset(Usart2RxBuffer.pBuffer , 0 , USART2_BUF_SIZE);
		Usart2RxBuffer.Buffer_Len = 0;
		USART2_ready_buf_ok = Idle;
		USART2_SendNByte((uint8_t *)cmd, strlen((const char *)cmd));
		//AT_AIR720_DEBUG_F("%s:send!!!!",cmd);
		wait=waittime;
		if(ack && wait)
		{
			while(--wait)
			{
				delay_ms(10);
				/* 接收到一帧数据 */
				//AT_AIR720_DEBUG_F("%s:wait!!!!",cmd);
				if (USART2_ready_buf_ok == RevOK)
				{
					USART2_ready_buf_ok = Idle;
          AT_AIR720_DEBUG_F("cmd rcv =%s\r\n",Usart2RxBuffer.pBuffer);
					/* 接收到期待的应答结果 */
					if (air_check_cmd(ack))
					{
						AT_AIR720_DEBUG_F("air_send_cmd:2:%s ACK OK!!!!!!!!!!\r\n",cmd);
						times = 0;
						res = 1;
						//AT_AIR720_DEBUG_F("%s:send ok!!!!",cmd);
						break;
					}
				}
        
        IWDG_Feed();														//喂狗
			}

			
		}
	}
	return res;
}
/**
  * @brief	air_send_HTTPACTIONCmd
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
uint8_t  air_send_HTTPACTIONCmd(uint8_t index, uint32_t *pLen, uint16_t waittime)
{
	uint8_t res = 0;
	u8 times = 3,get_Wait_flg;
	uint16_t wait = waittime,len,i;
	const char *cmdTmp = "AT+HTTPACTION=0\r\n";
	const char *AckTmp = "+HTTPACTION:",*strx;
	//memset(Usart2_RX_BUF , 0 , 64);
	char *ACkOK = "OK";
	USART2_ready_buf_ok = 0;
	res=air_send_cmd(( char *)cmdTmp, ACkOK, 300);
	while(res &&waittime)
	{
		
		waittime--;	
		delay_ms(10);
		//AT_AIR720_DEBUG_F("%s:wait len!!!!","AT+HTTPACTION");
		if (USART2_ready_buf_ok == RevOK)
		{
      
        USART2_ready_buf_ok = Idle;
        AT_AIR720_DEBUG_F("cmd rcv =%s\r\n",Usart2RxBuffer.pBuffer);
      
				strx = strstr((const char*)Usart2RxBuffer.pBuffer, (const char*)AckTmp );
				for(i = 0;i< USART2_ready_buf_len;i++)
					printf("%02X ",USART2_ready_buf[i]);
				if(strx == NULL)
				{ 
					AT_AIR720_DEBUG_F("%s NULL!!!!",AckTmp);
					break;						
				}
				strx = strstr((const char*)strx, "," );
				if(strx == NULL)
				{
					break;
				}
				strx+=1;
				strx = strstr((const char*)strx, "," );
				if(strx == NULL)
				{
					break;
				}
				strx +=1;
				*pLen = atoi(strx);//获取接收长度

				res = 1;
				break;
	
			}

    IWDG_Feed();														//喂狗
		}

		return res;

}

/**
  * @brief	air_send_IMEI_Cmd
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
uint8_t  air_send_IMEI_Cmd(uint16_t waittime)
{
	uint8_t res = 1;
	u8 times = 3,get_Wait_flg;
	uint16_t wait = waittime,len,i;
	const char *cmdTmp = "AT+CGSN\r\n";
	const char *strx,*stry;
	//memset(Usart2_RX_BUF , 0 , 64);
	char *ACkOK = "OK";
  times = 10;
	while(times--){
    USART2_ready_buf_ok = 0;
    memset(USART2_ready_buf,0,USART2_BUF_SIZE);
    USART2_SendNByte((uint8_t *)cmdTmp, strlen((const char *)cmdTmp));
    while(waittime)
    {
      
      waittime--;	
      delay_ms(10);
      //AT_AIR720_DEBUG_F("%s:wait len!!!!","AT+HTTPACTION");
      if (USART2_ready_buf_ok == RevOK)
      {   
        strx = (const char*)USART2_ready_buf;
        //打印返回指令
        for(i = 0;i< USART2_ready_buf_len;i++)
          printf("%02X ",USART2_ready_buf[i]);
        printf("\r\n");
      
        //检索8 6 6 7 1 4 0 4 6 8 1 8 3 5 6 之前的"\r\n" 
        strx = strstr((const char*)strx, "\r\n86" );
        if(strx == NULL)
        {
          AT_AIR720_DEBUG_F("strx == NULL\r\n");
          break;
        }
        strx+=2;
        //检索8 6 6 7 1 4 0 4 6 8 1 8 3 5 6 之后的"\r\n" 
        stry = strstr((const char*)(strx), "\r\n" );
        if(stry == NULL)
        {
          AT_AIR720_DEBUG_F("stry == NULL\r\n");
          break;
        }
        len = (int)(stry)-(int)(strx);
        
        //
        if((len<=0)||(len>17)||(len>sizeof(Air_IMEI)))
        {
          AT_AIR720_DEBUG_F("((len<=0)||(len>17)||(len>sizeof(Air_IMEI)))\r\n");
          AT_AIR720_DEBUG_F("len=%d,stry=0x%8X,strx=0x%8X\r\n",len,(int)stry,(int)strx);
          break;
        }
        //中间段为IMEI
        memset(Air_IMEI,0,sizeof(Air_IMEI));
        for(i = 0;i < len;i++)
        {
          if((*(strx+i)>='0')||(*(strx+i)<='9'))
          {
            Air_IMEI[i]= *(strx+i);
          }
          else{
            memset(Air_IMEI,0,sizeof(Air_IMEI));
            AT_AIR720_DEBUG_F("((*(strx+i)<'0')||(*(strx+i)>'9'))\r\n");
            return 0;
          }
        }
        AT_AIR720_DEBUG_F("IMEI=%s\r\n",Air_IMEI);
        //USART2_SendNByte(Air_IMEI,len);
        //AT_AIR720_DEBUG("\r\n");
        
        
        return 0;
  
      }
    
      delay_ms(300);
    }
  }
  return res;

}

/**
  * @brief	air_send_ICCID_Cmd
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
uint8_t  air_send_ICCID_Cmd(uint16_t waittime)
{
	uint8_t res = 1;
	u8 times = 3,get_Wait_flg;
	uint16_t wait = waittime,len,i;
	const char *cmdTmp = "AT+ICCID\r\n";
	const char *strx,*stry;
	//memset(Usart2_RX_BUF , 0 , 64);
	char *ACkOK = "OK";
  times = 10;
	while(times--){
    USART2_ready_buf_ok = 0;
    memset(USART2_ready_buf,0,USART2_BUF_SIZE);
    USART2_SendNByte((uint8_t *)cmdTmp, strlen((const char *)cmdTmp));
    while(waittime)
    {
      
      waittime--;	
      delay_ms(10);
      //AT_AIR720_DEBUG_F("%s:wait len!!!!","AT+HTTPACTION");
      if (USART2_ready_buf_ok == RevOK)
      {   
        strx = (const char*)USART2_ready_buf;
        //打印返回指令
        for(i = 0;i< USART2_ready_buf_len;i++)
          printf("%02X ",USART2_ready_buf[i]);
        printf("\r\n");
      
      /*
      AT+ICCID

      +ICCID: 89860464011970002199

      OK
      */
        //检索89860464011970002199之前的"\r\n" 
        strx = strstr((const char*)strx, "\r\n+ICCID: 8986" );
        if(strx == NULL)
        {
          AT_AIR720_DEBUG_F("strx == NULL\r\n");
          break;
        }
        strx+=10;
        //检索89860464011970002199之后的"\r\n" 
        stry = strstr((const char*)(strx), "\r\n" );
        if(stry == NULL)
        {
          AT_AIR720_DEBUG_F("stry == NULL\r\n");
          break;
        }
        len = (int)(stry)-(int)(strx);
        
        //
        if((len<=0)||(len>20)||(len>sizeof(Air_ICCID)))
        {
          AT_AIR720_DEBUG_F("((len<=0)||(len>17)||(len>sizeof(Air_ICCID)))\r\n");
          AT_AIR720_DEBUG_F("len=%d,stry=0x%8X,strx=0x%8X\r\n",len,(int)stry,(int)strx);
          break;
        }
        //中间段为IMEI
        memset(Air_ICCID,0,sizeof(Air_ICCID));
        for(i = 0;i < len;i++)
        {
          if((*(strx+i)>='0')||(*(strx+i)<='9'))
          {
            Air_ICCID[i]= *(strx+i);
          }
          else{
            memset(Air_ICCID,0,sizeof(Air_ICCID));
            AT_AIR720_DEBUG_F("((*(strx+i)<'0')||(*(strx+i)>'9'))\r\n");
            return 0;
          }
        }
        AT_AIR720_DEBUG_F("Air_ICCID=%s\r\n",Air_ICCID);
        //USART2_SendNByte(Air_IMEI,len);
        //AT_AIR720_DEBUG("\r\n");
        
        
        return 0;
  
      }
    
      delay_ms(300);
    }
  }
  return res;

}

uint8_t bcd_h_asc ( uint8_t data)
{
	return ((data>>4)+0x30);
}
uint8_t bcd_l_asc ( uint8_t data)
{
	return ((data&0x0f)+0x30);
}
static uint8_t check_code(uint8_t size,uint8_t *buf)
{
	uint8_t i;
	uint8_t check_c ;
	if(size<5)
		return 0;
	
	check_c =buf[2];                               //            
	for(i=3;i<(size-1);i++)
	check_c =check_c^buf[i];
	 
	return check_c;
}
extern config_t Config;
extern uint8_t LoRa_receive_buf[LoRa_RCV_BUF_SIZE];

extern volatile uint32_t Air720RestCounter;
#define AIR720_SQ_DEPTH (8)
#define AIR720_SQ_WIDTH (128)
extern sequeue_t *SX1276_Send_sq_init(uint8_t row,uint16_t col);

	
sequeue_t * Air720_Send_Sq;
sequeue_t * Air720_SqInit(void)
{    	 
	return Create_Empty_Sequeue(AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);

}

sequeue_t * Air720_Rev_Sq;
sequeue_t * Air720_RevSqInit(void)
{    	 
	return Create_Empty_Sequeue(AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);

}
tCounterTimeOut_t time_gw_heartbeat;
tCounterTimeOut_t time_gw_force_rst;
void Air720_Init(void)
{    	 
	GPIO_InitTypeDef    GPIO_InitStructure;

  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);//使能GPIOB时钟

  //GPIO初始化设置
  GPIO_InitStructure.GPIO_Pin = AIR720_RESET_PIN;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式
  GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;//推挽输出
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//上拉
  GPIO_Init(GPIOD, &GPIO_InitStructure);//初始化
	GPIO_ResetBits(GPIOD,  AIR720_RESET_PIN);

	delay_ms(500);
	GPIO_SetBits(GPIOD,AIR720_RESET_PIN);
	

	Air720_Send_Sq = Air720_SqInit();
	Air720_Rev_Sq = Air720_RevSqInit();
  
  time_gw_heartbeat.counter =TickCounter;
  time_gw_heartbeat.timeOut =60*1000;
  
	
}
Uint8 AT[]="AT\r\n";
#define SERVICE_IP 
tAT_AIRE720_StateCodes AT_aire720_State = AT_AIRE720_STATE_INIT;
extern GATE_CONFIG_T gt_config_para;
tCounterTimeOut_t time_at_air720_receive;
#define UDP_CONNECT_RETRY_TIMES (50)
void Air720_send(uint8_t*pbuf, uint8_t Size)
{
  char at_cmd[32];
  uint8_t at_len;
  at_len = sprintf((char *)at_cmd,"AT+CIPSEND=%d\r\n",Size);
  
  USART2_SendNByte((uint8_t *)at_cmd, at_len);	
  delay_ms(10);
  USART2_SendNByte((uint8_t *)pbuf, Size);	
  /*
	if(air_send_cmd(at_cmd, ">", 2))
	{
		USART2_SendNByte((uint8_t *)pbuf, Size);	
		//AT_AIR720_DEBUG_F("UDP send ready!!!!");
	
	}	
*/
}
uint16_t  UDP_0C_frame(void)
{	

	uint8_t temp,index;
	uint8_t check;

	uint8_t i;
  uint8_t frame[128];
	tUNION32_T ptmp_32;
  
  index = 0;
	frame[index++]=0xFF;			
	frame[index++]=0xEE;
	frame[index++]=0x00;			
	frame[index++]=0x00;
	
	frame[index++]=0x0C;  // 1        
		
	frame[index++]=gt_config_para.DevId[0]; 	//网关ID(4B)              
	frame[index++]=gt_config_para.DevId[1];
	frame[index++]=gt_config_para.DevId[2]; 
	frame[index++]=gt_config_para.DevId[3];

	frame[index++]=0x00;			//预留
	frame[index++]=0x00;			//预留
	frame[index++]=0x00;			//
	frame[index++]=0x00;      //是否加密，网关自己的0c指令不关注
  
	frame[index++]=gt_config_para.DevId[0]; 	//网关ID(4B)              
	frame[index++]=gt_config_para.DevId[1];
	frame[index++]=gt_config_para.DevId[2]; 
	frame[index++]=gt_config_para.DevId[3];
  
	frame[index++]=gt_config_para.DevType;    //网关类型  0x1,网关  0x2,液位仪  0x3,采集器  0x4,NB油机  0x5,NB液位仪  0x9,英泰赛福模块
	frame[index++]=0x00;                      //通道号
  
  ptmp_32.data_32=CURRENT_SOFTWARE_VER;
	frame[index++]=ptmp_32.data_8[0]; 	      //网关App版本号(4B)              
	frame[index++]=ptmp_32.data_8[1];
	frame[index++]=ptmp_32.data_8[2]; 
	frame[index++]=ptmp_32.data_8[3];


	frame[index++]=gt_config_para.BLVer[0]; 	//网关BL版本(4B)              
	frame[index++]=gt_config_para.BLVer[1];
	frame[index++]=gt_config_para.BLVer[2]; 
	frame[index++]=gt_config_para.BLVer[3];


	frame[index++]=gt_config_para.BLVer[0]; 	//网关Set版本(2B)   低16位           
	frame[index++]=gt_config_para.BLVer[1];
	frame[index++]=gt_config_para.RstCnt[0];  //复位次数
	frame[index++]=gt_config_para.RstCnt[1];


	frame[index++]=0x00;  //逻辑和校验

	frame[2] = ((index-5) >> 0) & 0xff;
	frame[3] = ((index-5) >> 8) & 0xff;
	
  
  //计算逻辑和校验
	check =0x00;
	for(i=0;i<(index-1);i++)
	{
		check = check ^ frame[i];
		
	}	
		
	frame[index-1]=check;
	
	
  AT_AIR720_DEBUG_F("0C len=%02d,msg=\r\n",index);
  AT_AIR720_DEBUG_H(frame,index);
  AT_AIR720_DEBUG("\r\n");
  
  //将组装好的0D包，入队列
  En_Queue(Air720_Send_Sq,frame,sizeof(frame),index);
	

//      
	return (index+1);
}

int Air720_analysis(uint8_t *sbuf,uint8_t slen){
	int ReturnCode = -1;
	uint8_t  check=0;
	uint8_t  scrc=0x00;
  uint8_t  at720frame[128];
  uint8_t  index;
  uint8_t  temp;
  uint32_t uTemp_32=0;
  int i;
	tUNION32_T *ptmp_32 = NULL;
	tUNION16_T *ptmp_16 = NULL;
	uint8_t  findChannel=0;
  uint8_t   offset=0;
	uint32_t  fCMD1=0;
	uint32_t  fGwID=0;
  uint8_t   fencrypt=0;
	uint32_t  fNodeID=0;
  uint32_t  fport=0;
  uint32_t  fgun=0;
  uint8_t   fDevType=0;
  uint8_t   fChannel=0;
  uint32_t  fAppVer=0;
  uint32_t  fBLVer=0;
  uint32_t  fSetVer=0;
  
  
  IWDG_Feed();														//喂狗
	//校验
	if((sbuf==NULL)||(slen == 0))
	{
		AT_AIR720_DEBUG_F("error:sbuf == NULL,or slen == 0\r\n");
		return ReturnCode;
	}
	//帧头(1Byte)
	if((sbuf[0]!=0xFF)||(sbuf[1]!=0xEE))
	{
		AT_AIR720_DEBUG_F("error:帧头错误,0x%02X%02X\r\n",sbuf[0],sbuf[1]);
		return ReturnCode;
	}
	//帧长度(1Byte)
	if((sbuf[2]!=slen-5)||(sbuf[3]!=0))
	{
		AT_AIR720_DEBUG_F("error:sbuf[2]!=slen-5,sbuf[2]=0x%02X,slen=0x%02X\r\n",sbuf[2],slen);
		return ReturnCode;
	}
	//和校验
  check = 0;
  for(i=0;i<slen-1;i++)
		{
			check = check ^ sbuf[i];
		}
	scrc = sbuf[slen-1];
	if(check != scrc)
	{
		AT_AIR720_DEBUG_F("error:Sum check error!,check=0x%02X,scrc=0x%02X\r\n",check,scrc);
		return ReturnCode;
	}
  //
  //网关ID是否匹配
  offset = 5;
  fGwID = ((tUNION32_T *)(sbuf+offset))->data_32;
  uTemp_32 = ((tUNION32_T *)&gt_config_para.DevId[0])->data_32;
  if(fGwID!=uTemp_32){
    AT_AIR720_DEBUG_F("error:网关ID不匹配thisGwID=0x%08X,fGwID=0x%08X\r\n",uTemp_32,fGwID);
		return ReturnCode;
  }
  
  IWDG_Feed();														//喂狗
  //解析
  if(sbuf[4]==0x0C){//心跳相关的指令
    offset = 13;
    fNodeID = ((tUNION32_T *)(sbuf+offset))->data_32;
  
    //NodeID是否匹配
    //查询设备是否已在列表中
    findChannel=0;
    for(i=0;i<NODE_NUM;i++){
      ptmp_32 = (tUNION32_T *)&node_config_para[i].DevId[0];
      if(ptmp_32->data_32==fNodeID){
        findChannel=i+1;
        break;
      }
    }
    if(findChannel){
      AT_AIR720_DEBUG_F("找到设备绑定信息!ID=0x%08X,Channel=%d\r\n",fNodeID,findChannel);
      
      AT_AIR720_DEBUG_F("0C len=%02d,msg=\r\n",slen);
      AT_AIR720_DEBUG_H(sbuf,slen);
      AT_AIR720_DEBUG("\r\n");
      
      //帧结构完全一致，只需转发
      En_Queue(Air720_Send_Sq,sbuf,slen,slen);
      set_led_en_process();
      start_led(findChannel-1,500,80,400);
      //心跳计数器清零
      //time_gw_heartbeat.counter = TickCounter;
      return 0;
    }
    else{
      AT_AIR720_DEBUG_F("未找到设备绑定信息!ID=0x%08X\r\n",fNodeID);
      return -1;
    }
  }
  //非加密FFEE45000DFFFFFFFF00000000190001630101303030303030313133303638303030303030353933303939BB1AFF8601303130323033303035383034303239363538303531317481
  //加  密FFEE37000D03000161000000011B00016301000000123456789000001234567890BB188101A111000101010112345678901234567890000100E51254
  else if(sbuf[4]==0x0D){//业务上报相关的指令
    offset = 13;
    fNodeID = ((tUNION32_T *)(sbuf+offset))->data_32;
  
    //NodeID是否匹配
    //查询设备是否已在列表中
    findChannel=0;
    for(i=0;i<NODE_NUM;i++){
      ptmp_32 = (tUNION32_T *)&node_config_para[i].DevId[0];
      if(ptmp_32->data_32==fNodeID){
        findChannel=i+1;
        break;
      }
    }
    if(findChannel){
      
      set_led_en_process();
      start_led(findChannel-1,500,20,400);
      AT_AIR720_DEBUG_F("找到设备绑定信息!ID=0x%08X,Channel=%d\r\n",fNodeID,findChannel);
      //创建0D上报帧
      index=0;
      for(i=0;i<17;i++){
        //前17个字节一致，
        at720frame[index++] = sbuf[i];
      }
      fport = sbuf[17];
      at720frame[index++] = (findChannel-1)*2 + fport + 1;  //端口号（1-12）
      fgun = sbuf[18];
      at720frame[index++] = fgun+ 1;  //枪号（1-8）
      
      fencrypt = sbuf[12];//是否加密，指英泰赛福
      
      //如果是加密的
      if(fencrypt){
        
        //UDP总累计油量(12B)  比如0000001234.56
        offset=20;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,6);
        
        //UDP总累计金额(12B), 比如0000002222.56
        offset=27;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,6);
        
        temp = index;						// 记录当前长度
        //  非加密真实返回数据
        //	BB 1A FF 86 01   32 34 31 36 31 35    30 30 30 30 30 31     30 30 30 30 35 33      35 33 31 39     74 												
        at720frame[index++]=0xBB;   //32		   //帧头                                      35
        at720frame[index++]=0x1A;   //33			 //帧长度                                    36      
        at720frame[index++]=0xFF;   //34		   //帧号                                      37  
        at720frame[index++]=0x86;   //35		   //86表示当次加油数据                        38
        
        at720frame[index++]=0x01;   //36      //状态                                		   39
        
        
        //日期,(6B),05日14时19分
        offset=41;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,3);
        
        //加油机返回记录   1升
        offset=46;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,3);
        
        //加油机返回记录金额
        offset=51;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,3);
        //单价  53.19				
        offset=55;
        index+=Hex2Ascii(at720frame+index,sbuf+offset,2);
        
        at720frame[index++] = 0x00; //小帧逻辑和校验
        
        //计算小帧长度，固定0x1A
        //小帧逻辑和校验
        check = 0;
        
        AT_AIR720_DEBUG_F("temp=%d\r\n",temp);
        for(i=temp+2;i<index-1;i++)
        {
          check = check ^ at720frame[i];
        }
        at720frame[index-1] = check; //小帧逻辑和校验
        
        
        
        at720frame[index++] = 0x00; //UDP大帧逻辑和校验校验
        //计算UDP帧长度，
        at720frame[2] = ((index-5) >> 0) & 0xff;
        at720frame[3] = ((index-5) >> 8) & 0xff;
        check = 0;
        for(i=0;i<index-1;i++)
        {
          check = check ^ at720frame[i];
        }
        //计算UDP帧逻辑和校验
        at720frame[index-1] = check;//UDP大帧逻辑和校验校验
        
        AT_AIR720_DEBUG_F("0D len=%02d,msg=\r\n",index);
        AT_AIR720_DEBUG_H(at720frame,index);
        AT_AIR720_DEBUG("\r\n");
        
        //将组装好的0D包，入队列
        En_Queue(Air720_Send_Sq,at720frame,sizeof(at720frame),index);
        //心跳计数器清零
//        time_gw_heartbeat.counter = TickCounter;
        return 0;
      }
      //否则为非加密的
      else{
        
        //从第19-69，共51个数是一致的
        memcpy(at720frame+index,sbuf+index,51);
        index+=51;
        at720frame[index++] = 0x00; //小帧逻辑和校验
        
        //计算小帧长度，固定0x1A
        at720frame[44]=0x1A;
        //小帧逻辑和校验
        check = 0;
        temp = 43;
        AT_AIR720_DEBUG_F("temp=%d\r\n",temp);
        for(i=temp+2;i<index-1;i++)
        {
          check = check ^ at720frame[i];
        }
        at720frame[index-1] = check; //小帧逻辑和校验
        
        
        
        at720frame[index++] = 0x00; //UDP大帧逻辑和校验校验
        //计算UDP帧长度，
        at720frame[2] = ((index-5) >> 0) & 0xff;
        at720frame[3] = ((index-5) >> 8) & 0xff;
        check = 0;
        for(i=0;i<index-1;i++)
        {
          check = check ^ at720frame[i];
        }
        //计算UDP帧逻辑和校验
        at720frame[index-1] = check;//UDP大帧逻辑和校验校验
        
        AT_AIR720_DEBUG_F("0D len=%02d,msg=\r\n",index);
        AT_AIR720_DEBUG_H(at720frame,index);
        AT_AIR720_DEBUG("\r\n");
        
        //将组装好的0D包，入队列
        En_Queue(Air720_Send_Sq,at720frame,sizeof(at720frame),index);
        //心跳计数器清零
//        time_gw_heartbeat.counter = TickCounter;
        return 0;
      }
      
    }
    else{
      AT_AIR720_DEBUG_F("未找到设备绑定信息!ID=0x%08X\r\n",fNodeID);
      return -1;
    }
    
  }
  else if(sbuf[4]==0x0E){
  }
  return 0;
}

/**
  * @brief	实现升级包的读，并完成写
  * @param	cmd			发送的命令
  * @param	ack			期待的应答结果
  * @param	waittime 	等待时间(单位:10ms)
  * @retval	0 发送成功
			1 发送失败
  */
int   Update_Read_Write(uint16_t srclen)
{
#define DOWM_BYTE_SIZE (1024)//每次下载的字节大小,必须为整字节数
#define DOWM_WORD_SIZE (DOWM_BYTE_SIZE>>2)//	
	
	uint16_t packetsize = DOWM_BYTE_SIZE;
	
	int16_t res =-1;
  uint16_t i,j;
	uint16_t cnt = 0 ,len_tail,cnt_tail,byte_tail,dlen,wlen;
	uint8_t *pBuff = NULL ;
  uint8_t flg,cntOk;
	Uint32 BuffTmp,addr;
	BuffTmp = 0;
	BuffTmp += packetsize + 41;//总bufer大小，41为指令的大小
	if(BuffTmp>USART2_BUF_SIZE)
	{
		AT_AIR720_DEBUG_F("buffer is SMALLL!!!");
		return 1;
	}
	
	cnt = srclen/(packetsize);//计算下载次数
	len_tail = srclen%(packetsize);//不够一包剩余字节

	addr = APP3_SECTOR1_START_ADD;//flash编程地址
	FLASH_If_EraseSector(addr);
	//packetsize = 10;
	cntOk = 0;
	//while(1)
	{

	for(i=0;i<cnt;i++)
  {
    AT_AIR720_DEBUG_F("down: %d\n!!!",i);
    pBuff = air_send_HTTPREADCmd(addr,packetsize,300);
    if(pBuff != NULL)//1024
    { 
      //写flash
      for(j = 0; j<(packetsize>>2) ;j++)
      {
        BuffTmp = *(Uint32*)(pBuff + j*sizeof(Uint32)); 
        FLASH_ProgramWord((uint32_t)(addr + j*sizeof(Uint32)), BuffTmp);
      }
      cntOk++;
      addr +=packetsize;
    }
   //指示在下载
   if(gt_config_para.pcb_ver ==0){
     LED_Set(0,LED_FLASH); 
   }
   else{
     LED_MODE_Set(LED_FLASH);
   }
  }

} 
    if(i != cntOk)
    {
      AT_AIR720_DEBUG_F("down is FAIL!!!");
      return -1;
    }
		if(len_tail)
		{
      pBuff = air_send_HTTPREADCmd(addr,len_tail,300);
			if(pBuff != NULL)//1024
			{
				cnt_tail= len_tail>>2;
				//写flash
				for(i = 0; i<cnt_tail ;i++)
				{
					BuffTmp = *(Uint32*)(pBuff + i*sizeof(Uint32)); 
					FLASH_ProgramWord((uint32_t)(addr + i*sizeof(Uint32)), BuffTmp);
				}
	
        res = 0;
			}
	
		}
    return res;
	
	}

int aire720_closeUDP_openHTTP(const Uint8 *pSrc,Uint8 len){
  
  Uint8 sout[128];
  Uint32 lout;
  int res=255;
  Uint32 uTemp32 = 0;
  
    AT_AIR720_DEBUG_F("关闭UDP或TCP,AT+CIPCLOSE!!!!,%d\r\n",uTemp32++);
    if(air_send_cmd("AT+CIPCLOSE\r\n", "CLOSE OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+CIPCLOSE  ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+CIPCLOSE  failed!!!!\r\n");
    }
    
    AT_AIR720_DEBUG_F("设置HTTP功能的承载类型,AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"!!!!,%d\r\n",uTemp32++);
		if(air_send_cmd("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"! ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"! failed!!!!\r\n");
    }
    
		AT_AIR720_DEBUG_F("设置pdp承载参数之APN,AT+SAPBR=3,1,\"APN\",\"\"!!!!,%d\r\n",uTemp32++);
		if(air_send_cmd("AT+SAPBR=3,1,\"APN\",\"\"\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=3,1,\"APN\",\"\" ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+SAPBR=3,1,\"APN\",\"\" failed!!!!\r\n");
    }
    
		IWDG_Feed();	
		AT_AIR720_DEBUG_F("激活该承载的GPRS PDP上下文,AT+SAPBR=1,1!!!!,%d\r\n",uTemp32++);
		if(air_send_cmd("AT+SAPBR=1,1\r\n", "OK", 200))	      /* 激活该承载的GPRS PDP上下文 模式 */
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=1,1 ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+SAPBR=1,1 failed!!!!\r\n");
    }

		AT_AIR720_DEBUG_F("查询下承载的状态,AT+SAPBR=2,1!!!!,%d\r\n",uTemp32++);
		if(air_send_cmd("AT+SAPBR=2,1\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=2,1 ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+SAPBR=2,1 failed!!!!\r\n");
    }
    
		IWDG_Feed();	
		AT_AIR720_DEBUG_F("HTTP协议栈初始化,AT+HTTPINIT!!!!,%d\r\n",uTemp32++);
		if(air_send_cmd("AT+HTTPINIT\r\n", "OK", 200))	      /* 设置为快发模式 */
		{
			AT_AIR720_DEBUG_F("AT+HTTPINIT ok!!!!\r\n");
		}
    else{
      AT_AIR720_DEBUG_F("AT+HTTPINIT failed!!!!\r\n");
    }
    
    memset(sout,0,sizeof(sout));
    lout=sprintf((char *)(sout),"AT+HTTPPARA=\"URL\",\"");
    memcpy(sout+lout,(char *)pSrc,len);
    lout+=len;
    lout=sprintf((char *)(sout+lout),"\"\r\n");
    
		IWDG_Feed();	
		AT_AIR720_DEBUG_F("建立http链接,%s!!!!,%d\r\n",sout,uTemp32++);
		if(air_send_cmd((char *)&sout[0], "OK", 300))/*建立http链接*/
		{
			AT_AIR720_DEBUG_F("AT+HTTPPARA OK!!!!\r\n");
      res=0;
		}
    else{
      AT_AIR720_DEBUG_F("AT+HTTPPARA failed!!!!\r\n");
    }
    return res;
}

//const char *pURl = "http://47.104.15.180:8081/chfs/shared/A61010002.bin";//
int32_t Down_Update_Packet(const Uint8 *pSrc,Uint8 len/*路径长度*/)
{
	int8_t res=-1;
  Uint8 tmp[100];
	 char *ptmp;
	Uint16 cmdLen;
	Uint16 reTry=0;
	static Uint32 codelen,vaildcodelen;
	 //关闭之前的链接
	
	//http配置
	#if 1//ok
    //一旦关闭之前的连接，则等待一段时间后，必须重新建立连接，可通过强制复位实现
    time_gw_force_rst.counter=TickCounter;
    time_gw_force_rst.timeOut=5*60*1000;
    AT_AIR720_DEBUG_F("复位时间设为5分钟\r\n");
  
  
    aire720_closeUDP_openHTTP(pSrc,len);
  #if 0
		if(air_send_cmd("AT+CIPCLOSE\r\n", "CLOSE OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+CIPCLOSE  ok!!!!\r\n");
		}
		if(air_send_cmd("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=3,1 ok!!!!\r\n");
		}
		
		if(air_send_cmd("AT+SAPBR=3,1,\"APN\",\"\"\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=3,1 ok!!!!\r\n");
		}
		IWDG_Feed();	
		if(air_send_cmd("AT+SAPBR=1,1\r\n", "OK", 200))	      /* 激活该承载的GPRS PDP上下文 模式 */
		{
			AT_AIR720_DEBUG_F("AT+SAPBR ok!!!!\r\n");
		}

		if(air_send_cmd("AT+SAPBR=2,1\r\n", "OK", 200))
		{
			AT_AIR720_DEBUG_F("AT+SAPBR=2,1 ok!!!!\r\n");
		}
		IWDG_Feed();	
		if(air_send_cmd("AT+HTTPINIT\r\n", "OK", 200))	      /* 设置为快发模式 */
		{
			AT_AIR720_DEBUG_F("AT+HTTPINIT ok!!!!\r\n");
		}

		ptmp ="AT+HTTPPARA=\"URL\",\"";
		memcpy(tmp,(void *)ptmp,strlen(ptmp));
    memcpy(tmp+strlen(ptmp),(char *)pSrc,len);
    //strcat((char *)&tmp[0],(char *)pSrc);
    memcpy(tmp+strlen(ptmp)+len,"\"\r\n",strlen("\"\r\n"));
		//strcat((char *)&tmp[0],"\"\r\n");
		IWDG_Feed();	
		if(air_send_cmd((char *)&tmp[0], "OK", 300))/*建立http链接*/
		{
		
			AT_AIR720_DEBUG_F("AT+HTTPPARA OK!!!!\r\n");
			
		}
    #endif
		#endif
		IWDG_Feed();	
		//发送"AT+HTTPACTION=0\r\n"，等待get数据成功，并且获取数据长度
    for(reTry=0;reTry<5;reTry++){
      if(air_send_HTTPACTIONCmd(NULL, &codelen, 500))/*建立http链接*/
      {
        
        AT_AIR720_DEBUG_F("AT+HTTPACTION=0,get len=%d!!!!,reTry=%d\r\n",codelen,reTry);
        if((codelen>=10)&&(codelen<=128*1024)){
          break;
        }
      }
    }    
    if((codelen<10)||(codelen>128*1024)){
      AT_AIR720_DEBUG_F("升级包长度错误\r\n");
      NVIC_SystemReset();// 强制复位
    }
		IWDG_Feed();	
#if 0	
		if(air_send_HTTPREADCmd(0,codelen,  300))/*读取数据codelen = 10; */
		{
		
			AT_AIR720_DEBUG_F("AT+HTTPREADCmd=0!!!!,%d\r\n",vaildcodelen);
			res = 0;
		}
	#else
return	Update_Read_Write(codelen);

#endif		
}

#define F1_CMD2_DOWM_SVR2WG_START_UPDATE  0x01      //下行，网关->采集器，启动升级
tUpdare_Paras  Updare_Paras_form_S;
/********************************
  * @brief  Air720_Update_Down
  * @par    pddata  	[tUpdare_Paras*]  
  * @
  * @retval 0初始成功，非0失败
  ********************************/
int8_t Air720_Update_Down(void)
{
	//切换模式
	tUpdare_Paras *ptmp = &Updare_Paras_form_S;
	
	//Uint16 len = strlen((const char *)pURl);
	//ptmp->srcUrlLen = len;
	if((ptmp == NULL) || (ptmp->srcUrlLen < 30 ))//URL太短，小于50个字符，认为不合法
	{
		AT_AIR720_DEBUG_F("input para error:pddata == NULL\r\n");
		return -EINVAL;
	}
	AT_AIR720_DEBUG_F("Air720_Update_Down\r\n");
	//模式切换
	if(Down_Update_Packet(&ptmp->ppath[0],ptmp->srcUrlLen)!=0){
		AT_AIR720_DEBUG_F("Air720_Update_Down exit: dowm fail!!!!!!!!!!!\r\n");
  }
	else
  {
    Clr_Queue(lora_rx_sq);
    Clr_Queue(lora_tx_sq);
    set_ota_http_time_init();
    
    if(Updare_Paras_form_S.desDeviceType == DEVICE_TYPE_OIL_GATEWAY){//升级网关
      set_ota_upstate(0x71,Updare_Paras_form_S.firmWareType);
      set_main_WorkMode(GATEWAY_UPDATE_MODE);
    }
    if(Updare_Paras_form_S.desDeviceType == DEVICE_TYPE_NODE){//升级采集器
      
      OTA_Wg2Node(DEVICE_TYPE_NODE,0xFFFFFFFF,OTA_UPDATE_FIREWARE_TYPE_APP,0xFFFFFFFF);// 
      set_main_WorkMode(NODE_UPDATE_MODE);
    }
		AT_AIR720_DEBUG_F("Air720_Update_Down OK!!\r\n");
  }
  return 0;
}

/********************************
  * @brief  Air720_Receive_Handle
  * @par    sbuf  	[uint8_t*]  帧缓存地址
  * @par    slen    [uint8_t]   帧长度
  * @retval 0初始成功，非0失败
  ********************************/
DEV_WORK_MODE_T Air720_Receive_Handle(uint8_t *sbuf,uint16_t slen)
{
	int8_t ReturnCode = -1;
	uint8_t  scrc=0x0000,cmd1Tmp,cmd2Tmp;
	DEV_WORK_MODE_T GtWorkMode =DEV_MODE_ALL ;
  uint8_t  O9cmd2=0;
	int  i,j;
	uint8_t  check=0;
	uint8_t  uTemp_8=0;
	uint8_t  findChannel=0;
	uint32_t uTemp_32=0;
  uint8_t  data_offset=0;
	uint32_t addrPkg=0;
  uint32_t id=0;
  uint32_t ver=0;
  uint8_t  state=0;
  //uint8_t  arair720[8][128]={0};
	uint16_t sendLen,RevLen,sumCheck;
  static uint32_t cmdCnt=0;
  
	tUNION32_T *ptmp_32 = NULL,*ptmp_32_2=NULL;
	tUNION16_T *ptmp_16 = NULL;
  uint8_t *pbuf;
  //Frame09_t *pdst;
	//校验
	
	if((sbuf == NULL)||(slen == 0))
	{
		AT_AIR720_DEBUG_F("error:sbuf == NULL,or slen == 0,%p\r\n",sbuf);
		return GtWorkMode;
	}
  
  AT_AIR720_DEBUG_F("len=%d,msg=\r\n",USART2_ready_buf_len);
  for(i=0;i<USART2_ready_buf_len;i++)
    printf("%02X ",sbuf[i]);
  printf("\r\n");
  
  pbuf = sbuf;
  
  
	if((pbuf[0]==0xFF)&&(pbuf[1]==0xEE)){
    En_Queue(Air720_Rev_Sq,pbuf+2,AIR720_SQ_WIDTH,pbuf[2]+5);//AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);
  }
  
  for(i=0;i<USART2_ready_buf_len;i++){
    if((pbuf[i+0]==0x0D)&&(pbuf[i+1]==0x0A)&&(pbuf[i+2]==0xFF)&&(pbuf[i+3]==0xEE)){
      En_Queue(Air720_Rev_Sq,pbuf+2,AIR720_SQ_WIDTH,pbuf[i+4]+5);//AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);
    }
  }
  
  //0D 0A FF EE 05 00 0D 0E 00 01 61 77 0D 0A 
  
  
	//帧头(1Byte)
	if((pbuf[0]==0xFF)&&(pbuf[1]==0xEE)){
    slen = pbuf[2]+5;
    //接收到任何FF EE的数据，复位时间后延
    time_gw_force_rst.counter=TickCounter;
    AT_AIR720_DEBUG_F("接收到服务器指令,CMD=0x%02X,cmdCnt=%010d\r\n",pbuf[4],cmdCnt++);
  }
	else
	{
//		AT_AIR720_DEBUG_F("非服务器指令");
//		for(i=0;i<USART2_ready_buf_len;i++)
//		printf("%02X ",pbuf[i]);
//		return ReturnCode;
    
    for(i=0;i<USART2_ready_buf_len;i++){
      
    }
    
    for(i=0;i<USART2_ready_buf_len;i++){
      
      if((pbuf[i+0]==0x0D)&&(pbuf[i+1]==0x0A)&&(pbuf[i+2]==0xFF)&&(pbuf[i+3]==0xEE)&&(pbuf[i+4]==0xF1)){
        //接收到任何FF EE的数据，复位时间后延
        time_gw_force_rst.counter=TickCounter;
        AT_AIR720_DEBUG_F("接收到服务器指令,CMD=0x%02X,cmdCnt=%010d\r\n",(pbuf[i+6]),cmdCnt++);
        slen = pbuf[i+4]+5;
        pbuf = pbuf+i+2;
        break;
      }
      if(i==USART2_ready_buf_len-1){
        AT_AIR720_DEBUG_F("非服务器指令,Rx=\r\n");
        AT_AIR720_DEBUG_NB(pbuf,USART2_ready_buf_len);
        printf("\r\n");
        return GtWorkMode;
      }
    }
	}
  
 	//和校验
  check = 0;
  for(i=0;i<slen-1;i++)
	{
		check = check ^ pbuf[i];
	}
	scrc = pbuf[slen-1];
	if(check != scrc)
	{
		AT_AIR720_DEBUG_F("error:Sum check error!,check0x%02X,scrc=0x%02X\r\n",check,scrc);
		return GtWorkMode;
	}

	pbuf+=2;//指向长度
	//帧长度(1Byte)
	ptmp_16 =(tUNION16_T *)pbuf;
	RevLen = ptmp_16->data_16 ;
	pbuf+=2;//指向命令字

   //解析
	ptmp_16 =(tUNION16_T *)pbuf;
	cmd1Tmp = ptmp_16->data_8[0];
	cmd2Tmp = ptmp_16->data_8[1];
	pbuf  +=2;//指向设备ID
	if(cmd1Tmp == F1_CMD2)
	{
		switch(cmd2Tmp)
		{
			case 0xFF://启动升级，F1_CMD2_DOWM_SVR2WG_START_UPDATE
				//
        AT_AIR720_DEBUG_F("接收到升级指令!!!!!!!!!!!!!!!!!!!!!!\r\n");
				ptmp_32 = (tUNION32_T *)pbuf;
				ptmp_32_2 = (tUNION32_T *)&gt_config_para.DevId;
				pbuf+=4;//指向参数信息
				if((ptmp_32->data_32 == ptmp_32_2->data_32) ||(ptmp_32->data_32== 0xFFFFFFFF))
				{//提取信息
					pbuf+=1;
					Updare_Paras_form_S.firmWareType = *pbuf++;//提取固件类型
					Updare_Paras_form_S.desDeviceType = *pbuf++;
					ptmp_32 =(tUNION32_T *)pbuf;
					ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.desDeviceID;
					ptmp_32_2->data_32 = ptmp_32->data_32;
					pbuf +=4;
					
					Updare_Paras_form_S.desDeviceChannel = *pbuf++;
					
					ptmp_32 =(tUNION32_T *)pbuf;
					ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.softWareOldVer;
					ptmp_32_2->data_32 = ptmp_32->data_32;
					pbuf +=4;
					
					ptmp_32 =(tUNION32_T *)pbuf;
					ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.softWareNewVer;
					ptmp_32_2->data_32 = ptmp_32->data_32;
					pbuf +=4;
					//路径长度
					Updare_Paras_form_S.srcUrlLen = *pbuf++;
          AT_AIR720_DEBUG_F("路径长度=%d\r\n",Updare_Paras_form_S.srcUrlLen);
					//路径
					memcpy(Updare_Paras_form_S.ppath,pbuf,Updare_Paras_form_S.srcUrlLen);
          AT_AIR720_DEBUG_F("url=\r\n");
          AT_AIR720_DEBUG_NB(Updare_Paras_form_S.ppath,Updare_Paras_form_S.srcUrlLen);
          printf("\r\n");
					//
					GtWorkMode = GATEWAY_UPDATE_DOWN_MODE;
					AT_AIR720_DEBUG_F("F1_CMD2_DOWM_SVR2WG_START_UPDATE\r\n");
					
				}else
				{
					//id不匹配不做处理
				}
				break;
			case O9_CMD2:
				
			
				break;
      default:
        break;
		
		}
	
	
	}

    IWDG_Feed();														//喂狗
 
    return GtWorkMode; 
}

/********************************
  * @brief  Air720_Receive_Handle
  * @par    sbuf  	[uint8_t*]  帧缓存地址
  * @par    slen    [uint8_t]   帧长度
  * @retval 0初始成功，非0失败
  ********************************/
DEV_WORK_MODE_T Air720_Receive_Handler2(uint8_t *pbuf,uint16_t plen)//接收，拆包，入队列
{
  uint32_t i=0;
  static uint32_t rcvCnt=0;
	DEV_WORK_MODE_T GtWorkMode =DEV_MODE_ALL ;
	
  AT_AIR720_DEBUG_F("接收,rcvCnt=%d,plen=%d:\r\n",rcvCnt++,plen);
  if(plen<10)
    return DEV_MODE_ALL;
  AT_AIR720_DEBUG_NB(pbuf,plen);
  AT_AIR720_DEBUG("\r\n");
  
	if((pbuf[0]==0xFF)&&(pbuf[1]==0xEE)){
    En_Queue(Air720_Rev_Sq,pbuf,AIR720_SQ_WIDTH,pbuf[2]+5);//AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);
    AT_AIR720_DEBUG_F("单独，接收到服务器指令,len=%d\r\n",pbuf[2]+5);
    AT_AIR720_DEBUG_H(pbuf,pbuf[2]+5);
  }
  
  for(i=0;i<plen-5;i++){
    if((pbuf[i+0]==0x0D)&&(pbuf[i+1]==0x0A)&&(pbuf[i+2]==0xFF)&&(pbuf[i+3]==0xEE)){
      En_Queue(Air720_Rev_Sq,pbuf+i+2,AIR720_SQ_WIDTH,pbuf[i+4]+5);//AIR720_SQ_DEPTH,AIR720_SQ_WIDTH);
      AT_AIR720_DEBUG_F("复合，接收到服务器指令,len=%d\r\n",pbuf[i+4]+5);
      AT_AIR720_DEBUG_H(pbuf+i+2,pbuf[i+4]+5);
    }
    else{
     
    }
  }
  return GtWorkMode;
}

/********************************
  * @brief  Air720_Receive_process
  * @par    sbuf  	[uint8_t*]  帧缓存地址
  * @par    slen    [uint8_t]   帧长度
  * @retval 0初始成功，非0失败
  ********************************/
DEV_WORK_MODE_T Air720_Receive_process()//接收，拆包，入队列
{
  uint32_t i=0;
  uint8_t  sout[128]={0};
  uint8_t  lout=0;
  uint8_t *pbuf;
  uint8_t  slen=0;
	uint8_t  check=0;
	uint8_t  scrc=0x00;
  uint8_t  cmd1Tmp,cmd2Tmp;
  
	tUNION32_T *ptmp_32 = NULL;
  tUNION32_T *ptmp_32_2=NULL;
	tUNION16_T *ptmp_16 = NULL;
  
  tUpdate_t *pUpdateS =NULL;
  
	DEV_WORK_MODE_T GtWorkMode =DEV_MODE_ALL ;
  uint16_t RevLen;
  static uint32_t cmdCnt=0;
  
  
	if(!Check_Seqeue_Empty(Air720_Rev_Sq))
	{
    
		De_Queue(Air720_Rev_Sq,sout,sizeof(sout),(uint8_t *)&lout);
    
    AT_AIR720_DEBUG_F("处理服务器指令,cmdCnt=%d\r\n",cmdCnt++);
    
    pbuf=sout;
    slen = pbuf[2]+5;
    //和校验
    check = 0;
    for(i=0;i<slen-1;i++)
    {
      check = check ^ pbuf[i];
    }
    scrc = pbuf[slen-1];
    if(check != scrc)
    {
      AT_AIR720_DEBUG_F("error:Sum check error!,check0x%02X,scrc=0x%02X\r\n",check,scrc);
      return GtWorkMode;
    }

    pbuf+=2;//指向长度
    //帧长度(1Byte)
    ptmp_16 =(tUNION16_T *)pbuf;
    RevLen = ptmp_16->data_16 ;
    pbuf+=2;//指向命令字

     //解析
    ptmp_16 =(tUNION16_T *)pbuf;
    cmd1Tmp = ptmp_16->data_8[0];
    cmd2Tmp = ptmp_16->data_8[1];
    pbuf  +=2;//指向设备ID
    
    
    AT_AIR720_DEBUG_F("处理服务器指令,cmdCnt=%d,cmd1Tmp=0x%02X,cmd2Tmp=0x%02X,\r\n",cmdCnt,cmd1Tmp,cmd2Tmp);
    
    if(cmd1Tmp == F1_CMD2)
    {
      switch(cmd2Tmp)
      {
        case F1_CMD2_DOWM_SVR2WG_START_UPDATE://启动升级，
          //
          AT_AIR720_DEBUG_F("接收到升级指令!!!!!!!!!!!!!!!!!!!!!!\r\n");
          ptmp_32 = (tUNION32_T *)pbuf;
          ptmp_32_2 = (tUNION32_T *)&gt_config_para.DevId;
          pbuf+=4;//指向参数信息
          if((ptmp_32->data_32 == ptmp_32_2->data_32) ||(ptmp_32->data_32== 0xFFFFFFFF))
          {//提取信息
            pbuf+=1;
            Updare_Paras_form_S.firmWareType = *pbuf++;//提取固件类型
            Updare_Paras_form_S.desDeviceType = *pbuf++;
            ptmp_32 =(tUNION32_T *)pbuf;
            ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.desDeviceID;
            ptmp_32_2->data_32 = ptmp_32->data_32;
            pbuf +=4;
            
            Updare_Paras_form_S.desDeviceChannel = *pbuf++;
            
            ptmp_32 =(tUNION32_T *)pbuf;
            ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.softWareOldVer;
            ptmp_32_2->data_32 = ptmp_32->data_32;
            pbuf +=4;
            
            ptmp_32 =(tUNION32_T *)pbuf;
            ptmp_32_2 = (tUNION32_T *)&Updare_Paras_form_S.softWareNewVer;
            ptmp_32_2->data_32 = ptmp_32->data_32;
            pbuf +=4;
            //路径长度
            Updare_Paras_form_S.srcUrlLen = *pbuf++;
            AT_AIR720_DEBUG_F("路径长度=%d\r\n",Updare_Paras_form_S.srcUrlLen);
            //路径
            memcpy(Updare_Paras_form_S.ppath,pbuf,Updare_Paras_form_S.srcUrlLen);
            AT_AIR720_DEBUG_F("url=\r\n");
            AT_AIR720_DEBUG_NB(Updare_Paras_form_S.ppath,Updare_Paras_form_S.srcUrlLen);
            printf("\r\n");
//            //
//            i=10;
//            while(i--){
//              IWDG_Feed();														//喂狗
//              AT_AIR720_DEBUG_F("F1_CMD2_DOWM_SVR2WG_START_UPDATE\r\n");
//              delay_ms(1000);
//            }
//            return GtWorkMode;
            gt_config_para.is_udp_update = 1;//是UDP升级
            
            GtWorkMode = GATEWAY_UPDATE_DOWN_MODE;
            set_main_WorkMode(GtWorkMode);
            AT_AIR720_DEBUG_F("F1_CMD2_DOWM_SVR2WG_START_UPDATE\r\n");
            
          }else
          {
            //id不匹配不做处理
          }
          break;
        default:
          break;
      
      }
    
    }
    else if(0x0C){
      //接收到任何FF EE的数据，复位时间后延
      time_gw_force_rst.counter=TickCounter;
      AT_AIR720_DEBUG_F("心跳清零\r\n");
    }
    else if(0x0D){
    }
    else if(0xF2){
      if(cmd2Tmp==0x11){
        AT_AIR720_DEBUG_F("接收到复位网关指令!!!!!!!!!!!!!!!!!!!!!!\r\n");
        NVIC_SystemReset();// 复位
      }
    }
    
	}
  
  return GtWorkMode;
}
//////////////////////////////////////////////////////////////////////////////////////////////

int aire720_closeHTTP_openUDP(int AireConnectState){
  
  Uint8 sout[128];
  Uint32 lout;
  int res=255;
  int i=0;
  Uint32 uTemp32 = 0;
  
  static Uint32 CIICR_retry_time=0;
        
        if(AireConnectState){
          AT_AIR720_DEBUG_F("关闭UDP或TCP,AT+CIPCLOSE!!!!,%d\r\n",uTemp32++);
          if(air_send_cmd("AT+CIPCLOSE\r\n", "CLOSE OK", 200))
          {
            AT_AIR720_DEBUG_F("AT+CIPCLOSE  ok!!!!\r\n");
          }
          else{
            AT_AIR720_DEBUG_F("AT+CIPCLOSE  failed!!!!\r\n");
          }
        }
        AT_AIR720_DEBUG_F("AT,%d\r\n",uTemp32++);
        if(air_send_cmd("AT\r\n", "OK", 200))
        {
          AT_AIR720_DEBUG_F("AT ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT failed!!!!\r\n\r\n");
        }
        
        AT_AIR720_DEBUG_F("ATTE0,%d\r\n",uTemp32++);
        if(air_send_cmd("ATTE0\r\n", "OK", 200))
        {
          AT_AIR720_DEBUG_F("ATTE0 ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("ATTE0 failed!!!!\r\n\r\n");
        }
        
        AT_AIR720_DEBUG_F("设置为快发模式,AT+CIPQSEND=1,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIPQSEND=1\r\n", "OK", 200))	      // 设置为快发模式
        {
          AT_AIR720_DEBUG_F("AT+CIPQSEND ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CIPQSEND failed!!!!\r\n\r\n");
        }
        
        AT_AIR720_DEBUG_F("启动任务，设置APN,AT+CSTT,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CSTT\r\n", "OK", 200))	            // 启动任务，设置APN
        {
          AT_AIR720_DEBUG_F("AT+CSTT ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CSTT failed!!!!\r\n\r\n");
        }
        
        
        AT_AIR720_DEBUG_F("激活移动场景，获取IP地址,AT+CIICR%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIICR\r\n", "OK", 200))	            // 激活移动场景，获取IP地址
        {
          AT_AIR720_DEBUG_F("AT+CIICR ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CSTT failed!!!!retry=%d\r\n\r\n",CIICR_retry_time);
          CIICR_retry_time++;
          if(CIICR_retry_time>5){
            return res;
          }
          
        }
        //LED_RUN_Set(LED_FLASH);
        
        IWDG_Feed();
        
        // 确保模块工作正常
        AT_AIR720_DEBUG_F("查询分配的IP地址,AT+CIFSR,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIFSR\r\n", ".", 200))					    //查询分配的IP地址
        {
          AT_AIR720_DEBUG_F("AT+CIFSR ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CIFSR failed!!!!\r\n\r\n");
          return res;
        }
        //LED_RUN_Set(LED_FLASH);
        IWDG_Feed();
        res=0;
        return 0;
}

/***返回工作模式**/
int flg = 1;
void AT_aire720_process(DEV_WORK_MODE_T *pmode){
  Uint16 retryTimes = 0,sendlen,flg = 1;
  Uint16 lora_rcv_len = 0;
	Uint8 lora_rcv_buffer[128];
  Uint16 at_send_len = 0;
	Uint8 at_send_buffer[128];
  Uint16 cmd_len = 0;
  Uint32 uTemp32 = 0;
	Uint8 cmd_str[32];
  Uint8 buffer[256];
	DEV_WORK_MODE_T WorkMode = *pmode,ret;
  static Uint32 retry_time=0;
  
  static Uint32 CIICR_retry_time=0;
  int i;
	char *pchar = "AT+CPIN1111111111111111111111\r\n";
  //心跳，超过一定时间没有节点的数据，则网关自己上传心跳
  if((*pmode == GATEWAY_WORK_MODE)&&(TickCounter - time_gw_heartbeat.counter > time_gw_heartbeat.timeOut)){
    time_gw_heartbeat.counter = TickCounter;
    UDP_0C_frame();
    AT_AIR720_DEBUG_F("gw heartbeat time out\r\n");
  }

  IWDG_Feed();														//喂狗
  
  if(!Check_Seqeue_Empty(lora_rx_sq)){
    IWDG_Feed();														//喂狗
    lora_rcv_len = 0;
    memset(lora_rcv_buffer,0,sizeof(lora_rcv_buffer));
    
    De_Queue(lora_rx_sq,lora_rcv_buffer,sizeof(lora_rcv_buffer),(uint8_t *)&lora_rcv_len);
    
    AT_AIR720_DEBUG_F("lora receive:len=%02d,msg=\r\n",lora_rcv_len);
    AT_AIR720_DEBUG_H(lora_rcv_buffer,lora_rcv_len);
    AT_AIR720_DEBUG("\r\n");
    
    IWDG_Feed();														//喂狗
    Air720_analysis(lora_rcv_buffer,lora_rcv_len);
    IWDG_Feed();														//喂狗
    
    //int Air720_analysis(uint8_t *sbuf,uint8_t slen){
  }

  switch(AT_aire720_State){
    case AT_AIRE720_STATE_IDLE:
     // AT_aire720_State = AT_AIRE720_STATE_SEND;
      break;
    case AT_AIRE720_STATE_INIT:
			Air720_Init();
    #if 0
      AT_AIR720_DEBUG_F("尝试联网,retry_time=%d\r\n",retry_time++);
      if(aire720_closeHTTP_openUDP(0)){
      AT_AIR720_DEBUG_F("尝试联网 failed!!!!retry_time=%d\r\n",retry_time++);
        if(retry_time>5){
          AT_aire720_State =AT_AIRE720_STATE_CONNECTING;
          retry_time=0;
        }
        break;
      }
      else{
        AT_AIR720_DEBUG_F("尝试联网 OK\r\n");
      }
#endif
      if(1){
        
        for(i=0;i<10;i++){
          AT_AIR720_DEBUG_F(".\r\n");
          IWDG_Feed();														//喂狗
          delay_ms(1000);
          //LED_RUN_Set(LED_FLASH);
        }
        
          
        AT_AIR720_DEBUG_F("start AT\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT\r\n");
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
      
        AT_AIR720_DEBUG_F("start ATE0&W\r\n");
        cmd_len = sprintf((char *)cmd_str,"ATE0&W\r\n");
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
        
        AT_AIR720_DEBUG_F("start AT+CIPMUX=0\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT+CIPMUX=0\r\n");
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
        
        
        AT_AIR720_DEBUG_F("start AT+CIPQSEND=1\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT+CIPQSEND=1\r\n");	      // 设置为快发模式
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
        
        
        AT_AIR720_DEBUG_F("start AT+CSTT\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT+CSTT\r\n");             // 启动任务，设置APN
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
        
        AT_AIR720_DEBUG_F("start AT+CIICR\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT+CIICR\r\n");	          // 激活移动场景，获取IP地址
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
        
        AT_AIR720_DEBUG_F("start AT+CIFSR\r\n");
        cmd_len = sprintf((char *)cmd_str,"AT+CIFSR\r\n");					  //查询分配的IP地址
        USART2_SendNByte(cmd_str, cmd_len);
        IWDG_Feed();														//喂狗
        delay_ms(1000);
        IWDG_Feed();														//喂狗
        //LED_RUN_Set(LED_FLASH);
      }
      else{
        
        AT_AIR720_DEBUG_F("AT_AIRE720_STATE_INIT!!!!,%d\r\n",uTemp32++);
        
        for(i=0;i<5;i++){
          AT_AIR720_DEBUG_F(".%d\r\n",uTemp32++);
          IWDG_Feed();														//喂狗
          delay_ms(1000);
          //LED_RUN_Set(LED_FLASH);
        
        }
        
        
        
        AT_AIR720_DEBUG_F("AT,%d\r\n",uTemp32++);
        if(air_send_cmd("AT\r\n", "OK", 200))
        {
          AT_AIR720_DEBUG_F("AT ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT failed!!!!\r\n\r\n");
        }
        
        AT_AIR720_DEBUG_F("ATTE0,%d\r\n",uTemp32++);
        if(air_send_cmd("ATTE0\r\n", "OK", 200))
        {
          AT_AIR720_DEBUG_F("ATTE0 ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("ATTE0 failed!!!!\r\n\r\n");
        }
        
        //AT_AIR720_DEBUG_F("设置为快发模式,AT+CIPQSEND=1,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIPQSEND=1\r\n", "OK", 200))	      // 设置为快发模式
        {
          AT_AIR720_DEBUG_F("AT+CIPQSEND ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CIPQSEND failed!!!!\r\n\r\n");
        }
        
        //AT_AIR720_DEBUG_F("启动任务，设置APN,AT+CSTT,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CSTT\r\n", "OK", 200))	            // 启动任务，设置APN
        {
          AT_AIR720_DEBUG_F("AT+CSTT ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CSTT failed!!!!\r\n\r\n");
        }
        
        
        //AT_AIR720_DEBUG_F("激活移动场景，获取IP地址,AT+CIICR%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIICR\r\n", "OK", 1000))	            // 激活移动场景，获取IP地址
        {
          AT_AIR720_DEBUG_F("AT+CIICR ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CSTT failed!!!!retry=%d\r\n\r\n",CIICR_retry_time);
          CIICR_retry_time++;
          if(CIICR_retry_time>5){
            AT_aire720_State =AT_AIRE720_STATE_CONNECTING;
            CIICR_retry_time=0;
          }
          break;
        }
        //LED_RUN_Set(LED_FLASH);
        
        IWDG_Feed();
        
        // 确保模块工作正常
        AT_AIR720_DEBUG_F("查询分配的IP地址,AT+CIFSR,%d\r\n",uTemp32++);
        if(air_send_cmd("AT+CIFSR\r\n", ".", 200))					    //查询分配的IP地址
        {
          AT_AIR720_DEBUG_F("AT+CIFSR ok!!!!\r\n\r\n");
        }
        else{
          AT_AIR720_DEBUG_F("AT+CIFSR failed!!!!\r\n\r\n");
        }
        //LED_RUN_Set(LED_FLASH);
        IWDG_Feed();
      }


			AT_aire720_State =AT_AIRE720_STATE_CONNECTING;
      break;
    case AT_AIRE720_STATE_CONNECTING:
						/* 连接服务器 */
			retryTimes = 0;
			while(retryTimes++ < UDP_CONNECT_RETRY_TIMES)
			{
				 IWDG_Feed();
#if TEST_TEST_TEST
          //124.70.207.36 9084
          //47.104.15.180 9082
          //
//          cmd_len = sprintf((char *)cmd_str,"AT+CIPSTART=\"UDP\",\"124.70.207.36\",\"9084\"\r\n");
          cmd_len = sprintf((char *)cmd_str,"AT+CIPSTART=\"UDP\",\"47.104.15.180\",\"9082\"\r\n");   
          AT_AIR720_DEBUG_F("%s,%d\r\n",cmd_str,uTemp32++);
#else
          cmd_len = sprintf((char *)cmd_str,"AT+CIPSTART=\"UDP\",\"47.104.15.180\",\"9080\"\r\n");      
          AT_AIR720_DEBUG_F("%s,%d\r\n",cmd_str,uTemp32++);
#endif
        
				if(air_send_cmd((char *)cmd_str, "OK", 100))/*建立UDP链接*/
				{
						AT_aire720_State = AT_AIRE720_STATE_CONNECT_OK;
						AT_AIR720_DEBUG_F("UDP connect ok!!!!,%d\r\n",uTemp32++);
						//Air720_send(cmd_str,cmd_len);
           // Air720_send((uint8_t *)pchar,strlen((char *)pchar));
			
          break;
				}
        //LED_RUN_Set(LED_FLASH);
        
				
			}
			if(AT_aire720_State != AT_AIRE720_STATE_CONNECT_OK)
			{
				AT_AIR720_DEBUG_F("ERROR:UDP connect fail!!!!,%d\r\n",uTemp32++);
				AT_AIR720_DEBUG_F("ERROR:UDP connect fail!!!!,%d\r\n",uTemp32++);
				AT_AIR720_DEBUG_F("ERROR:UDP connect fail!!!!,%d\r\n",uTemp32++);
				NVIC_SystemReset();// 复位
			}
			else
			{
				
        IWDG_Feed();														//喂狗
        delay_ms(200);
        
        AT_AIR720_DEBUG_F("%d\r\n",uTemp32++);
        if(air_send_IMEI_Cmd(10))
        {
          AT_AIR720_DEBUG_F("read imei,%d\r\n",uTemp32++);
        }
        //LED_RUN_Set(LED_FLASH);
        
        
        AT_AIR720_DEBUG_F("%d\r\n",uTemp32++);
        if(air_send_ICCID_Cmd(10))
        {
          AT_AIR720_DEBUG_F("read iccid,%d\r\n",uTemp32++);
        }
        //LED_RUN_Set(LED_FLASH);
        //联网之后先心跳
        UDP_0C_frame();
        //无服务器反馈指令时，设置强制复位时间1小时
        time_gw_force_rst.timeOut=60*60*1000;
			}
//			for(i=0;i<NODE_NUM;i++){
//        LED_Set(i,LED_OFF);
//      }
      LED_OFF_ALL();
      break;
    
    
    case AT_AIRE720_STATE_CONNECT_OK://指令收发
			//air_send_cmd("AT+CIPSEND=25", 0, 300);/*建立UDP链接*/
		

			  if(!Check_Seqeue_Empty(Air720_Send_Sq)){
					IWDG_Feed();														//喂狗
          at_send_len = 0;
          memset(at_send_buffer,0,sizeof(at_send_buffer));
          
          De_Queue(Air720_Send_Sq,at_send_buffer,sizeof(at_send_buffer),(uint8_t *)&at_send_len);
          
          //AT_AIR720_DEBUG_F("at_send_len=%d\r\n",at_send_len);
          
          Air720_send(at_send_buffer,at_send_len);
					IWDG_Feed();														//喂狗
          delay_ms(100);
					IWDG_Feed();														//喂狗
        }
  
      //接收处理
			#if 0
			 if(!Check_Seqeue_Empty(Air720_Rev_Sq)){
					IWDG_Feed();														//喂狗
				sendlen = 0;
				memset(buffer,0,sizeof(buffer));
				De_Queue(Air720_Rev_Sq,buffer,sizeof(buffer),(uint8_t *)&sendlen);
			
				Air720_Receive_Handle(buffer,sendlen);
			}
			if (USART2_ready_buf_ok == RevOK)
			{
				
				AT_AIR720_DEBUG_F("UDP ready Entery!!!!\r\n");
				flg = 0;
				for(i = 0;i<USART2_ready_buf_len; i++)
				{
					if(USART2_ready_buf[i] == 0xff)
						flg = 1;
					//if(flg)
					//AT_AIR720_DEBUG_F("0x%02X ",USART2_ready_buf[i]);
				
				}
				//AT_AIR720_DEBUG_F("%p\n",USART2_ready_buf);
				if((ret = Air720_Receive_Handler2(&USART2_ready_buf[0],USART2_ready_buf_len))!=DEV_MODE_ALL)
				*pmode = ret;
				USART2_ready_buf_ok = 0;
			}
			else
				memset(USART2_ready_buf,0,USART2_BUF_SIZE);
      
			#endif
      
      if (USART2_ready_buf_ok == RevOK){
        Air720_Receive_Handler2(&USART2_ready_buf[0],USART2_ready_buf_len);
        USART2_ready_buf_ok = 0;
        memset(USART2_ready_buf,0,USART2_BUF_SIZE);
      }
      if((ret = Air720_Receive_process())!=DEV_MODE_ALL){
        *pmode=ret;
        return;
      }
      break;
    case AT_AIRE720_STATE_RE_CONNECT:
//      
//      AT_AIR720_DEBUG_F("重新尝试联网,retry_time=%d\r\n",retry_time++);
//      if(aire720_closeHTTP_openUDP(1)){
//      AT_AIR720_DEBUG_F("尝试联网 failed!!!!retry_time=%d\r\n",retry_time++);
//        if(retry_time>5){
//          AT_aire720_State =AT_AIRE720_STATE_CONNECTING;
//          retry_time=0;
//        }
//        break;
//      }
//      else{
//        AT_AIR720_DEBUG_F("尝试联网 OK\r\n");
//      }
    
      //
//      AT_AIR720_DEBUG_F("关闭UDP或TCP,AT+CIPCLOSE!!!!,%d\r\n",uTemp32++);
//          if(air_send_cmd("AT+CIPCLOSE\r\n", "CLOSE OK", 200))
//          {
//            AT_AIR720_DEBUG_F("AT+CIPCLOSE  ok!!!!\r\n");
//          }
//          else{
//            AT_AIR720_DEBUG_F("AT+CIPCLOSE  failed!!!!\r\n");
//          }
      
      
			AT_aire720_State =AT_AIRE720_STATE_CONNECTING;
      break;
    default:
      AT_aire720_State = AT_AIRE720_STATE_IDLE;
      break;
  }
  return;
}

void set_at_aire720_workState(tAT_AIRE720_StateCodes  mode){
  AT_aire720_State = mode;
  return;
}

