#include <rtthread.h>
#include "main.h"
#include "flash.h"
#include "buffer.h"
#include "button.h"
#include "usart.h"
#include <stdlib.h>
#include "weight.h"
#include "display.h"
#include "plan.h"
#include "xBeeAppEscapingMode.h"

union frameinit_t dataframehead = {0x7E,0x00,0x01,0x01};

unsigned char WeightConst_product[40] = {0xD2,0xBB,0xBA,0xC5,0xC5,0xA3,0xC9,0xE1,0x20,0x20}; //产品名称
union plan_comp_t plan_comp = {0,0,0,0,0,0};
union pf_comp_t pf_comp = {0,0,0,0,0};


unsigned char WeightConst_Product_JS=0; //需要计算
unsigned char WeightConst_Product_Run=0; //开始运行
unsigned char WeightConst_Run=0; //整体开始运行

unsigned char WeightConst_Stop = 0;

unsigned char WeightConst_PlantempList[40]; //计划临时表
unsigned char WeightConst_Nextfeed[40]; //临时表
signed short WeightConst_NextWeightTarget;      //目标重量
unsigned char WeightConst_feed[40]; //原料名称					

signed short WeightConst_WeightTargetTemp;      //目标重量
		
signed short WeightConst_WeightTarget;      //目标重量				

unsigned char CompleteTarget_order = 0xFD; //已完成的顺序

signed short WeightConst_WeightTargetAllowMin;  //目标重量的允许跳转范围
signed short WeightConst_WeightTargetAllowMax;  //目标重量的允许跳转范围
unsigned char WeightConst_WeightHaveBegin = 0;  //已经确认开始
unsigned short WeightConst_DELAYTIME;
unsigned short WeightConst_DELAYON = 0;

unsigned char XbeeConst_lastsort;        //保存刚刚收到的顺序号
unsigned char XbeeConst_lastinorout;        //保存刚刚收到的发料或加料
unsigned char XbeeConst_FrameNum = 0;  //帧编号

unsigned char XbeeConst_CanSend=1;
unsigned char getPlaning=0;
static unsigned char XbeeConst_needRetry=0;         //等待秒数

rt_sem_t pop_product_sem = RT_NULL;

rt_sem_t delay_key_sem = RT_NULL;
unsigned char delayKeying = 0;
//定义时间
union TimeConst_t TimeConst={
		.data.year = 1,
		.data.month = 0, 
		.data.date = 32,
		.data.hh = 0,
		.data.mm = 0,
		.data.ss = 0
};

static  rt_thread_t tdelay_key_id = RT_NULL;
static void delay_key_entry(void *parameter)
{	
	 while(1)
	 {
			rt_sem_take(delay_key_sem, RT_WAITING_FOREVER);   //等待
		  delayKeying =1;
			rt_thread_mdelay(3000);
		  delayKeying =0;
   }
}

void delay_key_thread(void)
{
    tdelay_key_id = rt_thread_create("delay_key",
                            delay_key_entry, RT_NULL,
                            0x100, 6, 5);

    /* 如果获得线程控制块，启动这个线程 */
    if (tdelay_key_id != RT_NULL) rt_thread_startup(tdelay_key_id);
}

