#include <flashdb.h>
#include <rtthread.h>
#include "plan.h"
#include "buffer.h"
#include "button.h"
#include "display.h"
#include <string.h>

uint8_t  isCC = 0 ;
uint8_t  isTag = 0 ; //是否含识读标签
unsigned char  isn = 0;  //是否新大屏

uint8_t XbeeConst_DeviceAddress = 0x01;         
uint8_t XbeeConst_NetAddress = 0x00;
uint8_t XbeeConst_UseAPI = 0x02;
uint8_t WeightConst_TQ = 7;//0x05;
uint8_t WeightConst_BLE = 0;
uint8_t WeightConst_ChanCheShu = 0x02;
uint8_t WeightConst_SBType = 0x01;
int16_t WeightConst_WeightBegin = 0;    //按键开始重量

uint8_t ad_Percent=  0x00;             //   7，    校正重量，1字节
unsigned int  ad_Maxval=   0x00007530;       //   8，    最大称量，4字节
uint8_t ad_FS=       0x04;             //  12，    滤波深度，1字节
uint8_t ad_Point=    0x00;             //  13，    小数点，  1字节
uint8_t ad_Inteval=  0x02;             //  14，    分度值，  1字节
float  ad_Spanz =   0.9;       //  15，    分度内码数， 4字节
unsigned int  ad_Zero =    0x00000000;       //  19，    真零内码，  4字节
unsigned int  ad_Tare =    0x00002320;       //  23，    皮零内码，  4字节  

static uint32_t read_key = 1;
static uint32_t read_plan = 1;
static uint32_t read_weight = 1;

static struct fdb_default_kv_node default_kv_table[] = {       
    {"CH",                &XbeeConst_DeviceAddress, sizeof(XbeeConst_DeviceAddress)},     //  1,    车号，    1字节
    {"TQ",                &WeightConst_TQ,          sizeof(WeightConst_TQ)},              //  2,    提取方式，1字节
    {"PM",                &WeightConst_SBType,      sizeof(WeightConst_SBType)},          //  3,    屏幕类型，1字节     6、海安  7长屏铲车  8 新彩屏
    {"WL",                &XbeeConst_NetAddress,    sizeof(XbeeConst_NetAddress)},        //  4,    网络地址，1字节
    {"API",               &XbeeConst_UseAPI,        sizeof(XbeeConst_UseAPI)},            //  5,    使用API，1字节
    {"CC",                &WeightConst_ChanCheShu,  sizeof(WeightConst_ChanCheShu)},      //  6，   TMR数量，1字节
    {"BLE",               &WeightConst_BLE,         sizeof(WeightConst_BLE)},             //  27，    皮零内码，  4字节
///////////////////////////////////////////////////////////////////////////////////////
    {"ad_Percent",        &ad_Percent, sizeof(ad_Percent)},    //  7，    校正重量，1字节
    {"ad_Maxval",         &ad_Maxval,  sizeof(ad_Maxval)},      //  8， 最大称量，4字节
    {"ad_FS",             &ad_FS,      sizeof(ad_FS)},              //  12，   滤波深度，1字节
    {"ad_Point",          &ad_Point,   sizeof(ad_Point)},        //  13，    小数点，  1字节
    {"ad_Inteval",        &ad_Inteval, sizeof(ad_Inteval)},    //  14，    分度值，  1字节
    {"ad_Spanz",          &ad_Spanz,   sizeof(ad_Spanz)},        //  15，    分度内码数， 4字节
    {"ad_Zero",           &ad_Zero,    sizeof(ad_Zero)},          //  19，    真零内码，  4字节
    {"ad_Tare",           &ad_Tare,    sizeof(ad_Tare)},          //  23，    皮零内码，  4字节
		
	  {"read_key",          &read_key,    sizeof(read_key)},  
    {"read_plan",         &read_plan,   sizeof(read_plan)}, 
    {"read_weight",       &read_weight, sizeof(read_weight)}, 
		
    {"beginweight",       &WeightConst_WeightBegin, sizeof(WeightConst_WeightBegin)}, 
    {"begintime",         &TimeConst, sizeof(TimeConst)}, 
    {"completeorder",     &CompleteTarget_order, sizeof(CompleteTarget_order)}, 
		
    {"TimeConst",       &TimeConst, sizeof(TimeConst)}, 
};

#define FDB_LOG_TAG "[main]"

struct fdb_tsdb ts_keydb = { 0 };
struct fdb_tsdb ts_plandb = { 0 };
struct fdb_tsdb ts_weightdb = { 0 };
struct fdb_kvdb kvdb = { 0 };

