#include "bsp.h"

static u8 control_data=0;
static char cmd_buf[PAYLOAD_DATA_LEN]={0};

#ifdef DEBUG
static volatile SerialBuffType m_Usart1Rece = SerialBuffDefault();
#endif

//函数声明
static void NRF_RecvCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u8 *buf);
static void NRF_SendCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u16 ID,u8 *buf,u8 status);//发送回调函数

#ifdef DEBUG
static void Usart1_ReceOneChar(u8 ReceCharacter);
static void TimEndHandle(void);
static u32 Get_Val(const char *srcstr,const char *str);
static void USART1_Debug(void);
static void Get_Str(char *dststr,const char *srcstr,const char *str);
static void Print_MacAddr(char *str,u8 *addr);
#endif

int main(void)
{
	u32 main_time=0;
	u32 key_time=0;
	u8 key_flag=0;
	u8 led_flag=0;

	BspInit();
	NRF_SetDefaultRecvHandler(NRF_RecvCallBack);//设置回调函数
	NRF_SetDefaultSendHandler(NRF_SendCallBack);
#ifdef DEBUG
	BspUsart1IRQCallBack(Usart1_ReceOneChar);
	BspTim4SetIRQCallBack(TimEndHandle);
	printf("\r\nInitialize Succeed\r\n");
#endif
	if(NodeStatus.addr>=30&&NodeStatus.addr<0xFF)//判断地址是否合法
	{
		SetLed(0xff,100,100);
	}
	else
	{
		SetLed(0xff,18,18);
	}
    while (1)
	{
		IWDG_Feed();
		main_time = Get_RunTime();
		if (IS_TIMEOUT_10MS(eTimNrf, 1)&&(!NRF_GetThreadLockState()))//间隔10毫秒执行1次
        {
			NRF_Thread();//执行协议
        }
#ifdef DEBUG
		if (m_Usart1Rece.len > 0)
		{
			if (m_Usart1Rece.len > 1)
			{
				USART1_Debug();
			}
			else
			{
				switch (m_Usart1Rece.buf[0])
				{
					case 0x02: //Ctrl+b
						//功能待定
						break;    
					default :
						printf("\r\nError\r\n");			
						break;
				}
			}
			//MemSet((BYTE *)&m_Usart1Rece.buf,0,USART1_BUFF_LANGTH);
			m_Usart1Rece.len = 0;
		}
#endif
		/*
		*按键功能：
		*时间小于2秒,开关切换；
		*时间大于5秒,清除数据;
		*/
		if(!KEY)//Key键按下
		{
			if(!key_flag)//松开状态下,检测到按下
			{
				key_flag=1;
				key_time=main_time;//记录当前时间
			}
		}	
		if(key_flag)
		{
			if(!led_flag)
			{
				if(main_time - key_time > 500)//大于5秒
				{
					led_flag=1;
					SetLed(0xff,22,22);//220毫秒闪烁
				}
			}
		}
		if(KEY)//Key键松开时的处理
		{
			if(key_flag)//按下状态下,检测到松开
			{
				key_flag=0;
				led_flag=0;
				if(main_time - key_time > 500)//大于5秒
				{
					SetLed(0xff,50,50);//500毫秒闪烁
					NodeStatus.link_status=WAIT_CONNECT;
					NRF_SetWaitLinkTime(main_time);
					NRF_WaitDistributionAddr();
				}
				else if(main_time - key_time > 5 && main_time - key_time < 200)//Key按下时间大于50毫秒和小于2秒
				{
					control_data=!control_data;
					RELAY=control_data;
					if(CONNECTED==NodeStatus.link_status&&(NodeStatus.addr>=30&&NodeStatus.addr<0xFF))//如果是已连接
					{
						//control_data=!control_data;
						sprintf(cmd_buf,"{ck%03d%03d%d}",NodeStatus.addr/10,Get_Nid(NodeStatus.addr),control_data);
						NRF_SendData(NodeStatus.route_addr,NODE_KEY_DATA,(u8 *)cmd_buf,NRF_SendCallBack);//发送数据
					}
					else if(WAIT_CONNECT==NodeStatus.link_status)
					{
						NodeStatus.link_status=DISCONNECT;
						SetLed(0xff,100,100);//1秒闪烁
					}
					else
					{
						//功能待定
					}
				}	
			}
		}
    }
}

