#include <stdio.h>
#include "driverlib.h"
#include "device.h"

//
// Defines
//
#define MSG_DATA_LENGTH    8    // "Don't care" for a Receive mailbox
#define RX_MSG_OBJ_ID      1    // Use mailbox 1

//
// Globals
//
uint16_t rxMsgData[8];          // Buffer for received data

/**
 * hello.c
 */
int main(void)
{
    int i;

    //
    // Initialize device clock and peripherals
    //
    Device_init();

    //
    // Initialize GPIO
    //
    Device_initGPIO();

    //
    // Configure GPIO pins for CANTX/CANRX
    //
    GPIO_setPinConfig(GPIO_12_CANTXB);
    GPIO_setPinConfig(GPIO_17_CANRXB);

    //
    // Initialize the CAN controller
    //
    CAN_initModule(CANB_BASE);

    //
    // Setup CAN to be clocked off the M3/Master subsystem clock
    //
    CAN_selectClockSource(CANB_BASE, CAN_CLOCK_SOURCE_SYS);

    //
    // Set up the CAN bus bit rate to 500kbps for each module
    // Refer to the Driver Library User Guide for information on how to set
    // tighter timing control. Additionally, consult the device data sheet
    // for more information about the CAN module clocking.
    //
    CAN_setBitRate(CANB_BASE, DEVICE_SYSCLK_FREQ, 1000000, 10);

    //
    // Initialize the receive message object used for receiving CAN messages.
    // Possible flags: CAN_MSG_OBJ_NO_FLAGS, CAN_MSG_OBJ_USE_EXT_FILTER,
    //                 CAN_MSG_OBJ_USE_DIR_FILTER
    // Message Object Parameters:
    //      CAN Module: A
    //      Message Object ID Number: 1
    //      Message Identifier: 0x1F9FFFFA
    //      Message Frame: Extended
    //      Message Type: Receive
    //      Message ID Mask: 0x1F000000
    //      Message Object Flags: UMask, MXtd, MDir
    //      Message Object flag CAN_MSG_OBJ_USE_ID_FILTER enables usage 
    //       of msgIDMask parameter for Message Identifier based filtering
    //      Message Data Length: "Don't care" for a Receive mailbox
    CAN_setupMessageObject(CANB_BASE, RX_MSG_OBJ_ID, 0x1555aab4,
                           CAN_MSG_FRAME_EXT, CAN_MSG_OBJ_TYPE_RX, 
			   0x1555aab4, CAN_MSG_OBJ_NO_FLAGS,
			   MSG_DATA_LENGTH);

    //
    // Start CAN module B operations
    //
    CAN_startModule(CANB_BASE);

    for (i = 0 ; i < MSG_DATA_LENGTH ; i++)
	rxMsgData[i] = 0;

    //
    // Start reception - Just wait for data from another node
    //
    while (1) {
        //
        // Poll bit0 in CAN_NDAT_21 register to check completion of Reception
        //
        //if ((CAN_getStatus(CANB_BASE) & CAN_ES_RXOK) != 0) { 
	if ((CAN_getNewDataFlags(CANB_BASE) & (1 << (RX_MSG_OBJ_ID - 1))) != 0) {
            //
            // Get the received message
            //
            asm("  NOP");
            CAN_readMessage(CANB_BASE, RX_MSG_OBJ_ID, rxMsgData);
	}
    }
}
