#include "boot_macrodriver.h"
#include "boot_userdefine.h"
#include "r_rl78_can_sfr.h"
#include "r_rl78_can_drv.h"
#include "boot_can_user.h"

#define C_100MS_1MS 100

can_frame_t Boot_TxCanMessage;
can_frame_t Boot_RxCanMessage;

unsigned char BusOff_flag = 0;

void Copy_Array_to_Array(unsigned char *dest, unsigned char *src,unsigned char count)
{
	unsigned char i = 0;

	while( i < count)
	{
		i++;
		*dest++ = *src++;
	}
}

unsigned char TransmitCAN_Message(unsigned int ID,unsigned char Dlc,unsigned char *Data)
{
	can_frame_t Boot_TxCanMessage;
	Can_RtnType re_flag;
	Boot_TxCanMessage.IDL=ID;
	Boot_TxCanMessage.DLC=Dlc;
	Boot_TxCanMessage.IDE = 0;     	 /* IDE  0:Standard 1:Extend           */
	Boot_TxCanMessage.RTR = 0;     	 /* RTR  0:Data 1:Remote               */
	Boot_TxCanMessage.THDSE = 0;   	 /* Transmit History Data Store Enable */	
	Boot_TxCanMessage.IDH = 0;       /* ID Data (high)                     */
	Boot_TxCanMessage.DLC = 8;     	 /* DLC Data                           */
	Boot_TxCanMessage.LBL = 0;     	 /* Label Data                         */
	Boot_TxCanMessage.TS = 0;      	 /* Timestamp Data                     */
	Copy_Array_to_Array(Boot_TxCanMessage.DB,Data,Dlc);	
	re_flag=R_CAN_TrmByTRFIFO0_CH0(&Boot_TxCanMessage);
	if(re_flag == CAN_RTN_OK)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}

void BusOff_Detect(void)
{
	if(R_CAN_ReadChStatus_CH0()&0x02)
	{
		if(C0ERFLL&0x08)
		{
			if(BusOff_flag==0)
			{				
				BusOff_flag=1;//clear after 40 IGN cycle
			}			
		}
		if(C0ERFLL!=0)
		{
			C0ERFLL=0;
		}			
		C0CTRL&=0xfffc;
	}
	else
	{
		BusOff_flag=0;
	}
}

/******************************/
//获取can总线出错状态
//返回值
/******************************/
unsigned char GetCanBusOffErr(void)
{
	if(BusOff_flag==0)
		return 0;
	else
		return 1;
}

