#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>

#include "can_vca.h"

vca_handle_t canhandle;

/*--- handler on SIGINT signal : the program quit with CTL-C ---*/
void sortie(int sig)
{
	vca_close_handle(canhandle);
	printf("Terminated by user\n");
	exit(0);
}

int main(void)
	{
	int n,ret;
	unsigned long i=0;
	struct canmsg_t readmsg;
	struct sigaction act;

	/*------- register handler on SIGINT signal -------*/
	act.sa_handler=sortie;
	sigemptyset(&act.sa_mask);
	act.sa_flags=0;
	sigaction(SIGINT,&act,0);
	/*---------------------------------------*/	
    
    // open CAN handle on device /dev/can
	if (vca_open_handle(&canhandle, "/dev/can0", NULL, 0) != VCA_OK) {
		perror("open");
		printf("Error opening /dev/can0\n");
		exit(1);	
	}

	while (1) {
        // suspend and wait for message
        vca_wait(canhandle, 0, 0);
        // read message from VCA
		ret = vca_rec_msg_seq(canhandle, &readmsg, 1);
		if(ret < 0) {
			printf("Error reading message\n");
		}
		else if(ret == 0) {
			printf("No message arrived\n");
		}
		else {
			printf("Received message #%lu: id=%lX dlc=%u",i,readmsg.id,readmsg.length);
			for(n=0 ; n<readmsg.length ; n++)
				printf(" %.2X",(unsigned char)readmsg.data[n]);
			printf("\n");
			i++;
		}
	}
	return 0;
}
