#include "main.h"
#include "lte.h"
#include "myFIle.h"
#include "malloc.h"
#include "LTE_MQTT.h"
#include "usart.h"

uint8_t config_flag = 0;
uint8_t UART6_RxCounter = 0;
int socket;

//PG6 初始化、拉低
void SIM_CD_config()
{
		 GPIO_InitTypeDef GPIO_InitStruct = {0};
		__HAL_RCC_GPIOG_CLK_ENABLE();												   
		GPIO_InitStruct.Pin = GPIO_PIN_6;	
		GPIO_InitStruct.Mode = GPIO_MODE_INPUT;   
    GPIO_InitStruct.Pull = GPIO_PULLUP;
		GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
		HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);	
		HAL_GPIO_WritePin(GPIOG,GPIO_PIN_6,GPIO_PIN_RESET);
}

// 模块上电  
// 拉高PA4，给EC800M上电
void VBAT_config()
{
		GPIO_InitTypeDef GPIO_InitStructure;
		__HAL_RCC_GPIOA_CLK_ENABLE();												   
		GPIO_InitStructure.Pin = GPIO_PIN_4;	
		GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;        
    GPIO_InitStructure.Pull = GPIO_PULLUP;
		GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_LOW; 
		HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);	
		HAL_GPIO_WritePin(GPIOA,GPIO_PIN_4,GPIO_PIN_SET);
}

// 拉高PB12脚
// 开机：需要在稳定的高电平时，拉低一段时间，再拉高
// 本机因为初始化前为高电平，只需要拉低后即可开机 
//PWRKEY1电平与GPIOB12电平同步
void EC800M_open()
{	
		VBAT_config();  // 模块上电
	
		GPIO_InitTypeDef GPIO_InitStructure;
		__HAL_RCC_GPIOB_CLK_ENABLE();
		GPIO_InitStructure.Pin = GPIO_PIN_12 ;	
		GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;   
    GPIO_InitStructure.Pull = GPIO_PULLDOWN;   
		GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH; 
		HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);	
		//当GPIO引脚初始化前为低电平时，需要进行下列步骤		
//		delay_ms(35);
//		GPIO_WriteBit(GPIOB,GPIO_Pin_12,1);
//  	GPIO_WriteBit(GPIOB,GPIO_Pin_13,1);
//		delay_ms(500);
//		 
//		GPIO_WriteBit(GPIOB,GPIO_Pin_12,0);
//		GPIO_WriteBit(GPIOB,GPIO_Pin_13,0);

		delay_ms(1000);  // 延时一段时间
		HAL_GPIO_WritePin(GPIOB,GPIO_PIN_12,GPIO_PIN_SET);
}

// 发送AT指令并对RX数据进行匹配
int Iot_SendCmd(char* cmd, char* reply, int wait)
{
		uint8_t i=0;
		int time = wait * 100;
    int rssi,res;
    memset(UART6_RX_BUF, 0, BUFF_SIZE); 
		HAL_UART_Transmit(&USART_InitStruct_DEBUG, (uint8_t*)cmd, strlen(cmd), HAL_MAX_DELAY);
		
    LTE_Delay(time);
    while(UART6_RX_STAT != 1) // 判断是否接收数据
    {
        LTE_Delay(1);
        i++;
        if(i >= wait){
            printf("cat1 check out\r\n");
            return -1;   
        }
    }
    UART6_RX_STAT = 0;
		
    if (!strcmp(reply,"+CSQ"))
    {
				char* rss_str = strstr((char*)UART6_RX_BUF, "+CSQ:");
        if (!rss_str)		return 1;
       	
        sscanf(rss_str, "+CSQ:%d,%d", &rssi, &res);
        if (rssi != 99)		return 0;
       
    }
    else if (!strcmp(reply,"+QMTPUBEX"))
    {
				char	MQ_str[64] = {0};
				sprintf(MQ_str,"%s",UART6_RX_BUF);
				char* MQ_send = strstr(MQ_str + 5, ">");
        if (MQ_send){	
//					HAL_UART_Transmit(&USART_InitStruct_DEBUG, (uint8_t*)pubJsonString, strlen(pubJsonString), HAL_MAX_DELAY);				
					return 0;
				}
    }
    if (strstr((char*)UART6_RX_BUF, reply))		
		{
			return 0;
		}
    return 1;  
}

