diff --git a/include/hexagram/can.h b/include/hexagram/can.h index 55fa34e..0a68bc3 100644 --- a/include/hexagram/can.h +++ b/include/hexagram/can.h @@ -12,6 +12,8 @@ #define HEXAGRAM_CAN_DUMP_TYPE_UNKNOWN 0 #define HEXAGRAM_CAN_DUMP_TYPE_SOCKETCAN 29 +#define HEXAGRAM_CAN_DUMP_TSRESOL_USEC 6 + typedef struct _hexagram_can_dump { char magic[4]; uint32_t endian; @@ -30,6 +32,9 @@ typedef struct _hexagram_can_stream hexagram_can_stream; hexagram_can_stream *hexagram_can_stream_open_fd(int fd); +hexagram_can_stream *hexagram_can_stream_create(const char *file, + const char *iface); + void hexagram_can_stream_destroy(hexagram_can_stream *stream); int hexagram_can_stream_read(hexagram_can_stream *stream, @@ -37,4 +42,7 @@ int hexagram_can_stream_read(hexagram_can_stream *stream, uint32_t *timestamp_lo, struct can_frame *frame); +int hexagram_can_stream_write(hexagram_can_stream *stream, + struct can_frame *frame); + #endif /* _HEXAGRAM_CAN_H */ diff --git a/src/can.c b/src/can.c index 41375ca..8b5abe3 100644 --- a/src/can.c +++ b/src/can.c @@ -1,6 +1,10 @@ #include #include #include +#include +#include +#include +#include #include @@ -54,6 +58,36 @@ error_malloc: return NULL; } +hexagram_can_stream *hexagram_can_stream_create(const char *file, + const char *iface) { + int fd; + hexagram_can_dump header; + + if ((fd = open(file, O_CREAT | O_WRONLY)) < 0) { + goto error_open; + } + + memcpy(header.magic, HEXAGRAM_CAN_DUMP_MAGIC, strlen(HEXAGRAM_CAN_DUMP_MAGIC)); + + header.endian = HEXAGRAM_CAN_DUMP_ENDIAN; + header.type = PF_CAN; + header.tsresol = HEXAGRAM_CAN_DUMP_TSRESOL_USEC; + + strncpy(header.iface, iface, sizeof(header.iface)); + + if (write(fd, &header, sizeof(header)) < 0) { + goto error_write; + } + + return hexagram_can_stream_open_fd(fd); + +error_write: + close(fd); + +error_open: + return NULL; +} + void hexagram_can_stream_destroy(hexagram_can_stream *stream) { memset(stream, '\0', sizeof(*stream)); @@ -83,3 +117,23 @@ int hexagram_can_stream_read(hexagram_can_stream *stream, error_io: return -1; } + +int hexagram_can_stream_write(hexagram_can_stream *stream, + struct can_frame *frame) { + hexagram_can_frame data; + struct timeval now; + + if (gettimeofday(&now, NULL) < 0) { + goto error_gettimeofday; + } + + data.timestamp_hi = now.tv_usec & 0xffffffff00000000 >> 32; + data.timestamp_lo = now.tv_usec & 0x00000000ffffffff; + + memcpy(&data.frame, frame, sizeof(data.frame)); + + return write(stream->fd, &data, sizeof(data)); + +error_gettimeofday: + return -1; +}