#include "usart.h"
#include "mmodbus.h"
#include "dlt645.h"
#include "gateway_message.h"

uint8_t UART6_RX_BUF[BUFF_SIZE];
uint8_t UART6_RX_STAT=0;
uint32_t UART6_RX_NUM = 0;	


 /**
  * @brief  DEBUG_USART GPIO 配置,工作模式配置。115200 8-N-1 ，中断接收模式
  * @param  无
  * @retval 无
  */
void DEBUG_USART_Config(void)
{
  USART_InitTypeDef USART_InitStruct;
  GPIO_InitTypeDef GPIO_InitStruct;

  // Enable USART6 clock
  RCC_APB2PeriphClockCmd(DEBUG_USART_CLK, ENABLE);

  // Enable GPIOC clock
  RCC_AHB1PeriphClockCmd(DEBUG_USART_RX_GPIO_CLK, ENABLE);

  // Configure USART6 pins
  GPIO_InitStruct.GPIO_Pin = DEBUG_USART_RX_PIN | DEBUG_USART_TX_PIN;  // USART6_TX (PC6) and USART6_RX (PC7)
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(DEBUG_USART_TX_GPIO_PORT, &GPIO_InitStruct);

  // Connect USART6 pins to AF8
  GPIO_PinAFConfig(DEBUG_USART_RX_GPIO_PORT, DEBUG_USART_RX_SOURCE, DEBUG_USART_RX_AF);
  GPIO_PinAFConfig(DEBUG_USART_TX_GPIO_PORT, DEBUG_USART_TX_SOURCE, DEBUG_USART_TX_AF);

  // Configure USART6
  USART_InitStruct.USART_BaudRate = DEBUG_USART_BAUDRATE;
  USART_InitStruct.USART_WordLength = USART_WordLength_8b;
  USART_InitStruct.USART_StopBits = USART_StopBits_1;
  USART_InitStruct.USART_Parity = USART_Parity_No;
  USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(DEBUG_USART, &USART_InitStruct);
	

	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel 					 = DEBUG_USART_IRQ;      //IRQ通道
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;          		 //主优先级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority		 = 1;                //从优先级
	NVIC_InitStructure.NVIC_IRQChannelCmd				 = ENABLE;           //使能通道
	NVIC_Init(&NVIC_InitStructure);
	
  // Enable USART6
	USART_ITConfig(DEBUG_USART, USART_IT_IDLE, ENABLE); //开启空闲中断
	DMA_Cmd(DEBUG_USART_DMA_STREAM, ENABLE);						//使能DMA接收
  USART_Cmd(DEBUG_USART, ENABLE);
	USART_ClearFlag(DEBUG_USART, USART_FLAG_TC);
	

}

void DEBUG_USART_IRQHandler(void)
{
	uint16_t clear;
	if(USART_GetITStatus(DEBUG_USART,USART_IT_IDLE)!=RESET)
	{
		//清除空闲中断
		clear=USART6->SR;
		clear=USART6->DR;
		//关闭DMA
		DMA_Cmd(DEBUG_USART_DMA_STREAM,DISABLE);
		UART6_RX_NUM=BUFF_SIZE-DMA_GetCurrDataCounter(DEBUG_USART_DMA_STREAM);
		//清除DMA中断
		DMA_ClearFlag(DEBUG_USART_DMA_STREAM,DMA_IT_TCIF1);
		DMA_Cmd(DEBUG_USART_DMA_STREAM, ENABLE);
		//接收状态置位
		UART6_RX_STAT=1;
		
	}
}

/**
  * @brief  USART1 TX DMA 配置，内存到外设(USART1->DR)
  * @param  无
  * @retval 无
  */

