#include "bsp.h"

NODESTATUS NodeStatus;//节点状态
static RoutrTable route_table[MAX_NODE_NUM];
static PathTable path_table[MAX_NODE_NUM];
static HANDLEMULTIPACK IsHandle[DATA_BUF_COUNT];
static DATA_BUF DataBuf[DATA_BUF_COUNT];//数据缓冲,最大长度PAYLOAD_DATA_LEN
static u32 heart_time=0,wait_time=0;
static u16 link_time=0;
static u8 ThreadLock=0,isLink=0;
static u8 pipe1_mac[MAC_LEN]={0x00,0xB9,0x7F,0x55,0xB0};//通道1地址(本网络节点)
static u8 pipe2_mac[MAC_LEN]={0xFF,0xB9,0x7F,0x55,0xB0};//通道2地址(所有节点),分配地址
static HANDLERECECALLBACK RecvHandler=NULL;
static HANDLESENDCALLBACK SendHandler=NULL;

void NRF_Init(void)//初始化协议
{
	MemSet((BYTE *)&DataBuf,0,sizeof(DATA_BUF)*DATA_BUF_COUNT);//初始化缓冲区为空闲状态
	MemSet((BYTE *)&IsHandle,0,sizeof(HANDLEMULTIPACK)*DATA_BUF_COUNT);
	MemSet((BYTE *)&route_table,0,sizeof(RoutrTable)*MAX_NODE_NUM);//初始化节点状态
	MemSet((BYTE *)&NodeStatus,0,sizeof(NODESTATUS));//初始化节点状态
	if(NRF_IsHaveStoreData(NRF_STORE_FLAG,NRF_STORE_ADDRESS))
	{
		NRF_ReadParam();
	}
	NodeStatus.route_addr=0x01;
	NodeStatus.channel=124;//初始信道124,可用信道0~124
	NodeStatus.link_status=DISCONNECT;
	NRF_Config(NodeStatus.node_mac,NodeStatus.channel);//硬件初始化
	NRF_SetPipe1Mac(pipe1_mac);
	NRF_SetPipe2Mac(pipe2_mac);
	IS_TIMEOUT_10MS(eTim3, 0);
}

void NRF_SetPipe1Mac(u8 *addr)
{
	NRF_CE = 0;
	NRF_GetMacAddr(addr,0xff);//生成MAC地址
	if(addr[0]==0xFF)
	{
		addr[0]-=1;
	}
	NRF_WriteBuf(RX_ADDR_P1, addr, MAC_LEN);//写通道1,RX地址
	NRF_WriteReg(CONFIG, 0x0B);//接收模式
	NRF_CE = 1;
}

void NRF_SetPipe2Mac(u8 *addr)
{
	NRF_CE = 0;
	NRF_WriteReg(RX_ADDR_P2, addr[0]);//写通道2,RX地址
	NRF_WriteReg(CONFIG, 0x0B);//接收模式
	NRF_CE = 1;
}

void NRF_SetDefaultRecvHandler(HANDLERECECALLBACK pFun)
{
	RecvHandler=pFun;
}

void NRF_SetDefaultSendHandler(HANDLESENDCALLBACK pFun)
{
	SendHandler=pFun;
}

void NRF_SetWaitLinkTime(u32 time)
{
	wait_time=time;
}

u8 NRF_GetThreadLockState(void)
{
	return ThreadLock;
}

void NRF_WaitDistributionAddr(void)
{
	NRF_ClearStroreData(NRF_STORE_ADDRESS);
	MemSet((BYTE *)&NodeStatus.node_mac,0,MAC_LEN);//初始化mac地址
	NodeStatus.addr=0;
}

void NRF_StoreParam(void)
{
	NRFSTOREDATA store_data;
	MemSet((BYTE *)&store_data,0,sizeof(NRFSTOREDATA));
	store_data.addr=NodeStatus.addr;
	store_data.pwd=NodeStatus.pwd;
	MemCopy((BYTE *)store_data.local_mac,(BYTE *)NodeStatus.node_mac,MAC_LEN);
	EE_FlashWrite(NRF_STORE_FLAG,NRF_STORE_ADDRESS,(u8 *)&store_data,sizeof(NRFSTOREDATA));//擦除并写1页flash
	NRF_SetPipe1Mac(pipe1_mac);
}

