#include "bsp.h"
#include "wdg.h"
#include "timer.h"
#include "usart.h"
#include "led.h"
#include "key.h"
#include "esp8266.h"
#include "connect.h"
#include "pro_hal.h"
#include "pro_phy.h"
#include "pro_memory.h"
#include "Pro_interface.h"
#include "md5.h"
#include "aes.h"

//u8 sid=1;//模块类型
//u8 nid=4;//模块编号; 当sid=1,nid=2温湿度；nid=3,X；nid=4人体入侵检测；nid=5烟雾火警，nid=6水滴检测;
const char version_string[] = PRO_VERSION ""__DATE__"-"__TIME__""CONFIG_IDENT_STRING;//版本信息
static void NRF_RecvCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u8 *buf);

//调试
void USART1_RecvData(void);

int main(void)
{
	NRF_SetThreadLockState(1);//锁定
	BspInit();
	NRF_SetDefaultRecvHandler(NRF_RecvCallBack);//设置回调函数
	NRF_SetThreadLockState(0);//解锁
	
	printf("\r\ninitialize finish\r\n\r\n");
 	while(1)
	{
		ESP_RecvData();
		ESP_Connect();
		Idle();
	}	 
}

static void NRF_RecvCallBack(u8 src_addr,u8 dst_addr,u8 pack_type,u8 *buf)
{
	char body[PAYLOAD_DATA_LEN]={0};
	u8 sid,nid,data;
	
	printf("src=%d,dst=%d,type=%d\r\nbuf=%s\r\n\r\n",src_addr,dst_addr,pack_type,buf);
	GetBody(body,(char *)buf);//获取只是{xxxxxxxx}的字符
	sid=GetNumber(body,3,3);//获取sid
	nid=GetNumber(body,6,3);//获取nid
	data=GetNumber(body,9,1);//获取data
	switch(pack_type)
	{
		case NODE_KEY_DATA://1次只能1个按键学习
			if(Key.learn_a)//学习模式
			{
				Key.learn_a=0;
				Store_Data.addr_a=src_addr;//保存地址到FLASH
				NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
			}
			else if(Key.learn_b)
			{
				Key.learn_b=0;
				Store_Data.addr_b=src_addr;
				NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
			}
			else if(Key.learn_c)
			{
				Key.learn_c=0;
				Store_Data.addr_c=src_addr;
				NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
			}
			else if(Key.learn_d)
			{
				Key.learn_d=0;
				Store_Data.addr_d=src_addr;
				NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
			}
			if(sid>2&&nid<10)//{ck00x00xx}//正常开关数据
			{
				ESP_SensorUpdate(src_addr,data,UPLOAD);
				NRF_SendData(src_addr,NODE_KEY_DATA_ACK,(u8 *)"",NRF_SendCallBack);//发送数据接口
			}
			break;
		case WAY_KEY_DATA_ACK:
			if(sid>2&&nid<10)//{ck00x00xx}//正常开关数据
			{
				ESP_SensorUpdate(src_addr,data,UPLOAD);
			}
			break;	
		case ONE_DATA_ACK:
			if(sid>2&&nid<10)//{ck00x00xx}//正常开关数据
			{
				ESP_SensorUpdate(src_addr,data,UPDATE);
			}
			break;
		default: break;
	}
}

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

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