void USART_DMA_Config(void)
{
	// 使能串口和DMA时钟
  RCC_APB2PeriphClockCmd(DEBUG_USART_CLK, ENABLE);
  RCC_AHB1PeriphClockCmd(DEBUG_USART_DMA_CLK, ENABLE);
	
  DMA_InitTypeDef DMA_InitStructure;
  
  DMA_InitStructure.DMA_Channel = DEBUG_USART_DMA_CHANNEL;  
  /*设置DMA源：串口数据寄存器地址*/
  DMA_InitStructure.DMA_PeripheralBaseAddr = DEBUG_USART_DR_BASE;	 
  /*内存地址(要传输的变量的指针)*/
  DMA_InitStructure.DMA_Memory0BaseAddr = (u32)UART6_RX_BUF;
  /*方向：从外设到内存*/		
  DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralToMemory;	
  /*传输大小DMA_BufferSize=SENDBUFF_SIZE*/	
  DMA_InitStructure.DMA_BufferSize = BUFF_SIZE;
  /*外设地址不增*/	    
  DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; 
  /*内存地址自增*/
  DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;	
  /*外设数据单位*/	
  DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
  /*内存数据单位 8bit*/
  DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;	
  /*DMA模式：不断循环*/
  DMA_InitStructure.DMA_Mode = DMA_Mode_Normal;	 
  /*优先级：中*/	
  DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;      
  /*禁用FIFO*/
  DMA_InitStructure.DMA_FIFOMode = DMA_FIFOMode_Disable;        
  DMA_InitStructure.DMA_FIFOThreshold = DMA_FIFOThreshold_Full;    
  /*存储器突发传输 16个节拍*/
  DMA_InitStructure.DMA_MemoryBurst = DMA_MemoryBurst_Single;    
  /*外设突发传输 1个节拍*/
  DMA_InitStructure.DMA_PeripheralBurst = DMA_PeripheralBurst_Single;    
  /*配置DMA2的数据流*/		   
  DMA_Init(DEBUG_USART_DMA_STREAM, &DMA_InitStructure);
	USART_DMACmd(DEBUG_USART,USART_DMAReq_Rx,ENABLE);
	DMA_ITConfig(DEBUG_USART_DMA_STREAM,DMA_IT_TC,ENABLE);
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel                   = DMA2_Stream5_IRQn ;//串口1发送中断通道
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;                 //抢占优先级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority        = 2;		          //子优先级
	NVIC_InitStructure.NVIC_IRQChannelCmd                = ENABLE;			  //IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);
	
}

void DMA2_Stream5_IRQHandler() {
    if (DMA_GetITStatus(DMA2_Stream1, DMA_IT_TCIF1)) 
		{
        DMA_ClearITPendingBit(DMA2_Stream1, DMA_IT_TCIF1);
    }
}

/*
	485串口de控制端口
*/
void USART_485_DE_init()
{
	GPIO_InitTypeDef GPIO_InitStruct;
	RCC_AHB1PeriphClockCmd(USART_485_DE_GPIO_CLK, ENABLE);
	GPIO_InitStruct.GPIO_Pin = USART_485_DE_PIN; 
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(USART_485_DE_GPIO_PORT, &GPIO_InitStruct);

}
void USART_485_DE_TX()
{
	GPIO_WriteBit(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,1);
}
void USART_485_DE_RX()
{
	GPIO_WriteBit(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,0);
}
void USART_485_Send(uint8_t *message,uint16_t size)
{
	uint16_t i=0;
	USART_485_DE_TX();
	for(i=0;i<size;i++)
	{
		USART_SendData(USART_232,*(message+i));
		while (USART_GetFlagStatus(USART_232, USART_FLAG_TC) == RESET);
	}
	USART_485_DE_RX();
}
//void _485_Config(void)
//{
//	GPIO_InitTypeDef GPIO_InitStructure;
//	USART_InitTypeDef USART_InitStructure;

//	/* config USART clock */
//	RCC_AHB1PeriphClockCmd(_485_USART_RX_GPIO_CLK|_485_USART_TX_GPIO_CLK|_485_RE_GPIO_CLK, ENABLE);
//	RCC_APB1PeriphClockCmd(_485_USART_CLK, ENABLE); 

//	
//	  /* Connect PXx to USARTx_Tx*/
//  GPIO_PinAFConfig(_485_USART_RX_GPIO_PORT,_485_USART_RX_SOURCE, _485_USART_RX_AF);

//  /* Connect PXx to USARTx_Rx*/
//  GPIO_PinAFConfig(_485_USART_TX_GPIO_PORT,_485_USART_TX_SOURCE,_485_USART_TX_AF);

//	
//	/* USART GPIO config */
//   /* Configure USART Tx as alternate function push-pull */
//  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
//  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;

//  GPIO_InitStructure.GPIO_Pin = _485_USART_TX_PIN  ;
//  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//  GPIO_Init(_485_USART_TX_GPIO_PORT, &GPIO_InitStructure);

