#include "usart.h"
#include "mmodbus.h"
#include "dlt645.h"
#include "gateway_message.h"
#include "tcp_server.h"
#include "timer.h"
#include "updata.h"
#include "cjt188.h"

uint8_t rxByte;
uint8_t rx_232_Buffer[RX_BUFFER_SIZE];
uint16_t QueueHead; // 队列头指针
uint16_t QueueTail; // 队列尾指针
uint8_t recv_232_done;// 232接收完成标志符
uint32_t rxIndex = 0;


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

UART_HandleTypeDef 	USART_InitStruct_485;
UART_HandleTypeDef  USART_InitStruct_232;
UART_HandleTypeDef  USART_InitStruct_DEBUG;
UART_HandleTypeDef  USART_InitStruct_Test;
DMA_HandleTypeDef 	DMA_DEBUG_RX;

//重定向c库函数printf到串口，重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
		/* 发送一个字节数据到串口 */
		USART_485->DR = (ch & (uint16_t)0x01FF);
		
		/* 等待发送完毕 */
		while (__HAL_UART_GET_FLAG(&USART_InitStruct_485, USART_FLAG_TXE) == RESET);	
		return (ch);
}


/*           232串口配置             */

void USART_232_config(void)
{
    __HAL_RCC_GPIOA_CLK_ENABLE();
		__HAL_RCC_USART1_CLK_ENABLE();
  
		GPIO_InitTypeDef GPIO_InitStruct = {0};
    GPIO_InitStruct.Pin = USART_232_TX_PIN | USART_232_RX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART1;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
	
		USART_InitStruct_232.Instance = USART_232;
		USART_InitStruct_232.Init.BaudRate = USART_232_BAUDRATE;
		USART_InitStruct_232.Init.WordLength = UART_WORDLENGTH_8B;
		USART_InitStruct_232.Init.StopBits = UART_STOPBITS_1;
		USART_InitStruct_232.Init.Parity = UART_PARITY_NONE;
		USART_InitStruct_232.Init.Mode = UART_MODE_TX_RX;
		USART_InitStruct_232.Init.HwFlowCtl = UART_HWCONTROL_NONE;
		USART_InitStruct_232.Init.OverSampling = UART_OVERSAMPLING_8;
		HAL_UART_Init(&USART_InitStruct_232);
		
		HAL_NVIC_SetPriority(USART_232_IRQ, 1, 0);
    HAL_NVIC_EnableIRQ(USART_232_IRQ);
	
//		HAL_UART_Receive_IT(&USART_InitStruct_232, &rxByte, 1);
		__HAL_UART_ENABLE_IT(&USART_InitStruct_232, UART_IT_RXNE); // 使能接收中断	
		__HAL_UART_ENABLE_IT(&USART_InitStruct_232, UART_IT_IDLE); // 使能空闲中断	
}


void USART_232_IRQHandler(void){
		GATEWAY_PARAMS *get;
		get= get_gateway_config_params();
		if(get->comProtocol)// get->protocol  1:232 0:485
		{
				if(get->device_params->protocol == 3)
				mmodbus_callback(&USART_InitStruct_232);
				else if(get->device_params->protocol == 1 || get->device_params->protocol == 2)
				dlt_callback(&USART_InitStruct_232);
		}
		else
		{
			//HAL_UART_IRQHandler(&USART_InitStruct_232);
			if(RESET != __HAL_UART_GET_IT_SOURCE(&USART_InitStruct_232, UART_IT_RXNE))
			{			
				if (rxIndex < RX_BUFFER_SIZE - 1)
				{
						rx_232_Buffer[rxIndex] = USART_InitStruct_232.Instance->DR;
						rxIndex++;				
				}
				
				else
				{
						uint8_t data = USART1->DR;
				}
			}
			if (RESET != __HAL_UART_GET_FLAG(&USART_InitStruct_232, USART_FLAG_IDLE) && __HAL_UART_GET_IT_SOURCE(&USART_InitStruct_232, UART_IT_IDLE))
			{	
					uint8_t i;
					i = USART_InitStruct_232.Instance->SR;
					i = USART_InitStruct_232.Instance->DR;
					rxIndex = 0;
					recv_232_done = 1;					
					return;
			}
		}
}

