#include "uart_conf.h"
#include "includes.h"
#include "BSP.h"
#include "AT24c128.h"
#include "../globalDef.h"
#include "../network_mgr/net_ctrl.h"

#include "../storage/AT24C128Opt.h"
//volatile int USER_DEBUG_OUTPUT_EN = 1;

//uint8_t 						USART1_receive_buf[USART1_BUF_SIZE],USART1_ready_buf[USART1_BUF_SIZE];
//static 		int32_t 	USART1_ReceiveTimeCounter = 0;
//volatile 	uint16_t 	USART1_receive_index=0;
//volatile 	uint8_t 	USART1_ready_buf_ok = 0;
//volatile 	int 	USART1_ready_buf_len = 0;

////uint8_t 						USART2_receive_buf[USART2_BUF_SIZE],USART2_ready_buf[USART2_BUF_SIZE];
//static 		int32_t 	USART2_ReceiveTimeCounter = 0;
//volatile 	uint16_t 	USART2_receive_index=0;
//volatile 	uint8_t 	USART2_ready_buf_ok = 0;
//volatile 	int 	USART2_ready_buf_len = 0;

////uint8_t 						USART3_receive_buf[USART3_BUF_SIZE],USART3_ready_buf[USART3_BUF_SIZE];
//static 		int32_t 	USART3_ReceiveTimeCounter = 0;
//volatile 	uint16_t 	USART3_receive_index=0;
//volatile 	uint8_t 	USART3_ready_buf_ok = 0;
//volatile 	int 	USART3_ready_buf_len = 0;

PtTest g_ptTest;
char *answer[] = {
   "+PTMOD:ON,00000001\r\n",
   "+PTMOD:ON,00000001\r\n",
   "+PTMOD:OFF,00000001\r\n",
   "+INITDEVINFO:OK\r\n",
    "+EEPROMERASE:OK\r\n",
    "+RST:OK\r\n",
    "+EEPROMWR:OK\r\n",
    "+MQTTWR:OK\r\n",   //7
};

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

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

 //   return &(send_buf[0]);
}