static void NRF_ReadParam(void)
{
	if(NRF_IsHaveStoreData(NRF_STORE_FLAG,NRF_STORE_ADDRESS))
	{
		NRFSTOREDATA store_data;

		MemSet((BYTE *)&store_data,0,sizeof(NRFSTOREDATA));
		EE_FlashReadFlag(NRF_STORE_FLAG,NRF_STORE_ADDRESS,(u8 *)&store_data,sizeof(NRFSTOREDATA));
		NodeStatus.addr=store_data.addr;
		NodeStatus.pwd=store_data.pwd;
		MemCopy((BYTE *)NodeStatus.node_mac,(BYTE *)store_data.local_mac,MAC_LEN);
	}
}

void NRF_CalcCols(u8 *col,u8 addr)
{
	u8 i;

	for(i = 5; i > 0; i--)
	{
		*col = (*col << 1) ^ addr;
		col++;
	}
}

void NRF_InvMixColumn(u8 *column,u8 addr)
{
	u8 r[5];

	r[0] = column[1] ^ column[2] ^ column[3] ^ column[4];
	r[1] = column[0] ^ column[2] ^ column[3] ^ column[4];
	r[2] = column[0] ^ column[1] ^ column[3] ^ column[4];
	r[3] = column[0] ^ column[1] ^ column[2] ^ column[4];
	r[4] = column[0] ^ column[1] ^ column[2] ^ column[3];

	NRF_CalcCols(column,addr);

	r[0] ^= column[0] ^ column[1];
	r[1] ^= column[1] ^ column[2];
	r[2] ^= column[2] ^ column[3];
	r[3] ^= column[3] ^ column[4];
	r[4] ^= column[4] ^ column[0];

	NRF_CalcCols(column,addr);

	r[0] ^= column[0] ^ column[2];
	r[1] ^= column[1] ^ column[3];
	r[2] ^= column[2] ^ column[4];
	r[3] ^= column[3] ^ column[0];
	r[4] ^= column[4] ^ column[1];

	NRF_CalcCols(column,addr);

	column[0] ^= column[1] ^ column[2] ^ column[3] ^ column[4];
	r[0] ^= column[0];
	r[1] ^= column[0];
	r[2] ^= column[0];
	r[3] ^= column[0];
	r[4] ^= column[0];
	
	column[0] = r[0];
	column[1] = r[1];
	column[2] = r[2];
	column[3] = r[3];
	column[4] = r[4];
}

void NRF_GetMacAddr(u8 *mac,const u8 addr)
{
	u8 str[5]={0};
	u8 str1[10]={0};
	u8 i;
	
	sprintf((char *)str1,"%d",NodeStatus.pwd);
	if(addr>0&&addr<0xFF)
	{
		for(i=0;i<10;i++)//异或加密
		{
			 str1[i] ^= addr;
		}
		if(addr>0&&addr<128)
		{
			str[1] = (str1[0]+str1[1])<<2;
			str[2] = (str1[2]+str1[3])<<2;
			str[3] = (str1[4]+str1[5])<<2;
			str[4] = (str1[6]+str1[7])<<2;
			str[0] = (str1[8]+str1[9])<<2;
		}
		if(addr>=128&&addr<0xFF)
		{
			str[1] = (str1[0]+str1[1]);
			str[2] = (str1[2]+str1[3]);
			str[3] = (str1[4]+str1[5]);
			str[4] = (str1[6]+str1[7]);
			str[0] = (str1[8]+str1[9]);
		}
		NRF_InvMixColumn(str,addr);
	}
	else 
	{
		if(addr==0xFF)
		{
			str[0]=cal_crc8(str1, 10);
			str[1]=0xB9;
			str[2]=0x7F;
			str[3]=0x55;
			str[4]=0xB0;
		}
		if(addr==0)
		{
			for(i=0;i<5;i++)
			{
				 str[i] = 0xFF;
			}
		}
	}
	MemCopy((BYTE *)mac,(BYTE *)str,MAC_LEN);
}