void USART_232_Send(uint8_t *message,uint16_t size)
{
	recv_232_done = 0;
	HAL_UART_Transmit(&USART_InitStruct_232, message,size,HAL_MAX_DELAY);
}


/*           485串口配置             */
void USART_485_DE_init()
{
		__HAL_RCC_GPIOC_CLK_ENABLE();
		GPIO_InitTypeDef GPIO_InitStruct = {0};
		GPIO_InitStruct.Pin = USART_485_DE_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    HAL_GPIO_Init(USART_485_DE_GPIO_PORT, &GPIO_InitStruct);
}
void USART_485_DE_TX()
{
	HAL_GPIO_WritePin(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,GPIO_PIN_SET);
}
void USART_485_DE_RX()
{
	HAL_GPIO_WritePin(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,GPIO_PIN_RESET);
}

// 485发送数据
void USART_485_Send(uint8_t *message,uint16_t size)
{
	USART_485_DE_TX();
	HAL_UART_Transmit(&USART_InitStruct_485, message, size, HAL_MAX_DELAY);
	USART_485_DE_RX();
}
// USART_485 初始化
void USART_485_config()
{
		USART_485_DE_init();
	
		__HAL_RCC_USART3_CLK_ENABLE();
		__HAL_RCC_GPIOC_CLK_ENABLE();
	
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    // 配置 GPIOC Pin 11 和 10 分别作为 USART3 的 RX 和 TX 引脚
    GPIO_InitStruct.Pin = USART_485_RX_PIN | USART_485_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

    USART_InitStruct_485.Instance = USART_485;
    USART_InitStruct_485.Init.BaudRate = USART_485_BAUDRATE;
    USART_InitStruct_485.Init.WordLength = UART_WORDLENGTH_8B;
    USART_InitStruct_485.Init.StopBits = UART_STOPBITS_1;
    USART_InitStruct_485.Init.Parity = UART_PARITY_NONE;
    USART_InitStruct_485.Init.Mode = UART_MODE_TX_RX; // 既支持发送也支持接收
    USART_InitStruct_485.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    USART_InitStruct_485.Init.OverSampling = UART_OVERSAMPLING_16;
    HAL_UART_Init(&USART_InitStruct_485);

		HAL_NVIC_SetPriority(USART_485_IRQ, 0, 0);
    HAL_NVIC_EnableIRQ(USART_485_IRQ);
		// 初始化 DE 引脚 接收数据
    HAL_GPIO_WritePin(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,GPIO_PIN_RESET); 
		
//		HAL_UART_Receive_IT(&USART_InitStruct_485, &rxByte, 1);
		__HAL_UART_ENABLE_IT(&USART_InitStruct_485, UART_IT_RXNE); // 使能接收中断	
		__HAL_UART_ENABLE_IT(&USART_InitStruct_485, UART_IT_IDLE); // 使能空闲中断	
}

