#include "oscar.h"

osThreadId_t Oscar_Handle;
const osThreadAttr_t Oscar_attributes = {
	.name = "OSCAR",
	.stack_size = 1024,
	.priority = (osPriority_t)osPriorityBelowNormal,
};

// 事件
osEventFlagsId_t Oscar_EventHandle;
const osEventFlagsAttr_t Oscar_Event_attributes = {
	.name = "Oscar_Event"};

extern UART_HandleTypeDef huart1;
UART_HandleTypeDef *pOscarUart = &huart1;

uint8_t Oscar_SN_Command[8] = {0x01, 0x03, 0x00, 0x0A, 0x00, 0x05, 0xA5, 0xCB};

static uint8_t Oscar_Wavelength_Trans_Buf[2][8] = {
    //01 03 08 36 00 7A 26 47    (2102  122)
    //01 03 08 B0 00 7A C7 AE    (2224  122)
    {0x01, 0x03, 0x08, 0x36, 0x00, 0x7A, 0x26, 0x47},
    {0x01, 0x03, 0x08, 0xB0, 0x00, 0x7A, 0xC7, 0xAE}};
static uint8_t Oscar_Data_Trans_Buf[2][8] = {
    // 01 03 0A 36 00 7A 27 FF    (2614  122)
    // 01 03 0A B0 00 7A C6 16    (2736  122)
    {0x01, 0x03, 0x0A, 0x36, 0x00, 0x7A, 0x27, 0xFF},
    {0x01, 0x03, 0x0A, 0xB0, 0x00, 0x7A, 0xC6, 0x16}};
uint8_t Oscar_sn_buf[15] = {0};

// uint8_t Oscar_TEST_BUF[8]  ={0x01, 0x03, 0x00, 0x00, 0x00, 0x04, 0x44, 0x09};
// uint8_t Oscar_TEST_BUF2[8]  ={0x01, 0x03, 0x00, 0x00, 0x00, 0x04, 0x44, 0x09};
// uint8_t Oscar_TRANS_BUF[8]  ={0x01, 0x03, 0x00, 0x00, 0x00, 0x04, 0x44, 0x09};
uint8_t Oscar_RCV_BUF[1024] = {0};

UART_HELPER_TypeDef *Oscar_uart_helper;

Oscar_TypeDef oscar = {
	Oscar_Init,
	Oscar_Port,
	Oscar_Test,
	Oscar_Start,
	Oscar_Stop,
	NULL,
	0,	  // state
	0,	  // data_ok
	{0},  // buf
	0,	  // size_received
	0,	  // time base
	1000, // timeout ticks,  1000ms = 1S
	0,	  // event_flag
	0,	  // wavelength_ok
	NULL, // transRecord[3]
};

int Oscar_Init()
{
	Oscar_uart_helper = UART_HELPER_Init();

	if (Oscar_uart_helper == NULL)
		return -1;

	// TODO 接口
	UART_HELPER_Set_Huart(Oscar_uart_helper, pOscarUart);
	UART_HELPER_Set_Interface_Type(Oscar_uart_helper, Uart_Interface_Max3160_485);

	//  传输
	UART_HELPER_Setup_Trans_mode(Oscar_uart_helper, Uart_Trans_DMA);
	// UART_HELPER_Setup_Rcv_mode( Oscar_uart_helper, Uart_Trans_IT );
	UART_HELPER_Set_enable_idle(Oscar_uart_helper, Uart_IDLE_IT_ENABLE);

	//  回调GPIO 操作 数据操作
	UART_HELPER_Set_trans_GPIO(Oscar_uart_helper, Oscar_Trans_GPIO); // enbale rcv
	UART_HELPER_Set_trans_cplt_GPIO(Oscar_uart_helper, Oscar_Trans_Cplt_GPIO);

	UART_HELPER_Set_Callback(Oscar_uart_helper, &oscar, Oscar_CallBack);

	// 设置 Buf, 如果启用消息队列，不启用trans_buf
	UART_HELPER_Set_Rcv_Buf(Oscar_uart_helper, Oscar_RCV_BUF, sizeof(Oscar_RCV_BUF));
	// UART_HELPER_Set_Trans_Buf(Oscar_uart_helper, Oscar_SN_Command, sizeof(Oscar_SN_Command));

	//  GPIO 操作
	switch (Oscar_uart_helper->interface_type)
	{
	case Uart_Interface_Default:
		break;
	case Uart_Interface_485:
		usart6_send_enable();
		break;
	case Uart_Interface_Max3160_232:
		Oscar_MAX3160_232();
		break;
	case Uart_Interface_Max3160_485:
		max3160_485_receive_mode();
		break;
	default:
		break;
	}
	oscar.state = Oscar_State_Waiting;
	oscar.timebase_ticks = osKernelGetTickCount();

	// TODO enable trans queue
	// 最大队列数 8, 消息类型， 值传递（内含的buf为指针，如何包含大空间的buf,可选择指针传递 ）
	oscar.transQueue = osMessageQueueNew(8, sizeof(Record_Trans_Rcv_TypeDef), NULL);
}

