#include "config.h"

volatile u8 GPSConnectRXTask_Flag = 0;//GPSConnect接受任务标志位，1允许运行
volatile u8 GPSConnectTXTask_Flag = 0;//
volatile u8 GPSConnect_RX_Buff[1000] = {0x01,0x03,0x00,0x02,0x00,0x09,0x00,0x00};;
volatile u8 GPSConnect_TX_Buff[1000] = {0x01,0x03,0x00,0x02,0x00,0x09,0x00,0x00};;
volatile u8 GPSConnect_DMA_RX_Len  = 23;
/*_____ D E F I N I T I O N __________________________________________________*/

u16 BigToLittle( u16 BigData) 
{  
  return (BigData << 8 | BigData >> 8);  
}
//u32 BigToLittle( u32 BigData) 
//{  
//	union
//	{
//	  u32 Temp;
//		u8 Buff[4];
//	  }Dat;
//	
//	if(sizeof(BigData) == 2)
//    return (BigData << 8 | BigData >> 8);
//  else  if(sizeof(BigData) == 4)
//	{
//		Dat.Buff[0] = (BigData >> 24) & 0xff;
//		Dat.Buff[1] = (BigData >> 16) & 0xff;
//		Dat.Buff[2] = (BigData >> 8) & 0xff;
//		Dat.Buff[3] = (BigData >> 0) & 0xff;
//		return (Dat.Temp);
//	  }
//}
/****************************************************
函数名：GPSConnect_IO_Configuration
功能  ：GPSConnect卡通讯部分用到的IO初始化
参数  ：无
返回值：无
****************************************************/
void GPSConnect_IO_Configuration(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;	//定义GOIP配置结构体

  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);

	GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_USART6);
  GPIO_PinAFConfig(GPIOC, GPIO_PinSource7, GPIO_AF_USART6);
	
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_Init(GPIOC, &GPIO_InitStructure); 
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;//普通输出模式
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;//推挽输出
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;//100MHz
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;//上拉
  GPIO_Init(GPIOC, &GPIO_InitStructure);//初始化
}
/****************************************************
函数名：GPSConnect_NVGPSConnect_Configuration
功能  ：GPSConnect卡通讯部分用到的中断向量配置
参数  ：无
返回值：无
****************************************************/
void GPSConnect_NVIC_Configuration(void)
{
	NVIC_InitTypeDef NVIC_InitStructure;	//定义中断配置结构体
	
	NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream6_IRQn;  //USART6_TX_DMA
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
	
	NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;		//USART??
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;		//
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;		//
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ????
	NVIC_Init(&NVIC_InitStructure);	//??NVIC_InitStruct???????????NVIC???USART1
}