static uint32_t ts_keyTime = 0;
static uint32_t ts_planTime = 0;
static uint32_t ts_weightTime = 0;

rt_sem_t kv_db_lock;

static void lock(fdb_db_t db)
{
	 rt_sem_take(kv_db_lock, RT_WAITING_FOREVER);
	 __disable_irq();
}

static void unlock(fdb_db_t db)
{
	 rt_sem_release(kv_db_lock);
	 __enable_irq();
}

static fdb_time_t get_keydbtime(void)
{
    return ++ts_keyTime;
}

void write_Flash(const char *key, const void *value_buf, size_t buf_len)
{
		struct fdb_blob blob;
		fdb_kv_set_blob(&kvdb, key, fdb_blob_make(&blob, (void *)value_buf, buf_len));
}

void reset_read_ts(const char key)
{
		if (key == 'k'){ 				
					read_key = ts_keyTime+1;
					write_Flash("read_key", &read_key, sizeof(read_key));			
		}else if (key == 'p'){ 
					read_plan = ts_planTime+1;
					write_Flash("read_plan", &read_plan, sizeof(read_plan));
//          rt_kprintf("read_plan:%02X \n",read_plan);				
	  }else { 
					read_weight = ts_weightTime+1;
					write_Flash("read_weight", &read_weight, sizeof(read_weight));			
	  };
		
		
}

void init_allflash(void)
{
		//   fdb_kv_set_default(&kvdb);
		   fdb_tsl_clean(&ts_weightdb);
			 fdb_tsl_clean(&ts_plandb);
			 fdb_tsl_clean(&ts_keydb);
				ts_keyTime=0;
				ts_planTime=0;
				ts_weightTime=0;
				reset_read_ts('k');
				reset_read_ts('p');
				reset_read_ts('w');
}

static fdb_time_t get_plandbtime(void)
{
    return ++ts_planTime;
}

static fdb_time_t get_weightdbtime(void)
{
    return ++ts_weightTime;
}

uint32_t tsdb_recordcount(const char key)
{
		if (key== 'k'){ 
			 if (read_key > ts_keyTime || ts_keyTime == 0 ) return 0;
			 else
					return ts_keyTime-read_key+1;
		}
		else if (key== 'p'){ 
			if (read_plan > ts_planTime || ts_planTime == 0 ) return 0;
			 else
			 return ts_planTime-read_plan+1;
		};
		if (read_weight > ts_weightTime || ts_weightTime == 0 ) return 0;
		else
		 return ts_weightTime-read_weight+1;
} 

	
static  uint8_t foundF8 = 0;
static bool query_f8_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  unsigned char buf[tsl->log_len];
    fdb_tsdb_t db = arg;
	
	  rt_memset(buf, 0, tsl->log_len);
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &buf, tsl->log_len)));
    if ((buf[3]==0xf8 || buf[3]==0xE8) && tsl->status==FDB_TSL_WRITE)
		{
			foundF8 = 1;
			return true;
		}
		return false;
		//write_Flash("read_key", &ts_keyTime, sizeof(ts_keyTime)); 
}

void findF8(void)
{	 	
   fdb_tsl_iter_by_time(&ts_keydb, read_key, 0xFFFFFFFF, query_f8_cb, &ts_keydb);
}

static  uint8_t foundF4 = 0;
static bool query_f4_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  unsigned char buf[tsl->log_len];
    fdb_tsdb_t db = arg;
	
	  rt_memset(buf, 0, tsl->log_len);
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &buf, tsl->log_len)));
    if ((buf[3]==0xf4 || buf[3]==0xE4) && tsl->status==FDB_TSL_WRITE)
		{
			foundF4 = 1;
			return true;
		}
		return false;
		//write_Flash("read_key", &ts_keyTime, sizeof(ts_keyTime)); 
}

void findF4(void)
{	 	
   fdb_tsl_iter_by_time(&ts_keydb, read_key, 0xFFFFFFFF, query_f4_cb, &ts_keydb);
}

