#include "can_interface.h"
#include <string.h>

CanTxMsg tx_message;
CanRxMsg rx_message;
pcan_rx  pcan_rx_back = NULL;
pcan_tx  pcan_tx_back = NULL;

void can_rx_back_init(pcan_rx p_fun)
{
    pcan_rx_back = p_fun;
}

void can_tx_back_init(pcan_tx p_fun)
{
    pcan_tx_back = p_fun;
}

uint8_t can_msg_tx(uint32_t id, uint8_t id_type, uint8_t *p_data, uint8_t len)
{
    uint8_t flg = 0;
    if (id_type)
    {
        tx_message.ExtId = id; // 设置扩展标示符（29位）
    }
    else
    {
        tx_message.StdId = id_type; // 标准标识符为0
    }

    tx_message.IDE = id_type; // 使用扩展标识符
    tx_message.DLC = len;     // 发送两帧信息
    if (len == 0)
    {
        tx_message.RTR = CAN_RTR_Remote; // 消息类型为远程帧
    }
    else
    {
        tx_message.RTR = CAN_RTR_Data; // 消息类型为数据帧
        memcpy(tx_message.Data, p_data, len);
    }
    flg = CAN_Transmit(CAN1, &tx_message);

    return flg;
}

void can_tx_iqr(void)
{
    if (pcan_tx_back != NULL)
    {
        pcan_tx_back();
    }
}

void can_rx_iqr(void)
{
    CAN_Receive(CAN1, CAN_FIFO0, &rx_message);
    if (pcan_rx_back != NULL)
    {
        pcan_rx_back(rx_message);
    }
}