/****************************************************
函数名：GPSConnect_NVGPSConnect_Configuration
功能  ：GPSConnect卡通讯部分用到的串口配置
参数  ：无
返回值：无
****************************************************/
void GPSConnect_USART_Configuration(u32 BaudRate)
{
  USART_InitTypeDef USART_InitStructure;
	
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);
	USART_InitStructure.USART_BaudRate =BaudRate;// Baud;//?????
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
	USART_Init(USART6, &USART_InitStructure);
	USART_Cmd(USART6, ENABLE);
	
	USART_ITConfig(USART6, USART_IT_IDLE, ENABLE);  
  USART_ClearFlag(USART6, USART_FLAG_IDLE); 
	
	USART_DMACmd(USART6, USART_DMAReq_Tx | USART_DMAReq_Rx,ENABLE);
	
}
/*************************************************
函数名  ：DMA_Configuration（）
功能    ：DMA初始化
传入参数：无
返回值  ：无
**************************************************/
void GPSConnect_DMA_Configuration(void)
{
  DMA_InitTypeDef DMA_InitStructure;
 
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2, ENABLE);  
	
	/*******************发送TX1*********************/
	DMA_DeInit(DMA2_Stream6);		
	DMA_InitStructure.DMA_DIR = DMA_DIR_MemoryToPeripheral;   
	//DMA_InitStructure.DMA_BufferSize = UART_DMA_SEND_LEN;   
	DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;  
	DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;  
	DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;  
	DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;  
	DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;  
	DMA_InitStructure.DMA_Priority = DMA_Priority_High;  
	DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;  
	DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;  
	DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;  
	DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; 
	DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART6->DR; 	
	DMA_InitStructure.DMA_Channel = DMA_Channel_5; 
	//DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)MD_Connect_TX_Buff[0]; 	
	
	DMA_Init(DMA2_Stream6, &DMA_InitStructure); 		 
	DMA_ITConfig(DMA2_Stream6, DMA_IT_TC, ENABLE);	
	/*******************RX*********************/
	DMA_DeInit(DMA2_Stream1);		
	DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;   
	DMA_InitStructure.DMA_BufferSize = 1000;   
	DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;  
	DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;  
	DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;  
	DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;  
	DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;  
	DMA_InitStructure.DMA_Priority = DMA_Priority_High;  
	DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;  
	DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_1QuarterFull;  
	DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;  
	DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single; 
	DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&USART6->DR; 	
	DMA_InitStructure.DMA_Channel = DMA_Channel_5; 
	DMA_InitStructure.DMA_Memory0BaseAddr = (uint32_t)GPSConnect_RX_Buff; 	
	
	DMA_Init(DMA2_Stream1, &DMA_InitStructure); 		
	DMA_Cmd(DMA2_Stream1, ENABLE);
	
	
}
//F*****************************************************************************
//* NAME:    GPSConnect_TXDataCheck
//* PURPOSE: GPSConnect卡键盘通信校验函数
//* PARAMS: pData需要检验的数组地址，len数据长度
//* return:	 无
//******************************************************************************
u8 GPSConnect_TXDataCheck(volatile u8* pData, u8 len)
{
	u8 result;
	if(len == 0) len = 16;	
	result = *pData++;
	do
		{
		result ^= *pData++;
		}while(--len);	

	return	result & 0x7f;
}
void GPSConnect_DMATX_IRQHandler(void)
{  
	u16 i = 0;
	DMA_ClearFlag(DMA2_Stream6, DMA_IT_TCIF6);  
	GPSCount_TX_DMAStop();  //关闭DMA传输
	while(! USART_GetFlagStatus(USART6, USART_FLAG_TC))NULL;
	DMA_ClearFlag(DMA2_Stream1, DMA_IT_TCIF1);
	GPSCount_RX_DMAStart();   //打开DMA传输(Gas就收)长度在选择发送队列时设置
	GPSConnectTXTask_Flag = 1;
}
//F*****************************************************************************
//* NAME:    GPSConnect_DMARX_IRQHandler
//* PURPOSE: DMA传输完成中断，Gas ModBus
//* PARAMS: 无
//* return:	 无
//******************************************************************************

void GPSConnect_DMARX_IRQHandler(void)
{  
  u8 i = 0;
	u16 CRC_Temp = 0;
	if(USART_GetITStatus(USART6, USART_IT_IDLE) != RESET)//????????? 
	{
		USART_ClearFlag(USART6, USART_IT_IDLE);  
    GPSCount_RX_DMAStop();   //DMA接收
	  USART_ClearFlag(USART6, USART_IT_IDLE);  
		DMA_ClearFlag(DMA2_Stream1, DMA_IT_TCIF1);
		i = USART6->SR;
    i = USART6->DR;
		GPSCount_RX_DMALenSet(1000);//重置接受长度
		GPSCount_RX_DMAStart();
		GPSConnectRXTask_Flag = 1;
	}
}
void StringToHex(u8 *Str,u8 *H,u8 Len)
{
  u8 i = 0;
	for(i = 0;i < Len;i += 2)
	{
		if(*(Str + i) > 0x39)
	    *(H + (i / 2)) = (*(Str + i) - 0x37) << 4;
		else
			*(H + (i / 2)) = (*(Str + i) - 0x30) << 4;
		
		if(*(Str + i + 1) > 0x39)
	    *(H + (i / 2)) |= (*(Str + i + 1) - 0x37) & 0x0f;
		else
			*(H + (i / 2)) |= (*(Str + i + 1) - 0x30) & 0x0f;
	  }
  }