void setSendFrame_t(unsigned char Broadcast,unsigned char Radius,unsigned char TO) {
    userSendFrame_t.frameHead = 0x7E;//帧头
    userSendFrame_t.frameLen = 0;//数据长度Number of bytes between length and checksum fields.
    userSendFrame_t.frameType = 0x10;//帧类型，Transmit Request
    userSendFrame_t.frameID = 0x01;

    if (Broadcast == 1) {
        userSendFrame_t.des64DeviceAdd[0] = 0x00;//器件ID 高
        userSendFrame_t.des64DeviceAdd[1] = 0x00;//器件ID  |
        userSendFrame_t.des64DeviceAdd[2] = 0x00;//器件ID  |
        userSendFrame_t.des64DeviceAdd[3] = 0x00;//器件ID  |
        userSendFrame_t.des64DeviceAdd[4] = 0x00;//器件ID  |
        userSendFrame_t.des64DeviceAdd[5] = 0x00;//器件ID  |
        userSendFrame_t.des64DeviceAdd[6] = 0xFF;//器件ID  |
        userSendFrame_t.des64DeviceAdd[7] = 0xFF;//器件ID 低
    }
    else if (Broadcast == 2) {
        for (int i = 0; i < 8; i++)
            userSendFrame_t.des64DeviceAdd[i] = XbeeConst_CCAddress[i];
    }
    else {
        for (int i = 0; i < 8; i++)
            userSendFrame_t.des64DeviceAdd[i] = XbeeConst_CenterAddress[i];
    }
    userSendFrame_t.des16NetAdd = 0xFFFE ;//网络ID
    userSendFrame_t.broadcastRadius = Radius;//广播半径
    userSendFrame_t.transmitOptions = TO;
}

static void setTIME_entry(void *parameter) {
    while (1) {

        if ((TimeConst.data.date == 29) && (TimeConst.data.month == 2) && (TimeConst.data.year % 4)>0 ) {
            TimeConst.data.date = 1;
            TimeConst.data.month ++;
        }
        else if ((TimeConst.data.date == 30) && (TimeConst.data.month == 2) && (TimeConst.data.year % 4) == 0 ) {
            TimeConst.data.date = 1;
            TimeConst.data.month ++;
        }
        else if ((TimeConst.data.date == 31) && ((TimeConst.data.month == 4) || (TimeConst.data.month == 6) ||
                                              (TimeConst.data.month == 9) || (TimeConst.data.month == 11)) ) {
            TimeConst.data.date = 1;
            TimeConst.data.month ++;
        }
        else if (TimeConst.data.date == 32) {
            TimeConst.data.date = 1;
            TimeConst.data.month ++;
        }

        if (TimeConst.data.month == 13) {
            TimeConst.data.month = 1;
            TimeConst.data.year ++;
        }
				
        TimeConst.data.ss++;
        if (TimeConst.data.ss==60) {
            TimeConst.data.ss = 0;
            TimeConst.data.mm ++;
        }
        if (TimeConst.data.mm==60) {
            TimeConst.data.mm = 0;
            TimeConst.data.hh ++;
        }
        if (TimeConst.data.hh==24) {
           TimeConst.data.hh = 0;
           TimeConst.data.date ++;
        }
        rt_thread_mdelay(1000);				
    }
}

static  rt_thread_t tTimeid = RT_NULL;
void setTIME_thread(void)
{
    tTimeid = rt_thread_create("Timer", setTIME_entry, RT_NULL, 0x90, 3, 5);

    /* 如果获得线程控制块，启动这个线程 */
    if (tTimeid != RT_NULL) rt_thread_startup(tTimeid);
}