static bool query_f12_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  unsigned char buf[tsl->log_len];
	  unsigned char len = 0;
    fdb_tsdb_t db = arg;
	  if (tsl->log_len>40) len=40;
	  else len=tsl->log_len;
		rt_memset(WeightConst_PlantempList, 0x20, tsl->log_len);
		fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &buf, tsl->log_len)));
		rt_memcpy(WeightConst_PlantempList,buf, len);
		if (buf[3]==0x12 && tsl->status==FDB_TSL_WRITE)
		{
				WeightConst_Run = 1;
				rt_memset(WeightConst_product,0x20,40);				
				rt_memset(WeightConst_feed,0x20,40);				
				for (int i = 0; i <= buf[1]-10; i++) {
						WeightConst_product[i] = buf[i+4];   //产品名称
						if (WeightConst_SBType==1||WeightConst_SBType==6) 
								WeightConst_feed[i] = WeightConst_product[i];   //显示一秒牛舍
				}
				plan_comp.Buffer[0] = buf[buf[1]-5+1];   //产品名称
				plan_comp.Buffer[1] = buf[buf[1]-5];   //产品名称
				for (int i = 2; i < 6; i++) 
						plan_comp.Buffer[i] = buf[buf[1]-5+i];   //产品名称		       			
		}
		return false;
}

void findF12(void)
{	 
   uint8_t	i = 0;
	 if (read_plan>50) i = read_plan-50;
	
   fdb_tsl_iter_by_time(&ts_plandb, i, read_plan, query_f12_cb, &ts_plandb);
}

static  uint32_t foundkey = 0;
static bool query_key_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  //unsigned char buf[tsl->log_len];
    fdb_tsdb_t db = arg;
	  rt_memset(XbeeConst_FTxBuf0, 0, tsl->log_len);
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &XbeeConst_FTxBuf0, tsl->log_len)));
	  for (int i=tsl->log_len; i>0; i--)
		{
			XbeeConst_FTxBuf0[i] = XbeeConst_FTxBuf0[i-1];
		}
		XbeeConst_FTxBuf0[0] = tsl->log_len;
    if (tsl->status==FDB_TSL_WRITE)
		{
			foundkey = tsl->time;
			read_key = foundkey;
			return true;
		}
		return false;
}

uint32_t findkey(void)
{	 
	 foundkey = 0xFFFFFFFF;
   fdb_tsl_iter_by_time(&ts_keydb, read_key, 0xFFFFFFFF, query_key_cb, &ts_keydb);
	 return foundkey;
	//return 0xFFFFFFFF;
}

void save_read_ts(const char key)
{
	if (tsdb_recordcount(key)>0)
	{
		
		if (key == 'k'){ 	
        if (findkey()<0xFFFFFFFF){	
					if(XbeeConst_FrameNumLast == XbeeConst_FTxBuf0[XbeeConst_FTxBuf0[0]-1]){
						read_key++;			
						write_Flash("read_key", &read_key, sizeof(read_key));			
					}
				}
		}else if (key == 'p'){ 
					read_plan++;
					write_Flash("read_plan", &read_plan, sizeof(read_plan));			
//			    rt_kprintf("read_plan save_read_t:%02X \n",read_plan);			
	  }else { 
					read_weight++;
					write_Flash("read_weight", &read_weight, sizeof(read_weight));			
	  };
	}
}

static  uint32_t foundplan = 0;
static bool query_plan_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  //unsigned char buf[tsl->log_len];
    fdb_tsdb_t db = arg;
	  rt_memset(WeightConst_PlantempList, 0, tsl->log_len);
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &WeightConst_PlantempList, tsl->log_len)));
	
    if (tsl->status==FDB_TSL_WRITE)
		{
			foundplan = tsl->time;
			read_plan = tsl->time;
			return true;
		}
		return false;
}

uint32_t findplan(void)
{	 
	 foundplan = 0;
//	 rt_kprintf("read_plan findplan:%02X \n",read_plan);			
   fdb_tsl_iter_by_time(&ts_plandb, read_plan, 0xFFFFFFFF, query_plan_cb, &ts_plandb);
	 return foundplan;
}

static  uint32_t foundNextplan = 0;
static bool query_Nextplan_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
    fdb_tsdb_t db = arg;
	  uint8_t Nextfeedlength = 0;
	  rt_memset(WeightConst_Nextfeed, 0x20, tsl->log_len);
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &WeightConst_Nextfeed, tsl->log_len)));
	
    if (tsl->status==FDB_TSL_WRITE)
		{
			foundNextplan = tsl->time;
			if (WeightConst_Nextfeed[3]==0x15) {	
        Nextfeedlength = WeightConst_Nextfeed[1];		
				
				WeightConst_NextWeightTarget = WeightConst_Nextfeed[Nextfeedlength-6]<<8 ;         //目标总量
				WeightConst_NextWeightTarget = WeightConst_NextWeightTarget | WeightConst_Nextfeed[Nextfeedlength-5];
				for (int i = 0; i <= Nextfeedlength-11; i++)
						WeightConst_Nextfeed[i] = WeightConst_Nextfeed[i+4]; 
				for (int i = Nextfeedlength-11; i <= tsl->log_len; i++) 
						WeightConst_Nextfeed[i] = 0x20; 		
			}
			return true;
		}
		return false;
}

