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