void NRF_SendData(const u8 dst_addr,const u8 type,const u8 *buf,HANDLESENDCALLBACK fun)//发送数据接口
{
	static u32 id=0;
	u8 idx;

	if(dst_addr!=NodeStatus.addr)
	{
		idx=NRF_MallocIdleDataBufId();
		if(0xFF==idx)
		{
			return;
		}
		DataBuf[idx].status=WAIT_SEND;
		DataBuf[idx].HandleCallBack=fun;
		DataBuf[idx].payload.header.PID=NodeStatus.pwd;
		DataBuf[idx].payload.header.SID=id++;//获取唯一的ID
		DataBuf[idx].payload.header.the_addr=NodeStatus.addr;
		DataBuf[idx].payload.header.src_addr=NodeStatus.addr;
		DataBuf[idx].payload.header.dst_addr=dst_addr;
		DataBuf[idx].payload.header.ass_addr=dst_addr;
		DataBuf[idx].payload.header.hop_addr=0;
		DataBuf[idx].payload.header.hop_count=0;
		DataBuf[idx].payload.header.pack_type=type;
		MemCopy((BYTE *)DataBuf[idx].payload.buf,(BYTE *)buf,PAYLOAD_DATA_LEN);
		//if(CHECK_LINK==type) NodeStatus.heart_status=1;
		if(0xFFFFFFFF==id)
		{
			id=0;
		}
	}
}

static void NRF_AutoLink(void)//自动连接
{
	static u8 iFlag=0;
	static u8 nCnt=0;
	
	switch(NodeStatus.link_status)
	{
		case DISCONNECT:
			if(NodeStatus.addr>=30&&NodeStatus.addr<0xFF)
			{
				link_time++;
				if(link_time>500)//5秒
				{
					u8 path[MAX_HOP_NUM]={0};
					
					NRF_SendData(NodeStatus.route_addr,START_LINK,path,SendHandler);//发送数据接口
					link_time=0;
				}
				if(IS_TIMEOUT_10MS(eTim3, 3000)&&!iFlag)//30s
				{
					if(nCnt<3)
					{
						if(!NRF_CheckReg())
						{
							SetLed(0xff,300,20);
							NRF_Init();
							iFlag=1;
						}
						else
						{
							nCnt++;
						}
					}
				}
			}
			break;
		case WAIT_CONNECT:
			if(Get_RunTime()-wait_time>=WAIT_CONNECT_INTERVAL)//间隔20秒
			{
				NodeStatus.link_status=DISCONNECT;
				link_time=500;
				IS_TIMEOUT_10MS(eTim3, 0);
				if(NodeStatus.addr>=30&&NodeStatus.addr<0xFF)
				{
					SetLed(0xff,100,100);
				}
				else
				{
					SetLed(0xff,18,18);
				}
			}
			break;
		case CONNECTED:
			if(isLink)
			{
				if(Get_RunTime()-heart_time>=300)//连接后等待3秒发送本机状态到路由节点
				{
					char cmd_buf[PAYLOAD_DATA_LEN]={0};

					isLink=0;
					sprintf(cmd_buf,"{ck%03d%03d%d}",NodeStatus.addr/10,Get_Nid(NodeStatus.addr),
														GPIO_ReadInputDataBit(GPIOA,RELAY_PIN));
					NRF_SendData(NodeStatus.route_addr,NODE_KEY_DATA,(u8 *)cmd_buf,SendHandler);
				}
			}
			if(Get_RunTime()-heart_time>HEART_LINK_INTERVAL)//间隔25秒;1次
			{
				nCnt=0;
				iFlag=0;
				IS_TIMEOUT_10MS(eTim3, 0);
				NodeStatus.link_status=DISCONNECT;
				link_time=500;
				SetLed(0xff,100,100);
			}				
			break;
		default:break;
	}
}

u8 NRF_UpdateToRoutrTablePath(u8 idx,LPayload pPayLoad)//更新路径表
{
	u8 k;
	
	MemCopy((BYTE *)route_table[idx].path,(BYTE *)pPayLoad->buf,sizeof(pPayLoad->buf));
	if(pPayLoad->header.hop_addr)//上一跳地址有效
	{
		for(k=0; k<MAX_HOP_NUM; k++)//遍历路径表
		{
			if(!route_table[idx].path[k])//找到空位
			{
				route_table[idx].path[k]=pPayLoad->header.hop_addr;//把上一跳地址添加到路径表最后
				return TRUE;
			}
		}
	}
	return FALSE;
}