void NRF_RecvCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u8 *buf)
{
#ifdef DEBUG
	printf("src=%d,dst=%d,type=%d\r\n\r\n",src_addr,dst_addr,pack_type);
	//printf("buf=%s\r\n\r\n",buf);
#endif	
	if(NodeStatus.addr>=30&&NodeStatus.addr<0xFF)
	{
		switch(pack_type)
		{
			case BUILD_LINK://建立连接
#ifdef DEBUG
				SetLed(0,0,0);
#else
				SetLed(0xff,8,500);
#endif	
				break;
			case ONE_DATA:
				control_data=GetNumber((char *)buf,9,1);//获取data
				if(control_data>1) control_data=1;
				RELAY=control_data;//设置继电器状态
				sprintf(cmd_buf,"{ck%03d%03d%d}",NodeStatus.addr/10,Get_Nid(NodeStatus.addr),control_data);
				NRF_SendData(NodeStatus.route_addr,ONE_DATA_ACK,(u8 *)cmd_buf,NRF_SendCallBack);//发送数据
				break;
			case WAY_KEY_DATA:
				control_data=!control_data;
				RELAY=control_data;//设置继电器状态
				sprintf(cmd_buf,"{ck%03d%03d%d}",NodeStatus.addr/10,Get_Nid(NodeStatus.addr),control_data);
				NRF_SendData(NodeStatus.route_addr,WAY_KEY_DATA_ACK,(u8 *)cmd_buf,NRF_SendCallBack);//发送数据
				break;
//			case NODE_KEY_DATA_ACK:
//				//control_data=GetNumber((char *)buf,9,1);//获取data
//				//RELAY=control_data;//设置继电器状态
//				break;
			default:break;
		}
	}
}

void NRF_SendCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u16 ID,u8 *buf,u8 status)
{
#ifdef DEBUG
	if(status)
	{
		printf("ID=%d src=%d dst=%d type=%d OK\r\n\r\n",ID,src_addr,dst_addr,pack_type);
	}
	else
	{
		printf("ID=%d src=%d dst=%d type=%d FAIL\r\n\r\n",ID,src_addr,dst_addr,pack_type);
	}
#endif
}

#ifdef DEBUG
//USART1接收到一个字符
static void Usart1_ReceOneChar(u8 ReceCharacter)
{
    if (m_Usart1Rece.ind >= USART1_BUFF_LANGTH)
        return;
        
    if (m_Usart1Rece.len > 0)
        return;
        
    m_Usart1Rece.buf[m_Usart1Rece.ind++] = ReceCharacter;
	//USART1_SendByte(ReceCharacter);//串口1发送一个字符
    BspTim4Open();//定时器重新计数
}

//USART1接收字符超时回调函数
static void TimEndHandle(void)
{
    BspTim4Close();
    m_Usart1Rece.len = m_Usart1Rece.ind;
    m_Usart1Rece.ind = 0;
}

