2 * Copyright 2017 Max Staudt
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License 2 as published
6 * by the Free Software Foundation.
14 #include <sys/types.h>
15 #include <sys/socket.h>
16 #include <linux/can.h>
17 #include <linux/can/raw.h>
19 #include <sys/ioctl.h>
26 static int net_init(char *ifname)
30 struct sockaddr_can addr;
33 s = socket(PF_CAN, SOCK_RAW, CAN_RAW);
39 /* Convert interface name to index */
40 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
41 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
42 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
43 perror("SIOCGIFINDEX");
47 /* Open the CAN interface */
48 memset(&addr, 0, sizeof(addr));
49 addr.can_family = AF_CAN;
50 addr.can_ifindex = ifr.ifr_ifindex;
51 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
56 recv_own_msgs = 1; /* 0 = disabled (default), 1 = enabled */
57 setsockopt(s, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS,
58 &recv_own_msgs, sizeof(recv_own_msgs));
67 int main(int argc, char **argv)
74 struct BAP_RXer **baps;
77 printf("syntax: %s IFNAME CAN_ID [CAN_ID CAN_ID ...]\n", argv[0]);
81 can_id_count = argc - 2;
83 can_ids = calloc(can_id_count, sizeof(*can_ids));
84 baps = calloc(can_id_count, sizeof(*baps));
85 if (!can_ids || !baps) {
86 printf("Out of memory allocating meta structs.\n");
90 for (i = 0; i < can_id_count; i++) {
91 can_ids[i] = strtoul(argv[2 + i], NULL, 0);
92 baps[i] = vw_bap_rxer_alloc();
94 printf("Out of memory allocating BAP struct.\n");
98 printf("Listening for CAN ID: %x\n", can_ids[i]);
102 s = net_init(argv[1]);
110 retval = select(s+1, &rdfs, NULL, NULL, NULL);
111 /* We currently rely on Linux timeout behavior here,
112 * i.e. the timeout now reflects the remaining time */
116 } else if (!retval) {
117 /* Timeout, we NEED to check this first */
118 } else if (FD_ISSET(s, &rdfs)) {
119 struct can_frame frame;
122 ret = read(s, &frame, sizeof(frame));
124 perror("read from CAN socket");
128 for (i = 0; i < can_id_count; i++) {
129 if (can_ids[i] == frame.can_id) {
130 struct BAP_Frame *bap_frame;
131 struct BAP_RXer *bap = baps[i];
133 bap_frame = vw_bap_handle_can_frame(bap, &frame);
135 printf("%03x: ", frame.can_id);
136 vw_bap_frame_dump(bap_frame);
137 vw_bap_frame_free(bap_frame);