void Oscar_Port()
{
	Oscar_Handle = osThreadNew(Oscar_Task, NULL, &Oscar_attributes);
	// Oscar_EventHandle = osEventFlagsNew( &Oscar_Event_attributes );
}

int Oscar_Test()
{
	// 装载要发送的消息队列
	oscar.transRecord[0].size = sizeof(Oscar_SN_Command);
	oscar.transRecord[0].buf = Oscar_SN_Command;

	// log_i( "  oscar.transRecord[0]  buf  %d,  addr %d " , oscar.transRecord[0].buf[0], oscar.transRecord[0].buf );
	// log_i( "  Oscar_TEST_BUF  buf  %d,  addr  %d " ,Oscar_TEST_BUF[0], Oscar_TEST_BUF );
	osMessageQueuePut(oscar.transQueue, (void *)&oscar.transRecord[0], 0, osWaitForever);
	// 改变操作状态
	oscar.state = Oscar_State_Test; // 操作状态
	return 0;
}

void Oscar_Wavelength()
{
	// 装载要发送的消息队列 , 注意队列大小及
	oscar.transRecord[0].size = sizeof(Oscar_SN_Command);
	oscar.transRecord[0].buf = Oscar_Wavelength_Trans_Buf[0];
	osMessageQueuePut(oscar.transQueue, (void *)&oscar.transRecord[0], 0, osWaitForever);

	oscar.transRecord[1].size = sizeof(Oscar_SN_Command);
	oscar.transRecord[1].buf = Oscar_Wavelength_Trans_Buf[1];
	osMessageQueuePut(oscar.transQueue, (void *)&oscar.transRecord[1], 0, osWaitForever);

	// oscar.state = Oscar_State_Get_WAVELENGTH;  // 操作状态
	// osEventFlagsSet( Oscar_EventHandle, Oscar_Event_Get_Data );  // 事件
}

void Oscar_Start()
{
	// 装载要发送的消息队列 , 注意队列大小及
	oscar.transRecord[0].size = sizeof(Oscar_SN_Command);
	oscar.transRecord[0].buf = Oscar_Data_Trans_Buf[0];
	osMessageQueuePut(oscar.transQueue, (void *)&oscar.transRecord[0], 0, osWaitForever);

	oscar.transRecord[1].size = sizeof(Oscar_SN_Command);
	oscar.transRecord[1].buf = Oscar_Data_Trans_Buf[1];
	osMessageQueuePut(oscar.transQueue, (void *)&oscar.transRecord[1], 0, osWaitForever);

	oscar.state = Oscar_State_Get_DATA; // 操作状态
	// osEventFlagsSet( Oscar_EventHandle, Oscar_Event_Get_Data );  // 事件
}

void Oscar_Stop()
{
	oscar.state = Oscar_State_Stop;
	// TODO stop  task？
}