u16 mystrstr(u8 *s1,u8 *s2)
{
  int len2;
	u16 i= 0;
  if(!(len2=strlen(s2)))//此种情况下s2不能指向空，否则strlen无法测出长度，这条语句错误
    return 1;
  for(;*s1;++s1)
  {
		i ++;
   if(*s1==*s2 && strncmp(s1,s2,len2)==0)
      return i;
    }
  return NULL;
}
//F*****************************************************************************
//* NAME:    GPSConnect_Init
//* PURPOSE: GPSConnect通讯初始化
//* PARAMS: 无
//* return:	 无
//******************************************************************************
char Bluetooth_AT_UART[]="AT+UART=9600\r\n ";
char Bluetooth_AT_NAME[]="AT+NAME=TXH_V1.1.2_0000\r\n ";
char Print_Language[]={0x1b,0x74,0x23};
void GPSConnect_Init(void)
{
	u8 i = 0;
  GPSConnect_IO_Configuration();                //流量计相关IO初始化
	GPSConnect_USART_Configuration(115200);             //相关串口初始化
	GPSConnect_DMA_Configuration();               //流量计相关DMA初始化
  GPSConnect_NVIC_Configuration();         //流量计相关中断初始化
	TXHData.GPSDataTimer.Init = 0;           //清除初始化标志
	TXHData.GPSDataTimer.Flag = 0;           //清除到时标志
	TXHData.GPSDataTimer.ON_OFF = 1;         //打开
	TXHData.GPSDataTimer.Cycle = 1;          //设置为循环模式，发送时启动
	TXHData.GPSDataTimer.TimerCountMax = 10*1000;//（10S）
	
  GPSCount_TX_DMAAddrSet((u32)Print_Language);
  GPSCount_TX_DMALenSet(3);
	GPSCount_TX_DMAStart();
//	while(!GPSConnectTXTask_Flag);
//	delay_ms(500);
//	GPSConnect_USART_Configuration(9600);            
//	for(i = 0;i < 10;i ++)
//	  Bluetooth_AT_NAME[8+i] = BoxVersion[i];
//	for(i = 0;i < 4;i ++)
//	  Bluetooth_AT_NAME[19+i] = TXHData.POSData.WirelessData.IMEI[16+i];
//	GPSCount_TX_DMAAddrSet((u32)Bluetooth_AT_NAME);
//  GPSCount_TX_DMALenSet(25);
//	GPSCount_TX_DMAStart();
}

