#include "uart_conf.h"
#include "includes.h"
#include "BSP.h"
#include "AT24c128.h"
#include "net_proc.h"
#include "lora.h"
#include "ota.h"


PtTest g_ptTest;
char *answer[] = {
	"+PTMOD:ON,00000001\r\n",//0
	"+PTMOD:ON,00000001\r\n",//1
	"+PTMOD:OFF,00000001\r\n",//2
	"+INITDEVINFO:OK\r\n",//3
	"+INITDEVINFO:ERR,DEVICE_TYPE_MISMATCH\r\n",//4
	"+EEPROMERASE:OK\r\n",//5
	"+EEPROMERASE:ERR,DEVICE_TYPE_MISMATCH\r\n",//6
	"+RST:OK\r\n",//7
	"+EEPROMWR:OK\r\n",//8
	"+EEPROMWR:ERR\r\n",//9
	"+INITLORAPARAINDEX:OK\r\n",//10
	"+INITLORAPARAINDEX:ERR\r\n",//11
	"+OFFLINE:OK\r\n",//12
	"+OFFLINE:ERR\r\n",//13
};



char Send_Buf_Char[320];
char *gw_net_send_02(char *data,  uint16_t len, uint16_t *llen)
{
    int i;
    //char send_buf[320];
    char value = 0;
    int send_len=0;
    const uint16_t len1 = len;

    memset(Send_Buf_Char,0,sizeof(Send_Buf_Char));
    for(i = 0;i < len1;i++) {
        value = data[i];
        send_len += snprintf((char *)Send_Buf_Char + send_len, sizeof(Send_Buf_Char), "%02x", value);
    }
        *llen = send_len;

    return &(Send_Buf_Char[0]);
}