void Oscar_Task()
{
	// log_i( " ph tran mode : %d ", oscar.->trans_mode );
	// memset(  Oscar_RCV_Buf, 0, 2*Oscar_Rcv_Buf_Size );  /* ph*3 ph *2 否则内存泄漏 */
	oscar.event_flag = 0;
	uint64_t ticks;
	int err_con = 0;
	int st;
	Record_Trans_Rcv_TypeDef msgQueue;  // 消息队列
	int queue_seq = 0;   // 队列的计数

	for (;;)
	{
		switch (oscar.state)
		{
		case Oscar_State_Waiting:
			log_d(" Viper task..... : %d    %d ", oscar.state, oscar.state);
			osDelay(20);
			break;

		case Oscar_State_Test:
			// log_i( " temp test..... : %d  QueueGetCount  %d " , oscar.state , osMessageQueueGetCount(oscar.transQueue) );
			if (osMessageQueueGetCount(oscar.transQueue) == 0)
			{
				oscar.state = Oscar_State_Error;
				break;
			}
			// 取队列  值传递, 第三个参数为NULL 否则为消息长度
			osMessageQueueGet( oscar.transQueue, &msgQueue, sizeof(Record_Trans_Rcv_TypeDef), osWaitForever );
			// log_i(  " msgQueue  %d   %d " , msgQueue.size,  msgQueue.buf   );
			// log_i(  " msgQueue  %d  " , Oscar_TEST_BUF  );
			oscar.state = Oscar_State_Test_Start;
			continue;

		case Oscar_State_Test_Start:
			// log_i( " temp Oscar_State_Test_Start..... : %d    %d " , oscar.state , oscar.state );
			ticks = osKernelGetTickCount();
			UART_HELPER_Set_Trans_Buf(Oscar_uart_helper, msgQueue.buf, msgQueue.size);
			// HAL_UARTEx_ReceiveToIdle_DMA(&huart1, Oscar_RCV_BUF,1024);
			Oscar_Receive();
			Oscar_Transmit();
			oscar.state = Oscar_State_SN_Getting;
			continue;

		case Oscar_State_SN_Getting:
			log_d( " Oscar_ State_SN_Getting..... : %d    %d " , oscar.state , oscar.state );
			if ( (osKernelGetTickCount() - ticks) > 2000 )
			{
				log_d( " Oscar_ State_SN_Getting -> retry: %d   " , err_con++   );
				// err_con++;
				if (err_con > 5)
				{
					log_w(" Oscar_ testing  ******** error ");
					oscar.state = Oscar_State_Error;
				}
				oscar.state = Oscar_State_Test_Start;   // 重新发送取出来的队列
			}
			osDelay(200);
			continue;

		case Oscar_State_SN_OK:
			// SN 数据 拷贝
			memcpy( oscar.oscarsn_buf , oscar.result_buf, oscar.size_received );
			log_i("Oscar_ SN :   %c %c %c %c" 
					, oscar.oscarsn_buf[9] , oscar.oscarsn_buf[10], oscar.oscarsn_buf[11], oscar.oscarsn_buf[12] );
				
			// 获得序列号 状态OK
			osEventFlagsSet(Oscar_EventHandle, Oscar_Event_Ready);

			// TODO 判断队列是否有元素
			if (osMessageQueueGetCount(oscar.transQueue) == 0)
			{
				oscar.state = Oscar_State_Get_WAVELENGTH;
				// TODO 停止DMA
				if (Oscar_uart_helper->rcv_mode == Uart_Trans_DMA)
				{
					HAL_UART_DMAStop(Oscar_uart_helper->huart);
				}
				continue;
			}
			else
			{
				osMessageQueueGet(oscar.transQueue, &msgQueue, sizeof(Record_Trans_Rcv_TypeDef), osWaitForever);
				// osEventFlagsClear( Oscar_EventHandle, Oscar_Event_Test_OK );
				oscar.state = Oscar_State_Test_Start;
				continue;
			}
			break;

		case Oscar_State_Get_WAVELENGTH:
			log_i(" get wavelenth .....   ");
			if (oscar.wavelength_ok == 1)
			{
				oscar.state = Oscar_State_Ready;
				break;
			}
			Oscar_Wavelength();
			oscar.state = Oscar_State_Get_DATA;
			osDelay(1);
			continue;

		case Oscar_State_Ready:
			// log_d( "  Oscar_ State_Ready .....   "  );
			osDelay(1);
			continue;

		case Oscar_State_Get_DATA:
			log_i("  Oscar_ State_Get_DATA .....   ");
			oscar.data_ok = 0;
			oscar.size_received = 0;
			memset( oscar.result_buf, 0, sizeof(oscar.result_buf) );
			osEventFlagsClear(Oscar_EventHandle, Oscar_Event_Get_Data);

			// 队列是否有值
			if (osMessageQueueGetCount(oscar.transQueue) == 0)
			{
				oscar.state = Oscar_State_Error;
				break;
			}
			osMessageQueueGet(oscar.transQueue, &msgQueue, sizeof(Record_Trans_Rcv_TypeDef), osWaitForever);

			oscar.state = Oscar_State_Get_DATA_Trans;
			continue;
		case Oscar_State_Get_DATA_Trans:
			log_i("  Oscar_ State_Get_DATA Trans .....   ");
			ticks = osKernelGetTickCount();
			UART_HELPER_Set_Trans_Buf(Oscar_uart_helper, msgQueue.buf, msgQueue.size);
			Oscar_Receive();
			Oscar_Transmit();
			oscar.state = Oscar_State_Get_DATA_Wait;
			continue;
		case Oscar_State_Get_DATA_Wait:
			if (osKernelGetTickCount() - ticks > 2000)
			{
				err_con++;
				if (err_con > 3)
				{
					log_w(" Oscar_  wait ....... error ");
					oscar.state = Oscar_State_Error;
				}
				oscar.state = Oscar_State_Get_DATA_Trans;
			}
			osDelay(1);
			continue;

		case Oscar_State_Get_DATA_OK:
			log_d(" Oscar_ one_measurement data ok  ...  ");
			oscar.data_ok = 0;
			oscar.state = Oscar_State_Get_DATA_Check;
			continue;

		case Oscar_State_Get_DATA_Check:
			log_d(" Oscar_ data check  ********  ");

			// validate
			if ( Oscar_Validate() != 1 )
			{
				oscar.state = Oscar_State_Error;
				break;
			}

			if (oscar.wavelength_ok == 0)
			{
				// WL 数据 拷贝
				memcpy( oscar.Oscar_Wavelength_Buf[queue_seq], oscar.result_buf, oscar.size_received );
				oscar.state = Oscar_State_Get_Queue_MSG;
				break;
			}
			if (oscar.wavelength_ok == 1)
			{
				// DATA 数据 拷贝
				memcpy( oscar.Oscar_Data_Buf[queue_seq], oscar.result_buf, oscar.size_received );
				oscar.state = Oscar_State_Get_Queue_MSG;
				break;
			}

			osDelay(10);
			continue;

		case Oscar_State_Get_Queue_MSG:
			log_d(" Oscar_ State_Get_Queue_MSG ........ msg queue count: %d  msg_seq  %d", 
					osMessageQueueGetCount(oscar.transQueue), queue_seq);
			//  处理DMA 相关事宜 ---DMA 

			// 队列是否有值
			if (osMessageQueueGetCount(oscar.transQueue) > 0)
			{
				log_d("  Queue_MSG  count>0 ........ ");
				queue_seq++;
				oscar.state = Oscar_State_Get_DATA;
				break;
			}
			queue_seq = 0;
			oscar.state = Oscar_State_Ready;
			continue;

		case Oscar_State_Stop:
			// log_d(" Oscar_ state  stop ..... ");
			osDelay(10);
			continue;

		case Oscar_State_Timeout:
			log_e(" Oscar_ timeout ..... ");
			oscar.state = Oscar_State_Waiting;
			// TODO 停止DMA
			if ( Oscar_uart_helper->rcv_mode == Uart_Trans_DMA )
			{
				HAL_UART_DMAStop( Oscar_uart_helper->huart );
			}
			osDelay(5);
			break;

		case Oscar_State_Error:
			log_e(" Oscar_ error ..... ");
			oscar.state = Oscar_State_Waiting;
			// TODO 停止DMA
			if ( Oscar_uart_helper->rcv_mode == Uart_Trans_DMA )
			{
				HAL_UART_DMAStop( Oscar_uart_helper->huart );
			}
			osDelay(5);
			break;
		}
		osDelay(20);
	}
}

