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


#include "can_vca.h"

int main(int argc, char *args[]) {
       #ifdef CAN_MSG_VERSION_2
	struct canmsg_t sendmsg={0,0,5,{0,0},8,{1,2,3,4,5,6,7,8}};
       #else /* CAN_MSG_VERSION_2 */
	struct canmsg_t sendmsg={0,0,5,0,8,{1,2,3,4,5,6,7,8}};
       #endif /* CAN_MSG_VERSION_2 */
    vca_handle_t canhandle;

	int i;

	if(argc < 2 || (argc == 2 && args[1][0] == '-' && args[1][1] == 'h')) {
        printf("\nsendcan COBID byte1 byte2 byte3 ...\n");
        printf("numeric format is hexadecimal\n");
        //printf("hexadecimal numbers starts with 0x (ie. 0xAB)\n\n");
        return 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);
	}
    
    // compose message from the command line
    // mesage format: id data_byte_1 ... data_byte_n
    sendmsg.id = strtol(args[1], 0, 16);
    sendmsg.length = argc - 2;
    if(sendmsg.length == 0) {
        sendmsg.length = 8;
    }
    else for(i=2; i<argc; i++) {
        sendmsg.data[i-2] = strtol(args[i], 0, 16);
    }
    

	printf("Sending message %lx   ", sendmsg.id);
    for(i=0; i<sendmsg.length; i++) printf("%02x ", sendmsg.data[i]);
	printf("\n");

    // send composed message
    vca_send_msg_seq(canhandle, &sendmsg, 1);
    vca_close_handle(canhandle);

	return 0;
}

	