//返回0,列表已满; 返回1,添加成功;
u8 NRF_AddNodeToRoutrTable(LPayload pPayLoad)//添加1个节点到路由表
{
	u8 i;

	for(i=0; i<MAX_NODE_NUM; i++)//遍历路由表
	{
		if(route_table[i].addr==pPayLoad->header.the_addr)//节点已存在
		{
			NRF_UpdateToRoutrTablePath(i,pPayLoad);//更新路径表
			return TRUE;
		}
	}
	for(i=0; i<MAX_NODE_NUM; i++)//没有找到地址
	{
		if(!route_table[i].addr)//找到空位
		{
			route_table[i].addr=pPayLoad->header.the_addr;//添加到路由表
			NRF_UpdateToRoutrTablePath(i,pPayLoad);//更新路径表
			return TRUE;
		}
	}
	return FALSE;
}

void NRF_DelNodePath(u8 node)//删除节点
{
	u8 i,j,k;

	for(i=0; i<MAX_NODE_NUM; i++)//遍历路由表
	{
		if(route_table[i].addr)
		{
			if(route_table[i].addr==node)
			{
				MemSet((BYTE *)&route_table[i],0,sizeof(RoutrTable));//从路由表删除1个节点
			}
			else
			{
				for(j=0; j<MAX_HOP_NUM; j++)//遍历路径表
				{
					if(route_table[i].path[j]==node)//找到节点
					{
						route_table[i].path[j]=0;//删除节点
						for(k=j+1; k<MAX_HOP_NUM; k++)//从删除节点位置开始遍历路径表,后面的所有节点左移1位
						{
							route_table[i].path[k-1]=route_table[i].path[k];//左移
						}
					}
				}
			}
		}
	}
	for(i=0; i<MAX_NODE_NUM; i++)//路由表重新排序
	{
		if(!route_table[i].addr)
		{
			for(j=i+1; j<MAX_NODE_NUM; j++)
			{
				if(route_table[j].addr)//有地址的移到最前面
				{
					route_table[i].addr=route_table[j].addr;
					MemCopy((BYTE *)route_table[i].path,(BYTE *)route_table[j].path,sizeof(route_table[i].path));
					MemSet((BYTE *)&route_table[j],0,sizeof(RoutrTable));//从路由表删除1个节点
					break;
				}
			}
		}
	}
}

u8 NRF_FindNodePath(u8 node)//查找节点最短路径
{
	u8 i,j,k,n,min,addr;

	MemSet((BYTE *)&path_table,0,sizeof(PathTable)*MAX_NODE_NUM);
	for(i=0; i<MAX_NODE_NUM; i++)//遍历节点列表
	{
		if(route_table[i].addr)
		{
			if(route_table[i].addr==node)
			{
				return route_table[i].addr;//最短路径 立即返回
			}
			else
			{
				for(j=0; j<MAX_HOP_NUM; j++)//遍历路径表
				{
					if(route_table[i].path[j]==node)//在路径表找到地址
					{
						n=0;
						for(k=j+1; k<MAX_HOP_NUM; k++)//计算n值
						{
							if(route_table[i].path[k])//有地址
							{
								n++;//n值越大距离越远
							}
						}
						for(k=0; k<MAX_NODE_NUM; k++)//遍历路径索引表
						{
							if(!path_table[k].addr)//找到空位
							{
								path_table[k].idx=n;//保存n值
								path_table[k].addr=route_table[i].addr;//保存节点地址
								break;
							}
						}
						break;	
					}
				}
			}
		}
	}
	if(!path_table[0].addr)//没有节点地址
		return 0xFF;
	
	min=path_table[0].idx;
	addr=path_table[0].addr;
	for(i=0; i<MAX_NODE_NUM; i++)//遍历路径索引表
	{
		if(path_table[i].addr)//有节点地址
		{
			if(path_table[i].idx<min)//查找最小索引号
			{
				min=path_table[i].idx;
				addr=path_table[i].addr;
			}
		}
	}
	return addr;//返回节点地址(下一跳地址)
}

