
#include "soft_usart.h"
#include "common.h"
#include "main.h"
#include "system_init.h"
#include "usart_data_handle.h"
#include "string.h"
#include "main_task.h"

extern UART_HandleTypeDef huart1;
uint8_t FMU_uart_buf[MAX_UART_BUF] = {0};
/**
  * @file    USER_UART_IRQHandler
  * @brief   串口中断处理
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
void USER_UART_IRQHandler(UART_HandleTypeDef *huart)
{   
    uint32_t recv_count = 0;
	if (huart == &huart1)
	{
		if (RESET != __HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE))
		{
			__HAL_UART_CLEAR_IDLEFLAG(huart); 		
			HAL_UART_AbortReceive(huart);
			recv_count = MAX_UART_BUF - __HAL_DMA_GET_COUNTER(huart->hdmarx);

			rkfifo_in(&uart_rkfifo,FMU_uart_buf,recv_count);
			
			memset(FMU_uart_buf,0,MAX_UART_BUF);
			HAL_UART_Receive_DMA(huart, FMU_uart_buf, MAX_UART_BUF);

            rt_sem_release(&uart1_sem);
		}
	}
}


/**
  * @file    HAL_UART_ErrorCallback
  * @brief   uart错误中断回调函数
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
	if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) != RESET) //接收溢出检测
	{
		__HAL_UART_CLEAR_OREFLAG(huart);
	}

	if (__HAL_UART_GET_FLAG (huart, UART_FLAG_RXNE) != RESET)//接收数据
	{
	   __HAL_UART_CLEAR_FLAG (huart, UART_FLAG_RXNE);
	}

	__HAL_UART_CLEAR_PEFLAG (huart);

	if (huart == &huart1)
	{
		HAL_UART_Receive_DMA(huart, FMU_uart_buf, MAX_UART_BUF);
	}
}

/**
  * @file    usart1_send_msg
  * @brief   串口发送数据
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
uint32_t uart2_send_delay_time = 0;
void usart1_send_msg(uint8_t *data, uint8_t size)
{
	// HAL_UART_Transmit_DMA(&huart1, data, size);

	// uart2_send_delay_time = HAL_GetTick();

	rkfifo_in(&send_uart_rkfifo,data,size);
}

uint8_t send_uart_buf[512] = {0};
void send_uartfifo_msg(void)
{
	uint16_t len = 0;
	if(uart_send_is_ok(USART_1) == true)
    {
		len = rkfifo_out(&send_uart_rkfifo, &send_uart_buf, 512);

		if(len > 0) 
		{
			HAL_UART_Transmit_DMA(&huart1, send_uart_buf, len);
			uart2_send_delay_time = HAL_GetTick();
		}
	}
}

/**
  * @file    uart_send_is_ok
  * @brief   检测串口是否可用
  * @param   uart_num 串口号
  * @details 
  * @author  Zhang Sir 
 **/
bool uart_send_is_ok(uint8_t uart_num)
{ 
	//设备升级不发送
	// if(radar_update_flag == true)
	// 	return false;

	if (uart_num == USART_1)
	{
		if (huart1.gState == HAL_UART_STATE_READY && (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_TC) != RESET && __HAL_UART_GET_FLAG(&huart1, UART_FLAG_TXE) != RESET))
		{
		}
		else
		{
			return false;
		}

		//延迟1ms发送，防止如果是空闲中断接收，连续发送变成一包
		if(HAL_GetTick() - uart2_send_delay_time <= 1)
		{
			return false;
		}
	}

	return true;

}