#include <stdio.h>
#include <time.h>
#include "ecommlib.h"

int main()
{
	BYTE ReturnError = 0;  //This will be used for all error return status codes
	HANDLE EcomHandle; //This will be the HANDLE to our ECOM device used for all function calls	
	long EndTime;
	int i;

	EcomHandle = CANOpen(0, CAN_BAUD_250K, &ReturnError); //ECOM library call to open the first available ECOM device on the computer
	if (EcomHandle == 0 || ReturnError != 0)
	{
		char ErrMsg[400];
		GetFriendlyErrorMessage(ReturnError, ErrMsg, 400);  //ECOM Library call to get text describing error code
		printf("CANOpen failed with error message: ");
		printf(ErrMsg);
		return -1;
	}
	

	//Just a simple example, this will display all received 29-bit CAN packets for 10 seconds	
	EndTime = clock() + 10000;  
	while (clock() < EndTime)
	{
		EFFMessage RxMessage;  //This structure will hold the incoming CAN message
		
		ReturnError = CANReceiveMessageEx(EcomHandle, &RxMessage);  //ECOM library call to get a 29-bit message
		if (ReturnError == CAN_NO_RX_MESSAGES)
		{
			Sleep(1); //wait for messages since there are none yet
		}
		else if (ReturnError != 0)
		{
			//We got an error message (besides CAN_NO_RX_MESSAGES), so return and exit
			char ErrMsg[400];
			GetFriendlyErrorMessage(ReturnError, ErrMsg, 400);
			printf("CANReceiveMessageEx failed with error message: ");
			printf(ErrMsg);
			return -1;
		}
		else  //ReturnError == 0, which means we successfully received a message
		{
			//Display the important fields all on one line
			printf("CAN ID: %9d, Len: %d, Data: ", RxMessage.ID, RxMessage.DataLength);
			for (i = 0; i < RxMessage.DataLength; i++)
				printf("%3d ", RxMessage.data[i]);

			printf("\n");
		}
	}

	//Now we are all done, so clean up by closing the ECOM
	CloseDevice(EcomHandle);
	return 0;
}