extern uint8_t rcv_buf_pt[256]; 
char sendbuff[320] = {0};
uint8_t eeprom_buf[64] = {0};
uint32_t eeprom_addr=0;
#define EEPROM_PAGE 256
#define EEPROM_BUF_LEN 64
void uart_cmd_task(uint8_t *data, uint8_t len)
{
	OS_ERR  err;
	uint16_t eeprom_first = 0;
	int      i            = 0;
	int      result       = 0;
	int      len1         = 0;
    uint16_t len11;
	unsigned int lora_index;

	uint32_t device_id;            //设备sn
	uint32_t device_type;          //设备类型
	uint32_t manufactures;         //产品制造商
	uint32_t batch_number;         //批次号
	uint32_t production_data;      //出厂日期
	uint32_t pcb_ver;              //PCB版本
   
    char tempbuff[130] = {0};
    char type[5]       = {0};
    char ssn[11]       = {0};
    char pcb[3]        = {0};
    char bn[5]         = {0};
    char mfrs[5]       = {0};
    char pd[9]         = {0};
    char port[6]       = {0};
    char usr[40]       = {0};
    char pwd[40]       = {0};
	
	//eeprom
	char     eepaddr[5]   = {0};
	char     eeplen[5]    = {0};
	uint32_t eep_addr     = 0;
	uint32_t eep_len      = 0;
	uint16_t eep_len_temp = 0;
	char     * p_data     = NULL;

	//测试离线升级
	char     master_snb[15] = {0};
	char     slave_snb[15]  = {0};
	char     des_snb[15]    = {0};
	unsigned int master_sn      = 0;
	unsigned int slave_sn       = 0;
	unsigned int des_sn         = 0;

    if(0 == strncmp((char*)data,"AT+PTMOD=ON\r\n",len)){ // 产测开始指令
        g_ptTest.bTestStart = PT_ON;
        uart_msg_send(UART1_ID, (char *)answer[0], strlen(answer[0]));
			
			device_fixed_info.Work_State = DEV_WORK_STATE_PT;
			//关闭所有灯
			close_all_led();
		
//		if(hd_id == PCB_V1)//关闭编码器中断
		{
			encoder_irq_set(DISABLE);
		}
    }
		else if(strstr((char*)data,"AT+PTMOD\r\n")){ // 查询当前是否在产测模式下 产测版本
					if(g_ptTest.bTestStart==PT_ON) uart_msg_send(UART1_ID, (char *)answer[1], strlen(answer[1]));
					else uart_msg_send(UART1_ID, (char *)answer[2], strlen(answer[2]));

		}
		if(g_ptTest.bTestStart == PT_ON)
		{
			 if(0 == strncmp((char*)data,"AT+PTMOD=OFF\r\n",len)){ //产测结束指令
					g_ptTest.bTestStart = PT_OFF;
					uart_msg_send(UART1_ID, (char *)answer[2], strlen(answer[2]));
				
				if(device_info.alrd == DEVICE_ALRD)//已初始化
				{
					device_fixed_info.Work_State = DEV_WORK_STATE_NORMAL;
				}
				else
				{
					device_fixed_info.Work_State = DEV_WORK_STATE_UNINIT;
					//未初始化时，将设备sn置为0xffffffff；设备类型是默认的
					device_info.device_id = 0xffffffff;
					device_info.device_type = (SOFTWARE_VERSION_APP&0xffff0000)>>16;
				}
				
//				if(hd_id == PCB_V1)//打开编码器中断
				{
					encoder_irq_set(ENABLE);
				}
			}
			
			else if(strstr((char*)data,"AT+INITDEVINFO=WBJW,")){ // 初始化信息 设备类型 sn 批次号  生产厂商 生产日期
				p_data=strstr((char*)data,"AT+INITDEVINFO=WBJW,");	
				if(strstr(p_data,"\r\n"))
				{
					result = sscanf((char*)p_data,"AT+INITDEVINFO=WBJW,%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,]\r\n",type,ssn,pcb,bn,mfrs,pd,tempbuff,port,usr,pwd);

					sscanf(type,"%04X",&device_type); // 设备类型
					sscanf(ssn,"%010u",&device_id);  //sn
					sscanf(pcb,"%02X",&pcb_ver);     //PCB版本
					sscanf(bn,"%04X",&batch_number); //批次号 
					sscanf(mfrs,"%04X",&manufactures); //生产厂商
					sscanf(pd,"%08X",&production_data); // 生产日期

					if(device_type_cmp(SOFTWARE_VERSION_APP,(u16)device_type) == 0)
					{
							uart_msg_send(UART1_ID, (char *)answer[4], strlen(answer[4]));
							memset(&rcv_buf_pt,0,sizeof(rcv_buf_pt));
							return;
					}
					
					device_info.alrd = DEVICE_ALRD;
					device_info.device_type = device_type;
					device_info.device_id = device_id;
					device_info.batch_number = batch_number;
					device_info.manufactures = manufactures;
					device_info.production_data = production_data;
					device_info.pcb_ver = pcb_ver;
					
					device_info_update();//写eeprom
				
					eeprom_first = EEPROM_FIRST_INIT_FLAG;
					AT24CXX_Write(EECFG_FIRST_INIT0, (uint8_t *)&eeprom_first, 2);

					uart_msg_send(UART1_ID, (char *)answer[3], strlen(answer[3]));
				}
			}
			else if(0 == strncmp((char*)data,"AT+DEVINFO\r\n",len)){ // 读取信息

					device_info_get();//读取eeprom中的设备信息
					memset(sendbuff,0,sizeof(sendbuff));
					strcpy(sendbuff,"+DEVINFO:"); // 文件头

					memset(tempbuff,0,sizeof(tempbuff));
					sprintf(tempbuff,"%04x,%010u,%02x,%04x,",device_info.device_type,\
									device_info.device_id,\
									device_info.pcb_ver,device_fixed_info.MCU_Type_ID);
					strcat(sendbuff,tempbuff);

					gw_net_send_02((char*)device_fixed_info.MCU_UUID,12,&len11);
					memset(tempbuff,0,sizeof(tempbuff));
					memcpy(tempbuff,Send_Buf_Char,len11);
					strcat(sendbuff,tempbuff);
					strcat(sendbuff,",");

					memset(tempbuff,0,sizeof(tempbuff));

					sprintf(tempbuff,"%s,%08x,%08x,%04x,%04x,%08x,,,,","", device_fixed_info.Soft_ver_boot,\
									device_fixed_info.Soft_ver_app,device_info.batch_number,\
									device_info.manufactures,device_info.production_data);
					strcat(sendbuff,tempbuff);

					len1 = strlen(sendbuff);

					sendbuff[len1] = 0x0D;
					sendbuff[len1+1] = 0x0A;


					uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));
			}
			else if(strstr((char*)data,"AT+EEPROMERASE="))//擦除整片eeprom
			{
				p_data = strstr((char*)data,"AT+EEPROMERASE=");
				if(strstr(p_data,"\r\n"))
				{
					result = sscanf((char*)p_data,"AT+EEPROMERASE=%[^,]\r\n",type);
					sscanf(type,"%04X",&device_type); // 设备类型
					if(device_type_cmp(SOFTWARE_VERSION_APP,(u16)device_type) == 0)
					{
							uart_msg_send(UART1_ID, (char *)answer[6], strlen(answer[6]));
							memset(&rcv_buf_pt,0,sizeof(rcv_buf_pt));
							return;
					}
					
					eeprom_addr = 0;
					memset(eeprom_buf,0,EEPROM_BUF_LEN);

					for(i = 0; i < EEPROM_PAGE; i++)
					{
						AT24CXX_Write(eeprom_addr, eeprom_buf, EEPROM_BUF_LEN);
						eeprom_addr += EEPROM_BUF_LEN;
					}
					
					uart_msg_send(UART1_ID, (char *)answer[5], strlen(answer[5]));
					
					//清除接收数据FIFO
					uart_blocking_read((char *)tempbuff, UART_DEBUG, 1);
				}
			}
			else if(strstr((char*)data,"AT+RST\r\n"))//复位
			{
				uart_msg_send(UART1_ID, (char *)answer[7], strlen(answer[7]));
				OSTimeDlyHMSM(0, 0, 0, 100, OS_OPT_TIME_DLY, &err);
				NVIC_SystemReset();
			}
			else if(strstr((char*)data,"AT+EEPROMWR="))//测外部eeprom写
			{
				p_data=strstr((char*)data,"AT+EEPROMWR=");
				if(strstr(p_data,"\r\n"))
				{
					memset(tempbuff,0,sizeof(tempbuff));
					result = sscanf((char*)p_data,"AT+EEPROMWR=%[^,],%[^,],%[^,]\r\n",eepaddr,eeplen,tempbuff);

					sscanf(eepaddr,"%04X",&eep_addr); //地址
					sscanf(eeplen,"%04X",&eep_len);  //长度
					eep_len_temp = asciitohex(tempbuff,eeprom_buf,strlen(tempbuff)-2);			
					
					if(eep_len == eep_len_temp) //OK
					{
						AT24CXX_Write(eep_addr,(uint8_t *)eeprom_buf,eep_len);
						uart_msg_send(UART1_ID, (char *)answer[8], strlen(answer[8]));
					}
					else//ERR
					{
						uart_msg_send(UART1_ID, (char *)answer[9], strlen(answer[9]));
					}
				}
				
			}
			else if(strstr((char*)data,"AT+EEPROMRD="))//测外部eeprom读
			{
				p_data=strstr((char*)data,"AT+EEPROMRD=");
				if(strstr(p_data,"\r\n"))
				{
					result = sscanf((char*)p_data,"AT+EEPROMRD=%[^,],%[^,]\r\n",eepaddr,eeplen);

					sscanf(eepaddr,"%04X",&eep_addr); //地址
					sscanf(eeplen,"%04X",&eep_len);  //长度
					
					AT24CXX_Read(eep_addr,eeprom_buf,eep_len);
					
					memset(Send_Buf_Char,0,sizeof(Send_Buf_Char));
					gw_net_send_02((char*)eeprom_buf,eep_len,&len11);
					
					memset(sendbuff,0,sizeof(sendbuff));
					strcpy(sendbuff,"+EEPROMRD:"); // 文件头
					
					memset(tempbuff,0,sizeof(tempbuff));
					len11 = sprintf(tempbuff,"%04x,%04x,",eep_addr,eep_len);
					strcat(sendbuff,tempbuff);
					
					strcat(sendbuff,Send_Buf_Char);
					
					len1 = strlen(sendbuff);

					sendbuff[len1] = 0x0D;
					sendbuff[len1+1] = 0x0A;


					uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));	
				}
			}
			else if(strstr((char*)data,"AT+INITLORAPARAINDEX=WBJW,")) //写LoRa参数当前组索引号
			{
				p_data=strstr((char*)data,"AT+INITLORAPARAINDEX=WBJW,");
				if(strstr(p_data,"\r\n"))
				{
					result = sscanf((char*)p_data,"AT+INITLORAPARAINDEX=WBJW,%[^,]\r\n",type);
					sscanf(type,"%u",&lora_index); // 设备类型
					if(lora_index < LORA_GROUP_MAX)//正确
					{
						eepaddr[0] = lora_index;
						eepaddr[1] = ~eepaddr[0];
						AT24CXX_Write(LORA_ADDR,(uint8_t *)eepaddr,2);
						uart_msg_send(UART1_ID, (char *)answer[10], strlen(answer[10]));
					}
					else
					{
						uart_msg_send(UART1_ID, (char *)answer[11], strlen(answer[11]));
					}
				}
			}
			else if(strstr((char*)data,"AT+LORAPARAINDEX\r\n")) //读LoRa参数当前组索引号
			{
				memset(sendbuff,0,sizeof(sendbuff));
				strcpy(sendbuff,"+LORAPARAINDEX:"); // 文件头
				
				AT24CXX_Read(LORA_ADDR,(uint8_t *)eepaddr,2);
				
				memset(tempbuff,0,sizeof(tempbuff));
				sprintf(tempbuff,"%u",eepaddr[0]);
				strcat(sendbuff,tempbuff);
				
				len1 = strlen(sendbuff);
				sendbuff[len1] = 0x0D;
				sendbuff[len1+1] = 0x0A;
				uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));
			}
			else if(strstr((char*)data,"AT+ENCRYPT\r\n")) //读连接器加密状态
			{
				memset(sendbuff,0,sizeof(sendbuff));
				strcpy(sendbuff,"+ENCRYPT:"); // 文件头
				
				memset(tempbuff,0,sizeof(tempbuff));
				sprintf(tempbuff,"%u",device_fixed_info.Encrypt);
				strcat(sendbuff,tempbuff);
				
				len1 = strlen(sendbuff);
				sendbuff[len1] = 0x0D;
				sendbuff[len1+1] = 0x0A;
				uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));
			}
			else if(strstr((char*)data,"AT+OFFLINE=")) //测试。下发离线升级指令
			{
				p_data=strstr((char*)data,"AT+OFFLINE=");
				if(strstr(p_data,"\r\n"))
				{
					result = sscanf((char*)p_data,"AT+OFFLINE=%[^,],%[^,],%[^,]\r\n",master_snb,slave_snb,des_snb);

					sscanf(master_snb,"%u",&master_sn);
					sscanf(slave_snb,"%u",&slave_sn);
					sscanf(des_snb,"%u",&des_sn);

					if(slave_sn != des_sn)//失败
					{
						uart_msg_send(UART1_ID, (char *)answer[13], strlen(answer[13]));
						printf("slave sn:%010u, des sn:%010u\n",slave_sn,des_sn);
					}
					else //成功
					{
						uart_msg_send(UART1_ID, (char *)answer[12], strlen(answer[12]));

						//退出产测
						g_ptTest.bTestStart = PT_OFF;
						uart_msg_send(UART1_ID, (char *)answer[2], strlen(answer[2]));
						
						if(device_info.alrd == DEVICE_ALRD)//已初始化
						{
							device_fixed_info.Work_State = DEV_WORK_STATE_NORMAL;
						}
						else
						{
							device_fixed_info.Work_State = DEV_WORK_STATE_UNINIT;
							//未初始化时，将设备sn置为0xffffffff；设备类型是默认的
							device_info.device_id = 0xffffffff;
							device_info.device_type = (SOFTWARE_VERSION_APP&0xffff0000)>>16;
						}

						//Lora发送命令
						lora_offline_update(master_sn,slave_sn,des_sn);
					}
					
				}
			}
		}
		
		memset(&rcv_buf_pt,0,sizeof(rcv_buf_pt));

}

