#include <ctype.h>
#include <errno.h>
#include <libgen.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>

#include <linux/can.h>
#include <linux/can/raw.h>

#include "lib.h"
int main(int argc, char *argv) {
	int s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
	struct sockaddr_can addr;
	char ctrlmsg[CMSG_SPACE(sizeof(struct timeval) + 3*sizeof(struct timespec) + sizeof(__u32))];
	struct msghdr msg;
	int max_dlen= CAN_MAX_DLEN;
	unsigned char view = CANLIB_VIEW_ASCII;
	int nbytes;
	struct iovec iov;
	struct canfd_frame frame;

	if (s < 0) {
		perror("socket");
		return 1;
	}

	addr.can_family = AF_CAN;
	addr.can_ifindex = 0;

	if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("bind");
		exit(1);
	}

	iov.iov_base = &frame;
        msg.msg_name = &addr;
        msg.msg_iov = &iov;
        msg.msg_iovlen = 1;
        msg.msg_control = &ctrlmsg;


	while (1) {
		iov.iov_len = sizeof(frame);
		msg.msg_namelen = sizeof(addr);
		msg.msg_controllen = sizeof(ctrlmsg);
		msg.msg_flags = 0;

                nbytes = recvmsg(s, &msg, 0);
		//printf("%04x\n", frame.can_id);
		if (frame.can_id == 0x00000561) {
			printf("%.*s", frame.len, frame.data);
			//fprint_long_canframe(stdout, &frame, NULL, view, max_dlen);
		}
		//printf("\n");
	}


	exit(0);
}