//  /* Configure USART Rx as alternate function  */
//  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; 
//	GPIO_InitStructure.GPIO_Pin = _485_USART_RX_PIN;
//  GPIO_Init(_485_USART_RX_GPIO_PORT, &GPIO_InitStructure);

//  
//  /* 485收发控制管脚 */
//  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
//  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
//  GPIO_InitStructure.GPIO_Pin = _485_RE_PIN  ;
//  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//  GPIO_Init(_485_RE_GPIO_PORT, &GPIO_InitStructure);
//	  
//	/* USART mode config */
//	USART_InitStructure.USART_BaudRate = _485_USART_BAUDRATE;
//	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_Rx | USART_Mode_Tx;

//	USART_Init(_485_USART, &USART_InitStructure); 
//  USART_Cmd(_485_USART, ENABLE);
//	
//	NVIC_Configuration();
//	/* 使能串口接收中断 */
//	USART_ITConfig(_485_USART, USART_IT_RXNE, ENABLE);
//	
//	GPIO_ResetBits(_485_RE_GPIO_PORT,_485_RE_PIN); //默认进入接收模式
//}

/*
	485串口在未配置情况下，初始化的参数
*/
void USART_485_config()
{

	USART_485_DE_init();
	USART_InitTypeDef USART_InitStruct;
  GPIO_InitTypeDef GPIO_InitStruct;

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);
	
	GPIO_PinAFConfig(USART_485_RX_GPIO_PORT, USART_485_RX_SOURCE, USART_485_RX_AF);
  GPIO_PinAFConfig(USART_485_TX_GPIO_PORT, USART_485_TX_SOURCE, USART_485_TX_AF);
	
  GPIO_InitStruct.GPIO_Pin = USART_485_TX_PIN ;
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOC, &GPIO_InitStruct);
	
  GPIO_InitStruct.GPIO_Pin = USART_485_RX_PIN;
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
	GPIO_Init(GPIOC, &GPIO_InitStruct);

	
  USART_InitStruct.USART_BaudRate = USART_485_BAUDRATE;
  USART_InitStruct.USART_WordLength = USART_WordLength_8b;
  USART_InitStruct.USART_StopBits = USART_StopBits_1;
  USART_InitStruct.USART_Parity = USART_Parity_No;
  USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(USART_485, &USART_InitStruct);

  USART_Cmd(USART_485, ENABLE);
	
	USART_ClearFlag(USART_485, USART_FLAG_TC);
	USART_ITConfig(USART_485,USART_IT_RXNE,ENABLE);
	USART_ITConfig(USART_485,USART_IT_IDLE,ENABLE);
	
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = USART_485_IRQ;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;

	NVIC_Init(&NVIC_InitStruct);
}
/*
 *  函数名：void Config_485_Port(uint32_t baudrate, uint8_t databits, uint8_t stopbits, uint8_t parity, uint8_t flowcontrol)
 *  输入参数：baudrate,databits,stopbits,parity,flowcontol 串口的配置参数
 *  输出参数：无
 *  返回值：无
 *  函数作用：根据输入参数进行配置485串口参数
 */

void Config_485_Port(uint32_t baudrate, uint8_t databits, uint8_t stopbits, uint8_t parity, uint8_t flowcontrol)
{
	uint8_t wordLength;
	if(parity!=0)
	{
		wordLength=databits+1;
  }else wordLength=databits;
	USART_InitTypeDef USART_InitStruct;
  GPIO_InitTypeDef GPIO_InitStruct;

  RCC_AHB1PeriphClockCmd(USART_485_CLK, ENABLE);

  RCC_APB2PeriphClockCmd(USART_485_RX_GPIO_CLK, ENABLE);

  GPIO_InitStruct.GPIO_Pin = USART_485_RX_PIN | USART_485_TX_PIN; 
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOC, &GPIO_InitStruct);

  GPIO_PinAFConfig(USART_485_RX_GPIO_PORT, USART_485_RX_SOURCE, USART_485_RX_AF);
  GPIO_PinAFConfig(USART_485_TX_GPIO_PORT, USART_485_TX_SOURCE, USART_485_TX_AF);

  USART_InitStruct.USART_BaudRate = baudrate;
  USART_InitStruct.USART_WordLength = (wordLength== 9) ? USART_WordLength_9b : USART_WordLength_8b;
  USART_InitStruct.USART_StopBits = USART_StopBits_1;
  USART_InitStruct.USART_Parity = USART_Parity_No;
	USART_InitStruct.USART_Parity =(parity == 1) ? (USART_Parity_Odd) : (parity == 2 ? USART_Parity_Even : USART_Parity_No);
	
  USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(USART_485, &USART_InitStruct);

  USART_Cmd(USART_485, ENABLE);
	USART_ClearFlag(USART1, USART_FLAG_TC);
	USART_ITConfig(USART_485,USART_IT_RXNE,ENABLE);
	USART_ITConfig(USART_485,USART_IT_IDLE,ENABLE);
	
	 // 配置485接收中断优先级
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = USART_485_IRQ;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStruct);
	
}
/*
	232串口配置
*/

