#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include  <stdint.h>
#include "Can_User.h"

CAN_HandleTypeDef CanHandle;
TIM_HandleTypeDef TimHandle;
CAN_FilterTypeDef CanFilter;
uint32_t temp;
CAN_ProtocolStatusTypeDef ProtocolStatus;
CAN_TxHeaderTypeDef CanTxHeader;
CAN_TxHeaderTypeDef CanTxHeader133;
CAN_TxHeaderTypeDef CanTxHeader143;
CAN_TxHeaderTypeDef CanTxHeader153;
CAN_TxHeaderTypeDef CanTxHeader163;
uint8_t TxData[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint8_t TxData13F[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint8_t TxData14F[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint8_t TxData15F[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint8_t TxData16F[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint32_t CANTXCnt[5] = {0x0 , 0x0 , 0x0 , 0x0 , 0x0};
uint32_t CANRXCnt[5] = {0x0 , 0x0 , 0x0 , 0x0 , 0x0};
CAN_RxHeaderTypeDef CanRxHeader;
uint8_t RxData[8] = {0};
uint8_t F_CAN_TX_CLT = 0;           //0= 可以发送; 非0 = 禁止发送

uint8_t DLCtoBytes[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};

TIM_HandleTypeDef    Tim6Handle;

void CAN_User_APP_ErrorHandler();

void CAN_Config (void)
{
	/* Initialize CAN，接收的过滤器 */
	CanHandle.Instance                      = CAN1;
	CanHandle.Init.FrameFormat              = CAN_FRAME_CLASSIC;
	CanHandle.Init.Mode                     = CAN_MODE_NORMAL;
	CanHandle.Init.Prescaler                = 3U;/*分频系数，将 CAN 时钟源分频后得到时间量子（Tq）*/ 
	CanHandle.Init.NominalSyncJumpWidth     = 4U;/* 同步跳转宽度（SJW），定义位时序调整的最大步长 */
	CanHandle.Init.NominalTimeSeg1          = 12U;	/*时间段 1（Tseg1），包含传播段（Prop_Seg）和相位段 1（Phase_Seg1）。*/
	CanHandle.Init.NominalTimeSeg2          = 4U;	/*时间段 2（Tseg2），即相位段 2（Phase_Seg2）。*/
	if (HAL_CAN_Init(&CanHandle) != HAL_OK)
	{
		 CAN_User_APP_ErrorHandler();
	}
	
	/* Configure CAN filters */
	CanFilter.IdType         = CAN_STANDARD_ID;
	CanFilter.FilterChannel  = CAN_FILTER_CHANNEL_0;
	CanFilter.Rank           = CAN_FILTER_RANK_CHANNEL_NUMBER;
	CanFilter.FilterID       = 0x666;
	CanFilter.FilterFormat   = 0xFFFFFFFF;
	CanFilter.MaskID         = 0x0; /* When receiving, only the high 11 bits of the ID are compared */
	CanFilter.MaskFormat     = 0xFFFFFFFF;
	if (HAL_CAN_ConfigFilter(&CanHandle, &CanFilter) != HAL_OK)
	{
		 CAN_User_APP_ErrorHandler();
	}
	
		
	/* Start CAN */
	if (HAL_CAN_Start(&CanHandle) != HAL_OK)
	{
		 CAN_User_APP_ErrorHandler();
	}
	
	/* Add message to TX FIFO ,发送*/
	CanTxHeader.Identifier   = 0x555; 
	CanTxHeader.IdType       = CAN_STANDARD_ID;
	CanTxHeader.TxFrameType  = CAN_DATA_FRAME;
	CanTxHeader.FrameFormat  = CAN_FRAME_CLASSIC;
	CanTxHeader.Handle       = 0x0;
	CanTxHeader.DataLength   = CAN_DLC_BYTES_8;

	__HAL_CAN_ENABLE_IT(&CanHandle, CAN_IT_RX_COMPLETE | CAN_IT_BUS_ERROR);
		
}

void CAN_RX_Service(void)
{
	/* Waiting for reception to complete */
	// while (__HAL_CAN_GET_RX_FIFO_FILL_LEVEL(&CanHandle) == CAN_RX_FIFO_EMPTY)
	// {
	// }
	if (CAN_Received == 0U)
	{
		/* Read received data */
		if (HAL_CAN_GetRxMessage(&CanHandle, &CanRxHeader, RxData) == HAL_OK)
		{
			printf("jie shou dao de zhi wei:%x ,%x ,%x ,%x ,%x ,%x ,%x ,%x \n\r",RxData[0],RxData[1],RxData[2],RxData[3],RxData[4],RxData[5],RxData[6],RxData[7]);
			BenCiXieRu[0] = (uint32_t) (RxData[4] + (RxData[5] << 8U) + (RxData[6] << 16U) + (RxData[7] << 24U));
			ZhiXingCiShu = (uint32_t) (RxData[0] + (RxData[1] << 8U) + (RxData[2] << 16U) + (RxData[3] << 24U));
			CAN_Received = 1U;
		}
	}
	
	
}

void CAN_TX_Service(void)
{
	if (CAN_Received == 2U)
	{
		TxData[0] = NVSTestCountRead[0] & 0xFFu;
		TxData[1] = ((NVSTestCountRead[0] >> 8u) & 0xFFu);
		TxData[2] = ((NVSTestCountRead[0] >> 16u) & 0xFFu);
		TxData[3] = ((NVSTestCountRead[0] >> 24u) & 0xFFu);
		TxData[4] = 0;
		TxData[5] = 0;
		TxData[6] = 0;
		TxData[7] = 0;
		if (HAL_CAN_AddMessageToTxFifo(&CanHandle, &CanTxHeader, TxData, CAN_TX_FIFO_PTB) == HAL_OK)
		{
			/* Enable PTB transmission */
			if (HAL_CAN_ActivateTxRequest(&CanHandle, CAN_TXFIFO_PTB_SEND) != HAL_OK)
			{
				printf("----fa bao wen shi bai le !!!---\n\r");
			}
		}
		CAN_Received = 0U;
		printf("--------------一次读写任务分割线--------------------\n\r");
	}
}


//void reset_can(void){
////	__HAL_RCC_CAN1_FORCE_RESET();
////	__HAL_RCC_CAN1_RELEASE_RESET();
//	CAN_Config();
//}

void HAL_CAN_BusErrorCallback(CAN_HandleTypeDef *hcan)
{
	__HAL_RCC_CAN1_FORCE_RESET();
	__HAL_RCC_CAN1_RELEASE_RESET();
	CAN_Config();
}

/**
  * @brief  Update interrupt callback
  * @param  None
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    switch(temp)
    {
        case 0:
			temp = 1;
			if (HAL_CAN_AddMessageToTxFifo(&CanHandle, &CanTxHeader, TxData, CAN_TX_FIFO_STB) == HAL_OK)
			{

				if (HAL_CAN_ActivateTxRequest(&CanHandle, CAN_TXFIFO_STB_SEND_ALL) == HAL_OK)
				{
					CANTXCnt[0]++;    
					TxData[0] = (uint8_t)CANTXCnt[0] & 0xFF;
					TxData[1] = (uint8_t)(CANTXCnt[0] >> 8) & 0xFF;
					TxData[2] = (uint8_t)(CANTXCnt[0] >> 16) & 0xFF;
					TxData[3] = (uint8_t)(CANTXCnt[0] >> 24) & 0xFF;
				}
			}
//					else
//					{
//						CAN_User_APP_ErrorHandler();
//					}
          	break;
        default:
			temp = 0;
			break;
    }  
}

void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef *hcan)
{
    /* Read received data */
    if (HAL_CAN_GetRxMessage(&CanHandle, &CanRxHeader, RxData) != HAL_OK)
    {
		CAN_User_APP_ErrorHandler();
    }
    else
    {
		if(CanRxHeader.Identifier == 0x12F)
		{
			CANRXCnt[0]++;
			TxData[4] = (uint8_t)CANRXCnt[0] & 0xFF;
			TxData[5] = (uint8_t)(CANRXCnt[0] >> 8) & 0xFF;
			TxData[6] = (uint8_t)(CANRXCnt[0] >> 16) & 0xFF;
			TxData[7] = (uint8_t)(CANRXCnt[0] >> 24) & 0xFF;
		} 
    }
}

void CAN_User_APP_ErrorHandler(void)
{
	while (1)
	{
	}
}

