/*  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 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[])
{
	CANMSG *msg;
	char buf[2048];
	int i, max, packets=0;
	unsigned int w_count = 0;

	int port;
	int dispType = 0;
	int packetCount = 0;
	int timeDelay = 100;
	int fd_W;

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

	printf("Enter Ddisplay type (0:Show Message 1:Show packet count)");
	scanf("%d",&dispType);

	printf("Enter delay(ms)");
	scanf("%d",&timeDelay);

	/*Open can port*/
	fd_W= mxcan_open(port);

	while(1)
	{
		memset(buf,0,sizeof(buf));
		msg = (CANMSG*) buf;
		for (i=0;i < MAX_MSG_SIZE; i++, msg++)
		{ 
			//msg->identifier = 0x00001563;
			msg->identifier = 0x1A2B3C4D;
			msg->flags = EXTENDED_FRAME;
			msg->data[0]=w_count+i+1;
			msg->data[1]=w_count+i+2;
			msg->data[2]=w_count+i+3;
			msg->data[3]=w_count+i+4;
			msg->data[4]=w_count+i+5;
			msg->data[5]=w_count+i+6;
			msg->data[6]=w_count+i+7;
			msg->data[7]=w_count+i+8;
			msg->length = 8;
			w_count = (w_count+1)%10000000;

			if(dispType == 0)
			{
				print_can_message(msg);
			}
		}
		max = mxcan_write(fd_W, buf, MAX_MSG_SIZE*sizeof(CANMSG),NULL);
		if (max <= 0)
		{
			printf("No data is sent.\n");
		}
		packetCount += MAX_MSG_SIZE*sizeof(CANMSG);

		if(dispType == 1)
		{
			
			printf("\rmxcan_write : total packet sent = %d CANMSG = %d", packetCount, sizeof(CANMSG));
		}

		Sleep(timeDelay);
	}
	
	/*Close can port*/
	mxcan_close(fd_W);
	
	return 0;
}

