#include "xcanps.h"
#include "xgpiops.h"
#include "xparameters.h"
#include "xil_printf.h"


XGpioPs Gpio;	/* The driver instance for GPIO Device. */
#define GPIO_DEVICE_ID  	XPAR_XGPIOPS_0_DEVICE_ID

int GpioInit(u16 DeviceId)
{
	int Status;
	XGpioPs_Config *ConfigPtr;

	/* Initialize the GPIO driver. */
	ConfigPtr = XGpioPs_LookupConfig(GPIO_DEVICE_ID);
	Status = XGpioPs_CfgInitialize(&Gpio, ConfigPtr,
					ConfigPtr->BaseAddr);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	XGpioPs_SetDirectionPin(&Gpio, 54+6, 1);
	XGpioPs_SetOutputEnablePin(&Gpio, 54+6, 1);

	/* Set the GPIO output to be low. */
	XGpioPs_WritePin(&Gpio, 54+6, 0x1);

	return XST_SUCCESS;
}

#define CAN_RX_DEV XPAR_XCANPS_1_DEVICE_ID	//յcan豸
#define CAN_TX_DEV XPAR_XCANPS_0_DEVICE_ID	//͵can豸

/*
 * Maximum CAN frame length in words.
 */
#define XCANPS_MAX_FRAME_SIZE_IN_WORDS (XCANPS_MAX_FRAME_SIZE / sizeof(u32))

#define FRAME_DATA_LENGTH 		8  //֡򳤶

#define TEST_MESSAGE_ID			2000	//֡ID

/*
 *freqCAN_REF_CLK = 30MHzvivadobdļprocessing_system7_0Clock ConfigurationlO Peripheral ClocksCANʱ
 *freqBIT_RATE = freqCAN_REF_CLK / ((can.BRPR[BRP] + 1) * (3 + can.BTR[TS1] + can.BTR[TS2]))
 *can.BTR[TS1] = TEST_BTR_FIRST_TIMESEGMENT
 *can.BTR[TS2] = TEST_BTR_SECOND_TIMESEGMENT
 *(can.BRPR[BRP] + 1) = freqCAN_REF_CLK / (freqBIT_RATE * (3 + can.BTR[TS1] + can.BTR[TS2]))
 */

const char CAN_BAUD_SET[4][4]=
{
	/*1000K*/
	{3,2,5,2},/*BTR_SJW, BTR_TS2, BTR_TS1, BRPR*/

	/*500K*/
	{3,4,3,5},/*BTR_SJW, BTR_TS2, BTR_TS1, BRPR*/

	/*100K*/
	{3,2,15,14},/*BTR_SJW, BTR_TS2, BTR_TS1, BRPR*/

	/*50K*/
	{3,2,15,29},/*BTR_SJW, BTR_TS2, BTR_TS1, BRPR*/
};



static int SendFrame(XCanPs *InstancePtr);
static int RecvFrame(XCanPs *InstancePtr);


static u32 TxFrame[XCANPS_MAX_FRAME_SIZE_IN_WORDS];
static u32 RxFrame[XCANPS_MAX_FRAME_SIZE_IN_WORDS];

/* Driver instance */
static XCanPs Can_Rx;
static XCanPs Can_Tx;


int CanPsInit(u16 DeviceId, XCanPs *Can, char *BAUS_SET)
{
	int Status;
	XCanPs_Config *ConfigPtr;

	/*
	 * ʼCAN豸
	 */
	ConfigPtr = XCanPs_LookupConfig(DeviceId);
	if (ConfigPtr == NULL) {
		return XST_FAILURE;
	}
	Status = XCanPs_CfgInitialize(Can,
					ConfigPtr,
					ConfigPtr->BaseAddr);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * CANԲԼ豸ǷԼǷʼɹ.
	 */
	Status = XCanPs_SelfTest(Can);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	/*
	 * ģʽȻܶԲʷƵĴ(BRPR)λʱĴ(BTR)
	 */
	XCanPs_EnterMode(Can, XCANPS_MODE_CONFIG);
	while(XCanPs_GetMode(Can) != XCANPS_MODE_CONFIG);

	/*
	 * òԤƵĴ(BRPR)λʱĴ(BTR)
	 */
	XCanPs_SetBaudRatePrescaler(
		Can,
		BAUS_SET[3]
	);

	XCanPs_SetBitTiming(
		Can,
		BAUS_SET[0],
		BAUS_SET[1],
		BAUS_SET[2]
	);

	//ģʽ
	XCanPs_EnterMode(Can, XCANPS_MODE_NORMAL);

	while(XCanPs_GetMode(Can) != XCANPS_MODE_NORMAL);

	return Status;
}

