/*
 * bsp_FDCAN.c
 *
 *  Created on: Oct 26, 2023
 *      Author: shiya
 */
#include "BSP/bsp_FDCAN.h"

uint8_t GF_BSP_FDCAN_Init(void)
{
  if (HAL_FDCAN_ActivateNotification(&hfdcan1, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0) != HAL_OK)
  {
    Error_Handler();
  }

  if (HAL_FDCAN_ActivateNotification(&hfdcan1, FDCAN_IT_BUS_OFF, 0) != HAL_OK)
  {
    Error_Handler();
  }

  HAL_FDCAN_Start(&hfdcan1);

  if (HAL_FDCAN_ActivateNotification(&hfdcan2, FDCAN_IT_RX_FIFO0_NEW_MESSAGE, 0) != HAL_OK)
  {
    Error_Handler();
  }

  if (HAL_FDCAN_ActivateNotification(&hfdcan2, FDCAN_IT_BUS_OFF, 0) != HAL_OK)
  {
    Error_Handler();
  }

  HAL_FDCAN_Start(&hfdcan2);

  return 1;
}

void HAL_FDCAN_ErrorStatusCallback(FDCAN_HandleTypeDef *hfdcan, uint32_t ErrorStatusITs)
{
  if(hfdcan->Instance == FDCAN1)
  {
    MX_FDCAN1_Init();
  }
  if(hfdcan->Instance == FDCAN2)
  {
    MX_FDCAN2_Init();
  }
}

void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hfdcan, uint32_t RxFifo0ITs)
{
	if(hfdcan->Instance == FDCAN1)
	{
		GF_BSP_Interrupt_Run_CallBack(DF_BSP_InterCall_FDCAN1_RxFifo0Callback);
	}
	else if(hfdcan->Instance == FDCAN2)
	{
		GF_BSP_Interrupt_Run_CallBack(DF_BSP_InterCall_FDCAN2_RxFifo0Callback);
	}
}

FDCAN_TxHeaderTypeDef TXHeader1;
FDCAN_TxHeaderTypeDef TXHeader2;
void GF_BSP_FDCAN_Senddata(uint8_t FDCAN_CH, uint32_t FrameID, uint8_t DataLength,uint8_t *Txdata)
{
    if (DataLength > 8)
	{
		return;
	}
	if(FDCAN_CH == 1)
	{
	 TXHeader1.BitRateSwitch=FDCAN_BRS_OFF;
     TXHeader1.DataLength=(uint32_t)DataLength << 16;//数据长度大于8的话会有错误
	 TXHeader1.FDFormat=FDCAN_CLASSIC_CAN;
	 TXHeader1.IdType=FDCAN_STANDARD_ID;
	 TXHeader1.Identifier=FrameID;
	 TXHeader1.TxFrameType=FDCAN_DATA_FRAME;
	 HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan1, &TXHeader1,Txdata);
	}
	else if(FDCAN_CH == 2)
	{
	 TXHeader2.BitRateSwitch=FDCAN_BRS_OFF;
	 TXHeader2.DataLength=(uint32_t)DataLength << 16;//数据长度大于8的话会有错误
	 TXHeader2.FDFormat=FDCAN_CLASSIC_CAN;
	 TXHeader2.IdType=FDCAN_STANDARD_ID;
	 TXHeader2.Identifier=FrameID;
	 TXHeader2.TxFrameType=FDCAN_DATA_FRAME;
	 HAL_FDCAN_AddMessageToTxFifoQ(&hfdcan2, &TXHeader2,Txdata);
	}
}
