#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;
    const char *candev = "/dev/can0";

	int i;
    int msg_arg = 1;

	if(argc < 2 || (argc == 2 && args[1][0] == '-' && args[1][1] == 'h')) {
        const char *msg = "SYNOPSIS:\n"
            "\tsendcan [options] COBID byte1 byte2 byte3 ...\n"
            "\tnumeric format is hexadecimal\n"
            "OPTIONS:\n"
            "\t-d can_device (default is %s)\n";
        printf(msg, candev);
        exit(0);
    }
    
    if(argc > 3 && args[1][0] == '-' && args[1][1] == 'd') {
        candev = args[2];
        msg_arg = 3;
    }
    
    // open CAN handle on device /dev/can
    if (vca_open_handle(&canhandle, candev, NULL, 0) != VCA_OK) {
		perror("open");
		printf("Error opening %s\n", candev);
		exit(1);
	}
    
    // compose message from the command line
    // mesage format: id data_byte_1 ... data_byte_n
    sendmsg.id = strtol(args[msg_arg++], 0, 16);
    sendmsg.length = argc - msg_arg;
    if(sendmsg.length == 0) {
        sendmsg.length = 8;
    }
    else for(i=msg_arg; i<argc; i++) {
        sendmsg.data[i-msg_arg] = strtol(args[i], 0, 16);
    }
    
	printf("Sending message %lx [", sendmsg.id);
    for(i=0; i<sendmsg.length; i++) {
        if(i > 0) printf(" ");
        printf("%02x", sendmsg.data[i]);
    }
	printf("]\n");

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

	return 0;
}