/*
 *  函数名：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;

		__HAL_RCC_USART3_CLK_ENABLE();
		__HAL_RCC_GPIOC_CLK_ENABLE();
	
		GPIO_InitTypeDef GPIO_InitStruct = {0};

		// 配置 GPIOC Pin 11 和 10 分别作为 USART3 的 RX 和 TX 引脚
    GPIO_InitStruct.Pin = USART_485_RX_PIN | USART_485_TX_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
    HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

		USART_InitStruct_485.Instance = USART_485;
    USART_InitStruct_485.Init.BaudRate = baudrate;
    USART_InitStruct_485.Init.WordLength = (wordLength== 9) ? UART_WORDLENGTH_9B : UART_WORDLENGTH_8B;
    USART_InitStruct_485.Init.StopBits = UART_STOPBITS_1;
    USART_InitStruct_485.Init.Parity = (parity == 1) ? (UART_PARITY_ODD) : (parity == 2 ? UART_PARITY_EVEN : UART_PARITY_NONE);
    USART_InitStruct_485.Init.Mode = UART_MODE_TX_RX; // 既支持发送也支持接收
    USART_InitStruct_485.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    USART_InitStruct_485.Init.OverSampling = UART_OVERSAMPLING_16;
    HAL_UART_Init(&USART_InitStruct_485);

		HAL_NVIC_SetPriority(USART_485_IRQ, 0, 0);
    HAL_NVIC_EnableIRQ(USART_485_IRQ);
		// 初始化 DE 引脚 接收数据
    HAL_GPIO_WritePin(USART_485_DE_GPIO_PORT,USART_485_DE_PIN,GPIO_PIN_RESET); 
		
//		HAL_UART_Receive_IT(&USART_InitStruct_485, &rxByte, 1);
		__HAL_UART_ENABLE_IT(&USART_InitStruct_485, UART_IT_RXNE); // 使能接收中断	
		__HAL_UART_ENABLE_IT(&USART_InitStruct_485, UART_IT_IDLE); // 使能空闲中断	
	
}

void USART_485_IRQHandler(void){
			GATEWAY_PARAMS *get;
			get= get_gateway_config_params();
			if(get->device_params->protocol == 3)
				mmodbus_callback(&USART_InitStruct_485);
			else if(get->device_params->protocol == 1 || get->device_params->protocol == 2)
				dlt_callback(&USART_InitStruct_485);
			else if (get->device_params->protocol == 4)
				cjt_callback(&USART_InitStruct_485);
}


void DEBUG_USART_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};

  // Enable USART6 clock
  __HAL_RCC_USART6_CLK_ENABLE();
  // Enable GPIOC clock
  __HAL_RCC_GPIOC_CLK_ENABLE();

  // Configure USART6 pins
	GPIO_InitStruct.Pin = DEBUG_USART_RX_PIN | DEBUG_USART_TX_PIN;
  GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF8_USART6;// Connect USART6 pins to AF8
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
	
	// Configure USART6
	USART_InitStruct_DEBUG.Instance = DEBUG_USART;
	USART_InitStruct_DEBUG.Init.BaudRate = DEBUG_USART_BAUDRATE;
	USART_InitStruct_DEBUG.Init.WordLength = UART_WORDLENGTH_8B;
	USART_InitStruct_DEBUG.Init.StopBits = UART_STOPBITS_1;
	USART_InitStruct_DEBUG.Init.Parity = UART_PARITY_NONE;
	USART_InitStruct_DEBUG.Init.Mode = UART_MODE_TX_RX; // 既支持发送也支持接收
	USART_InitStruct_DEBUG.Init.HwFlowCtl = UART_HWCONTROL_NONE;
	USART_InitStruct_DEBUG.Init.OverSampling = UART_OVERSAMPLING_16;
	HAL_UART_Init(&USART_InitStruct_DEBUG);

	HAL_NVIC_SetPriority(DEBUG_USART_IRQ, 2, 1);
  HAL_NVIC_EnableIRQ(DEBUG_USART_IRQ);
	
	// Enable USART6
	__HAL_UART_ENABLE_IT(&USART_InitStruct_DEBUG, UART_IT_IDLE); // 使能空闲中断
//	__HAL_UART_ENABLE_IT(&USART_InitStruct_DEBUG, UART_IT_RXNE); // 使能接收中断		
	__HAL_DMA_ENABLE(&DMA_DEBUG_RX);						//使能DMA
  __HAL_UART_ENABLE(&USART_InitStruct_DEBUG);
//	__HAL_UART_CLEAR_FLAG(&USART_InitStruct_DEBUG, USART_FLAG_TC);
	
}


void DEBUG_USART_IRQHandler(void)
{	
	if(RESET != __HAL_UART_GET_FLAG(&USART_InitStruct_DEBUG, UART_FLAG_IDLE)) // 判断是否是空闲中断
	{
		__HAL_UART_CLEAR_IDLEFLAG(&USART_InitStruct_DEBUG); //清空空闲中断标志位
		//关闭DMA
		__HAL_DMA_DISABLE(&DMA_DEBUG_RX);
//		HAL_UART_DMAStop(&USART_InitStruct_DEBUG); 
		UART6_RX_NUM = BUFF_SIZE - __HAL_DMA_GET_COUNTER(&DMA_DEBUG_RX);
		//清除DMA中断
		__HAL_DMA_CLEAR_FLAG(&DMA_DEBUG_RX,DMA_FLAG_TCIF1_5);
		__HAL_DMA_ENABLE(&DMA_DEBUG_RX);
		//接收状态置位
		UART6_RX_STAT=1;
	}
}

void USART_DMA_Config(void)
{
	// 使能串口和DMA时钟
	__HAL_RCC_USART6_CLK_ENABLE();
	__HAL_RCC_DMA2_CLK_ENABLE();
  
	DMA_DEBUG_RX.Instance = DEBUG_USART_DMA_STREAM;
	DMA_DEBUG_RX.Init.Channel = DEBUG_USART_DMA_CHANNEL;
	/*方向：从外设到内存*/		
	DMA_DEBUG_RX.Init.Direction =  DMA_PERIPH_TO_MEMORY;
	/*外设地址不增*/	 
	DMA_DEBUG_RX.Init.PeriphInc = DMA_PINC_DISABLE;
	/*内存地址自增*/
	DMA_DEBUG_RX.Init.MemInc = DMA_MINC_ENABLE;
	 /*外设数据单位*/	
	DMA_DEBUG_RX.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
	/*内存数据单位 8bit*/
	DMA_DEBUG_RX.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;	
	/*DMA模式：不断循环*/
	DMA_DEBUG_RX.Init.Mode = DMA_NORMAL;
	/*优先级：中*/	
	DMA_DEBUG_RX.Init.Priority = DMA_PRIORITY_MEDIUM;
	/*禁用FIFO*/
	DMA_DEBUG_RX.Init.FIFOMode = DMA_FIFOMODE_DISABLE;
	DMA_DEBUG_RX.Init.FIFOThreshold= DMA_FIFO_THRESHOLD_FULL;  
	
	HAL_DMA_Init(&DMA_DEBUG_RX);
	__HAL_LINKDMA(&USART_InitStruct_DEBUG, hdmarx, DMA_DEBUG_RX);	
	
	SET_BIT(USART_InitStruct_DEBUG.Instance->CR3, USART_CR3_DMAR);
	HAL_DMA_Start(&DMA_DEBUG_RX,DEBUG_USART_DR_BASE, (uint32_t)UART6_RX_BUF, BUFF_SIZE);
	__HAL_DMA_ENABLE_IT(&DMA_DEBUG_RX,DMA_IT_TC);
	
	HAL_NVIC_SetPriority(DMA2_Stream1_IRQn, 2, 2);
  HAL_NVIC_EnableIRQ(DMA2_Stream1_IRQn);
}

void DMA2_Stream1_IRQHandler() {
    if (__HAL_DMA_GET_IT_SOURCE(&DMA_DEBUG_RX,DMA_IT_TC)) 
		{
        __HAL_DMA_CLEAR_FLAG(&DMA_DEBUG_RX,DMA_IT_TC);
    }
}
 

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *husart)
{	
		// USART 232
    if(husart->Instance == USART_232)
		{	
				// 将接收到的数据存储在缓冲区中
				rx_232_Buffer[rxIndex] = rxByte;
				rxIndex++;						
				HAL_UART_Receive_IT(husart, &rxByte, 1);
			}
		// USART 485
		if(husart->Instance == USART_485)
		{
				if (rxIndex < RX_BUFFER_SIZE)
        {
            // 将接收到的数据存储在缓冲区中
						rx_232_Buffer[rxIndex] = rxByte;
						rxIndex++;
        }							
				memset(rx_232_Buffer, 0, rxIndex);
				rxIndex = 0;
				HAL_UART_Receive_IT(husart, &rxByte, 1);
		}
		if(husart->Instance == USART6)
		{
	
		}
}
/*********************************************END OF FILE**********************/