static void NRF_NrfSendData(void)//根据缓冲区状态发送数据,发送前先检测干扰
{
	u8 index;
	
	index=NRF_SearchDataBuf(WAIT_SEND);
	if(0xFF==index)
	{
		index=NRF_SearchDataBuf(WAIT_SEND_RETRY);
	}
	if(0xFF!=index)//数据缓冲区有待发送数据
	{
		if(!NRF_DisturbanceDetect())//检测是否有其它节点在发送数据
		{
			u8 send_mac[MAC_LEN]={0};
			u8 dst_addr;
			
			switch(DataBuf[index].payload.header.pack_type)
			{
				case ASSIGN_ADDR:
				case DEL_NODE:
					DataBuf[index].isBroadcast=1;
				break;
				default:
					dst_addr=NRF_FindNodePath(DataBuf[index].payload.header.dst_addr);//寻找最短路径
					if(0xFF!=dst_addr)
					{
						NRF_GetMacAddr(send_mac,dst_addr);//获取MAC地址
					}
					else//路由表没有地址,广播
					{
						DataBuf[index].isBroadcast=1;
					}
				break;
			}
			NodeStatus.shift_failed_count=0;
			NodeStatus.shift_count++;
			if(!DataBuf[index].isBroadcast)
			{
				if(NRF_SendPayload(ACK,send_mac,NodeStatus.channel,
									(u8 *)&DataBuf[index].payload))//通道0发送数据
				{	
					DataBuf[index].status=SEND_SUCCESS;
				}
				else
				{
					DataBuf[index].status=WAIT_SEND_RETRY;
					DataBuf[index].send_failed_count++;
				}
			}
			else//广播
			{
				switch(DataBuf[index].payload.header.pack_type)
				{
					case ASSIGN_ADDR:
						NRF_SendPayload(NO_ACK,pipe2_mac,NodeStatus.channel,
										(u8 *)&DataBuf[index].payload);//通道2发送数据(向所有节点广播)
					break;
					default:
						NRF_SendPayload(NO_ACK,pipe1_mac,NodeStatus.channel,
										(u8 *)&DataBuf[index].payload);//通道1发送数据(向本网络节点广播)
					break;
				}
				DataBuf[index].status=SEND_FAILED;
			}
			NRF_RxMode(NodeStatus.node_mac,NodeStatus.channel);
		}
		else
		{
			NodeStatus.shift_failed_count++;
			if(NodeStatus.shift_failed_count>300)
			{
				NodeStatus.shift_failed_count=0;
				//NRF_SetChannel(Pro_AppropriateChannelDetect());//检测拥挤程度最低的信道
				NRF_Init();
			}
		}
	}
}

static void NRF_RelayPackage(LPayload pPayLoad)//转发
{
	u8 idx;
	
	if(pPayLoad->header.PID==NodeStatus.pwd)//网络ID
	{
		idx=NRF_MallocIdleDataBufId();
		if(0xFF!=idx)
		{
			DataBuf[idx].status=WAIT_SEND;
			MemCopy((BYTE*)&DataBuf[idx].payload,(BYTE *)pPayLoad,sizeof(Payload));
			switch(pPayLoad->header.pack_type)
			{
				case ASSIGN_ADDR:
				case BUILD_LINK:
				case START_LINK:
					DataBuf[idx].payload.header.hop_count+=1;//跳跃索引加1
					DataBuf[idx].payload.header.hop_addr=DataBuf[idx].payload.header.the_addr;//上一跳地址=本数据包的发送地址
					DataBuf[idx].payload.header.the_addr=NodeStatus.addr;//本次发送地址=本节点地址
					break;
				default:
					break;
			}
		}
#ifdef DEBUG
		//printf("\r\n***Relay-Package***\r\n");
#endif
	}
}