void setWeightConst_initProduct(void) {
	  rt_memset(WeightConst_product,0x20,40);		
    rt_memset(WeightConst_feed,0x20,40);			
		rt_memset(WeightConst_Nextfeed,0x20,40);	
    if (WeightConst_SBType==1||WeightConst_SBType==6) {
        if (!isWeight)
        {
            WeightConst_feed[0]=0xC7;
            WeightConst_feed[1]=0xEB;
            WeightConst_feed[2]=0xC8;
            WeightConst_feed[3]=0xA1;
            WeightConst_feed[4]=0xBC;
            WeightConst_feed[5]=0xC6;
            WeightConst_feed[6]=0xBB;
            WeightConst_feed[7]=0xAE;
        }
        else
        {
            WeightConst_feed[0]=0xD6;
            WeightConst_feed[1]=0xD8;
            WeightConst_feed[2]=0xC1;
            WeightConst_feed[3]=0xBF;
            WeightConst_feed[4]=0x20;
            WeightConst_feed[5]=0x20;
            WeightConst_feed[6]=0x20;
            WeightConst_feed[7]=0x20;
        }
    }
    else if (WeightConst_SBType==3) {
        WeightConst_feed[0]=0xC7;
        WeightConst_feed[1]=0xEB;
        WeightConst_feed[2]=0xC8;
        WeightConst_feed[3]=0xA1;
        WeightConst_feed[4]=0xBC;
        WeightConst_feed[5]=0xC6;
        WeightConst_feed[6]=0xBB;
        WeightConst_feed[7]=0xAE;
    }		
	
		plan_comp.data.incount = 0;    //原料数量1
		plan_comp.data.outcount = 0;   //投喂数量1		
		plan_comp.data.reget = 0;      //计划是否是重取
		plan_comp.data.swpos = 0;      //目标总量小数位
		plan_comp.data.sumweight = 0;  //目标总量
		plan_comp.data.shifts = 0;     //班次
		
		
    WeightConst_WeightTarget = 0;         //目标总量
		
		
    pf_comp.data.addorout = 0; //加料发料
//	WeightConst_WeightTarget_ZF = 0; //目标总量正负
    pf_comp.data.tw_pos = 0; //目标总量小数位
    pf_comp.data.az_pos = 0; //误差小数位
    pf_comp.data.autosecond = 0;  //目标重量的允许跳转时间   1- 3秒 2-  6秒 3- 9秒

    pf_comp.data.autozone = 0; ;  //目标重量的允许跳转范围
    pf_comp.data.needBegin = 0;
    pf_comp.data.pfsort = 0xFE; //顺序
    pf_comp.data.delaytime = 0;		
    pf_comp.data.JMP = 0;
		
    WeightConst_Product_Run = 0;
    XbeeConst_lastsort = 0;
    XbeeConst_lastinorout = 0;
		if (WeightConst_SBType>2 && WeightConst_SBType<7) {
				rt_event_send(&display_event, EVENT_clearall);
				rt_event_send(&display_event, EVENT_Current_noweight);
		}
}