// EC800M 的初始化
void ec800_init()
{
    uint16_t cat1_timeout = 0;
    while(Iot_SendCmd("AT\r\n","OK", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		cat1_timeout = 0;
		while(Iot_SendCmd("AT+CFUN?\r\n","OK", 1)){
				LTE_Delay(1);
				cat1_timeout ++;
				if(cat1_timeout >= 2000){
						printf(" uart false\r\n");
						return;   
				}
		}
		cat1_timeout = 0;
		Iot_SendCmd("AT+QCFG=\"nat\",0\r\n","OK", 1);
		while(Iot_SendCmd("AT+QCFG=\"nat\"\r\n","OK", 1)){
				LTE_Delay(1);
				cat1_timeout ++;
				if(cat1_timeout >= 2000){
						printf(" uart false\r\n");
						return;   
				}
		}

    cat1_timeout = 0;
    printf("uart ok\r\n");
    while(Iot_SendCmd("AT+CPIN?\r\n","READY", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
    cat1_timeout = 0;
    printf("simcard ok\r\n");
    while(Iot_SendCmd("AT+CSQ\r\n","+CSQ", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
//		cat1_timeout = 0;
//    while(Iot_SendCmd("AT+COPS?\r\n","0,0", 1)){
//        LTE_Delay(1);
//        cat1_timeout ++;
//        if(cat1_timeout >= 2000){
//            return;   
//        }
//    }
		
		cat1_timeout = 0;
    while(Iot_SendCmd("AT+COPS=0,0,\"CHN-CT\",7\r\n","0,0", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		
    cat1_timeout = 0;
    while(Iot_SendCmd("AT+CEREG?\r\n","0,1", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
    printf("网络注册 ok\r\n");
    cat1_timeout = 0;
    while(Iot_SendCmd("AT+CGATT?\r\n","+CGATT: 1", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
    printf(" 网络附着 ok\r\n");
}

// TCP初始化
void ec800_TCP(){
    uint16_t cat1_timeout = 0;
    while(Iot_SendCmd("AT+QHTTPCFG=\"contextid\",1\r\n","OK", 1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
  
		cat1_timeout = 0;    
    while(Iot_SendCmd("AT+QHTTPCFG=\"contenttype\",1\r\n","OK", 3)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		
    // APN 联通：UNINET   移动：CMNET   电信：CTNET
		cat1_timeout = 0;
    while(Iot_SendCmd("AT+QICSGP=1,1,\"CTNET\",\"\",\"\",1\r\n","OK", 3)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		
    cat1_timeout = 0;
    while(Iot_SendCmd("AT+QIACT?\r\n","+QIACT", 3)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		
    cat1_timeout = 0;
     while(Iot_SendCmd("AT+QIACT=1\r\n","OK", 1)){
         LTE_Delay(1);
         cat1_timeout ++;
         if(cat1_timeout >= 2000){
             return;   
         }
     }
		 
		cat1_timeout = 0;
    while(Iot_SendCmd("AT+QIACT?\r\n","OK", 3)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
		// 周期性发送心跳包
//			cat1_timeout = 0;
//			char message[64];
//			memset(message, 0, sizeof(message));
//			snprintf(message, sizeof(message), "AT+QICFG=\"send/auto\",1,120,\"C000\"\r\n");
//			while(Iot_SendCmd(message,"OK",2)){
//					LTE_Delay(1);
//					cat1_timeout ++;
//					if(cat1_timeout >= 2000){
//						 return;
//					}
//			}
}

// 连接网址
void http_set_url(char *url)
{
    uint16_t cat1_timeout = 0;
    char message[32];
    snprintf(message, sizeof(message), "AT+QHTTPURL=%d,%d\r\n", strlen(url), 5);
    while(Iot_SendCmd(message,"CONNECT", 2)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
    cat1_timeout = 0;
    printf("ready to send url\r\n");
    while(Iot_SendCmd(url,"OK", 5)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return;   
        }
    }
    cat1_timeout = 0;
    printf("url set OK\r\n");
}



//定义通过串口6发送AT指令命令
int LTE_SendCmd(char *cmd, char* reply) 
{
	UART6_RxCounter = 0; 
	int timeout = 10;
	memset(UART6_RX_BUF, 0, BUFF_SIZE);
	HAL_UART_Transmit(&USART_InitStruct_DEBUG, (uint8_t*)cmd, strlen(cmd), HAL_MAX_DELAY);
	while(timeout--) {
		LTE_Delay(1);
		if(strstr((char*)&UART6_RX_BUF, reply))
			break;
		printf("time = %d ", timeout);
	}
	printf("\r\n");
	if(timeout <= 0)
		return 1; 
	return 0; 
}

// HTTP获取数据
int LTE_HTTP_get()
{
	uint16_t cat1_timeout;
	int err,httprspcode,content_length,fd;
__start:
	 //发送 HTTP GET 请求，最大响应时间为 80 秒
	cat1_timeout = 0;
   while(Iot_SendCmd("AT+QHTTPGET=80\r\n","OK",1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            goto __start;   
        }
    }
	 LTE_Delay(500);
	 char* getStr = mymalloc(SRAMEX, 64); 
	 getStr = strstr((char*)&UART6_RX_BUF,"+QHTTPGET:");
   if (!getStr) {
			myfree(SRAMEX, getStr);
      goto __start;
    }
	 sscanf(getStr, "+QHTTPGET: %d,%d,%d ", &err, &httprspcode, &content_length);
	 if(200 == httprspcode)
	 {
		 printf("connect OK\r\n");
		 myfree(SRAMEX, getStr);		 
	 }
	 else
	 {
		 myfree(SRAMEX, getStr);
		 goto __start;
	 }

	 // 读取 HTTP 响应信息并将其储存到 UFS 文件中
		cat1_timeout = 0;
		while(Iot_SendCmd("AT+QHTTPREADFILE=\"UFS:test.txt\",80 \r\n","OK",20)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return TIMEOUT;   
        }
    }
		
		cat1_timeout = 0;
		// 打开文件
		while(Iot_SendCmd("AT+QFOPEN=\"test.txt\",2\r\n","OK",5)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
            return TIMEOUT;   
        }
    }
		char* readStr = mymalloc(SRAMEX, 128); 
	  readStr = strstr((char*)&UART6_RX_BUF,"+QFOPEN:");
		if(!readStr)
		{
			myfree(SRAMEX, readStr);	
			goto __start;
		}
		sscanf(readStr, "+QFOPEN:%d ", &fd);// 获取文件指针
		myfree(SRAMEX, readStr);
		
		// 读取文件
		char* readMessage = mymalloc(SRAMEX, 32); 
    sprintf(readMessage,"AT+QFREAD=%d\r\n", fd);
		while(Iot_SendCmd(readMessage,"OK",40)){
      printf("%s\n",UART6_RX_BUF);  
			LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
						myfree(SRAMEX, readMessage);
            goto __start;   
        }
    }
		myfree(SRAMEX, readMessage);
		DeleteDirFile("device.txt");
		write_file("device.txt",(char*)&UART6_RX_BUF,strlen((char*)&UART6_RX_BUF));
		config_flag = 1;
		
		cat1_timeout = 0;
		// 关闭文件
		char closeCMD[32]; 
		sprintf(closeCMD,"AT+QFCLOSE=%d\r\n", fd);
		while(Iot_SendCmd(closeCMD,"OK",1)){
        LTE_Delay(1);
        cat1_timeout ++;
        if(cat1_timeout >= 2000){
						myfree(SRAMEX, closeCMD);
            return TIMEOUT;   
        }
    }
		return SUCCESS;
}