void uart_cmd_task(uint8_t *data, uint8_t len)
{
    int i=0,j=0,flag =0;
    int result = 0;
    int len1 = 0;
//    uint32_t id=0,n = 0;
    uint16_t addr,len11;
		
    char sendbuff[256] = {0};
    char *pstr = NULL,*lastPt = NULL;
   char tempbuff[128] = {0};
   char type[4] = {0};
   char ssn[11] = {0};
   char pcbVr[3] = {0};
   char bn[5] = {0};
   char mfrs[5] = {0};
   char pd[9] = {0};
   char port[6] = {0};
   char user01[8] = {0};
   char password[16] = {0};
   uint8_t temp1 = 0, temp2 = 0;
   if(len<3) return;


    if(strstr((char*)data,"AT+PTMOD=ON\r\n")){ // 产测开始指令
        pstr = strstr((char*)data,"AT+PTMOD=ON\r\n");
        g_ptTest.bTestStart = 1;
        uart_msg_send(UART1_ID, (char *)answer[0], strlen(answer[0]));
        memset(pstr,0xFF,13);
        timeout_setValue(&g_ptTest.ptTime,10*60*1000);
        timeout_start(&g_ptTest.ptTime);
    }
    else if(strstr((char*)data,"AT+PTMOD=OFF\r\n")){ //产测结束指令
        pstr = strstr((char*)data,"AT+PTMOD=OFF\r\n");
        g_ptTest.bTestStart = 0;
        timeout_stop(&g_ptTest.ptTime);
        uart_msg_send(UART1_ID, (char *)answer[0], strlen(answer[0]));
        memset(pstr,0xFF,13);
    }
    
    if(strstr((char*)data,"AT+INITDEVINFO=WBJW,")){ // 初始化信息 设备类型 sn 批次号  生产厂商 生产日期
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+INITDEVINFO=WBJW,");
         if(strstr(pstr,"\r\n")) {
             lastPt = pstr;
            pstr =  pstr + strlen("AT+INITDEVINFO=WBJW,");//strstr((char*)data,"AT+INITDEVINFO=WBJW,");
            result = sscanf((char*)pstr,"%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%s",type,ssn,pcbVr,bn,mfrs,pd,tempbuff,port,sendbuff);
           //sscanf((char*)sendbuff,"%[^,],%s",user01, password);
        i = 0; flag = 0; j=0;
        do{
            if(sendbuff[i]!=',' ){
                if(flag==0){
                    user01[i] = sendbuff[i];
                }
                else if(flag==1){
                    password[j ] = sendbuff[i];
                    j++;
                }
            }
            else {
                if(flag==0) flag = 1;
            }
            i++;
        }while(sendbuff[i]!='\0');
        sscanf(type,"%04X",&g_firmwareMsg.gatewayMsg.hardwareMsg.devicType); // 设备类型
            if(g_firmwareMsg.gatewayMsg.hardwareMsg.devicType!=GATEWAY_DEVICE_TYPE){
                memset(tempbuff,0,sizeof(tempbuff));
                strcpy(tempbuff,(char*)"+INITDEVINFO:ERR,Device_mismatch\r\n");
                uart_msg_send(UART1_ID, (char *)tempbuff, strlen(tempbuff));
                return;
            }
            fram_init_mqtt_msg();
            sscanf(ssn,"%010u",&g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn);  //sn
            sscanf(pcbVr,"%02X",&g_firmwareMsg.gatewayMsg.hardwareMsg.pcbVersion); // PCB版本号
            sscanf(bn,"%04X",&g_firmwareMsg.gatewayMsg.hardwareMsg.factoryMsg); // 生产厂商
            sscanf(mfrs,"%04X",&g_firmwareMsg.gatewayMsg.hardwareMsg.seqNo); //批次号
            sscanf(pd,"%08X",&g_firmwareMsg.gatewayMsg.hardwareMsg.data); // 生产日期
            sscanf(tempbuff,"%s",g_firmwareMsg.mqttidport.ip); // mqtt 服务器地址
            sscanf(port,"%s",g_firmwareMsg.mqttidport.port); //mqtt 端口号
            sscanf(user01,"%s",g_firmwareMsg.mqttidport.admin);
            sscanf(password,"%s",g_firmwareMsg.mqttidport.password);
            g_firmwareMsg.gatewayMsg.hardwareMsg.bInit = 1;
            fram_write_gateway_hardware_msg(); // 写入EEPROOM
            g_firmwareMsg.mqttidport.flag = 1;
            fram_write_mqtt_msg();
            fram_write_eeprom_powerUpFlag();
            memset(lastPt,0xFF,20);
            uart_msg_send(UART1_ID, (char *)answer[3], strlen(answer[3]));
         }
    }
    else if(strstr((char*)data,"AT+DEVINFO\r\n")){ // 读取信息
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+DEVINFO\r\n");
        fram_read_gateway_hardware_msg();
        fram_read_mqtt_msg();
        memset(sendbuff,0,sizeof(sendbuff));
        strcpy(sendbuff,"+DEVINFO:"); // 文件头

        memset(tempbuff,0,sizeof(tempbuff));
        sprintf(tempbuff,"%04x,%010u,%02x,%04x,",g_firmwareMsg.gatewayMsg.hardwareMsg.devicType,\
                g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn,\
                g_firmwareMsg.gatewayMsg.hardwareMsg.pcbVersion,g_firmwareMsg.gatewayMsg.devicTypeID);
        strcat(sendbuff,tempbuff);

        memset(tempbuff,0,sizeof(tempbuff));
        gw_net_send_02((char*)g_firmwareMsg.gatewayMsg.Uuid,(char*)tempbuff,12,&len11);
        strcat(sendbuff,tempbuff);
        strcat(sendbuff,",");

        memset(tempbuff,0,sizeof(tempbuff));
        strncpy(tempbuff,(char*)g_firmwareMsg.gatewayMsg.Imei,15);
        strcat(sendbuff,tempbuff);

        memset(tempbuff,0,sizeof(tempbuff));
        sprintf(tempbuff,",%08x,%08x,%04x,%04x,%08x",g_firmwareMsg.gatewayMsg.verMsg.gate_bootloaderVr,\
                g_firmwareMsg.gatewayMsg.verMsg.gate_appVr,g_firmwareMsg.gatewayMsg.hardwareMsg.factoryMsg,\
                g_firmwareMsg.gatewayMsg.hardwareMsg.seqNo,g_firmwareMsg.gatewayMsg.hardwareMsg.data);
        strcat(sendbuff,tempbuff);

        memset(tempbuff,0,sizeof(tempbuff));
        sprintf(tempbuff,",%s,%s,%s,%s",g_firmwareMsg.mqttidport.ip,g_firmwareMsg.mqttidport.port, \
                                        g_firmwareMsg.mqttidport.admin,g_firmwareMsg.mqttidport.password);

        strcat(sendbuff,tempbuff);

        len1 = strlen(sendbuff);

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

        memset(pstr,0xFF,12);
        uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));
    }
    else if(strstr((char*)data,"AT+EEPROMERASE=")){ // 撤除EEPROM
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+EEPROMERASE=");
        if(strstr(pstr,"\r\n")){
            lastPt = pstr;
            pstr =  pstr + strlen("AT+EEPROMERASE=");
             memset(type,0,sizeof(type));
             result = sscanf((char*)pstr,"%[^,]",type);
             sscanf(type,"%04X",&g_firmwareMsg.gatewayMsg.hardwareMsg.devicType); // 设备类型
             if(g_firmwareMsg.gatewayMsg.hardwareMsg.devicType!=GATEWAY_DEVICE_TYPE){
                 memset(tempbuff,0,sizeof(tempbuff));
                 strcpy(tempbuff,(char*)"+EEPROMERASE:ERR,Device_mismatch\r\n");
                 uart_msg_send(UART1_ID, (char *)tempbuff, strlen(tempbuff));
                 return;
             }
            fram_init();
            memset(lastPt,0xFF,15);
            uart_msg_send(UART1_ID, (char *)answer[4], strlen(answer[4]));
            uart_blocking_read(sendbuff,UART1_ID,1);
        }
    }
    else if(strstr((char*)data,"AT+EEPROMWR=")) { // EEPROM 写
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+EEPROMWR=");
        if(strstr(pstr,"\r\n")){
            lastPt = pstr;
            pstr =  pstr + strlen("AT+EEPROMWR=");

            memset(type,0,sizeof(type));
            memset(mfrs,0,sizeof(mfrs));
            memset(bn,0,sizeof(bn));
            memset(tempbuff,0,sizeof(tempbuff));
            result = sscanf((char*)pstr,"%[^,],%[^,],%[^,],%s",bn,type,mfrs,tempbuff);
            sscanf(type,"%04x",&addr);  //sn
            sscanf(mfrs,"%04x",&len11); // PCB版本号
            sscanf(bn,"%04X",&g_firmwareMsg.gatewayMsg.hardwareMsg.devicType); // 设备类型
            if(g_firmwareMsg.gatewayMsg.hardwareMsg.devicType!=GATEWAY_DEVICE_TYPE){
                memset(tempbuff,0,sizeof(tempbuff));
                strcpy(tempbuff,(char*)"+EEPROMWR:ERR,Device_mismatch\r\n");
                uart_msg_send(UART1_ID, (char *)tempbuff, strlen(tempbuff));
                return;
            }
            len1 = 0;
            for(i = 0; i < len11*2; i+=2)
            {
                    temp1 = HexToChar(tempbuff[i]);
                    temp2 = HexToChar(tempbuff[i+1]);
                    sendbuff[len1] = (temp1<<4) | temp2;
                    len1++;
            }
            AT24CXX_Write(addr,(uint8_t*)sendbuff,len11);
            uart_msg_send(UART1_ID, (char *)answer[6], strlen(answer[6]));
            memset(lastPt,0xFF,12);
        }
    }
    else if(strstr((char*)data,"AT+EEPROMRD")){ // EEPROM 读取
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+EEPROMRD");
        if(strstr(pstr,"\r\n")){
            lastPt = pstr;
            pstr =  pstr + strlen("AT+EEPROMRD=");
            memset(type,0,sizeof(type));
            memset(mfrs,0,sizeof(type));
            memset(tempbuff,0,sizeof(tempbuff));
            result = sscanf((char*)pstr,"%[^,],%s",type,mfrs);
            sscanf(type,"%04x",&addr);  //sn
            sscanf(mfrs,"%04x",&len11); // PCB???

            AT24CXX_Read(addr,(u8*)tempbuff,len11);

            memset(sendbuff,0,sizeof(sendbuff));
            sprintf(sendbuff,"+EEPROMRD:%04x,",len11);
            result = 15;
            for(i=0;i<len11;i++){
                len1 += snprintf((char *)sendbuff + result + len1, sizeof(sendbuff), "%02x", tempbuff[i]);
            }
            uart_msg_send(UART1_ID, sendbuff, len1+result);
            memset(lastPt,0xFF,11);
        }
    }
    else if(strstr((char*)data,"AT+MQTTWR=WBJW,")) { // MQTT信息写入
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+MQTTWR=WBJW,");
        if(strstr(pstr,"\r\n")){
            lastPt = pstr;
            pstr =  pstr + strlen("AT+MQTTWR=WBJW,");
            memset(tempbuff,0,sizeof(tempbuff));
            memset(port,0,sizeof(port));
            memset(user01,0,sizeof(user01));
            memset(password,0,sizeof(password));
            result = sscanf((char*)pstr,"%[^,],%[^,],%[^,],%s",tempbuff,port,user01,password);
            fram_init_mqtt_msg();
            sscanf(tempbuff,"%s",g_firmwareMsg.mqttidport.ip); // mqtt 服务器地址
            sscanf(port,"%s",g_firmwareMsg.mqttidport.port); //mqtt 端口号
            sscanf(user01,"%s",g_firmwareMsg.mqttidport.admin);
            sscanf(password,"%s",g_firmwareMsg.mqttidport.password);
            g_firmwareMsg.mqttidport.flag = 1;
            fram_write_mqtt_msg();
            uart_msg_send(UART1_ID, (char *)answer[7], strlen(answer[7]));
            memset(lastPt,0xFF,15);
        }
    }
    else if(strstr((char*)data,"AT+MQTTRD\r\n")) { // mqtt 信息读取
        if( g_ptTest.bTestStart == 0) return;
        pstr = strstr((char*)data,"AT+MQTTRD\r\n");
        fram_read_mqtt_msg();
        memset(sendbuff,0,sizeof(sendbuff));
        strcpy(sendbuff,"+MQTTRD:"); // 文件头

        memset(tempbuff,0,sizeof(tempbuff));
        sprintf(tempbuff,"%s,%s,%s,%s",g_firmwareMsg.mqttidport.ip,g_firmwareMsg.mqttidport.port, \
                                g_firmwareMsg.mqttidport.admin,g_firmwareMsg.mqttidport.password);

        strcat(sendbuff,tempbuff);
        len1 = strlen(sendbuff);
        sendbuff[len1] = 0x0D;
        sendbuff[len1+1] = 0x0A;

        uart_msg_send(UART1_ID, sendbuff, strlen(sendbuff));
        memset(pstr,0xFF,11);
    }
    else if(strstr((char*)data,"AT+RST\r\n")) { //复位
        if( g_ptTest.bTestStart == 0) return;
        uart_msg_send(UART1_ID, (char *)answer[5], strlen(answer[5]));
        delay_ms(100);//延时100ms
        NVIC_SystemReset();//复位
    }
    else if(strstr((char*)data,"AT+PTMOD\r\n")){ // 查询当前是否在产测模式下 产测版本
        pstr = strstr((char*)data,"AT+PTMOD\r\n");
        if(g_ptTest.bTestStart==1) uart_msg_send(UART1_ID, (char *)answer[1], strlen(answer[1]));
        else uart_msg_send(UART1_ID, (char *)answer[2], strlen(answer[2]));
        memset(pstr,0xFF,10);
    }
		