uint32_t findNextplan(void)
{	 
	 foundNextplan = 0;
   fdb_tsl_iter_by_time(&ts_plandb, read_plan+1, 0xFFFFFFFF, query_Nextplan_cb, &ts_plandb);
	 return foundNextplan;
}


static  uint32_t foundweight = 0;
static  uint32_t read_weight_temp = 0;
static bool query_weight_cb(fdb_tsl_t tsl, void *arg)
{
    struct fdb_blob blob;
	  unsigned char buf[7];
    fdb_tsdb_t db = arg;
    fdb_blob_read((fdb_db_t) db, fdb_tsl_to_blob(tsl, fdb_blob_make(&blob, &buf, 7)));
	  for (int i=7; i>0; i--)
				XbeeConst_FTxBuf0[4+foundweight*7+i] = buf[7-i];

		read_weight_temp = tsl->time;
		foundweight++;

		return foundweight>3;
}

uint32_t findweight(void)
{		
	 unsigned char CRCNum=0;
	 foundweight = 0;
	 read_weight_temp = read_weight;
	 rt_memset(XbeeConst_FTxBuf0, 0, 0x22);
  
   fdb_tsl_iter_by_time(&ts_weightdb, read_weight, 0xFFFFFFFF, query_weight_cb, &ts_weightdb);
	 if (foundweight>3){
		   XbeeConst_FTxBuf0[0] = 0x22;
			 XbeeConst_FTxBuf0[1] = 0x7E;
			 XbeeConst_FTxBuf0[2] = 0x20;
			 XbeeConst_FTxBuf0[3] = XbeeConst_DeviceAddress;
			 XbeeConst_FTxBuf0[4] = 0xF0;
			 XbeeConst_FTxBuf0[33] = XbeeConst_FrameNum ++;
			 for (int i=1; i< 34; i++)  CRCNum+=XbeeConst_FTxBuf0[i];
			 XbeeConst_FTxBuf0[34] = 0xFF - CRCNum;
		   read_weight = read_weight_temp;
	 }
	 return foundweight;

}

uint8_t ts_pushArrary(fdb_tsdb_t db, uint8_t *buf, uint8_t length)  
{
		struct fdb_blob blob;	
		fdb_err_t result = FDB_NO_ERR;
		foundF8 = 0;
	  foundF4 = 0;
		if (strcmp(((fdb_db_t)db)->name, "key") == 0 && (buf[3] == 0xF8 || buf[3] == 0xE8))
			findF8();
		
    if (strcmp(((fdb_db_t)db)->name, "key") == 0 && (buf[3] == 0xF4 || buf[3] == 0xE4))
			findF4();
		
		if (foundF8==0 && foundF4==0){
				result = fdb_tsl_append(db, fdb_blob_make(&blob, buf, length));	
				if (result != FDB_NO_ERR)
				{	 
//					rt_kprintf("ts_pushArrary:%02X \n", ts_planTime);		
					return 0;
				}
		}		
	
		return 1;
}