void pop_product_entry(void *parameter) {
		while(1)
		{
				rt_sem_take(pop_product_sem, RT_WAITING_FOREVER);   //等待串口消息
		//	  rt_sem_init(pop_product_sem,"pop_product_sem", 0, RT_IPC_FLAG_FIFO);	
				for (int CheckWeight_i = 0; CheckWeight_i < 30; CheckWeight_i++) {
						WeightConst_AutoSingleNSecondNum[CheckWeight_i][0]=0;
						WeightConst_AutoSingleNSecondNum[CheckWeight_i][1]=0;
						WeightConst_AutoSingleNSecondNum[CheckWeight_i][2]=0;
				}
				
				while(1){
						WeightConst_WeightHaveBegin=0;
						if (tsdb_recordcount('p')>0) {
								findplan();
								unsigned char setWeightConst_length=0;

								setWeightConst_length = WeightConst_PlantempList[1];
//							rt_kprintf("pop:");	
//							for(int i=0;i<setWeightConst_length;i++)
//							  rt_kprintf("%02X ",WeightConst_PlantempList[i]);	
//							rt_kprintf("\n");	
								WeightConst_Run = 1;
								if (WeightConst_PlantempList[3]==0x12) {
										save_read_ts('p');	
//                    rt_kprintf("pop 0x12 \n");									
									  rt_sem_take(display_lock, RT_WAITING_FOREVER);								
									  setWeightConst_initProduct();									
										rt_memset(WeightConst_product,0x20,40);				
										rt_memset(WeightConst_feed,0x20,40);		
										for (int i = 0; i <= setWeightConst_length-10; i++) {
												WeightConst_product[i] = WeightConst_PlantempList[i+4];   //产品名称
												if (WeightConst_SBType==1||WeightConst_SBType==6) {
														WeightConst_feed[i] = WeightConst_product[i];   //显示一秒牛舍
												}
										}
										plan_comp.Buffer[0] = WeightConst_PlantempList[setWeightConst_length-5+1];   //产品名称
										plan_comp.Buffer[1] = WeightConst_PlantempList[setWeightConst_length-5];   //产品名称
										for (int i = 2; i < 6; i++) {
												plan_comp.Buffer[i] = WeightConst_PlantempList[setWeightConst_length-5+i];   //产品名称
										}	
										pf_comp.data.pfsort = 0xFD;
										WeightConst_Stop = 0;
										if (WeightConst_SBType>2 && WeightConst_SBType<7) {
												rt_event_send(&display_event, EVENT_PlanName);
										}
										rt_sem_release(display_lock);
										rt_thread_mdelay(1000);			
								}

								else if (WeightConst_PlantempList[3]==0x15) {		
									  rt_sem_take(display_lock, RT_WAITING_FOREVER);
										rt_memset(WeightConst_feed,0x20,40);				
										for (int i = 0; i <= setWeightConst_length-11; i++) 
												WeightConst_feed[i] = WeightConst_PlantempList[i+4];  //饲料名称
										
										WeightConst_WeightTarget = WeightConst_PlantempList[setWeightConst_length-6]<<8 ;         //目标总量
										WeightConst_WeightTarget = WeightConst_WeightTarget | WeightConst_PlantempList[setWeightConst_length-5];
										
										WeightConst_WeightTargetTemp = WeightConst_WeightTarget;
										
										for (int i = 0; i < 5; i++) 
												pf_comp.Buffer[i] = WeightConst_PlantempList[setWeightConst_length-4 + i];
//										rt_kprintf("pop 15 pfsort:%02X \n",pf_comp.data.pfsort);
										if ( pf_comp.data.tW_minus ==1)
												WeightConst_WeightTarget	= WeightConst_WeightTarget * -1;		//目标总量正        

										WeightConst_Product_Run = (pf_comp.data.pfsort<253);

										WeightConst_DELAYTIME = 0;
										CanButton = 0x01;
										WeightConst_oksum=0;
					          WeightConst_WeightOK = 0;

										if (pf_comp.data.firstReget)	{
												pf_comp.data.needBegin = 0;
												plan_comp.data.reget = 0;
												WeightConst_Product_JS = 0;
										}
										else  WeightConst_Product_JS = 1;

										if (pf_comp.data.needBegin == 0 || CompleteTarget_order == pf_comp.data.pfsort)
				                getTargetWeight();
										
										rt_sem_release(display_lock);
										
                    if (pf_comp.data.pfsort>=253)
										{
											reset_read_ts('p');
										//	setWeightConst_initProduct();
										}
//										if (pf_comp.data.needBegin == 1 && isTag==1 && WeightConst_WeightTarget_addorout==1)
//											 ReadTag(1);                     
										
										if (WeightConst_SBType>2 && WeightConst_SBType<7) {
				//                if (WeightConst_WeightTarget_order==0xFF && WeightConst_SBType==4)
				//                    checkfinish=1;
												if (WeightConst_Product_Run)
												{													  
														if (plan_comp.data.reget>0)
															rt_event_send(&display_event, EVENT_Current_noweight);
														else
															rt_event_send(&display_event, EVENT_Current);	
												}
												else
												{
														rt_event_send(&display_event, EVENT_clearall);
														rt_event_send(&display_event, EVENT_Current_noweight);
												}	
												findNextplan();
												rt_event_send(&display_event, EVENT_Next);		
										}
										break;
								}	
						}
				
					  rt_thread_mdelay(10);			
				}
		}
}

