/* Example of SocketCAN for PISO-CAN200/400 Cards
 *
 *    Author: Golden Wang
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2, or (at your option)
 *    any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software Foundation,
 *    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 
*/

/* File level history (record changes for this file here.)
 *
 *    v 0.0.0 25 Mar 2010 by Golden Wang
 *         create, blah blah... 
*/

#include "pisocan.h"

extern int optind, opterr, optopt;

static int skt = -1;


void print_usage(char *prg)
{
	fprintf(stderr, "Usage: %s [can-interface]\n", prg);
}

int main(int argc, char **argv)
{
	int ret, i;
	struct can_frame frame;

	if (optind == argc) {
		print_usage(basename(argv[0]));
		exit(0);
	}
	
	ret = SocketCAN_Open(argv[optind], &skt);

	if(ret)
	{
		printf("Create Socket Error : %d\n",ret);
		exit(0);
	}

	do
        {
		printf("\nPress 'Enter' to send data from interface %s\n", argv[optind]);
                getchar();

		frame.can_id = 0x123;	
                frame.data[0] = 0x01;
                frame.data[1] = 0x02;
                frame.data[2] = 0x03;
                frame.data[3] = 0x04;
                frame.data[4] = 0x05;
                frame.data[5] = 0x06;
                frame.data[6] = 0x07;
                frame.data[7] = 0x08;
                frame.can_dlc = 8;

		ret = SocketCAN_SendMsg(skt, &frame);

		if (!ret)
		{
                	printf("Send CAN Message ID : 0x%x Length : %d\n", frame.can_id, frame.can_dlc);
			for(i = 0; i < frame.can_dlc; i++)
			{
				printf("Data[%d] : %02X\n",i ,frame.data[i]);
			}

			printf("\nPress 'Esc' to quit or Press 'Enter' to run again\n");
		}
		else
		{
			printf("Send CAN Message Error : %d\n",ret);
			SocketCAN_Close(skt);
			exit(0);
		}

        }while((getchar() != 27));

	SocketCAN_Close(skt);

	return 0;
}