void read_Flash(void)
{
		struct fdb_blob blob;
	
		fdb_kv_get_blob(&kvdb, "CH", fdb_blob_make(&blob, &XbeeConst_DeviceAddress, sizeof(XbeeConst_DeviceAddress)));
		fdb_kv_get_blob(&kvdb, "TQ", fdb_blob_make(&blob, &WeightConst_TQ, sizeof(WeightConst_TQ)));
		fdb_kv_get_blob(&kvdb, "PM", fdb_blob_make(&blob, &WeightConst_SBType, sizeof(WeightConst_SBType)));
		fdb_kv_get_blob(&kvdb, "WL", fdb_blob_make(&blob, &XbeeConst_NetAddress, sizeof(XbeeConst_NetAddress)));
		fdb_kv_get_blob(&kvdb, "API", fdb_blob_make(&blob, &XbeeConst_UseAPI, sizeof(XbeeConst_UseAPI)));
		fdb_kv_get_blob(&kvdb, "CC", fdb_blob_make(&blob, &WeightConst_ChanCheShu, sizeof(WeightConst_ChanCheShu)));
		fdb_kv_get_blob(&kvdb, "BLE", fdb_blob_make(&blob, &WeightConst_BLE, sizeof(WeightConst_BLE)));
    if (WeightConst_BLE>1) isCC=1;
	
		fdb_kv_get_blob(&kvdb, "ad_Percent", fdb_blob_make(&blob, &ad_Percent, sizeof(ad_Percent)));
		fdb_kv_get_blob(&kvdb, "ad_Maxval", fdb_blob_make(&blob, &ad_Maxval, sizeof(ad_Maxval)));
		fdb_kv_get_blob(&kvdb, "ad_FS", fdb_blob_make(&blob, &ad_FS, sizeof(ad_FS)));
		fdb_kv_get_blob(&kvdb, "ad_Point", fdb_blob_make(&blob, &ad_Point, sizeof(ad_Point)));
		fdb_kv_get_blob(&kvdb, "ad_Inteval", fdb_blob_make(&blob, &ad_Inteval, sizeof(ad_Inteval)));
		fdb_kv_get_blob(&kvdb, "ad_Spanz", fdb_blob_make(&blob, &ad_Spanz, sizeof(ad_Spanz)));
		fdb_kv_get_blob(&kvdb, "ad_Zero", fdb_blob_make(&blob, &ad_Zero, sizeof(ad_Zero)));
		fdb_kv_get_blob(&kvdb, "ad_Tare", fdb_blob_make(&blob, &ad_Tare, sizeof(ad_Tare)));
	
	  fdb_kv_get_blob(&kvdb, "read_key", fdb_blob_make(&blob, &read_key, sizeof(read_key)));
	  fdb_kv_get_blob(&kvdb, "read_plan", fdb_blob_make(&blob, &read_plan, sizeof(read_plan)));
	  fdb_kv_get_blob(&kvdb, "read_weight", fdb_blob_make(&blob, &read_weight, sizeof(read_weight)));
		
		fdb_kv_get_blob(&kvdb, "beginweight", fdb_blob_make(&blob, &WeightConst_WeightBegin, sizeof(WeightConst_WeightBegin)));
		fdb_kv_get_blob(&kvdb, "begintime", fdb_blob_make(&blob, &TimeConst, sizeof(TimeConst)));
	  fdb_kv_get_blob(&kvdb, "completeorder", fdb_blob_make(&blob, &CompleteTarget_order, sizeof(CompleteTarget_order)));
		
	  fdb_kv_get_blob(&kvdb, "TimeConst", fdb_blob_make(&blob, &TimeConst, sizeof(TimeConst)));
}


void onbordflash_init(void)
{
		fdb_err_t result;
	  struct fdb_default_kv default_kv;
	
	  kv_db_lock = rt_sem_create("kv_db_lock", 1, RT_IPC_FLAG_FIFO);
    default_kv.kvs = default_kv_table;
    default_kv.num = sizeof(default_kv_table) / sizeof(default_kv_table[0]);		
	
	  fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_LOCK, lock);
    fdb_kvdb_control(&kvdb, FDB_KVDB_CTRL_SET_UNLOCK, unlock);
	
	  result = fdb_kvdb_init(&kvdb, "env", "kv", &default_kv, NULL);

    if (result != FDB_NO_ERR) {
      return ;
		}			
		/////////////
		fdb_tsdb_control(&ts_keydb, FDB_TSDB_CTRL_SET_LOCK, lock);
		fdb_tsdb_control(&ts_keydb, FDB_TSDB_CTRL_SET_UNLOCK, unlock);
	
		result = fdb_tsdb_init(&ts_keydb, "key", "ts_key", get_keydbtime, 48, NULL);
	
	  if (result != FDB_NO_ERR) {
          return ;
		}
		/* read last saved time for simulated timestamp */
		fdb_tsdb_control(&ts_keydb, FDB_TSDB_CTRL_GET_LAST_TIME, &ts_keyTime);
		/////////////////		
		
		/////////////
		fdb_tsdb_control(&ts_plandb, FDB_TSDB_CTRL_SET_LOCK, lock);
		fdb_tsdb_control(&ts_plandb, FDB_TSDB_CTRL_SET_UNLOCK, unlock);
	
		result = fdb_tsdb_init(&ts_plandb, "plan", "ts_plan", get_plandbtime, 48, NULL);
	
	  if (result != FDB_NO_ERR) {
          return ;
		}
		/* read last saved time for simulated timestamp */
		fdb_tsdb_control(&ts_plandb, FDB_TSDB_CTRL_GET_LAST_TIME, &ts_planTime);
		/////////////////		
		/////////////
		fdb_tsdb_control(&ts_weightdb, FDB_TSDB_CTRL_SET_LOCK, lock);
		fdb_tsdb_control(&ts_weightdb, FDB_TSDB_CTRL_SET_UNLOCK, unlock);
	
		result = fdb_tsdb_init(&ts_weightdb, "weight", "ts_weight", get_weightdbtime, 7, NULL);
	
	  if (result != FDB_NO_ERR) {
          return ;
		}
		/* read last saved time for simulated timestamp */
		fdb_tsdb_control(&ts_weightdb, FDB_TSDB_CTRL_GET_LAST_TIME, &ts_weightTime);
		/////////////////
		read_Flash();
}