void sendgetTime(void) {  //向上位机取时间
    // key8 协议(取时间)：0x7E 0x04 0x01 0xF8 0x01 0x01
    // 1位起始位 + 1位长度 + 1位源地址 + 1位命令 + 1帧编号 + 1校验
    unsigned char buf[6] ;
    unsigned char CRCNum=0;
    buf[0]= 0x7E;
    buf[1]= 0x04;
    buf[2]= XbeeConst_DeviceAddress;
	
    buf[3]= 0xF8;
    buf[4] = XbeeConst_FrameNum++;
    for (int i=0; i< 5; i++) CRCNum+=buf[i];
    buf[5] = 0xff - CRCNum;
	  
	  if( READ_BIT(RCC->CSR, RCC_CSR_IWDGRSTF) == RESET)  //看门狗重启不需要获取时间
    {
       ts_pushArrary(&ts_keydb, buf, buf[1]+2); 
    }
	  __HAL_RCC_CLEAR_RESET_FLAGS();
    if (tsdb_recordcount('p') > 0)	{
				findF12();
			  rt_event_send(&display_event, EVENT_PlanName);
			  rt_thread_mdelay(1000);
				rt_sem_release(pop_product_sem);
		}
}


void sendkey2(int BtnType) {
    /* key2 协议(上报2号按键)：0x7E 0x0B 0x01 0xF2 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x01
     * 1位起始位 + 1位长度 + 1位源地址 + 1位命令 + 7位重量 + 1上次接收顺序号 + 1帧上次inorout + 1帧编号 + 1校验
     */
    unsigned char buf[17];
    unsigned char CRCNum;
	  union timekeyweight_t xBytes;

    CRCNum = 0;
    xBytes = getTimeWeight(2);
    buf[0]= 0x7E;
    buf[1]= 0x0F;
    buf[2]= XbeeConst_DeviceAddress;

    buf[3]= BtnType;
    
    for (int i=9; i >0; i--) buf[i+3]= xBytes.Buffer[9-i];

    if (BtnType==0xF4) {
        beep();
        XbeeConst_lastsort=0xFD;
        buf[13] = 0x00;  //上次接收到的顺序号
        buf[14] = 0x00;	//上次接收到的顺序号
    }
    else 	{
        buf[13] = XbeeConst_lastsort;  //上次接收到的顺序号
        buf[14] = XbeeConst_lastinorout;	//上次接收到的顺序号
    }

    buf[15] = XbeeConst_FrameNum ++;

    for (int i=0; i< 16; i++) CRCNum+=buf[i];

    buf[16] = 0xff - CRCNum;
    ts_pushArrary(&ts_keydb, buf, buf[1]+2);

    if (BtnType==0xF4) {
      //  WeightConst_Product_JS = 0;
			  getPlaning = 1;
				rt_sem_take(weight_lock, RT_WAITING_FOREVER);
        WeightConst_WeightBegin = WeightConst_WeightCur;
				rt_sem_release(weight_lock);
        write_Flash("beginweight", &WeightConst_WeightBegin, sizeof(WeightConst_WeightBegin));
        write_Flash("TimeConst", &TimeConst, sizeof(TimeConst));			
    }
}


