hexagram/bin/can2dump.c
2019-05-23 01:49:26 -05:00

106 lines
2.3 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <inttypes.h>
#include <fcntl.h>
#include <hexagram/can.h>
#include <hexagram/capture.h>
#include "can2dump.h"
char *hexagram_arglist_can2dump(void) {
return "ifname [file.can] [candump.txt]";
}
static int usage(int argc, char **argv, const char *message, ...) {
if (message) {
va_list args;
va_start(args, message);
vfprintf(stderr, message, args);
va_end(args);
}
fprintf(stderr, "usage: hexagram %s %s\n", argv[0], hexagram_arglist_can2dump());
return 1;
}
int hexagram_main_can2dump(int argc, char **argv) {
hexagram_capture *capture;
const char *ifname;
FILE *fh;
struct timeval timestamp;
struct can_frame frame;
if (argc <= 1) {
return usage(argc, argv, "No CAN interface name provided");
}
ifname = argv[1];
if (argc == 2) {
if ((capture = hexagram_capture_open_fd(fileno(stdin), O_RDONLY)) == NULL) {
perror("hexagram_capture_open_fd()");
goto error_capture_open;
}
fh = stdout;
} else if (argc == 3) {
if ((capture = hexagram_capture_open_file(argv[2], O_RDONLY)) == NULL) {
perror("hexagram_capture_open_file()");
goto error_capture_open;
}
fh = stdout;
} else if (argc == 4) {
if ((capture = hexagram_capture_open_file(argv[2], O_RDONLY)) == NULL) {
perror("hexagram_capture_open_file()");
goto error_capture_open;
}
if ((fh = fopen(argv[3], "w")) == NULL) {
goto error_fopen;
}
} else {
usage(argc, argv, NULL);
exit(1);
}
while (hexagram_capture_read(capture, &timestamp, &frame) >= 0) {
uint8_t i;
fprintf(fh, "%7s %03X [%d] ",
ifname, frame.can_id, frame.can_dlc);
for (i=0; i<frame.can_dlc; i++) {
fprintf(fh, " %02X", frame.data[i]);
}
fprintf(fh, "\n");
}
if (argc == 2) {
hexagram_capture_destroy(capture);
} else if (argc >= 3) {
hexagram_capture_close(capture);
}
return 0;
error_fopen:
if (argc == 2) {
hexagram_capture_destroy(capture);
} else if (argc >= 3) {
hexagram_capture_close(capture);
}
error_capture_open:
return 1;
}