#include "CAN841.h"
#include "RTX.h"
#include <stdio.h>


#define PORT1 0
#define PORT2 1
#define PHYS_SEG 0xDA00;

#define FAIL 0
#define SUCCESS 1

void main(void)
{
	UI gSegment=PHYS_SEG;
	PVOID vAddress;

	CAN_STRUCT can1, can2;
	MSG_STRUCT txmsg, rxmsg;

	int i;

	char str_input[8];
	char str_quit;

	// Memory mapping
	unsigned long temp;
	LARGE_INTEGER physAddr;

	temp = PHYS_SEG;
	temp = temp << 4;
	physAddr.QuadPart = temp;
	vAddress = RtMapMemory(physAddr, 0xDFFF, 1);
	if(vAddress==NULL) printf("\n>>> Failure on RtMapMemory..!\n");
	else
	{
		printf("\n>>> RtMapMemory Successful!\n");

		// Initalize the CAN module
		canInitHW(vAddress, IRQ_POLLING, IRQ_POLLING);

		canReset(PORT1);
		canReset(PORT2);;

		// Configure the structures for each CAN port
		can1.acc_code=0;
		can1.acc_mask=0xFF;
		can1.bt0=0xC0;
		can1.bt1=0x14;

		can2.acc_code=0;
		can2.acc_mask=0xFF;
		can2.bt0=0xC0;
		can2.bt1=0x14;

		canConfig(PORT1,can1);
		canConfig(PORT2,can2);

		// Start the CAN ports so they can transmit and receive msgs
		canNormalRun(PORT1);
		canNormalRun(PORT2);

		while(1)
		{
	
			// Clear stdin and str_input of any previous values
			rewind(stdin);
			for(i=0; i < 8; i++)
				str_input[i] = 0;

			// Get string to echo from user
			printf("\n>>> Enter a 1-8 character string: ");
			scanf("%8s", &str_input);

			// Configure message structure
			txmsg.id=0;
			txmsg.rtr=0;
			txmsg.dlen=8;

			for(i=0; i<txmsg.dlen; i++)
				txmsg.data[i]=str_input[i];
			
			if (!canSendMsg(PORT1, txmsg))
			{
				printf(">>> 0x%2X\n", CAN_ERR_CODE);
				break;
			}

			Sleep(500);

			while(1)
			{
				if(canReceiveMsg(PORT2, &rxmsg) == 1)
				{
					printf(">>> Data Received on Port 2:\n");
					
					for(i=0;i<rxmsg.dlen;i++)
					{
						printf(">>>> 0x%2X '%c'\n", rxmsg.data[i], rxmsg.data[i]);
					}
					break;
				}
			}

			// Ask user to quit program
			rewind(stdin);

			printf("\n>>> Quit (y or n)? ");
			scanf("%c", &str_quit);
			if (str_quit == 'y' || str_quit == 'Y')
				break;
		}

		// Properly dispose of all the resources being used
		canReset(PORT1);
		canReset(PORT2);
		canExitHW();
		BOOL temp = RtUnmapMemory(vAddress);
	}
}
