#include "can.h"
#include "device/can.h"
#include "stm32f3xx_hal.h"
// CAN 调试结构体实例

// 初始化 CAN
void CAN_Init(CAN_HandleTypeDef *hcan_Cur)
{   //重置CAN
    HAL_CAN_Init(hcan_Cur); // 初始化CAN
    // 仅初始化CAN，不配置接收过滤器
    HAL_CAN_Start(hcan_Cur); // 开启CAN
}

// CAN 发送函数，添加超时机制
uint8_t CAN_SendData(CAN_HandleTypeDef *hcan_Cur, uint8_t *pData, uint16_t ID)
{
    HAL_StatusTypeDef HAL_RetVal = HAL_ERROR;
    uint8_t FreeTxNum = 0;
    CAN_TxHeaderTypeDef TxMessage;

    TxMessage.StdId = ID;
    TxMessage.DLC = 8;  /* 默认一帧传输长度为8 */
    TxMessage.IDE = CAN_ID_STD;
    TxMessage.RTR = CAN_RTR_DATA;

    uint32_t timeout = 5000; // 增加超时时间
    while (FreeTxNum == 0 && timeout > 0) 
    {
        FreeTxNum = HAL_CAN_GetTxMailboxesFreeLevel(hcan_Cur);
        if (FreeTxNum > 0) break; // 如果有空闲邮箱，退出循环
        osDelay(1); // 避免忙等待
        timeout--;
    }
    if (timeout == 0) 
    {
        return 1; // 超时，发送失败
    }

    HAL_RetVal = HAL_CAN_AddTxMessage(hcan_Cur, &TxMessage, pData, (uint32_t *)CAN_TX_MAILBOX1);

    if (HAL_RetVal != HAL_OK)
    {
        return 1; // 发送失败
    }

    return 0; // 发送成功
}