#include "NM_includes.h"
#include "GPIO.h"
#include <mc9s12xhy256.h>


unsigned char GetBusOffState(void)
{
 if ((CAN0RFLG_TSTAT == 0x03) || (CAN0RFLG_RSTAT == 0x03))
 
    return 1;  
  return 0;
}

void AbortAllCanTx(void)
{
  CAN0TARQ = 0x07;              //请求终止所有报文发送.
}

/*-------------------------------------------------------------------------
* Function Name  : NM_D_BusOff_Recover
* Description    :
* Input          :
* Output         : None
* Return         : None
* onther         :
--------------------------------------------------------------------------*/
void NM_D_BusOff_Recover()
{
    if (GetBusOffState()) {//CHECK BUSOFF EVENT
        if (NmPara.NmBusOffCtrl.RecoverTime == 0) {
            NmPara.NmBusOffCtrl.RecoverTime = 19;
      //      bsp_Busoff_Recover();
        }
        if (NmPara.NmBusOffCtrl.RecoverTime > 0) {
            NmPara.NmBusOffCtrl.RecoverTime--;
        }
    } else {
        NmPara.NmBusOffCtrl.RecoverTime = 0;
    }
}

void SetCanSTBLevel(unsigned char n) 
{
  if (n == LOW) {
  CAN0_STB=0;
    //CAN_STB_P = LOW;  
  } else if (n == HIGH) {
  CAN0_STB=1;
    //CAN_STB_P = HIGH;
  }
}

/*-------------------------------------------------------------------------
* Function Name  : NM_D_Init
* Description    : CAN Init and handle data link layer
* Input          :
* Output         : None
* Return         : None
* onther         :
--------------------------------------------------------------------------*/
void NM_D_Init(unsigned char state)
{
    switch (state) {
        case BusInit:
            SetCanSTBLevel(LOW);
             MSCAN0_Init();
           // MSCAN_Init(1);
            break;
        case BusSleep:
            AbortAllCanTx();
           /// RQ_MSCAN_TO_SLEEP_PRG();
           MSCAN0_Enter_Low_Power_Mode();
            SilentNM();        
            SetCanSTBLevel(HIGH);
            break;
        default:
            ;
    }
}

/*-------------------------------------------------------------------------
* Function Name  : NM_D_Online
* Description    : Enable app msg send and set app msg send delay timer
* Input          :
* Output         : None
* Return         : None
* onther         :
--------------------------------------------------------------------------*/
void NM_D_Online(void)
{
    NmPara.AppMsgSendRequest = 1;
}
/*-------------------------------------------------------------------------
* Function Name  : NM_D_Offline
* Description    : Disable app msg send
* Input          :
* Output         : None
* Return         : None
* onther         :
--------------------------------------------------------------------------*/
void NM_D_Offline(void)
{
    NmPara.AppMsgSendRequest = 0;
}