void sendkey1(int BtnType, int remote) {
    /* key1 协议(上报1号按键)：0x7E 0x0B 0x01 0xF1 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x01 0x01
     * 1位起始位 + 1位长度 + 1位源地址 + 1位命令 + 7位重量 + 1位任务顺序号 + 1帧编号 + 1校验
     */
    unsigned char buf[17];
    unsigned char CRCNum;
	  union timekeyweight_t xBytes;
    CRCNum = 0;
    xBytes = getTimeWeight(BtnType);
    buf[0]= 0x7E;
    buf[1]= 0x0F;
    if (isCC)
        buf[2]= ((remote<< 4) & 0x0f) | (XbeeConst_DeviceAddress& 0x0f);
    else
        buf[2]= XbeeConst_DeviceAddress & 0x0f;

    buf[3]= BtnType;
    for (int i=9; i >0; i--) buf[i+3]= xBytes.Buffer[9-i];

    buf[13]= pf_comp.data.pfsort;  //应该附上当前计划的当前料的顺序号
    buf[14]= 0x00;  //应该附上当前计划的当前料的顺序号
    buf[15] = XbeeConst_FrameNum ++;
    for (int i=0; i< 16; i++)
        CRCNum+=buf[i];

    buf[16]= 0xff - CRCNum;

		ts_pushArrary(&ts_keydb, buf, buf[1]+2);		
																
		CompleteTarget_order = pf_comp.data.pfsort;
    write_Flash("TimeConst", &TimeConst, sizeof(TimeConst));	
		
    save_read_ts('p');			
    beep();
    alarm_off();

    if (pf_comp.data.pfsort == 0xFE) {
				rt_sem_take(display_lock, RT_WAITING_FOREVER);
        setWeightConst_initProduct();
				rt_sem_release(display_lock);
    }
    else
    {
        if (pf_comp.data.delaytime)
            WeightConst_DELAYON = 1;
        else
        {		
						rt_sem_take(weight_lock, RT_WAITING_FOREVER);
            WeightConst_WeightBegin = WeightConst_WeightCur;
						rt_sem_release(weight_lock);
					  write_Flash("beginweight", &WeightConst_WeightBegin, sizeof(WeightConst_WeightBegin));	
           // WeightConst_Product_JS = 1;
					  rt_sem_release(pop_product_sem); //弹出最新内容
            WeightConst_DELAYON = 0;
        }
    }
}


void getTargetWeight(void)
{
    WeightConst_WeightHaveBegin = 1;

    if (pf_comp.data.tw_pos > WeightConst_WeightWS) { //  把目标的小数点转换成当前称的小数点位
        WeightConst_WeightTarget = WeightConst_WeightTarget/mypow(10,pf_comp.data.tw_pos - WeightConst_WeightWS);
        pf_comp.data.tw_pos = WeightConst_WeightWS;
    }
    else if (pf_comp.data.tw_pos < WeightConst_WeightWS) {
        WeightConst_WeightTarget = WeightConst_WeightTarget*mypow(10,WeightConst_WeightWS - pf_comp.data.tw_pos);
        pf_comp.data.tw_pos = WeightConst_WeightWS;
    }

//	WeightConst_WeightBegin = WeightConst_WeightCur;
    if (WeightConst_Product_JS == 1) { //这段计算出实际目标重量
				rt_sem_take(weight_lock, RT_WAITING_FOREVER);
			  if (WeightConst_WeightBegin == -30000)
					 WeightConst_WeightBegin = WeightConst_WeightCur;
				rt_sem_release(weight_lock);
				
        if (pf_comp.data.addorout == 0)
            WeightConst_WeightTarget = WeightConst_WeightBegin + WeightConst_WeightTarget;
        else
            WeightConst_WeightTarget = WeightConst_WeightBegin - WeightConst_WeightTarget;
    }
    else
        WeightConst_WeightBegin=-30000;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (pf_comp.data.az_pos > pf_comp.data.tw_pos) { //  把目标误差的小数点转换成当前称的小数点位
        pf_comp.data.autozone = pf_comp.data.autozone/mypow(10,pf_comp.data.az_pos-pf_comp.data.tw_pos);
        pf_comp.data.az_pos = pf_comp.data.tw_pos;
    }
    else if (pf_comp.data.az_pos < pf_comp.data.tw_pos) {
        pf_comp.data.autozone = pf_comp.data.autozone*mypow(10,pf_comp.data.tw_pos-pf_comp.data.az_pos);
        pf_comp.data.az_pos = pf_comp.data.tw_pos;
    }

    WeightConst_WeightTargetAllowMin = WeightConst_WeightTarget	- pf_comp.data.autozone;  //目标重量的允许跳转范围
    WeightConst_WeightTargetAllowMax = WeightConst_WeightTarget	+ pf_comp.data.autozone;
    WeightConst_AutoSingleNSecondPoint=0;
    WeightConst_oksum = 0;
    WeightConst_allsum = 0;

//		if (isTag==1)
//    {
//              Rec_watchTag_point=0;  //接收标签
//              ReadTag_state=0;   //读标签状态  0  没读或已读成功，1  开始读 ，2  正在读
//              WriteTag_state=0;  //写标签状态  0  没写或已写成功，1  开始写 ，2  正在写  
//    }
//		
		if (WeightConst_SBType>2 && WeightConst_SBType<7) {
			 rt_event_send(&display_event, EVENT_Stop);
		}
    /*
    	if (WeightConst_WeightTrg_address>0){
        //setTrg_Command(WeightConst_WeightTrg_address, 1);  //打开对应地址的继电器
    		sendControlCOMM(WeightConst_WeightTrg_address,1);
    		sendControlCOMM(WeightConst_WeightTrg_address,1);
    		sendControlCOMM(WeightConst_WeightTrg_address,1);
    	}
    	*/
}