//    if(strstr((char*)data,"AT+HSN="))
//    {
//        result = sscanf((char*)data,"AT+HSN=%08X%n",&id,&n);
//        if(result==1)
//        {
//            g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn = id;
//            fram_read_gateway_hardware_msg();

//            printf("+HSN:OK\r\n");
//            NVIC_SystemReset();//复位
//        }
//        else
//        {
//            printf("ERR4:%s\r\n",(char*)data);//Parameter error
//        }
//    }
//    else if(strstr((char*)data,"AT+HSN\r\n"))
//    {
//        printf("+HSN:%08X\r\n",g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn);
//    }
//    else if(strstr((char*)data,"AT+DSN="))
//    {
//        result = sscanf((char*)data,"AT+DSN=%d\r\n%n",&id,&n);
//        if(result==1)
//        {
//            g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn = id;
//            fram_read_gateway_hardware_msg();
//            printf("+DSN:OK\r\n");
//            NVIC_SystemReset();//复位
//        }
//        else
//        {
//            printf("ERR4:%s\r\n",(char*)data);//Parameter error
//        }
//    }
//    else if(strstr((char*)data,"AT+DSN\r\n"))
//    {

//        printf("+DSN:%010d\r\n",g_firmwareMsg.gatewayMsg.hardwareMsg.gateway_sn);
//    }
//    else if(strstr((char*)data,"AT+HELP\r\n"))
//    {
//        printf("\r\n提示符  \"<\"  \">\"  不用输入\r\n");
//        printf("AT+DSN=<COINNOVATION>,<DSN>            设置SN(DSN十进制设备编号)\r\n");
//        printf("AT+DSN                                 查询SN（十进制）\r\n");
//        printf("AT+HSN                                 查询SN（十六进制）\r\n");

//    }
}

