/* 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 16 Apr 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;
	struct can_filter rfilter;

        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);
        }

	/* only receive the CAN frame of CAN ID 0x123 */
//      rfilter.can_id   = 0x123;
//      rfilter.can_mask = CAN_SFF_MASK;
//
        /* receive all CAN frame */
	rfilter.can_id   = 0;
	rfilter.can_mask = 0;

	SocketCAN_SetCANFilter(skt, &rfilter, sizeof(rfilter));

	printf("\nReceive CAN message from interface %s\n", argv[optind]);

	while (1) 
	{
		ret = SocketCAN_ReceiveMsg(skt, &frame);

		if(!ret)
		{
			if (frame.can_id & CAN_RTR_FLAG) 
			{
				printf("remote request");
			} 
			else 
			{
				printf("Receive 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("\n");
			}
		}
		else
		{
			printf("Receive CAN Message Error : %d\n",ret);
                        SocketCAN_Close(skt);
                        exit(0);
		}
	}

	return 0;
}
