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