void saveApi(rt_sem_t lock_sem,UART_HandleTypeDef *huart, uint8_t *pData)
{	
		//保存命令
		pData[0] = 0x41;
		pData[1] = 0x54;
		pData[2] = 0x57;
		pData[3] = 0x52;
		pData[4] = 0x0D;
		HAL_UART_Transmit_DMA(huart, pData, 5);
		if (rt_sem_take(lock_sem, 2000) == RT_EOK) {
			 //退出命令
				pData[0] = 0x41;
				pData[1] = 0x54;
				pData[2] = 0x43;
				pData[3] = 0x4E;
				pData[4] = 0x0D;
				HAL_UART_Transmit_DMA(huart, pData, 5);	
				if (rt_sem_take(lock_sem, 2000) != RT_EOK)
					rt_sem_release(lock_sem);
				else rt_sem_release(lock_sem);									
		} else rt_sem_release(lock_sem);
}

void enterApi(rt_sem_t lock_sem, UART_HandleTypeDef *huart, uint8_t *pData)
{
    unsigned char i;
		for (i = 0; i < 3; i++)
				pData[i] = 0x2B;
		rt_sem_take(lock_sem, RT_WAITING_FOREVER);
		HAL_UART_Transmit_DMA(huart, pData, 3);
}

void setAPI(void)
{
    if (!XbeeConst_UseAPI)
    {
        enterApi(uart3_lock, &huart3, usart3_send_data);
		  	if (rt_sem_take(uart3_lock, 2000) == RT_EOK) {
				  usart3_send_data[0] = 0x41;
					usart3_send_data[1] = 0x54;
					usart3_send_data[2] = 0x41;
					usart3_send_data[3] = 0x50;
					usart3_send_data[4] = 0x30;
					usart3_send_data[5] = 0x0D;
					
					HAL_UART_Transmit_DMA(&huart3, usart3_send_data, 6);
					if (rt_sem_take(uart3_lock, 2000) == RT_EOK) {
							saveApi(uart3_lock, &huart3, usart3_send_data);
					 } else rt_sem_release(uart3_lock);					
				} else rt_sem_release(uart3_lock);
    }
		
		enterApi(uart2_lock, &huart2, usart2_send_data);
		if (rt_sem_take(uart2_lock, 2000) == RT_EOK) {
			//设置API Enable =2
			usart2_send_data[0] = 0x41;
			usart2_send_data[1] = 0x54;
			usart2_send_data[2] = 0x41;
			usart2_send_data[3] = 0x50;
			if (XbeeConst_UseAPI>0)
					usart2_send_data[4] = 0x32;
			else
					usart2_send_data[4] = 0x30;
			usart2_send_data[5] = 0x0D;
			
			HAL_UART_Transmit_DMA(&huart2, usart2_send_data, 6);
			if (rt_sem_take(uart2_lock, 2000) == RT_EOK) {
					saveApi(uart2_lock, &huart2, usart2_send_data);
				  beep();
				  rt_thread_mdelay(500);
				  beep();
				  return;
			} else rt_sem_release(uart2_lock);					
		} else rt_sem_release(uart2_lock);
		beep();
}