int main()
{
	int Status;
	u8 *FramePtr;
	int Index;
	GpioInit(GPIO_DEVICE_ID);
	xil_printf("CAN Polled Mode Example Test \r\n");

	Status = CanPsInit(CAN_RX_DEV, &Can_Rx, &CAN_BAUD_SET[0]);
	if (Status != XST_SUCCESS) {
		xil_printf("CAN_RX_DEV Init Failed\r\n");
		return XST_FAILURE;
	}

	Status = CanPsInit(CAN_TX_DEV, &Can_Tx, &CAN_BAUD_SET[0]);

	if (Status != XST_SUCCESS) {
		xil_printf("CAN_TX_DEV Init Failed\r\n");
		return XST_FAILURE;
	}

	while(1)
	{
			Status = SendFrame(&Can_Tx);
			if (Status != XST_SUCCESS) {
				printf("CAN_TX_DEV Send frame Failed\r\n");
				return XST_FAILURE;
			}
			else{
				printf("CAN_TX_DEV Send frame: ");
				FramePtr = (u8 *)(&TxFrame[2]);
				for (Index = 0; Index < FRAME_DATA_LENGTH; Index++) {
					printf("%x ",FramePtr[Index]);
				}
				printf("\r\n");
			}


			Status = RecvFrame(&Can_Rx);
			if (Status != XST_SUCCESS) {
				printf("CAN_RX_DEV Receive Frame Failed\r\n");
				return XST_FAILURE;
			}
			else{
				printf("CAN_RX_DEV Received frame: ");
				FramePtr = (u8 *)(&RxFrame[2]);
				for (Index = 0; Index < FRAME_DATA_LENGTH; Index++) {
					printf("%x ",FramePtr[Index]);
				}
				printf("\r\n");
			}
	}

	return XST_SUCCESS;
}


/*****************************************************************************/
/**
*
* Send a CAN frame.
*
* @param	InstancePtr is a pointer to the driver instance
*
* @return	XST_SUCCESS if successful, a driver-specific return code if not.
*
* @note
*
* This function waits until TX FIFO has room for at least one frame before
* sending a frame. So this function may block if the hardware is not built
* correctly.
*
******************************************************************************/
static int SendFrame(XCanPs *InstancePtr)
{
	u8 *FramePtr;
	int Index;
	int Status;

	/*
	 * Create correct values for Identifier and Data Length Code Register.
	 */
	TxFrame[0] = (u32)XCanPs_CreateIdValue((u32)TEST_MESSAGE_ID, 0, 0, 0, 0);
	TxFrame[1] = (u32)XCanPs_CreateDlcValue((u32)FRAME_DATA_LENGTH);

	/*
	 * Now fill in the data field with known values so we can verify them
	 * on receive.
	 */
	FramePtr = (u8 *)(&TxFrame[2]);
	for (Index = 0; Index < FRAME_DATA_LENGTH; Index++) {
		*FramePtr++ = (u8)Index;
	}

	/*
	 * Wait until TX FIFO has room.
	 */
	while (XCanPs_IsTxFifoFull(InstancePtr) == TRUE);

	/*
	 * Now send the frame.
	 *
	 * Another way to send a frame is keep calling XCanPs_Send() until it
	 * returns XST_SUCCESS. No check on if TX FIFO is full is needed anymore
	 * in that case.
	 */
	Status = XCanPs_Send(InstancePtr, TxFrame);

	return Status;
}


/*****************************************************************************/
/**
*
* This function receives a frame and verifies its contents.
*
* @param	InstancePtr is a pointer to the driver instance.
*
* @return	XST_SUCCESS if successful, a driver-specific return code if not.
*
* @note
*
* This function waits until RX FIFO becomes not empty before reading a frame
* from it. So this function may block if the hardware is not built
* correctly.
*
******************************************************************************/
static int RecvFrame(XCanPs *InstancePtr)
{
	int Status;

	/*
	 * Wait until a frame is received.
	 */
	while (XCanPs_IsRxEmpty(InstancePtr) == TRUE);

	/*
	 * Receive a frame and verify its contents.
	 */
	Status = XCanPs_Recv(InstancePtr, RxFrame);
	if (Status == XST_SUCCESS) {
		/*
		 * Verify Identifier and Data Length Code.
		 */
//		if (RxFrame[0] !=
//			(u32)XCanPs_CreateIdValue((u32)TEST_MESSAGE_ID, 0, 0, 0, 0))
//			return XST_LOOPBACK_ERROR;
//
//		if ((RxFrame[1] & ~XCANPS_DLCR_TIMESTAMP_MASK) != TxFrame[1])
//			return XST_LOOPBACK_ERROR;
	}

	return Status;
}