void SendWifi_entry(void *parameter) {
   while (1) 
	 {
			if ((XbeeConst_needRetry>(40+XbeeConst_DeviceAddress)) && XbeeConst_CanSend==0) {  //需要2秒后重发
					if ((XbeeConst_FTxBuf0[4]&0xF0) == 0xF0) {
							XbeeConst_FTxBuf0[4]=XbeeConst_FTxBuf0[4]-16;
							XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]] = 0;
							for (int i=1; i< XbeeConst_FTxBuf0[0]; i++){
									XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]] += XbeeConst_FTxBuf0[i];								
							}             
							XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]] = 0xff - XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]];
					}

					if (XbeeConst_UseAPI>0) {
							rt_sem_take(uart2_lock, RT_WAITING_FOREVER);
							setSendFrame_t(XbeeConst_FTxBuf0[4]==0xF8 || XbeeConst_FTxBuf0[4]==0xE8,0x00,0xC0);
					//	  setSendFrame_t(1,0x00,0xC0);
							XbeeConst_PTxBuf0 = xBeeApp2MakeFrame(&userSendFrame_t, XbeeConst_FTxBuf0);
							for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_PTxBuf0[0]; SendWifi_i++)  //将缓冲区发出
									usart2_send_data[SendWifi_i-1] = XbeeConst_PTxBuf0[SendWifi_i];
						
//	{								
//											usart2_send_data[SendWifi_i-1] = XbeeConst_PTxBuf0[SendWifi_i];
//	 rt_kprintf(" %02X",usart2_send_data[SendWifi_i-1]);
//}
//		rt_kprintf("\n");	
							HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_PTxBuf0[0]);
							rt_thread_mdelay(50);							
						  rt_sem_release(uart2_lock);
					}
					else{
						  rt_sem_take(uart2_lock, RT_WAITING_FOREVER);
							for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_FTxBuf0[0]; SendWifi_i++)  //将缓冲区发出
									usart2_send_data[SendWifi_i-1] = XbeeConst_FTxBuf0[SendWifi_i];
						  
							HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_FTxBuf0[0]);
							rt_thread_mdelay(50);							
						  rt_sem_release(uart2_lock);
					}

					XbeeConst_needRetry = 0;  //重置重发定时计数
					XbeeConst_FrameNumLast = XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]-1];
			}
			else	if (XbeeConst_CanSend==1 && tsdb_recordcount('k')>0) { //可以重发/队列大于0/开头是7e						
				 if (findkey()<0xFFFFFFFF)
						{
							XbeeConst_CanSend = 0; //锁定无线不可发送直至解锁
							XbeeConst_needRetry = 0;  //重置重发定时计数
							XbeeConst_FrameNumLast = XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]-1];
							if (XbeeConst_UseAPI>0) {								
									rt_sem_take(uart2_lock, RT_WAITING_FOREVER);								
									setSendFrame_t(XbeeConst_FTxBuf0[4]==0xF8,0x00,0xC0);
									XbeeConst_PTxBuf0 = xBeeApp2MakeFrame(&userSendFrame_t, XbeeConst_FTxBuf0);									

									for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_PTxBuf0[0]; SendWifi_i++)  //将缓冲区发出
										 usart2_send_data[SendWifi_i-1] = XbeeConst_PTxBuf0[SendWifi_i];									
