/*  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 "stdafx.h"
#include <windows.h>
#include "..\SDK\mxcanbus.h"

#define MAX_MSG_SIZE			10

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				nRet;
	int				fd;
	int				port = 0;
	int				i, max=0, packets=0;
	unsigned int	w_count = 0;
	char			buf[2048];
	CANMSG			*msg;
	
	printf("Enter can port number:");
	scanf("%d",&port);

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

	/*Read the timeout */
	nRet=mxcan_set_write_timeout(fd,1000);
	if(nRet)
	{
		printf("mxcan_set_write_timeout fail.\r\n");
	}
	else
	{
		printf("mxcan_set_write_timeout success.\r\n");
	}

	/*Wait a message to test timeout function*/
	memset(buf,0,sizeof(buf));
	msg = (CANMSG*) buf;
	for (i=0;i < MAX_MSG_SIZE; i++, msg++)
	{
		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;

		print_can_message(msg);

	}
	max = mxcan_write(fd, buf, MAX_MSG_SIZE*sizeof(CANMSG),NULL);
	if (max <= 0)
	{
		printf("No data is sent.\n");
	}
			
		printf("mxcan_write = %d CANMSG = %d\n", max, sizeof(CANMSG));
	Sleep(100);
	/*Close can port*/
	mxcan_close(fd);
	return 0;
}