void GPSConnectTast(void)
{
	u16 i = 0,j = 0,k = 0;
	u32 Temp = 0;
	u8 Buff[20];
	u16 POS_ConnectRX_Len=0;
	u16 POS_ConnectRX_CMD = 0;
  if(GPSConnectRXTask_Flag == 1)
	{
	  GPSConnectRXTask_Flag = 0;
		if(GPSConnect_RX_Buff[0] == 0xF5)   // 判断接收缓冲区中的第一个字节是否为 0xF5
		{
				POS_ConnectRX_Len  = (GPSConnect_RX_Buff[1] << 8) | GPSConnect_RX_Buff[2]; // 提取长度码
				Temp = CRC_Check(&GPSConnect_RX_Buff[0] , POS_ConnectRX_Len);  // 计算数据包 CRC 校验码
				if(Temp == ((GPSConnect_RX_Buff[POS_ConnectRX_Len] << 8) | GPSConnect_RX_Buff[POS_ConnectRX_Len + 1]))  // 判断 CRC 校验码是否正确
				{
						POS_ConnectRX_CMD = GPSConnect_RX_Buff[3];  // 提取命令字节
						switch (POS_ConnectRX_CMD)  // 根据命令字节进行不同的操作
						{
							case 0xF1:  // 配置APN
							{
									for(i = 0;i < sizeof(TXHData.POSData.WirelessData.APN);i ++)  // 将 APN 缓冲区清零
											TXHData.POSData.WirelessData.APN[i] = 0;
									for(i = 0;i < POS_ConnectRX_Len - 4;i ++)  // 从接收缓冲区中提取 APN 数据
											TXHData.POSData.WirelessData.APN[i] = GPSConnect_RX_Buff[4+i];
									if(FMItemWrite(CF_POSData,0))  // 写入 APN 数据到 Flash 存储器中
									{
											POS_Network_APN_Set();  // 设置网络 APN 参数
											GPSConnect_TX_Buff[0] = 0xF5;  // 将发送缓冲区初始化
											GPSConnect_TX_Buff[1] = 0x00;
											GPSConnect_TX_Buff[2] = 0x05;
											GPSConnect_TX_Buff[3] = 0xF1;
											GPSConnect_TX_Buff[4] = 0x59;
											Temp = CRC_Check(&GPSConnect_TX_Buff[0] , 5);  // 计算发送数据包的 CRC 校验码
											GPSConnect_TX_Buff[5] = (Temp >> 8) & 0xff;  // 将 CRC 校验码写入发送缓冲区
											GPSConnect_TX_Buff[6] = Temp & 0xff;
											GPSCount_TX_DMAAddrSet((u32)GPSConnect_TX_Buff);  // 设置发送 DMA 的地址和长度
											GPSCount_TX_DMALenSet(7);
											GPSCount_TX_DMAStart();  // 启动 DMA 发送数据
									}
							}break;
							case 0xF2:  // 配置LORA子模块
							{
								TXHData.MD_LORA_Slave_Flag = 1;
								TXHData.MD_LORA_SlaveTimer.ON_OFF = 1;
//								delay_ms(200);
//								MD_Port_LORASet(0);
//								MD_Port_LORASet(1);
//								MD_Port_LORASet(2);
//								MD_Port_LORASet(3);
								{
									GPSConnect_TX_Buff[0] = 0xF5;  // 将发送缓冲区初始化
									GPSConnect_TX_Buff[1] = 0x00;
									GPSConnect_TX_Buff[2] = 0x05;
									GPSConnect_TX_Buff[3] = 0xF2;
									GPSConnect_TX_Buff[4] = 0x59;
									Temp = CRC_Check(&GPSConnect_TX_Buff[0] , 5);  // 计算发送数据包的 CRC 校验码
									GPSConnect_TX_Buff[5] = (Temp >> 8) & 0xff;  // 将 CRC 校验码写入发送缓冲区
									GPSConnect_TX_Buff[6] = Temp & 0xff;
									GPSCount_TX_DMAAddrSet((u32)GPSConnect_TX_Buff);  // 设置发送 DMA 的地址和长度
									GPSCount_TX_DMALenSet(7);
									GPSCount_TX_DMAStart();  // 启动 DMA 发送数据
								  }
							}break;
						  case 0xF3:  // 配置LORA子模块
							{
								TXHData.MD_LORA_Slave_Flag = 0;
								TXHData.MD_LORA_SlaveTimer.Init = 1;
								{
									GPSConnect_TX_Buff[0] = 0xF5;  // 将发送缓冲区初始化
									GPSConnect_TX_Buff[1] = 0x00;
									GPSConnect_TX_Buff[2] = 0x05;
									GPSConnect_TX_Buff[3] = 0xF3;
									GPSConnect_TX_Buff[4] = 0x59;
									Temp = CRC_Check(&GPSConnect_TX_Buff[0] , 5);  // 计算发送数据包的 CRC 校验码
									GPSConnect_TX_Buff[5] = (Temp >> 8) & 0xff;  // 将 CRC 校验码写入发送缓冲区
									GPSConnect_TX_Buff[6] = Temp & 0xff;
									GPSCount_TX_DMAAddrSet((u32)GPSConnect_TX_Buff);  // 设置发送 DMA 的地址和长度
									GPSCount_TX_DMALenSet(7);
									GPSCount_TX_DMAStart();  // 启动 DMA 发送数据
								  }
							}break;
						}
				}
		}
		else if(GPSConnect_RX_Buff[25] == 'O' && GPSConnect_RX_Buff[26] == 'K')   // 判断接收缓冲区中“OK\r\n”判断是不是蓝牙设置回复
		{
		  TXHData.USART6_Drive = Bluetooth;
		  }
		else
		{
			Temp = mystrstr(GPSConnect_RX_Buff,"RMC");
			if(Temp)
				TXHData.USART6_Drive = GPS;
			if(GPSConnect_RX_Buff[Temp + 14] == 'A')//则提取经度和纬度信息
			{
				for(k = 0;k < 9;k ++)// 提取经度类型信息，保存到TXHData结构体中
					Buff[k] = GPSConnect_RX_Buff[Temp + 16 + k];
				TXHData.GPSData.GPS.Longitude = (float)atof(Buff) / 100;
				TXHData.GPSData.GPS.LongitudeType = GPSConnect_RX_Buff[Temp + 26];
				
				for(k = 0;k < 9;k ++)// 提取维度类型信息，保存到TXHData结构体中
					Buff[k] = GPSConnect_RX_Buff[Temp + 28 + k];
				TXHData.GPSData.GPS.Latitude = (float)atof(Buff) / 100;
				TXHData.GPSData.GPS.LatitudeType = GPSConnect_RX_Buff[Temp + 39];
				}
			else if(GPSConnect_RX_Buff[Temp + 14] == 'V')// 如果第15个字符是'V'，则经纬度信息无效，置为0
			{
				TXHData.GPSData.GPS.Latitude = 0;
				TXHData.GPSData.GPS.LatitudeType = 0;
				TXHData.GPSData.GPS.Latitude = 0;
				TXHData.GPSData.GPS.LatitudeType = 0;
				}
			}
		}
}