static void USART1_Debug(void)//调试
{
	u32 value;
	u8 mac_buf[MAC_LEN]={0};
	u8 buf[PAYLOAD_LEN]={0};

	value=Get_Val((char *)m_Usart1Rece.buf," ");
	Get_Str((char *)buf,(char *)m_Usart1Rece.buf," ");
	printf("buf=%s val=%d\r\n",buf,value);
	if(strstr((char *)m_Usart1Rece.buf,"nrf-addr"))
	{
		printf("=========NRF ADDR=========\r\n");
		NRF_ReadBuf(TX_ADDR,mac_buf,MAC_LEN);//读出TX地址
		Print_MacAddr("TX_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P0,mac_buf,MAC_LEN);//读出Pipe0地址
		Print_MacAddr("Pipe0_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P1,mac_buf,MAC_LEN);//读出Pipe1地址
		Print_MacAddr("Pipe1_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P2,mac_buf,1);//读出Pipe2地址
		Print_MacAddr("Pipe2_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P3,mac_buf,1);//读出Pipe3地址
		Print_MacAddr("Pipe3_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P4,mac_buf,1);//读出Pipe4地址
		Print_MacAddr("Pipe4_ADDR",mac_buf);
		NRF_ReadBuf(RX_ADDR_P5,mac_buf,1);//读出Pipe5地址
		Print_MacAddr("Pipe5_ADDR",mac_buf);
		printf("==========================\r\n");
	}
	else if(strstr((char *)m_Usart1Rece.buf,"MAC"))
	{
		u8 mac[5]={0};
		NRF_GetMacAddr(mac,value);//生成MAC地址
		Print_MacAddr("TEST-MAC",mac);
	}
	else if(strstr((char *)m_Usart1Rece.buf,"nrf-send"))
	{
		printf("send_addr=%d value=%d\r\n",NodeStatus.addr,value);
		NRF_SendData(value,ONE_DATA,(u8 *)buf,NRF_SendCallBack);//发送数据接口
	}
	else if(strstr((char *)m_Usart1Rece.buf,"nrf-reg"))
	{
		printf("======NRF REG======\r\n");
		printf("CONFIG=%02x\r\n",NRF_ReadReg(CONFIG));
		printf("EN_AA=%02x\r\n",NRF_ReadReg(EN_AA));
		printf("EN_RXADDR=%02x\r\n",NRF_ReadReg(EN_RXADDR));
		printf("SETUP_AW=%02x\r\n",NRF_ReadReg(SETUP_AW));
		printf("SETUP_RETR=%02x\r\n",NRF_ReadReg(SETUP_RETR));
		printf("RF_SETUP=%02x\r\n",NRF_ReadReg(RF_SETUP));
		printf("STATUS=%02x\r\n",NRF_ReadReg(STATUS));
		printf("RX_PW_P0=%02x\r\n",NRF_ReadReg(RX_PW_P0));
		printf("RX_PW_P1=%02x\r\n",NRF_ReadReg(RX_PW_P1));
		printf("FIFO_STATUS=%02x\r\n",NRF_ReadReg(FIFO_STATUS));
		printf("CD=%02x\r\n",NRF_ReadReg(CD));
		printf("==================\r\n");
	}
	else if(strstr((char *)m_Usart1Rece.buf,"nrf-param"))
	{
		printf("======NodeStatus======\r\n");
		switch(NodeStatus.link_status)
		{
			case DISCONNECT:
				printf("link_status=DISCONNECT\r\n");
				break;
			case WAIT_CONNECT:
				printf("link_status=WAIT_CONNECT\r\n");
				break;
			case CONNECTED:
				printf("link_status=CONNECTED\r\n");
				break;
			case WAIT_CHANGE:
				printf("link_status=WAIT_CHANGE\r\n");
				break;
		}
		printf("channel=%d\r\n",NodeStatus.channel);
		printf("addr=%d\r\n",NodeStatus.addr);
		Print_MacAddr("mac",NodeStatus.node_mac);
		printf("sys_pwd=%d\r\n",NodeStatus.pwd);
		printf("shift_failed_count=%d\r\n",NodeStatus.shift_failed_count);
		printf("shift_count=%d\r\n",NodeStatus.shift_count);
		printf("recv_count=%d\r\n",NodeStatus.recv_count);
		printf("======================\r\n");
	}
}

//从str中得到参数//srcstr:字符串;str:标识符
static u32 Get_Val(const char *srcstr,const char *str)	
{	
	while(*srcstr!=*str)//偏移到参数开始的地方
	{
		srcstr++;
		if(*srcstr=='\0')
		{
			return 0;//遇到结束符了
		}
	}
	srcstr++;
	//return atoi(srcstr);	
	return strtol(srcstr,NULL,10);
}

//str:标识符
static void Get_Str(char *dststr,const char *srcstr,const char *str)
{
	u8 len=0;
	
	while(1)
	{										   
		if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n'||*srcstr==*str)
		{
			*dststr='\0';
			return;//拷贝完成了.
		}
		*dststr=*srcstr;//拷贝
		srcstr++;
		dststr++;
		len++;
		if(len>=PAYLOAD_LEN-1)
		{
			*dststr='\0';
			return;
		}
	}
}

void Print_MacAddr(char *str,u8 *addr)
{
	u8 i;

	printf("%s:",str);
	for(i=0;i<MAC_LEN;i++)
	{
		printf("%02x ",addr[i]);
	}
	printf("\r\n");
}
#endif

