#include "soft_uart.h"
#include "usart.h"
#include "stdbool.h"
#include "soft_timer.h"
#include "soft_adc.h"
#include "soft_flow.h"
#include "soft_crc.h"
#include <string.h>
#include "stdbool.h"
#include "tim.h"
#include "hard_led.h"
#include "soft_can.h"
#include "stdio.h"
#include "soft_bms.h"
#include "soft_terrain.h"
#include "soft_obstacle.h"
#include "soft_okcell.h"
#include "soft_adc.h"
#include "soft_p_2_c.h"
#include "soft_engine.h"
#include "stm32f1xx_it.h"
#include "bsp_serial.h"
#include "rkfifo.h"
#include "stm32f1xx_hal_def.h"
#include "soft_update.h"
#include "common.h"
#include "soft_water_device.h"
#include "config.h"
#include "soft_seed_device.h"

uint8_t Update_buf[150] = {0};

Vk_protocol vk_protocol;
rkfifo_t send_uart_rkfifo;

bool radar_update_flag = false; //雷达升级标志
Uart uart_info = {.vk_dev_pack_num = 1};


/**
  * @file    printf
  * @brief   串口发送重定向
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
int _write(int fd, char *pBuffer, int size)
{
	uint32_t uart3_send_count_time = HAL_GetTick();
	while (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) == 0 &&
		   HAL_GetTick() - uart3_send_count_time < 5)
		;
	HAL_UART_Transmit(&huart3, (uint8_t *)pBuffer, size, 0xff);
	return size;
}


/**
  * @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_info.vk_dev_update_flag == true)
	// 	return false;

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

		//延迟1ms发送，防止如果是空闲中断接收，连续发送变成一包
		if(HAL_GetTick() - uart2_send_delay_time <= 1)
		{
			return false;
		}
	}
	else if (uart_num == USART_3)
	{
		if (huart3.gState == HAL_UART_STATE_READY && (__HAL_UART_GET_FLAG(&huart3, UART_FLAG_TC) != RESET && __HAL_UART_GET_FLAG(&huart3, UART_FLAG_TXE) != RESET))
		{
		}
		else
		{
			return false;
		}

		if(HAL_GetTick() - uart3_send_delay_time <= 1)
		{
			return false;
		}
	}

	return true;

}

/**
  * @file    uart2_send_msg
  * @brief   串口2发送
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
uint32_t uart2_send_delay_time = 0;
uint32_t uart3_send_delay_time = 0;
void uart2_send_msg(uint8_t *data, uint8_t size)
{
	// static uint32_t send_time = 0;

	// send_time = HAL_GetTick();
	// //防止连续发送使多个数据变成一个
	// while (HAL_GetTick() - send_time <= 1)
	// 	;

	rkfifo_in(&send_uart_rkfifo,data,size);
	// HAL_UART_Transmit_DMA(&huart2, data, size);

	// uart2_send_delay_time = HAL_GetTick();
	//bspSerialWrite(&serial2,data,size);
}
uint8_t send_uart_buf[256] = {0};

void send_uartfifo_msg(void)
{
	uint16_t len = 0;
	if(uart_send_is_ok(USART_2) == true)
    {
		len = rkfifo_out(&send_uart_rkfifo, &send_uart_buf, 256);

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

//uart3 发送调用函数
void uart3_send_msg(uint8_t *data, uint8_t size)
{
	static uint32_t send_time3 = 0;

	send_time3 = HAL_GetTick();
	while (HAL_GetTick() - send_time3 <= 1)
		;
	HAL_UART_Transmit_DMA(&huart3, data, size);
	uart3_send_delay_time = HAL_GetTick();
}


/**
  * @file    UART_Init
  * @brief   UART23初始化接收空闲中断 开起DMA
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
void UART_Init(void)
{
	//uart2
	//__HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE); //接收到一个字节产生一次中断
	//HAL_UART_Receive_IT(&huart2, &test_buf, 1);

	__HAL_UART_ENABLE_IT(&huart2, UART_IT_IDLE); //uart2  空闲中断
	HAL_UART_Receive_DMA(&huart2, (uint8_t *)uart_info.uart2_recv_buf, MAX_UART_BUF);
	//开启错误处理机制
	__HAL_UART_ENABLE_IT(&huart2, UART_IT_ERR);
	
	//uart3
	//HAL_UART_Receive_IT(&huart3, (uint8_t *)uart_info.uart3_recv_buf, 1);

	__HAL_UART_ENABLE_IT(&huart3, UART_IT_IDLE);
	HAL_UART_Receive_DMA(&huart3, (uint8_t *)uart_info.uart3_recv_buf, MAX_UART_BUF/2);
	//开启错误处理机制
	__HAL_UART_ENABLE_IT(&huart3, UART_IT_ERR);

}


/**
  * @file    USER_UART_IRQHandler
  * @brief   user用户中断函数
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
uint32_t read_DR;
rkfifo_t recv_rkfifo;
void USER_UART_IRQHandler(UART_HandleTypeDef *huart)
{
	if (huart == &huart2)
	{
		if (RESET != __HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE))
		{
			read_DR = huart2.Instance->DR;
			__HAL_UART_CLEAR_IDLEFLAG(&huart2); 		
			HAL_UART_AbortReceive(&huart2);//HAL_UART_DMAStop 有问题
			uart_info.uart_dma_recv_counts = MAX_UART_BUF - __HAL_DMA_GET_COUNTER(huart->hdmarx);
			for(uint8_t i = 0;i<uart_info.uart_dma_recv_counts;i++)
			{
				if(uart_info.uart2_recv_buf[i] == 0xfe && uart_info.uart2_recv_buf[i+5] == 27)
				{
					time_heart[0] = HAL_GetTick();
					time_count[0]++;
				}
			}
			rkfifo_in(&recv_rkfifo,uart_info.uart2_recv_buf,uart_info.uart_dma_recv_counts);
			
			memset(uart_info.uart2_recv_buf,0,MAX_UART_BUF);
			HAL_UART_Receive_DMA(&huart2, uart_info.uart2_recv_buf, MAX_UART_BUF);
		}
	}

    if(huart == &huart3)
	{
		if (RESET != __HAL_UART_GET_FLAG(&huart3, UART_FLAG_IDLE))
		{	
			read_DR = huart3.Instance->DR;
			__HAL_UART_CLEAR_IDLEFLAG(&huart3); //清除中断标志位，不清除一直在中断里	
			HAL_UART_AbortReceive(&huart3);

			uart_info.uart_dma_recv_counts = MAX_UART_BUF - __HAL_DMA_GET_COUNTER(huart->hdmarx);

			//串口三接奥安，上飞发动机
			if (aoan_engine_Link.connect_status != COMP_NOEXIST)
			{
				decode_aoan_engine(uart_info.uart3_recv_buf, uart_info.uart_dma_recv_counts);
			}
			else if (vkv3_engine_link.connect_status != COMP_NOEXIST)
			{
				decode_vkv3_engine(uart_info.uart3_recv_buf, uart_info.uart_dma_recv_counts);
			}
			else
			{
				//根据协议选择设备
				decode_vkv3_engine(uart_info.uart3_recv_buf, uart_info.uart_dma_recv_counts);
				decode_aoan_engine(uart_info.uart3_recv_buf, uart_info.uart_dma_recv_counts);
			}

			HAL_UART_Receive_DMA(&huart3, (uint8_t *)uart_info.uart3_recv_buf, MAX_UART_BUF/2);
		}
	}
}


/**
  * @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 == &huart2)
	{
		HAL_UART_Receive_DMA(&huart2, (uint8_t *)uart_info.uart2_recv_buf, MAX_UART_BUF);
	}
	else if (huart == &huart3)
	{
		HAL_UART_Receive_DMA(&huart3, (uint8_t *)uart_info.uart3_recv_buf, MAX_UART_BUF/2);
	}

}


/**
  * @file    HAL_UART_TxCpltCallback
  * @brief   uart发送回调
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
	if (huart == &huart2)
	{
		
	}
}


/**
  * @file    check_uart_data
  * @brief   接收数据组包解析
  * @param   
  * @details 
  * @author  Zhang Sir 
 **/