//	{								
//											usart2_send_data[SendWifi_i-1] = XbeeConst_PTxBuf0[SendWifi_i];
//	 rt_kprintf(" %02X",usart2_send_data[SendWifi_i-1]);
//}
//		rt_kprintf("\n");		
									HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_PTxBuf0[0]);
							    rt_thread_mdelay(50);							
									rt_sem_release(uart2_lock);
							}
							else
							{
								  rt_sem_take(uart2_lock, RT_WAITING_FOREVER);
									for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_FTxBuf0[0]; SendWifi_i++)  //将缓冲区发出
											usart2_send_data[SendWifi_i-1] = XbeeConst_FTxBuf0[SendWifi_i];
									HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_FTxBuf0[0]);
							    rt_thread_mdelay(50);							
									rt_sem_release(uart2_lock);
							}
					}
			}
		  else if (XbeeConst_CanSend==1	&& tsdb_recordcount('w')>4) { //可以重发/队列大于0/开头是7e		
					if (findweight()>3){	
							XbeeConst_CanSend = 0; //锁定无线不可发送直至解锁
							XbeeConst_needRetry = 0;  //重置重发定时计数
							XbeeConst_FrameNumLast = XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]-1];						
							if (XbeeConst_UseAPI>0) {									
									rt_sem_take(uart2_lock, RT_WAITING_FOREVER);						
									setSendFrame_t(XbeeConst_FTxBuf0[4]==0xF8,0x00,0xC0);
									XbeeConst_PTxBuf0 = xBeeApp2MakeFrame(&userSendFrame_t, XbeeConst_FTxBuf0);
									for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_PTxBuf0[0]; SendWifi_i++)  //将缓冲区发出								
											usart2_send_data[SendWifi_i-1] = XbeeConst_PTxBuf0[SendWifi_i];
					
                 HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_PTxBuf0[0]);							
									rt_thread_mdelay(50);							
									rt_sem_release(uart2_lock);								
							}
							else{
									rt_sem_take(uart2_lock, RT_WAITING_FOREVER);
									for (int SendWifi_i = 1; SendWifi_i <= XbeeConst_FTxBuf0[0]; SendWifi_i++)  //将缓冲区发出
										usart2_send_data[SendWifi_i-1] = XbeeConst_FTxBuf0[SendWifi_i];			
									HAL_UART_Transmit_DMA(&huart2, usart2_send_data, XbeeConst_FTxBuf0[0]);							
									rt_thread_mdelay(50);							
									rt_sem_release(uart2_lock);								
							}
					}
			}
			XbeeConst_needRetry++;
			rt_thread_mdelay(100);				
	 }      
}


static  rt_thread_t SendWifiid = RT_NULL;

void SendWifi_thread(void)
{
    SendWifiid = rt_thread_create("SendWifi", SendWifi_entry, RT_NULL, 0x300,5, 5);

    /* 如果获得线程控制块，启动这个线程 */
    if (SendWifiid != RT_NULL) rt_thread_startup(SendWifiid);
}

static  rt_thread_t pop_productid = RT_NULL;

void pop_product_thread(void)
{
    pop_productid = rt_thread_create("popproduct", pop_product_entry, RT_NULL, 0x400, 5, 5);

    /* 如果获得线程控制块，启动这个线程 */
    if (pop_productid != RT_NULL) rt_thread_startup(pop_productid);
}
