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