Msg_Rx_Stage recv_step;
Vk_protocol fcu_protocol;
Vk_protocol vk_data = {.head = 0XFE,
						   .system_id = 0,
						   .head_bytes = 6,
						   .check_bytes = 2};
						   
void check_uart_data(rkfifo_t *fifo)
{
	uint8_t c = 0;
	static uint32_t vk_recv_time = 0;
	static uint8_t i = 0;

	while (rkfifo_out(fifo, &c, 1) != 0)
	{	

		if(recv_step != RX_HEAD && HAL_GetTick() - vk_recv_time > 200)
		{
			recv_step = RX_HEAD;
		}

		//解析出一包完整的数据
		switch (recv_step)
		{
		case RX_HEAD:
			if(c == vk_data.head)
			{
				vk_recv_time = HAL_GetTick();
				recv_step = RX_PAYLOAD_LEN;
			}
			break;
		case RX_PAYLOAD_LEN:
			vk_data.len = c;
			recv_step = RX_SEQ;
			break;
		case RX_SEQ:
			vk_data.seq = c;
			recv_step = RX_SYSID;
			break;
		case RX_SYSID:
			if(c == vk_data.system_id)
			{
				recv_step = RX_GROUPID;
			}
			else
			{
				recv_step = RX_HEAD;
			}
			break;
		case RX_GROUPID:
			if(c == GROUP_ID_FCU || c == GROUP_ID_PMU_UPDATE || c == GROUP_ID_F_UPDATE ||
			 c == GROUP_ID_B_UPDATE || c == GROUP_ID_T_UPDATE|| c == GROUP_ID_WEIGHT_UPDATE)
			{
				vk_data.group_id = c;
				recv_step = RX_MSGID;
			}
			else
			{
				recv_step = RX_HEAD;
			}
			break;
		case RX_MSGID:
			vk_data.msg_id = c;
			if(c == 27)
			{
				time_heart[2] = HAL_GetTick();
				time_count[2]++;
			}
			recv_step = RX_PAYLOAD;
			i = 0;
			break;
		case RX_PAYLOAD:
			vk_data.payload[vk_data.head_bytes + i] = c;
			i++;
			if(i == vk_data.len)
			{
				recv_step = RX_CHECK_LOW; 
			}
			else if(vk_data.len == 0) //没有payload
			{
				recv_step = RX_CHECK_HIGH;
			}
			break;
		case RX_CHECK_LOW:
			vk_data.payload[vk_data.head_bytes + i] = c;
			i++;
			recv_step = RX_CHECK_HIGH;
			break;
		case RX_CHECK_HIGH:
			vk_data.payload[vk_data.head_bytes + i] = c;

			vk_data.payload[0] = vk_data.head;
			vk_data.payload[1] = vk_data.len;
			vk_data.payload[2] = vk_data.seq;
			vk_data.payload[3] = vk_data.system_id;
			vk_data.payload[4] = vk_data.group_id;
			vk_data.payload[5] = vk_data.msg_id;
			
			if(0 == Get_Crc16(&vk_data.payload[0],vk_data.len + vk_data.head_bytes + vk_data.check_bytes))
			{
				if(vk_data.group_id == GROUP_ID_FCU || vk_data.group_id == GROUP_ID_PMU_UPDATE)
				{
					fcu_protocol.msg_id = vk_data.msg_id;
					memcpy(&fcu_protocol.payload[0],&vk_data.payload[0],vk_data.len + vk_data.head_bytes + vk_data.check_bytes);
					uart_info.fcu_buf_flag = true; 
				}
				//莫之比雷达升级
				else if(((vk_data.group_id == GROUP_ID_F_UPDATE && uavr11_info.Link.connect_status != COMP_NOEXIST) ||
					 	(vk_data.group_id == GROUP_ID_B_UPDATE && uavr12_info.Link.connect_status != COMP_NOEXIST) ||
					    (vk_data.group_id == GROUP_ID_T_UPDATE && uavr56_info.Link.connect_status != COMP_NOEXIST)))
				{	
					if(uart_info.use_update_buf_flag == false)
					{
						uart_info.update_time = HAL_GetTick();
						memcpy(&Update_buf[0],&vk_data.payload[0],vk_data.len + vk_data.head_bytes + vk_data.check_bytes);
						uart_info.use_update_buf_flag = true;

						if (vk_data.msg_id == 200)
						{
							{
								radar_update_flag = true;
								update_count = 0;
							}
						}
					}
					else
					{
						if(HAL_GetTick() - uart_info.update_time > 3000)
						{
							uart_info.use_update_buf_flag = false;
						}
					}
				}
				//VK协议设备升级 
				else if (vk_data.group_id == GROUP_ID_WEIGHT_UPDATE ||
						(vk_data.group_id == GROUP_ID_F_UPDATE /*&& mimo_f_info.Link.connect_status != COMP_NOEXIST*/) || //mimo
					 	(vk_data.group_id == GROUP_ID_B_UPDATE /*&& mimo_b_info.Link.connect_status != COMP_NOEXIST*/) || //mimo
					    (vk_data.group_id == GROUP_ID_T_UPDATE /*&& mimo_ter_info.Link.connect_status != COMP_NOEXIST*/)) //mimo
				{
#ifdef mimo_update
					if(vk_data.msg_id == 200)
					{
						if(EZup_par.step == STEP_DEFAULT)//mimo
						{//mimo
							memset(&EZup_par,0,sizeof(ez_update));//mimo
							memset(&uart_info.fcu_buf_flag,0,sizeof(Uart));
							memcpy(&uart_info.bin_size,&vk_data.payload[6],4);
							uart_info.vk_dev_pack_num = 1;
							uart_info.vk_dev_update_flag = true;  
							EZup_par.update_flag = true;//mimo

							EZup_par.step = STEP_FIND_NODE;//mimo
						}
					}
#else
					if(vk_data.msg_id == 200)
					{
						memset(&uart_info.fcu_buf_flag,0,sizeof(Uart));
						memcpy(&uart_info.bin_size,&vk_data.payload[6],4);
						uart_info.vk_dev_pack_num = 1;
						uart_info.vk_dev_update_flag = true;
					}
#endif

					//if(uart_info.use_update_buf_flag == false)
					//{
						memcpy(&Update_buf[0],&vk_data.payload[0],vk_data.len + vk_data.head_bytes + vk_data.check_bytes);
						//判断是否是需要的包序号
						if(uart_info.vk_dev_pack_num > (Update_buf[PACK_NUM] + Update_buf[PACK_NUM + 1] * 256) &&
						 vk_data.msg_id == 201)
						{
							Update_ack_func(Update_buf[DEVICE],201,&Update_buf[PACK_NUM]);
						}

						uart_info.use_update_buf_flag = true;

						
					//}


				}

			}
			else
			{
				//vk_protocol_test[4]++;
			}
			recv_step = RX_HEAD;
			break;
		default:
			recv_step = RX_HEAD;
			//vk_protocol_test[5]++;
			break;
		}
		if( uart_info.fcu_buf_flag == true)
			break;
	}
}
