]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canplayer.c
can-utils: add Makefile for Android build system
[sojka/can-utils.git] / canplayer.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * canplayer.c - replay a compact CAN frame logfile to CAN devices
7  *
8  * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of Volkswagen nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * Alternatively, provided that this notice is retained in full, this
24  * software may be distributed under the terms of the GNU General
25  * Public License ("GPL") version 2, in which case the provisions of the
26  * GPL apply INSTEAD OF those given above.
27  *
28  * The provided data structures and external interfaces from this code
29  * are not restricted to be used by modules with a GPL compatible license.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
42  * DAMAGE.
43  *
44  * Send feedback to <linux-can@vger.kernel.org>
45  *
46  */
47
48 #include <stdio.h>
49 #include <string.h>
50 #include <time.h>
51 #include <libgen.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54
55 #include <net/if.h>
56 #include <sys/socket.h>
57 #include <sys/ioctl.h>
58 #include <sys/time.h>
59 #include <linux/can.h>
60 #include <linux/can/raw.h>
61
62 #include "lib.h"
63
64 #define DEFAULT_GAP     1       /* ms */
65 #define DEFAULT_LOOPS   1       /* only one replay */
66 #define CHANNELS        20      /* anyone using more than 20 CAN interfaces at a time? */
67 #define BUFSZ           400     /* for one line in the logfile */
68 #define STDOUTIDX       65536   /* interface index for printing on stdout - bigger than max uint16 */
69
70 struct assignment {
71         char txif[IFNAMSIZ];
72         int  txifidx;
73         char rxif[IFNAMSIZ];
74 };
75 static struct assignment asgn[CHANNELS];
76
77 extern int optind, opterr, optopt;
78
79 void print_usage(char *prg)
80 {
81         fprintf(stderr, "\nUsage: %s <options> [interface assignment]*\n\n", prg);
82         fprintf(stderr, "Options:              -I <infile>  (default stdin)\n");
83         fprintf(stderr, "                      -l <num>     "
84                 "(process input file <num> times)\n"
85                 "                                   "
86                 "(Use 'i' for infinite loop - default: %d)\n", DEFAULT_LOOPS);
87         fprintf(stderr, "                      -t           (ignore timestamps: "
88                 "send frames immediately)\n");
89         fprintf(stderr, "                      -g <ms>      (gap in milli "
90                 "seconds - default: %d ms)\n", DEFAULT_GAP);
91         fprintf(stderr, "                      -s <s>      (skip gaps in "
92                 "timestamps > 's' seconds)\n");
93         fprintf(stderr, "                      -x           (disable local "
94                 "loopback of sent CAN frames)\n");
95         fprintf(stderr, "                      -v           (verbose: print "
96                 "sent CAN frames)\n\n");
97         fprintf(stderr, "Interface assignment:  0..n assignments like "
98                 "<write-if>=<log-if>\n");
99         fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
100                 "vcan2 )\n");
101         fprintf(stderr, "extra hook: stdout=can0 ( print logfile line marked with can0 on "
102                 "stdout )\n");
103         fprintf(stderr, "No assignments => send frames to the interface(s) they "
104                 "had been received from.\n\n");
105         fprintf(stderr, "Lines in the logfile not beginning with '(' (start of "
106                 "timestamp) are ignored.\n\n");
107 }
108
109 /* copied from /usr/src/linux/include/linux/time.h ...
110  * lhs < rhs:  return <0
111  * lhs == rhs: return 0
112  * lhs > rhs:  return >0
113  */
114 static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
115 {
116         if (lhs->tv_sec < rhs->tv_sec)
117                 return -1;
118         if (lhs->tv_sec > rhs->tv_sec)
119                 return 1;
120         return lhs->tv_usec - rhs->tv_usec;
121 }
122
123 static inline void create_diff_tv(struct timeval *today, struct timeval *diff,
124                                   struct timeval *log) {
125
126         /* create diff_tv so that log_tv + diff_tv = today_tv */
127         diff->tv_sec  = today->tv_sec  - log->tv_sec;
128         diff->tv_usec = today->tv_usec - log->tv_usec;
129 }
130
131 static inline int frames_to_send(struct timeval *today, struct timeval *diff,
132                                  struct timeval *log)
133 {
134         /* return value <0 when log + diff < today */
135
136         struct timeval cmp;
137
138         cmp.tv_sec  = log->tv_sec  + diff->tv_sec;
139         cmp.tv_usec = log->tv_usec + diff->tv_usec;
140
141         if (cmp.tv_usec > 1000000) {
142                 cmp.tv_usec -= 1000000;
143                 cmp.tv_sec++;
144         }
145
146         if (cmp.tv_usec < 0) {
147                 cmp.tv_usec += 1000000;
148                 cmp.tv_sec--;
149         }
150
151         return timeval_compare(&cmp, today);
152 }
153
154 int get_txidx(char *logif_name) {
155
156         int i;
157
158         for (i=0; i<CHANNELS; i++) {
159                 if (asgn[i].rxif[0] == 0) /* end of table content */
160                         break;
161                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
162                         break;
163         }
164
165         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
166                 return 0; /* not found */
167
168         return asgn[i].txifidx; /* return interface index */
169 }
170
171 char *get_txname(char *logif_name) {
172
173         int i;
174
175         for (i=0; i<CHANNELS; i++) {
176                 if (asgn[i].rxif[0] == 0) /* end of table content */
177                         break;
178                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
179                         break;
180         }
181
182         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
183                 return 0; /* not found */
184
185         return asgn[i].txif; /* return interface name */
186 }
187
188 int add_assignment(char *mode, int socket, char *txname, char *rxname,
189                    int verbose) {
190
191         struct ifreq ifr;
192         int i;
193
194         /* find free entry */
195         for (i=0; i<CHANNELS; i++) {
196                 if (asgn[i].txif[0] == 0)
197                         break;
198         }
199
200         if (i == CHANNELS) {
201                 fprintf(stderr, "Assignment table exceeded!\n");
202                 return 1;
203         }
204
205         if (strlen(txname) >= IFNAMSIZ) {
206                 fprintf(stderr, "write-if interface name '%s' too long!", txname);
207                 return 1;
208         }
209         strcpy(asgn[i].txif, txname);
210
211         if (strlen(rxname) >= IFNAMSIZ) {
212                 fprintf(stderr, "log-if interface name '%s' too long!", rxname);
213                 return 1;
214         }
215         strcpy(asgn[i].rxif, rxname);
216
217         if (strcmp(txname, "stdout")) {
218                 strcpy(ifr.ifr_name, txname);
219                 if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
220                         perror("SIOCGIFINDEX");
221                         fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
222                         return 1;
223                 }
224                 asgn[i].txifidx = ifr.ifr_ifindex;
225         } else
226                 asgn[i].txifidx = STDOUTIDX;
227
228         if (verbose > 1) /* use -v -v to see this */
229                 printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
230                        mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
231
232         return 0;
233 }
234
235 int main(int argc, char **argv)
236 {
237         static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
238         struct sockaddr_can addr;
239         static struct can_frame frame;
240         static struct timeval today_tv, log_tv, last_log_tv, diff_tv;
241         struct timespec sleep_ts;
242         int s; /* CAN_RAW socket */
243         FILE *infile = stdin;
244         unsigned long gap = DEFAULT_GAP; 
245         int use_timestamps = 1;
246         static int verbose, opt, delay_loops, skipgap;
247         static int loopback_disable = 0;
248         static int infinite_loops = 0;
249         static int loops = DEFAULT_LOOPS;
250         int assignments; /* assignments defined on the commandline */
251         int txidx;       /* sendto() interface index */
252         int eof, nbytes, i, j;
253         char *fret;
254
255         while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
256                 switch (opt) {
257                 case 'I':
258                         infile = fopen(optarg, "r");
259                         if (!infile) {
260                                 perror("infile");
261                                 return 1;
262                         }
263                         break;
264
265                 case 'l':
266                         if (optarg[0] == 'i')
267                                 infinite_loops = 1;
268                         else
269                                 if (!(loops = atoi(optarg))) {
270                                         fprintf(stderr, "Invalid argument for option -l !\n");
271                                         return 1;
272                                 }
273                         break;
274
275                 case 't':
276                         use_timestamps = 0;
277                         break;
278
279                 case 'g':
280                         gap = strtoul(optarg, NULL, 10);
281                         break;
282
283                 case 's':
284                         skipgap = strtoul(optarg, NULL, 10);
285                         if (skipgap < 1) {
286                                 fprintf(stderr, "Invalid argument for option -s !\n");
287                                 return 1;
288                         }
289                         break;
290
291                 case 'x':
292                         loopback_disable = 1;
293                         break;
294
295                 case 'v':
296                         verbose++;
297                         break;
298
299                 case '?':
300                 default:
301                         print_usage(basename(argv[0]));
302                         return 1;
303                         break;
304                 }
305         }
306
307         assignments = argc - optind; /* find real number of user assignments */
308
309         if (infile == stdin) { /* no jokes with stdin */
310                 infinite_loops = 0;
311                 loops = 1;
312         }
313
314         if (verbose > 1) { /* use -v -v to see this */
315                 if (infinite_loops)
316                         printf("infinite_loops\n");
317                 else
318                         printf("%d loops\n", loops);
319         }
320
321         sleep_ts.tv_sec  =  gap / 1000;
322         sleep_ts.tv_nsec = (gap % 1000) * 1000000;
323
324         /* open socket */
325         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
326                 perror("socket");
327                 return 1;
328         }
329
330         addr.can_family  = AF_CAN;
331         addr.can_ifindex = 0;
332
333         /* disable unneeded default receive filter on this RAW socket */
334         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
335
336         if (loopback_disable) {
337                 int loopback = 0;
338
339                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
340                            &loopback, sizeof(loopback));
341         }
342
343         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
344                 perror("bind");
345                 return 1;
346         }
347
348         if (assignments) {
349                 /* add & check user assginments from commandline */
350                 for (i=0; i<assignments; i++) {
351                         if (strlen(argv[optind+i]) >= BUFSZ) {
352                                 fprintf(stderr, "Assignment too long!\n");
353                                 print_usage(basename(argv[0]));
354                                 return 1;
355                         }
356                         strcpy(buf, argv[optind+i]);
357                         for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
358                                 if (buf[j] == '=')
359                                         break;
360                         }
361                         if ((j == BUFSZ) || (buf[j] != '=')) {
362                                 fprintf(stderr, "'=' missing in assignment!\n");
363                                 print_usage(basename(argv[0]));
364                                 return 1;
365                         }
366                         buf[j] = 0; /* cut string in two pieces */
367                         if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
368                                 return 1;
369                 }
370         }
371
372         while (infinite_loops || loops--) {
373
374                 if (infile != stdin)
375                         rewind(infile); /* for each loop */
376
377                 if (verbose > 1) /* use -v -v to see this */
378                         printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
379
380                 /* read first non-comment frame from logfile */
381                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
382                         if (strlen(buf) >= BUFSZ-2) {
383                                 fprintf(stderr, "comment line too long for input buffer\n");
384                                 return 1;
385                         }
386                 }
387
388                 if (!fret)
389                         goto out; /* nothing to read */
390
391                 eof = 0;
392
393                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
394                            device, ascframe) != 4) {
395                         fprintf(stderr, "incorrect line format in logfile\n");
396                         return 1;
397                 }
398
399                 if (use_timestamps) { /* throttle sending due to logfile timestamps */
400
401                         gettimeofday(&today_tv, NULL);
402                         create_diff_tv(&today_tv, &diff_tv, &log_tv);
403                         last_log_tv = log_tv;
404                 }
405
406                 while (!eof) {
407
408                         while ((!use_timestamps) ||
409                                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
410
411                                 /* log_tv/device/ascframe are valid here */
412
413                                 if (strlen(device) >= IFNAMSIZ) {
414                                         fprintf(stderr, "log interface name '%s' too long!", device);
415                                         return 1;
416                                 }
417
418                                 txidx = get_txidx(device); /* get ifindex for sending the frame */
419  
420                                 if ((!txidx) && (!assignments)) {
421                                         /* ifindex not found and no user assignments */
422                                         /* => assign this device automatically       */
423                                         if (add_assignment("auto", s, device, device, verbose))
424                                                 return 1;
425                                         txidx = get_txidx(device);
426                                 }
427
428                                 if (txidx == STDOUTIDX) { /* hook to print logfile lines on stdout */
429
430                                         printf("%s", buf); /* print the line AS-IS without extra \n */
431                                         fflush(stdout);
432
433                                 } else if (txidx > 0) { /* only send to valid CAN devices */
434
435                                         if (parse_canframe(ascframe, &frame)) {
436                                                 fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
437                                                 return 1;
438                                         }
439
440                                         addr.can_family  = AF_CAN;
441                                         addr.can_ifindex = txidx; /* send via this interface */
442  
443                                         nbytes = sendto(s, &frame, sizeof(struct can_frame), 0,
444                                                         (struct sockaddr*)&addr, sizeof(addr));
445
446                                         if (nbytes != sizeof(struct can_frame)) {
447                                                 perror("sendto");
448                                                 return 1;
449                                         }
450
451                                         if (verbose) {
452                                                 printf("%s (%s) ", get_txname(device), device);
453                                                 fprint_long_canframe(stdout, &frame, "\n", 1);
454                                         }
455                                 }
456
457                                 /* read next non-comment frame from logfile */
458                                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
459                                         if (strlen(buf) >= BUFSZ-2) {
460                                                 fprintf(stderr, "comment line too long for input buffer\n");
461                                                 return 1;
462                                         }
463                                 }
464
465                                 if (!fret) {
466                                         eof = 1; /* this file is completely processed */
467                                         break;
468                                 }
469
470                                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
471                                            device, ascframe) != 4) {
472                                         fprintf(stderr, "incorrect line format in logfile\n");
473                                         return 1;
474                                 }
475
476                                 if (use_timestamps) {
477                                         gettimeofday(&today_tv, NULL);
478
479                                         /* test for logfile timestamps jumping backwards OR      */
480                                         /* if the user likes to skip long gaps in the timestamps */
481                                         if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
482                                             (skipgap && abs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
483                                                 create_diff_tv(&today_tv, &diff_tv, &log_tv);
484
485                                         last_log_tv = log_tv;
486                                 }
487
488                         } /* while frames_to_send ... */
489
490                         if (nanosleep(&sleep_ts, NULL))
491                                 return 1;
492
493                         delay_loops++; /* private statistics */
494                         gettimeofday(&today_tv, NULL);
495
496                 } /* while (!eof) */
497
498         } /* while (infinite_loops || loops--) */
499
500 out:
501
502         close(s);
503         fclose(infile);
504
505         if (verbose > 1) /* use -v -v to see this */
506                 printf("%d delay_loops\n", delay_loops);
507
508         return 0;
509 }