void Oscar_Trans_GPIO(void)
{
	// HAL_GPIO_WritePin(R_W_GPIO_Port,R_W_Pin, SET);
	// HAL_GPIO_WritePin(NULL,0, SET);
	HAL_GPIO_WritePin(SEL_232_485_GPIO_Port, SEL_232_485_Pin, SET);
	HAL_GPIO_WritePin(HDPLX_GPIO_Port, HDPLX_Pin, RESET);
	HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, SET);
}

void Oscar_Trans_Cplt_GPIO(void)
{
	// HAL_GPIO_WritePin(R_W_GPIO_Port,R_W_Pin, RESET);
	// HAL_GPIO_WritePin(NULL,0, RESET);
	HAL_GPIO_WritePin(SEL_232_485_GPIO_Port, SEL_232_485_Pin, SET);
	HAL_GPIO_WritePin(HDPLX_GPIO_Port, HDPLX_Pin, SET);
	HAL_GPIO_WritePin(DE485_GPIO_Port, DE485_Pin, RESET);
}

int Oscar_Transmit()
{
	//  TODO 结合队列
	oscar.size_received = 0;
	if (Oscar_uart_helper->transferring == 0)
	{
		return UART_HELPER_Trans(Oscar_uart_helper, Oscar_uart_helper->trans_record->buf, Oscar_uart_helper->trans_record->size);
	}
	return 0;
}