void USART_232_config()
{
	USART_InitTypeDef USART_InitStruct;
  GPIO_InitTypeDef GPIO_InitStruct;
	
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
	
	GPIO_PinAFConfig(USART_232_RX_GPIO_PORT, USART_232_RX_SOURCE, USART_232_RX_AF);
  GPIO_PinAFConfig(USART_232_TX_GPIO_PORT, USART_232_TX_SOURCE, USART_232_TX_AF);
	
	
  GPIO_InitStruct.GPIO_Pin = USART_232_RX_PIN | USART_232_TX_PIN; 
  GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
  GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStruct);
	



  USART_InitStruct.USART_BaudRate = USART_232_BAUDRATE;
  USART_InitStruct.USART_WordLength = USART_WordLength_8b;
  USART_InitStruct.USART_StopBits = USART_StopBits_1;
  USART_InitStruct.USART_Parity = USART_Parity_No;
  USART_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_Init(USART_232, &USART_InitStruct);
	
  USART_Cmd(USART_232, ENABLE);
	
	USART_ClearFlag(USART1, USART_FLAG_TC);
	
	USART_ITConfig(USART_232,USART_IT_RXNE,ENABLE);
	USART_ITConfig(USART_232,USART_IT_IDLE,ENABLE);
	
 // 配置USART1接收中断优先级
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStruct);
	
	
}

/*****************  发送一个字符 **********************/
void Usart_SendByte( USART_TypeDef * pUSARTx, uint8_t ch)
{
	/* 发送一个字节数据到USART */
	USART_SendData(pUSARTx,ch);
		
	/* 等待发送数据寄存器为空 */
	while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);	
}


/*****************  发送字符串 **********************/
void Usart_SendString( USART_TypeDef * pUSARTx, char *str)
{
	unsigned int k=0;
  do 
  {
      Usart_SendByte( pUSARTx, *(str + k) );
      k++;
  } while(*(str + k)!='\0');
  
  /* 等待发送完成 */
  while(USART_GetFlagStatus(pUSARTx,USART_FLAG_TC)==RESET)
  {}
}
/*****************  输出Hex字符串可能包含0x00**********************/
void Usart_SendHex( USART_TypeDef * pUSARTx, uint8_t *str,uint16_t hexLength)
{
	unsigned int k=0;
	do 
  {
      Usart_SendByte( pUSARTx, *(str + k) );
      k++;
  } while(k==hexLength);
  
  /* 等待发送完成 */
  while(USART_GetFlagStatus(pUSARTx,USART_FLAG_TC)==RESET)
  {}
}
/*****************  发送一个16位数 **********************/
void Usart_SendHalfWord( USART_TypeDef * pUSARTx, uint16_t ch)
{
	uint8_t temp_h, temp_l;
	
	/* 取出高八位 */
	temp_h = (ch&0XFF00)>>8;
	/* 取出低八位 */
	temp_l = ch&0XFF;
	
	/* 发送高八位 */
	USART_SendData(pUSARTx,temp_h);	
	while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);
	
	/* 发送低八位 */
	USART_SendData(pUSARTx,temp_l);	
	while (USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);	
}
void USART3_IRQHandler(){
			GATEWAY_PARAMS *get;
			get= get_gateway_config_params();
			if(get->device_params->protocol == 3)
			mmodbus_callback();
			else if(get->device_params->protocol == 1 || get->device_params->protocol == 2)
			dlt_callback();
}

/*********************************************END OF FILE**********************/
