]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canplayer.c
slcand : added new commandline option to support direct assignment of a CAN
[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 <socketcan-users@lists.berlios.de>
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/ioctl.h>
57 #include <sys/time.h>
58 #include <linux/can.h>
59 #include <linux/can/raw.h>
60
61 #include "lib.h"
62
63 #define DEFAULT_GAP     1       /* ms */
64 #define DEFAULT_LOOPS   1       /* only one replay */
65 #define CHANNELS        20      /* anyone using more than 20 CAN interfaces at a time? */
66 #define BUFSZ           400     /* for one line in the logfile */
67 #define STDOUTIDX       65536   /* interface index for printing on stdout - bigger than max uint16 */
68
69 struct assignment {
70         char txif[IFNAMSIZ];
71         int  txifidx;
72         char rxif[IFNAMSIZ];
73 };
74 static struct assignment asgn[CHANNELS];
75
76 extern int optind, opterr, optopt;
77
78 void print_usage(char *prg)
79 {
80         fprintf(stderr, "\nUsage: %s <options> [interface assignment]*\n\n", prg);
81         fprintf(stderr, "Options:              -I <infile>  (default stdin)\n");
82         fprintf(stderr, "                      -l <num>     "
83                 "(process input file <num> times)\n"
84                 "                                   "
85                 "(Use 'i' for infinite loop - default: %d)\n", DEFAULT_LOOPS);
86         fprintf(stderr, "                      -t           (ignore timestamps: "
87                 "send frames immediately)\n");
88         fprintf(stderr, "                      -g <ms>      (gap in milli "
89                 "seconds - default: %d ms)\n", DEFAULT_GAP);
90         fprintf(stderr, "                      -s <s>      (skip gaps in "
91                 "timestamps > 's' seconds)\n");
92         fprintf(stderr, "                      -x           (disable local "
93                 "loopback of sent CAN frames)\n");
94         fprintf(stderr, "                      -v           (verbose: print "
95                 "sent CAN frames)\n\n");
96         fprintf(stderr, "Interface assignment:  0..n assignments like "
97                 "<write-if>=<log-if>\n");
98         fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
99                 "vcan2 )\n");
100         fprintf(stderr, "extra hook: stdout=can0 ( print logfile line marked with can0 on "
101                 "stdout )\n");
102         fprintf(stderr, "No assignments => send frames to the interface(s) they "
103                 "had been received from.\n\n");
104         fprintf(stderr, "Lines in the logfile not beginning with '(' (start of "
105                 "timestamp) are ignored.\n\n");
106 }
107
108 /* copied from /usr/src/linux/include/linux/time.h ...
109  * lhs < rhs:  return <0
110  * lhs == rhs: return 0
111  * lhs > rhs:  return >0
112  */
113 static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
114 {
115         if (lhs->tv_sec < rhs->tv_sec)
116                 return -1;
117         if (lhs->tv_sec > rhs->tv_sec)
118                 return 1;
119         return lhs->tv_usec - rhs->tv_usec;
120 }
121
122 static inline void create_diff_tv(struct timeval *today, struct timeval *diff,
123                                   struct timeval *log) {
124
125         /* create diff_tv so that log_tv + diff_tv = today_tv */
126         diff->tv_sec  = today->tv_sec  - log->tv_sec;
127         diff->tv_usec = today->tv_usec - log->tv_usec;
128 }
129
130 static inline int frames_to_send(struct timeval *today, struct timeval *diff,
131                                  struct timeval *log)
132 {
133         /* return value <0 when log + diff < today */
134
135         struct timeval cmp;
136
137         cmp.tv_sec  = log->tv_sec  + diff->tv_sec;
138         cmp.tv_usec = log->tv_usec + diff->tv_usec;
139
140         if (cmp.tv_usec > 1000000) {
141                 cmp.tv_usec -= 1000000;
142                 cmp.tv_sec++;
143         }
144
145         if (cmp.tv_usec < 0) {
146                 cmp.tv_usec += 1000000;
147                 cmp.tv_sec--;
148         }
149
150         return timeval_compare(&cmp, today);
151 }
152
153 int get_txidx(char *logif_name) {
154
155         int i;
156
157         for (i=0; i<CHANNELS; i++) {
158                 if (asgn[i].rxif[0] == 0) /* end of table content */
159                         break;
160                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
161                         break;
162         }
163
164         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
165                 return 0; /* not found */
166
167         return asgn[i].txifidx; /* return interface index */
168 }
169
170 char *get_txname(char *logif_name) {
171
172         int i;
173
174         for (i=0; i<CHANNELS; i++) {
175                 if (asgn[i].rxif[0] == 0) /* end of table content */
176                         break;
177                 if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
178                         break;
179         }
180
181         if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
182                 return 0; /* not found */
183
184         return asgn[i].txif; /* return interface name */
185 }
186
187 int add_assignment(char *mode, int socket, char *txname, char *rxname,
188                    int verbose) {
189
190         struct ifreq ifr;
191         int i;
192
193         /* find free entry */
194         for (i=0; i<CHANNELS; i++) {
195                 if (asgn[i].txif[0] == 0)
196                         break;
197         }
198
199         if (i == CHANNELS) {
200                 fprintf(stderr, "Assignment table exceeded!\n");
201                 return 1;
202         }
203
204         if (strlen(txname) >= IFNAMSIZ) {
205                 fprintf(stderr, "write-if interface name '%s' too long!", txname);
206                 return 1;
207         }
208         strcpy(asgn[i].txif, txname);
209
210         if (strlen(rxname) >= IFNAMSIZ) {
211                 fprintf(stderr, "log-if interface name '%s' too long!", rxname);
212                 return 1;
213         }
214         strcpy(asgn[i].rxif, rxname);
215
216         if (strcmp(txname, "stdout")) {
217                 strcpy(ifr.ifr_name, txname);
218                 if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
219                         perror("SIOCGIFINDEX");
220                         fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
221                         return 1;
222                 }
223                 asgn[i].txifidx = ifr.ifr_ifindex;
224         } else
225                 asgn[i].txifidx = STDOUTIDX;
226
227         if (verbose > 1) /* use -v -v to see this */
228                 printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
229                        mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
230
231         return 0;
232 }
233
234 int main(int argc, char **argv)
235 {
236         static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
237         struct sockaddr_can addr;
238         static struct can_frame frame;
239         static struct timeval today_tv, log_tv, last_log_tv, diff_tv;
240         struct timespec sleep_ts;
241         int s; /* CAN_RAW socket */
242         FILE *infile = stdin;
243         unsigned long gap = DEFAULT_GAP; 
244         int use_timestamps = 1;
245         static int verbose, opt, delay_loops, skipgap;
246         static int loopback_disable = 0;
247         static int infinite_loops = 0;
248         static int loops = DEFAULT_LOOPS;
249         int assignments; /* assignments defined on the commandline */
250         int txidx;       /* sendto() interface index */
251         int eof, nbytes, i, j;
252         char *fret;
253
254         while ((opt = getopt(argc, argv, "I:l:tg:s:xv?")) != -1) {
255                 switch (opt) {
256                 case 'I':
257                         infile = fopen(optarg, "r");
258                         if (!infile) {
259                                 perror("infile");
260                                 return 1;
261                         }
262                         break;
263
264                 case 'l':
265                         if (optarg[0] == 'i')
266                                 infinite_loops = 1;
267                         else
268                                 if (!(loops = atoi(optarg))) {
269                                         fprintf(stderr, "Invalid argument for option -l !\n");
270                                         return 1;
271                                 }
272                         break;
273
274                 case 't':
275                         use_timestamps = 0;
276                         break;
277
278                 case 'g':
279                         gap = strtoul(optarg, NULL, 10);
280                         break;
281
282                 case 's':
283                         skipgap = strtoul(optarg, NULL, 10);
284                         if (skipgap < 1) {
285                                 fprintf(stderr, "Invalid argument for option -s !\n");
286                                 return 1;
287                         }
288                         break;
289
290                 case 'x':
291                         loopback_disable = 1;
292                         break;
293
294                 case 'v':
295                         verbose++;
296                         break;
297
298                 case '?':
299                 default:
300                         print_usage(basename(argv[0]));
301                         return 1;
302                         break;
303                 }
304         }
305
306         assignments = argc - optind; /* find real number of user assignments */
307
308         if (infile == stdin) { /* no jokes with stdin */
309                 infinite_loops = 0;
310                 loops = 1;
311         }
312
313         if (verbose > 1) { /* use -v -v to see this */
314                 if (infinite_loops)
315                         printf("infinite_loops\n");
316                 else
317                         printf("%d loops\n", loops);
318         }
319
320         sleep_ts.tv_sec  =  gap / 1000;
321         sleep_ts.tv_nsec = (gap % 1000) * 1000000;
322
323         /* open socket */
324         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
325                 perror("socket");
326                 return 1;
327         }
328
329         addr.can_family  = AF_CAN;
330         addr.can_ifindex = 0;
331
332         /* disable unneeded default receive filter on this RAW socket */
333         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
334
335         if (loopback_disable) {
336                 int loopback = 0;
337
338                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
339                            &loopback, sizeof(loopback));
340         }
341
342         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
343                 perror("bind");
344                 return 1;
345         }
346
347         if (assignments) {
348                 /* add & check user assginments from commandline */
349                 for (i=0; i<assignments; i++) {
350                         if (strlen(argv[optind+i]) >= BUFSZ) {
351                                 fprintf(stderr, "Assignment too long!\n");
352                                 print_usage(basename(argv[0]));
353                                 return 1;
354                         }
355                         strcpy(buf, argv[optind+i]);
356                         for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
357                                 if (buf[j] == '=')
358                                         break;
359                         }
360                         if ((j == BUFSZ) || (buf[j] != '=')) {
361                                 fprintf(stderr, "'=' missing in assignment!\n");
362                                 print_usage(basename(argv[0]));
363                                 return 1;
364                         }
365                         buf[j] = 0; /* cut string in two pieces */
366                         if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
367                                 return 1;
368                 }
369         }
370
371         while (infinite_loops || loops--) {
372
373                 if (infile != stdin)
374                         rewind(infile); /* for each loop */
375
376                 if (verbose > 1) /* use -v -v to see this */
377                         printf (">>>>>>>>> start reading file. remaining loops = %d\n", loops);
378
379                 /* read first non-comment frame from logfile */
380                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
381                         if (strlen(buf) >= BUFSZ-2) {
382                                 fprintf(stderr, "comment line too long for input buffer\n");
383                                 return 1;
384                         }
385                 }
386
387                 if (!fret)
388                         goto out; /* nothing to read */
389
390                 eof = 0;
391
392                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
393                            device, ascframe) != 4) {
394                         fprintf(stderr, "incorrect line format in logfile\n");
395                         return 1;
396                 }
397
398                 if (use_timestamps) { /* throttle sending due to logfile timestamps */
399
400                         gettimeofday(&today_tv, NULL);
401                         create_diff_tv(&today_tv, &diff_tv, &log_tv);
402                         last_log_tv = log_tv;
403                 }
404
405                 while (!eof) {
406
407                         while ((!use_timestamps) ||
408                                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
409
410                                 /* log_tv/device/ascframe are valid here */
411
412                                 if (strlen(device) >= IFNAMSIZ) {
413                                         fprintf(stderr, "log interface name '%s' too long!", device);
414                                         return 1;
415                                 }
416
417                                 txidx = get_txidx(device); /* get ifindex for sending the frame */
418  
419                                 if ((!txidx) && (!assignments)) {
420                                         /* ifindex not found and no user assignments */
421                                         /* => assign this device automatically       */
422                                         if (add_assignment("auto", s, device, device, verbose))
423                                                 return 1;
424                                         txidx = get_txidx(device);
425                                 }
426
427                                 if (txidx == STDOUTIDX) { /* hook to print logfile lines on stdout */
428
429                                         printf("%s", buf); /* print the line AS-IS without extra \n */
430                                         fflush(stdout);
431
432                                 } else if (txidx > 0) { /* only send to valid CAN devices */
433
434                                         if (parse_canframe(ascframe, &frame)) {
435                                                 fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
436                                                 return 1;
437                                         }
438
439                                         addr.can_family  = AF_CAN;
440                                         addr.can_ifindex = txidx; /* send via this interface */
441  
442                                         nbytes = sendto(s, &frame, sizeof(struct can_frame), 0,
443                                                         (struct sockaddr*)&addr, sizeof(addr));
444
445                                         if (nbytes != sizeof(struct can_frame)) {
446                                                 perror("sendto");
447                                                 return 1;
448                                         }
449
450                                         if (verbose) {
451                                                 printf("%s (%s) ", get_txname(device), device);
452                                                 fprint_long_canframe(stdout, &frame, "\n", 1);
453                                         }
454                                 }
455
456                                 /* read next non-comment frame from logfile */
457                                 while ((fret = fgets(buf, BUFSZ-1, infile)) != NULL && buf[0] != '(') {
458                                         if (strlen(buf) >= BUFSZ-2) {
459                                                 fprintf(stderr, "comment line too long for input buffer\n");
460                                                 return 1;
461                                         }
462                                 }
463
464                                 if (!fret) {
465                                         eof = 1; /* this file is completely processed */
466                                         break;
467                                 }
468
469                                 if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
470                                            device, ascframe) != 4) {
471                                         fprintf(stderr, "incorrect line format in logfile\n");
472                                         return 1;
473                                 }
474
475                                 if (use_timestamps) {
476                                         gettimeofday(&today_tv, NULL);
477
478                                         /* test for logfile timestamps jumping backwards OR      */
479                                         /* if the user likes to skip long gaps in the timestamps */
480                                         if ((last_log_tv.tv_sec > log_tv.tv_sec) ||
481                                             (skipgap && abs(last_log_tv.tv_sec - log_tv.tv_sec) > skipgap))
482                                                 create_diff_tv(&today_tv, &diff_tv, &log_tv);
483
484                                         last_log_tv = log_tv;
485                                 }
486
487                         } /* while frames_to_send ... */
488
489                         if (nanosleep(&sleep_ts, NULL))
490                                 return 1;
491
492                         delay_loops++; /* private statistics */
493                         gettimeofday(&today_tv, NULL);
494
495                 } /* while (!eof) */
496
497         } /* while (infinite_loops || loops--) */
498
499 out:
500
501         close(s);
502         fclose(infile);
503
504         if (verbose > 1) /* use -v -v to see this */
505                 printf("%d delay_loops\n", delay_loops);
506
507         return 0;
508 }