int Oscar_Receive()
{
	return UART_HELPER_Start_Rcv(Oscar_uart_helper, Oscar_uart_helper->rcv_buf, Oscar_uart_helper->rcv_size);
	// return 0;
}

void Oscar_Set_Timeout_ms(uint64_t ms_ticks)
{
	oscar.timeout_ticks = ms_ticks;
}

int Oscar_Validate()
{
	return CRC16_Check(oscar.result_buf ,oscar.size_received);
}

int Oscar_CallBack(Oscar_TypeDef *pOscar, uint8_t *buf, uint16_t size)
{
	log_d(" Oscar_CallBack  -- state %d   size %d", oscar.state, size);

	uint16_t size_tmp;
	size_tmp = size;
	switch (oscar.state)
	{
	case Oscar_State_SN_Getting:
		if (size == 0)  return 0;
 
		//  添加数据
		if ( (size + oscar.size_received) >= sizeof(oscar.result_buf) )
		{
			size_tmp = sizeof(oscar.result_buf) - oscar.size_received;
		}
		// // log_d(" copy sn  %d  %d ", size,size_tmp);
		memcpy((uint32_t)(oscar.result_buf + oscar.size_received), Oscar_uart_helper->rcv_buf, size_tmp);
		oscar.size_received += size_tmp;

		//  Modbus 最小长度5
		if ( oscar.size_received < 5 )  return 0;		

		// Modbus 长度校验 
		if ( oscar.size_received == ( oscar.result_buf[2] + 5 ) )
		{
			oscar.state++;
		}
		break;

	case Oscar_State_Get_DATA_Wait:
		if ( size == 0 )  return 0;

		//  添加数据
		if ( (size + oscar.size_received) >= sizeof(oscar.result_buf) )
		{
			size_tmp = sizeof(oscar.result_buf) - oscar.size_received;
		}
		memcpy((uint32_t)(oscar.result_buf + oscar.size_received), Oscar_uart_helper->rcv_buf, size_tmp);
		oscar.size_received += size_tmp;;

		//  Modbus 最小长度5
		if (oscar.size_received<5)  return 0;	

		// Modbus 长度校验 
		if ( oscar.size_received == ( oscar.result_buf[2] + 5 ) )
		{
			oscar.state++;
		}

		// if (Oscar_uart_helper->enable_idle_it == 0)
		// {
		// 	// Modbus 长度校验，拷贝数据？
		// 	if (oscar.size_received == (oscar.result_buf[2] + 5))
		// 	{
		// 		oscar.state++;
		// 	}
		// 	return 0;
		// }
		// if (Oscar_uart_helper->enable_idle_it == 1)
		// {
		// 	// 长度校验，拷贝数据？
		// 	if (oscar.size_received == (oscar.result_buf[2] + 5))
		// 	{
		// 		oscar.state++;
		// 	}
		// 	return 0;
		// }
		break;
	default:
		break;
	}
	return 0;
}

// void Oscar_Set_Interface( Oscar_TypeDef *ph,  UartInterface_TypeDef * interface  )
// {
//     UartHelper_Set_Interface( oscar.uarthelper,   interface );
// }
// void Oscar_Set_Huart( Oscar_TypeDef *ph,  UART_HandleTypeDef * huart  )
// {
//     oscar.uarthelper->huart = huart;
//     // UartHelper_Set_Huart( oscar.uarthelper,    huart  );
// }
// void Oscar_Set_Interface_Type( Oscar_TypeDef *ph,    Uart_Interface_Type_Typedef interface_type  )
// {
//     oscar.interface_type = interface_type;
//     oscar.uarthelper->interface_type = interface_type;
//     UartInterface_Setup_Interface_type( oscar.uarthelper->interface ,oscar.interface_type);
// }