static void NRF_HandlePackage(LPayload pPayLoad)
{
	switch(pPayLoad->header.pack_type)
	{
		case START_LINK://节点->网关 路径
			NRF_AddNodeToRoutrTable(pPayLoad);//添加节点到路由表
			NRF_RelayPackage(pPayLoad);//转发
			break;
		case ASSIGN_ADDR://网关->节点 路径
			NRF_AddNodeToRoutrTable(pPayLoad);//添加节点到路由表
			if(WAIT_CONNECT==NodeStatus.link_status)
			{
				if(pPayLoad->header.ass_addr>=30&&pPayLoad->header.ass_addr<0xFF)//合法地址
				{
					NodeStatus.addr=pPayLoad->header.ass_addr;//获取地址
					NodeStatus.pwd=pPayLoad->header.PID;//获取网络ID
					NRF_GetMacAddr(NodeStatus.node_mac,NodeStatus.addr);//生成MAC地址
					NRF_StoreParam();//保存到FLASH
					NodeStatus.link_status=DISCONNECT;
					link_time=500;
					IS_TIMEOUT_10MS(eTim3, 0);
					SetLed(0xff,100,100);
				}
			}
			else
			{
				NRF_RelayPackage(pPayLoad);//转发
			}
			break;
		case DEL_NODE:
			NRF_DelNodePath(pPayLoad->header.ass_addr);//删除节点
			NRF_RelayPackage(pPayLoad);//转发
			if(pPayLoad->header.ass_addr==NodeStatus.addr)
			{
				NodeStatus.link_status=DISCONNECT;
				link_time=500;
				IS_TIMEOUT_10MS(eTim3, 0);
				SetLed(0xff,100,100);
			}
			break;
		default:
			if(pPayLoad->header.dst_addr==NodeStatus.addr)
			{
				u8 idx;
				switch(pPayLoad->header.pack_type)
				{
					case CHECK_LINK:
						heart_time=Get_RunTime();
						NRF_SendData(NodeStatus.route_addr,CHECK_LINK_ACK,(u8 *)"",SendHandler);//发送数据接口
						break;
					case BUILD_LINK:
						NRF_AddNodeToRoutrTable(pPayLoad);//添加节点到路由表
						heart_time=Get_RunTime();
						NodeStatus.link_status=CONNECTED;
						isLink=1;
						NRF_SendData(NodeStatus.route_addr,BUILD_LINK_ACK,(u8 *)"",SendHandler);//发送数据接口
					case ONE_DATA:
					case WAY_KEY_DATA:
					case NODE_KEY_DATA_ACK:
						idx=NRF_MallocIdleDataBufId();
						if(0xFF!=idx)
						{
							MemCopy((BYTE*)&DataBuf[idx].payload,(BYTE *)pPayLoad,PAYLOAD_LEN);
							DataBuf[idx].status=WAIT_HANDLER;
						}
						break;
					default:break;
				}
			}
			else
			{
				NRF_RelayPackage(pPayLoad);//转发
			}
			break;
	}
}

void NRF_RecvData(void)
{
	Payload tmp;
	u8 id;
#ifdef DEBUG	
	u8 status,pipe_num;

	status=NRF_ReadReg(STATUS);//读取status寄存器的值
	pipe_num=(status&RX_P_NO_MASK)>>1;
	printf("Pipe%d-Recv\r\n",pipe_num);
#endif	
	MemSet((BYTE *)&tmp,0,sizeof(Payload));
	NRF_ReadBuf(R_RX_PAYLOAD, (u8 *)&tmp, PAYLOAD_LEN);//保存接收到的数据
	NodeStatus.recv_count++;
	if(tmp.header.src_addr==NodeStatus.addr)//是自己的包
	{
		NRF_RxMode(NodeStatus.node_mac, NodeStatus.channel);
		return;
	}
	if(ASSIGN_ADDR==tmp.header.pack_type||tmp.header.PID==NodeStatus.pwd)
	{
		//10秒内处理过的包不再处理(在广播时会收到很多重复的包)
		if(!NRF_CmpMultiPack(tmp.header.src_addr,tmp.header.dst_addr,
							 tmp.header.pack_type,tmp.header.SID))
		{
			id=NRF_SearchHandleTimeoutId();
			if(0xFF!=id)
			{
				IsHandle[id].RID=tmp.header.SID;
				IsHandle[id].time=Get_RunTime();
				IsHandle[id].src_addr=tmp.header.src_addr;
				IsHandle[id].dst_addr=tmp.header.dst_addr;
				IsHandle[id].pack_type=tmp.header.pack_type;
				//BspTim2SetCounter(0);
				NRF_HandlePackage(&tmp);
			}
		}
	}
	NRF_RxMode(NodeStatus.node_mac, NodeStatus.channel);
}