void setNetAddress(void)
{
		if (!XbeeConst_UseAPI)
    {
        enterApi(uart3_lock, &huart3, usart3_send_data);
		  	if (rt_sem_take(uart3_lock, 2000) == RT_EOK) {
					usart3_send_data[0] = 0x41;
					usart3_send_data[1] = 0x54;
					usart3_send_data[2] = 0x49;
					usart3_send_data[3] = 0x44;
					usart3_send_data[4] = 0x37;
					usart3_send_data[5] = 0x46;
					usart3_send_data[6] = 0x46;
					usart3_send_data[7] = 0x45;
					usart3_send_data[8] = 0x0D;
					
					HAL_UART_Transmit_DMA(&huart3, usart3_send_data, 9);
					if (rt_sem_take(uart3_lock, 2000) == RT_EOK) {
							saveApi(uart3_lock, &huart3, usart3_send_data);
					 } else rt_sem_release(uart3_lock);					
				} else rt_sem_release(uart3_lock);
    }
		
		enterApi(uart2_lock, &huart2, usart2_send_data);
		if (rt_sem_take(uart2_lock, 2000) == RT_EOK) {
			//设置API Enable =2
			usart2_send_data[0] = 0x41;
			usart2_send_data[1] = 0x54;
			usart2_send_data[2] = 0x49;
			usart2_send_data[3] = 0x44;
			usart2_send_data[4] = 0x37;
			usart2_send_data[5] = 0x46;
			usart2_send_data[6] = 0x46;
			if(XbeeConst_NetAddress>0)
			{
					if (XbeeConst_NetAddress>9)	usart2_send_data[7] = (XbeeConst_NetAddress-10)+0x41;
					else	 usart2_send_data[7] = XbeeConst_NetAddress+0x30;
			}
			else	usart2_send_data[7] = 0x46;
			usart2_send_data[8] = 0x0D;
			
			HAL_UART_Transmit_DMA(&huart2, usart2_send_data, 9);
			if (rt_sem_take(uart2_lock, 2000) == RT_EOK) {
					saveApi(uart2_lock, &huart2, usart2_send_data);
				  beep();
				  rt_thread_mdelay(500);
				  beep();
				  return;
			} else rt_sem_release(uart2_lock);					
		} else rt_sem_release(uart2_lock);
		beep();
}
/*
void setBT(void)
{
    //进入命令
    // WeightConst_Weight_display[7] = 0x20;WeightConst_Weight_display[6] = 0x20;
    //	WeightConst_Weight_display[5] = 0x20;WeightConst_Weight_display[4] = 0x20;
    unsigned char sendCount=0,i;
    for (int SendDisplay_i = 0; SendDisplay_i < 8; SendDisplay_i++)   //显示重量
        WeightConst_Weight_display[SendDisplay_i]=0x20;
    USART3_Configuration(0);
    sendCount = 0;
    while(sendCount<2)
    {
        setBT_timer = 1;
        //AT+CLRBAND   AT+HOSTEN1
        usart3_send_data[0] = 0x41;
        usart3_send_data[1] = 0x54;
        usart3_send_data[2] = 0x2B;
        usart3_send_data[3] = 0x43;
        usart3_send_data[4] = 0x4C;
        usart3_send_data[5] = 0x52;
        usart3_send_data[6] = 0x42;
        usart3_send_data[7] = 0x41;
        usart3_send_data[8] = 0x4E;
        usart3_send_data[9] = 0x44;
        USART_Send_DMA(remoteSerial, 0x0A);

        while(setBT_timer>0 && setBT_timer<500);
        if (setBT_timer>=500)
            sendCount++;
        else if(setBT_timer==0)
            sendCount=4;
    }


    sendCount = 0;
    while(sendCount<2)
    {
        setBT_timer = 1;
        //41 54 2B 48 4F 53 54 45 4E 31   AT+HOSTEN1
        usart3_send_data[0] = 0x41;
        usart3_send_data[1] = 0x54;
        usart3_send_data[2] = 0x2B;
        usart3_send_data[3] = 0x48;
        usart3_send_data[4] = 0x4F;
        usart3_send_data[5] = 0x53;
        usart3_send_data[6] = 0x54;
        usart3_send_data[7] = 0x45;
        usart3_send_data[8] = 0x4E;
        usart3_send_data[9] = 0x31;
        USART_Send_DMA(remoteSerial, 0x0A);

        while(setBT_timer>0 && setBT_timer<500);
        if (setBT_timer>=500)
            sendCount++;
        else if(setBT_timer==0)
            sendCount=4;
    }

    sendCount = 0;
    while(sendCount<2)
    {
        setBT_timer = 1;
        //AT+RST
        usart3_send_data[0] = 0x41;
        usart3_send_data[1] = 0x54;
        usart3_send_data[2] = 0x2B;
        usart3_send_data[3] = 0x52;
        usart3_send_data[4] = 0x53;
        usart3_send_data[5] = 0x54;
        USART_Send_DMA(remoteSerial, 0x06);

        while(setBT_timer>0 && setBT_timer<500);
        if (setBT_timer>=500)
            sendCount++;
        else if(setBT_timer==0)
        {
            setBT_timer=1;
            while(setBT_timer>0 && setBT_timer<1000);
            sendCount=4;
        }
    }

    sendCount = 0;
    //  while(sendCount<2)
    {
        setBT_timer = 1;
        //AT+SCAN1
        usart3_send_data[0] = 0x41;
        usart3_send_data[1] = 0x54;
        usart3_send_data[2] = 0x2B;
        usart3_send_data[3] = 0x53;
        usart3_send_data[4] = 0x43;
        usart3_send_data[5] = 0x41;
        usart3_send_data[6] = 0x4E;
        usart3_send_data[7] = 0x31;
        USART_Send_DMA(remoteSerial, 0x08);

        while(setBT_timer>0 && setBT_timer<500);
        if (setBT_timer>=500)
            sendCount++;
        else if(setBT_timer==0)
        {
            setBT_timer=1;
            while(setBT_timer>0 && setBT_timer<5000);
            if (setBT_timer>=5000)
            {
                WeightConst_Weight_display[7] = 0xCA;
                WeightConst_Weight_display[6] = 0xA7;
                WeightConst_Weight_display[5] = 0xB0;
                WeightConst_Weight_display[4] = 0xDC;
                sendCount=4;
                WeightConst_BLE = 0;
                TMRWatchConst[Const_BLE].Data = WeightConst_BLE;
                EE_WriteVariable(TMRWatchConst_EEPROM_START_ADDRESS, TMRWatchConst[Const_BLE].VirtAddress,
                                 TMRWatchConst, &TMRWatchConst_CurWrAddress);

            }	//失败CAA7 B0DC   //失败
            else
            {
                setBT_timer = 1;
                //AT+BAND0
                usart3_send_data[0] = 0x41;
                usart3_send_data[1] = 0x54;
                usart3_send_data[2] = 0x2B;
                usart3_send_data[3] = 0x42;
                usart3_send_data[4] = 0x41;
                usart3_send_data[5] = 0x4E;
                usart3_send_data[6] = 0x44;
                usart3_send_data[7] = 0x30;
                USART_Send_DMA(remoteSerial, 0x08);

                while(setBT_timer>0 && setBT_timer<500);
                if (setBT_timer>=500)
                {
                    WeightConst_Weight_display[7] = 0xCA;
                    WeightConst_Weight_display[6] = 0xA7;
                    WeightConst_Weight_display[5] = 0xB0;
                    WeightConst_Weight_display[4] = 0xDC;
                    WeightConst_BLE = 0;
                    TMRWatchConst[Const_BLE].Data = WeightConst_BLE;
                    EE_WriteVariable(TMRWatchConst_EEPROM_START_ADDRESS, TMRWatchConst[Const_BLE].VirtAddress,
                                     TMRWatchConst, &TMRWatchConst_CurWrAddress);

                }	//失败CAA7 B0DC
                else if(setBT_timer==0)
                {
                    WeightConst_Weight_display[7] = 0xB3;
                    WeightConst_Weight_display[6] = 0xC9;
                    WeightConst_Weight_display[5] = 0xB9;
                    WeightConst_Weight_display[4] = 0xA6;
                    WeightConst_BLE = 1;
                    TMRWatchConst[Const_BLE].Data = WeightConst_BLE;
                    EE_WriteVariable(TMRWatchConst_EEPROM_START_ADDRESS, TMRWatchConst[Const_BLE].VirtAddress,
                                     TMRWatchConst, &TMRWatchConst_CurWrAddress);
                }		//成功B3C9 B9A6
            }
        }
    }

    USART3_Configuration(1);
}

void setNetAddress_byapi(u8 netid)
{   //7E 00 06 08 01 49 44 7F FE EC
    unsigned char sendCount=0,i;
    usart2_send_data[0] = 0x7E;
    usart2_send_data[1] = 0x00;
    usart2_send_data[2] = 0x06; 
    usart2_send_data[3] = 0x08;
    usart2_send_data[4] = 0x01;
    usart2_send_data[5] = 0x49;
    usart2_send_data[6] = 0x44;
    usart2_send_data[7] = 0x7F;
    if(netid)
        usart2_send_data[8] = 0xF0 + netid;
    else	usart2_send_data[8] = 0xFF;
    for (i = 3; i < 9; i++)
        sendCount = sendCount + usart2_send_data[i];
    usart2_send_data[9] = 0xFF-sendCount;
    USART_Send_DMA(xbeeSerial, 0x0A);
}
*/
