/*  Copyright (C) MOXA Inc. All rights reserved.

    This software is distributed under the terms of the
    MOXA License.  See the file COPYING-MOXA for details.
*/
/*
    mxcan_read.cpp

    This is for the read of canbus data.

    2010-10-31	Epson Chiang
		new release
*/


#include "stdafx.h"
#include <windows.h>
#include "..\SDK\mxcanbus.h"

#define MAX_MSG_SIZE			8

static unsigned int g_count = 0;

static void
print_can_message(CANMSG *msg)
{
	unsigned int i;

	printf("[0x%X 0x%X %d] ",msg->identifier,msg->flags, msg->length);
	for (i=0; i < msg->length; i++) printf("0x%X ", msg->data[i]);
	printf("\n");
}


int _tmain(int argc, _TCHAR* argv[])
{
	 int fd;
	 CANMSG *msg;
	int port = 0;
	ULONG ulPortIndex=0;
	DWORD dwBytesReturn=0;
	int max, packets=0;
	char buf[MAX_MSG_SIZE*sizeof(CANMSG)];
	unsigned int r_count = 0;
	int i=0;
	DWORD dwReadTotal=0;
	int dispType = 0;

	printf("Enter can port number:");
	scanf("%d",&port);

	printf("Enter Ddisplay type (0:Show Message 1:Show packet count)");
	scanf("%d",&dispType);
	
	/*Open can port*/
	fd = mxcan_open(port);

	while(1)
	{
		memset(buf,0,sizeof(buf));
		
		max = mxcan_read(fd, buf, MAX_MSG_SIZE*sizeof(CANMSG),NULL);
		
		if (max <= 0)
		{
			printf("No data\n");
			return -1;
		}
		dwReadTotal+=max;

		if(dispType == 1)
		{
			printf("\r-mxcan_read = %d dwReadTotal = %d", max, dwReadTotal);
		}

		if(dispType == 0)
		{
			/* Display the values */
			msg = (CANMSG*) buf;

			for (i=0;i < MAX_MSG_SIZE; i++, msg++)
			{
				print_can_message(msg);
			}
		}
	}

	/*Close can port*/
	mxcan_close(fd);
	
	return 0;
}

