#include "CAN_Communication_Matrix.h"
#include "CAN_Lib.h"
#include "COM_CAN.h"
#include "RTE_CAN_NM.h"
#include "RTE_CAN.h"
#include "System_Monitor.h"


uint8_t BusOffEvent;
uint8_t BUS_OFF_FLAG;
#pragma alignvar(8)
static uint32_t pTXBuff[CAN_TX_MSG_Block*ID_SEND_TOTAL];
#pragma alignvar(8)
static uint32_t pRXBuff[CAN_RX_MSG_Block*ID_TOTAL_MAX];
void COM_CAN_Init(void)
{
    /*CAN APP BUFFER INIT*/
    Can_TX_BuffInit((uint8_t *)pTXBuff,st_CANSendAttr,ID_SEND_TOTAL,Can_Write);
    Can_RX_BuffInit((uint8_t *)pRXBuff,CAN_MSG_CONST_ARRAY,ID_TOTAL_MAX);
    CAN_RX_SetEnable(0u);
    CAN_TX_SetEnable(CAN_APP_TX_ENABLE);
    /*NM INIT & BSP INIT*/
    RTE_CAN_NM_Init();
}

void COM_RX_Process(void)
{
    CanMSg_XMS_Analysis(5U);
}

void COM_TX_Process(void)
{
    Can_Write_Fun(50UL);
}


void COM_NM_Process(void)
{
    RTE_CAN_NM_Process();
}


/*
request nm
release nm

high voltage
low voltage
2ms
*/
void COM_NM_ACT(void)
{
    if ( SYS_OPR_STAT_RUN_NM )
    {
        if (SYS_OPR_STAT_IGN_ON_NM)
        {
            RTE_CAN_NM_Request(1u);
        }
        else
        {
            RTE_CAN_NM_Release(1u);
        }
    }
    else
    {
        
    }
}


uint8_t COM_CAN_BUS(void)
{
    uint8_t Ret = 0u;
    Ret = RTE_CAN_GetBusStatus();
    return Ret;
}





uint8_t CrcCheckSum(uint8_t data[], uint8_t len)
{
    uint8_t crc = 0xffu;
    uint8_t CRC_POLY = 0x2fu;
    uint8_t crcxor = 0xffu;
    uint8_t bit_index = 0u;
    uint8_t byte_index = 0u;
    uint8_t temp = 0u;


    for (byte_index = 0u; byte_index < len; ++byte_index )
    {
        crc ^= data[byte_index];
        for (bit_index = 0u; bit_index < 8u; ++bit_index)
        {
            if ((crc & 0x80u) != 0u)
            {
                temp = crc << 1u;
                crc = temp ^ CRC_POLY;
            }
            else
            {
                crc = (crc << 1u);
            }
        }
    }
    crc = crc ^ crcxor;
    return crc;
}

void CAN_QuickTimer_Init ( void )
{
    uint8_t i = 0u;
    for ( i = 0u; i < ID_SEND_TOTAL; i++)
    {
       // CanMsg[i].u32Timer = st_CANSendAttribute[i].u32MsgCycleOffset;
       // CanMsg[i].u32MsgCycle = st_CANSendAttribute[i].u32MsgCycle;
       // CanMsg[i].u32SendCnt = st_CANSendAttribute[i].u32InitSendCnt;
    }
}



void Can_BusOff_Fun(void)
{

}

void Can_BusOffRecover(void)
{

}

/**
  *获取busoff状态
  *@return busoff状态 0正常,1异常
  */
uint8_t getBUS_OFF_Status(void)
{
    return BusOffEvent;
}

/**
  *获取busoff标志
  *@return busoff状态 0正常,1异常
  */
uint8_t getBUS_OFF_FLAG(void)
{
    uint8_t FLAG = BUS_OFF_FLAG;
    if (!getBUS_OFF_Status())
    {
        BUS_OFF_FLAG = 0u;
    }
    return FLAG;
}