void USART1_RecvData(void)//调试
{
	if(USART1_Recv_Flag)
	{
		u16 value;
		u8 mac_buf[MAC_LEN]={0};
		u8 buf[PAYLOAD_DATA_LEN]={0};
	
		USART1_Recv_Flag=0;
		value=GetValue((char *)USART1_Recv_Buff," ");
		CopyString((char *)buf,(char *)USART1_Recv_Buff," ");
		printf("buffer=%s value=%d\r\n",buf,value);
		if(strstr((char *)buf,"help"))
		{
			printf("\r\n========== Help Menu ==========\r\n\r\n");
			printf("var? (variable)\r\n");
			printf("rst-h (esp8266 hard reset)\r\n");
			printf("rst-s (esp8266 soft reset)\r\n");
			printf("state val (esp8266 state)\r\n");
			printf("mode val (esp8266 mode)\r\n");
			printf("port val (connect port)\r\n");
			printf("pro-rst (protocol init)\r\n");
			printf("node-list (node addr list)\r\n");
			printf("path-list (node path list)\r\n");
			printf("add_routr_table val (add node to routr table)\r\n");
			printf("del_node val (del node)\r\n");
			printf("init_routr_table\r\n");
			printf("set_addr val (set node addr)\r\n");
			printf("nrf-send_test val (send addr)\r\n");
			printf("nrf-ft (FLUSH_TX)\r\n");
			printf("nrf-fr (FLUSH_RX)\r\n");
			printf("nrf-send addr (send data)\r\n");
			printf("nrf-param (node status)\r\n");
			printf("nrf-reg (great register)\r\n");
			printf("nrf-addr? (TX-ADDR,Pipe-ADDR)\r\n");
			printf("MAC val (MAC test)\r\n");
			printf("xxx MD5-TEST (MD5 test)\r\n");
			printf("xxx AES-TEST (AES test)\r\n");
			printf("ssid=xxx&pwd=xxx (set ssid or pwd)\r\n");
			printf("apiKey=xxx (set apiKey)\r\n");
			printf("server=xxx (set server)\r\n");
			printf("%s \r\n",version_string);//
			printf("\r\n===============================\r\n");
		}
		else if(strstr((char *)USART1_Recv_Buff,"BubbleSort"))
		{
			u8 arr[5] = { 1,2,3,4,5 }; 
			u8 i;
			printf("\r\n初始顺序为:\r\n");
			for(i = 0; i < 5; i++)  
			{  
				printf("%d",arr[i]);  
			}  

			BubbleSort(arr, 5);//冒泡排序
			printf("\r\n冒泡排序后顺序为:\r\n");

			for(i = 0; i < 5; i++)  
			{  
				printf("%d",arr[i]);  
			} 
		}
		else if(strstr((char *)USART1_Recv_Buff,"MAC"))
		{
			NRF_GetMacAddr(mac_buf,value);
			PrintAddr("TEST-MAC",mac_buf);
		}
		else if(strstr((char *)USART1_Recv_Buff,"MD5-TEST"))
		{
			unsigned char dst[16];

			MD5_String(dst,(char *)buf);
			PrintHex((u8 *)dst,sizeof(dst));
		}
		else if(strstr((char *)USART1_Recv_Buff,"AES-TEST"))
		{
			PrintHex(buf,sizeof(buf));
			AES_Encrypt(buf);//加密
			PrintHex(buf,sizeof(buf));
			AES_Decrypt(buf);//解密
			PrintHex(buf,sizeof(buf));
		}
		else if(strstr((char *)USART1_Recv_Buff,"ssid"))
		{
			char *srcstr=USART1_Recv_Buff;
			char *ssid=(char *)Store_Data.ssid;
			char *pwd=(char *)Store_Data.pwd;
			u8 ssid_len=0,pwd_len=0;

			printf("ssid_len=%d\r\n",sizeof(Store_Data.ssid));
			printf("pwd_len=%d\r\n",sizeof(Store_Data.pwd));
			while(1)
			{										   
				if(*srcstr=='=')
				{
					break;
				}
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n')
				{
					printf("ERROR\r\n");
					return;
				}
				srcstr++;
			}
			srcstr++;
			while(1)
			{										   
				if(*srcstr=='&')
				{
					*ssid='\0';
					break;//拷贝完成
				}
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n'||ssid_len>=sizeof(Store_Data.ssid))
				{
					printf("ERROR\r\n");
					return;
				}
				*ssid=*srcstr;//拷贝
				srcstr++;
				ssid++;
				ssid_len++;
			}
			while(1)
			{										   
				if(*srcstr=='=')
				{
					break;
				}
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n')
				{
					printf("ERROR\r\n");
					return;
				}
				srcstr++;
			}
			srcstr++;
			MemSet((BYTE *)&Store_Data.pwd,0,sizeof(Store_Data.pwd));
			while(1)
			{										   
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n'||pwd_len>=sizeof(Store_Data.pwd))
				{
					*pwd='\0';
					break;//拷贝完成
				}
				*pwd=*srcstr;//拷贝
				srcstr++;
				pwd++;
				pwd_len++;
			}
			if(pwd_len<8)
			{
				u8 i;
				
				for(i=pwd_len;i<8;i++)
				{
					*pwd='*';
					pwd++;
				}
			}
			printf("ssid=%s\r\npwd=%s\r\n",Store_Data.ssid,Store_Data.pwd);
			NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
		}
		else if(strstr((char *)USART1_Recv_Buff,"apiKey"))
		{
			char *srcstr=USART1_Recv_Buff;
			char *apiKey=(char *)Store_Data.apiKey;
			u8 key_len=0;

			while(1)
			{										   
				if(*srcstr=='=')
				{
					break;
				}
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n')
				{
					printf("ERROR\r\n");
					return;
				}
				srcstr++;
			}
			srcstr++;
			while(1)
			{										   
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n'||key_len>=16)
				{
					*apiKey='\0';
					break;//拷贝完成
				}
				*apiKey=*srcstr;//拷贝
				srcstr++;
				apiKey++;
				key_len++;
			}
			if(key_len<16)
			{
				u8 i;
				
				for(i=key_len;i<16;i++)
				{
					*apiKey='*';
					apiKey++;
				}
			}
			printf("apiKey=%s\r\n",Store_Data.apiKey);
			NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
		}
		else if(strstr((char *)USART1_Recv_Buff,"server"))
		{
			char *srcstr=USART1_Recv_Buff;
			char *server=(char *)Store_Data.server;
			u8 server_len=0;

			while(1)
			{										   
				if(*srcstr=='=')
				{
					break;
				}
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n')
				{
					printf("ERROR\r\n");
					return;
				}
				srcstr++;
			}
			srcstr++;
			while(1)
			{
				if(*srcstr=='\0'||*srcstr=='\r'||*srcstr=='\n'||server_len>=sizeof(Store_Data.server))
				{
					*server='\0';
					break;//拷贝完成
				}
				*server=*srcstr;//拷贝
				srcstr++;
				server++;
				server_len++;
			}
			printf("server=%s\r\n",Store_Data.server);
			NRF_WriteDataToStore(PRO_STORE_FLAG,PRO_STORE_FLASH_ADDRESS,(u8 *)&Store_Data,sizeof(Store_obj));
		}
		else if(strstr((char *)buf,"rst-h"))
		{
			ESP_HardReset();
		}
		else if(strstr((char *)buf,"rst-s"))
		{
			ESP_SoftReset();
		}
		else if(strstr((char *)buf,"state"))
		{
			esp8266.state=GetValue(USART1_Recv_Buff," ");
		}
		else if(strstr((char *)buf,"port"))
		{
			esp8266.port=GetValue(USART1_Recv_Buff," ");
		}
		else if(strstr((char *)buf,"mode"))
		{
			esp8266.mode=GetValue(USART1_Recv_Buff," ");
			if(esp8266.mode)
			{
				if(ESP_StartServer(esp8266.port))
				{
					esp8266.login=FALSE;
					esp8266.link=FALSE;
					esp8266.bind=FALSE;
					esp8266.state=SERVER;
					esp8266.ser_time=Get_RunTime();
					SetLed(0xff,100,100);
				}
			}
			if(!esp8266.mode)
			{
				if(ESP_CloseServer())
				{
					esp8266.mode=ESP_CLIENT;
					if(!esp8266.login)
						esp8266.state=WAIT_LOGIN;
					else if(!esp8266.link||!esp8266.bind)
						esp8266.state=LINK;
					else
					{
						esp8266.state=LIVE;
						SetLed(0xff,10,500);
					}
				}
			}
		}
		else if(strstr((char *)buf,"pro-rst"))
		{
			NRF_Init();
			NodeStatus.pwd=Get_NetworkID();
		}
		else if(strstr((char *)buf,"nrf-ft"))
		{
			NRF_ReadReg(FLUSH_TX);//清发送FIFO
		}
		else if(strstr((char *)buf,"nrf-fr"))
		{
			NRF_ReadReg(FLUSH_RX);//清接收FIFO
		}
		else if(strstr((char *)buf,"set_addr"))
		{
			NRF_SendData(value,ASSIGN_ADDR,buf,NRF_SendCallBack);
		}
		else if(strstr((char *)buf,"nrf-send_test"))
		{
			NRF_SendData(value,ONE_DATA,buf,NRF_SendCallBack);
		}
		else if(strstr((char *)buf,"node-list"))
		{
			PrintNode();
		}
		else if(strstr((char *)buf,"path-list"))
		{
			PrintRouteTable();
		}
		else if(strstr((char *)buf,"lost-list"))
		{
			PrintLost();
		}
		else if(strstr((char *)buf,"init_routr_table"))
		{
			NRF_InitRoutrTable();//初始化路由表Payload
		}
		else if(strstr((char *)buf,"del_node"))
		{
			NRF_DelNodePath(value);//删除节点路径
		}
		else if(strstr((char *)buf,"add_routr_table"))
		{
			Payload tmp;
			u8 i,k,n;
			
			n=value;
			for(k=0; k<10; k++)//
			{
				value=n;
				MemSet((BYTE *)&tmp,0,sizeof(Payload));
				tmp.header.the_addr=value+k;
				tmp.header.hop_addr=(value+20)+k;
				for(i=0; i<k; i++)
				{
					tmp.buf[i]=(value+10)+i;
				}
				NRF_AddNodeToRoutrTable(&tmp);//添加节点到路由表
				NRF_UpdateHearTable();//更新心跳表
			}
		}
		else if(strstr((char *)buf,"var?"))
		{
			printf("\r\n=========variable=========\r\n\r\n");
			printf("apiKey=%s\r\nserver=%s\r\n",Store_Data.apiKey,Store_Data.server);
			printf("ssid=%s\r\npwd=%s\r\n",Store_Data.ssid,Store_Data.pwd);
			printf("esp8266_state=%d\r\n",esp8266.state);
			printf("esp8266_mode=%d\r\n",esp8266.mode);
			printf("connect_port=%d\r\n",esp8266.port);//
			printf("Run Day:%d Time:%02d:%02d:%02d\r\n",
					run_time.date,run_time.hour,run_time.min,run_time.sec);
			printf("\r\n==========================\r\n");
		}
		else if(strstr((char *)buf,"nrf-addr"))
		{
			printf("\r\n=========NRF ADDR=========\r\n\r\n");
			NRF_ReadBuf(TX_ADDR,mac_buf,5);//读出TX地址
			PrintAddr("TX_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P0,mac_buf,5);//读出Pipe0地址
			PrintAddr("Pipe0_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P1,mac_buf,5);//读出Pipe1地址
			PrintAddr("Pipe1_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P2,mac_buf,1);//读出Pipe2地址
			PrintAddr("Pipe2_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P3,mac_buf,1);//读出Pipe3地址
			PrintAddr("Pipe3_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P4,mac_buf,1);//读出Pipe4地址
			PrintAddr("Pipe4_ADDR",mac_buf);
			NRF_ReadBuf(RX_ADDR_P5,mac_buf,1);//读出Pipe5地址
			PrintAddr("Pipe5_ADDR",mac_buf);
			printf("\r\n==========================\r\n");
		}
		else if(strstr((char *)buf,"nrf-reg"))
		{
			printf("\r\n======NRF REG======\r\n\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===================\r\n");
		}
		else if(strstr((char *)buf,"nrf-param"))
		{
			printf("\r\n======NodeStatus======\r\n\r\n");
			printf("channel=%d\r\n",NodeStatus.channel);
			printf("addr=%d\r\n",NodeStatus.addr);
			PrintAddr("mac",NodeStatus.node_mac);
			printf("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======================\r\n");
		}
		else
		{
			ESP_SendString((char*)USART1_Recv_Buff);
		}
	}
}