void NRF_HandleBuf(void)//根据缓冲区状态处理缓冲区
{
	u8 i;
	
	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		switch(DataBuf[i].status)
		{
			case WAIT_SEND_RETRY:
				if(DataBuf[i].send_failed_count>=MAX_FAILED_COUNT)
				{
					DataBuf[i].isBroadcast=1;
				}
				break;
			case WAIT_HANDLER:
				if(RecvHandler)
				{
					RecvHandler(DataBuf[i].payload.header.src_addr,
								DataBuf[i].payload.header.dst_addr,
								DataBuf[i].payload.header.pack_type,
								DataBuf[i].payload.buf);
				}
				NRF_FreeDataBuf(i);
				break;
			case SEND_SUCCESS:
				if(DataBuf[i].HandleCallBack)
				{
					DataBuf[i].HandleCallBack(DataBuf[i].payload.header.src_addr,
												DataBuf[i].payload.header.dst_addr,
												DataBuf[i].payload.header.pack_type,
												DataBuf[i].payload.header.SID,
												DataBuf[i].payload.buf,PACKAGE_SUCCESS);
				}
				NRF_FreeDataBuf(i);
				break;
			case SEND_FAILED:
				if(DataBuf[i].HandleCallBack)
				{
					DataBuf[i].HandleCallBack(DataBuf[i].payload.header.src_addr,
												DataBuf[i].payload.header.dst_addr,
												DataBuf[i].payload.header.pack_type,
												DataBuf[i].payload.header.SID,
												DataBuf[i].payload.buf,PACKAGE_FAILED);
				}
				NRF_FreeDataBuf(i);
				break;
			default:
				break;
		}
	}
}

u8 NRF_AppropriateChannelDetect(void)//检测拥挤程度最低的信道
{
	u8 channel,min_disturb_count=11,i,j;
	u8 disturb_count[125]={0};

	ThreadLock=1;
	//MemSet((BYTE *)disturb_count,0,125);
	channel=NRF_ReadChannel();
	for(i=0;i<10;i++)
	{
		for(j=0;j<125;j++)
		{
			NRF_SetChannel(i);
			if(NRF_DisturbanceDetect())
			{
				disturb_count[j]++;
			}
		}
	}
	NRF_SetChannel(channel);
	for(i=0;i<125;i++)
	{
		if(disturb_count[i]<min_disturb_count)
		{
			min_disturb_count=disturb_count[i];
			channel=i;
		}
	}
	NRF_ReadReg(FLUSH_RX);//清接收FIFO
	ThreadLock=0;
	return channel;
}

void NRF_Thread(void)//定时线程,执行协议
{
	NRF_AutoLink();
//	NRF_SendHeartPack();
	NRF_NrfSendData();
	NRF_HandleBuf();
}

u8 NRF_MallocIdleDataBufId(void)//得到一个空闲DATABUF,并将其标记为待用
{
	u8 i;
	
	ThreadLock=1;//锁定
	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		if(IDLE==DataBuf[i].status)
		{
			DataBuf[i].status=WAIT_USE;
			ThreadLock=0;//解锁
			return i;
		}
	}
	ThreadLock=0;//解锁
	return 0xFF;
}	

void NRF_FreeDataBuf(const u8 id)//释放被使用的DATABUF,仅改变为空闲状态
{
	if(id>(DATA_BUF_COUNT-1)||id==0xFF)
	{
		return;
	}
	ThreadLock=1;//锁定
	MemSet((BYTE *)&DataBuf[id],0,sizeof(DATA_BUF));
	ThreadLock=0;//解锁
}

u8 NRF_SearchDataByID(u16 ID)//根据ID搜索缓冲区
{
	u8 i;

	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		if(IDLE!=DataBuf[i].status&&ID==DataBuf[i].payload.header.SID)
		{
			return i;
		}
	}
	return 0xFF;
}

u8 NRF_SearchDataBuf(const u8 status)//查找状态为status的DataBuf,返回索引
{
	u8 i;
	
	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		if(status==DataBuf[i].status)
		{
			return i;
		}
	}
	return 0xFF;
}

u8 NRF_SearchHandleTimeoutId(void)
{
	u8 i;
	
	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		if(Get_RunTime()-IsHandle[i].time>MULTI_PACK_INTERVAL)
		{
			return i;
		}
	}
	return 0xFF;
}

u8 NRF_CmpMultiPack(const u8 src_addr,const u8 dst_addr,const u8 pack_type,const u16 ID)
{
	u8 i;

	for(i=0;i<DATA_BUF_COUNT;i++)
	{
		if(Get_RunTime()-IsHandle[i].time<MULTI_PACK_INTERVAL)
		{
			if(ID==IsHandle[i].RID&&pack_type==IsHandle[i].pack_type&&
				src_addr==IsHandle[i].src_addr&&dst_addr==IsHandle[i].dst_addr)
			{
				return TRUE;
			}
		}
	}
	return FALSE;
}
