#include "ml307a.h"
#include "mba32a.h"

uint8_t u4length=0;
uint8_t resetcount_4g=0;
bool u4RecvFlag = false;
bool ml307aFail = false;
uint8_t g_ML307A_8buf[2048]={0}; 
uint8_t g_ML307A_8buf_Down[2048]={0}; 
bool reset4Gmodule = false;

extern UART_HandleTypeDef huart3;
extern UART_HandleTypeDef huart4;

uint8_t sendCmd_4G(char *pCmd, char *pRes, uint32_t timeOut, uint8_t sendNum);
void ML307AReset(void);
	

void ML307A_Init(void)
{
	
	printf("\t###02\t4G_init%d...\r\n",resetcount_4g); \
	if(strstr((const char *)g_ML307A_8buf_Down, "+MATREADY") != NULL)
	{
		printf("#4G模块上电");
		memset(g_ML307A_8buf_Down,0,15);
		HAL_Delay(100);
		if(!sendCmd_4G("AT\r\n","OK",1,1))
		{
			ml307aFail=true;
			printf("4G模组异常！\r\n");
		}	
		if (ml307aFail)
		{
			printf("#4G模块初始化Fail");
		}
		else
		{
			if (sendCmd_4G("AT+CPIN?\r\n", "+CME ERROR: 10", 1, 1)) // 00检测是否有SIM卡 <+CPIN: READY\r\nOK>
			{
				printf("\tERROR!-->未检测到SIM卡\r\n");
				OLED_ShowString(42,50,(unsigned char*)" NO_SIM ",12,0);
			}
			else
			{
				HAL_Delay(200);
				if (sendCmd_4G("AT+CPIN?\r\n", "+CME ERROR: 13", 1, 1))
				{
					printf("\tERROR!-->SIM失败\r\n");
					OLED_ShowString(35,45,(unsigned char*)" SIM_Fail ",12,0);
				}
				else
				{
					sendCmd_4G("AT+CSQ\r\n", 		"ERROR", 1, 1);// 01查询信号值(信号强度,误码率) <+CSQ: 26,99\r\nOK>
					sendCmd_4G("AT+CEREG?\r\n", 	"ERROR", 1, 1);// 02查询附着成功（驻网：<*,@> @为1或5表示附着成功） <+CEREG: 0,1\r\nOK>
					//sendCmd_4G("AT+MIPCALL?\r\n", 	"ERROR", 1, 1);// 03查询PDP激活状态 <+MIPCALL: 1,1,"10.94.99.162"\r\nOK>
					//sendCmd_4G("AT+MQTTCFG=?\r\n",	"ERROR", 1, 1);// 04查询MQTT
					printf("init_success\r\n");
				}
			}

		}
	}
	else
	{
		ML307AReset();
	}
	
}


uint8_t sendCmd_4G(char *pCmd, char *pRes, uint32_t timeOut, uint8_t sendNum)
{
    uint8_t i = 0;
    uint32_t time;          
    for(i = 0; i < sendNum; i++)
	{
        time = timeOut * 10;
        USART_SendString(&huart4, pCmd);
		HAL_Delay(50);
		printf("------->%s",g_ML307A_8buf_Down);
		
        while(time--)
		{
			if(strstr((const char *)g_ML307A_8buf_Down, pRes) != NULL)             // 如果检索到关键词
			{
				return 1;
			}
			HAL_Delay(100);
        }
    }
    return 0;
}



/**
 @brief 重启模块
 @param 无
 @return 无
*/
void ML307AReset(void)
{
	reset4Gmodule=true;
	resetcount_4g+=1;
	printf("4G Module_Reset\n");    
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_RESET);
	HAL_Delay(5000);
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_1, GPIO_PIN_SET);
}




