]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canplayer.c
Minor fix and cosmetics in color handling in candump.c .
[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, 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 CHANNELS 20   /* anyone using more than 20 CAN interfaces at a time? */
66 #define BUFSZ 100     /* 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, "                      -t           (ignore timestamps: "
82             "send frames immediately)\n");
83     fprintf(stderr, "                      -g <ms>      (gap in milli "
84             "seconds - default: %d ms)\n", DEFAULT_GAP);
85     fprintf(stderr, "                      -v           (verbose: print "
86             "sent CAN frames)\n\n");
87     fprintf(stderr, "Interface assignment:  0..n assignments like "
88             "<write-if>=<log-if>\n");
89     fprintf(stderr, "e.g. vcan2=can0 ( send frames received from can0 on "
90             "vcan2 )\n");
91     fprintf(stderr, "No assignments => send frames to the interface(s) they "
92             "had been received from.\n\n");
93 }
94
95 /* copied from /usr/src/linux/include/linux/time.h ...
96  * lhs < rhs:  return <0
97  * lhs == rhs: return 0
98  * lhs > rhs:  return >0
99  */
100 static inline int timeval_compare(struct timeval *lhs, struct timeval *rhs)
101 {
102     if (lhs->tv_sec < rhs->tv_sec)
103         return -1;
104     if (lhs->tv_sec > rhs->tv_sec)
105         return 1;
106     return lhs->tv_usec - rhs->tv_usec;
107 }
108
109 static inline int frames_to_send(struct timeval *today, struct timeval *diff,
110                                  struct timeval *log)
111 {
112     /* return value <0 when log + diff < today */
113
114     struct timeval cmp;
115
116     cmp.tv_sec  = log->tv_sec  + diff->tv_sec;
117     cmp.tv_usec = log->tv_usec + diff->tv_usec;
118
119     if (cmp.tv_usec > 1000000) {
120         cmp.tv_usec -= 1000000;
121         cmp.tv_sec++;
122     }
123
124     return timeval_compare(&cmp, today);
125 }
126
127 int get_txidx(char *logif_name) {
128
129     int i;
130
131     for (i=0; i<CHANNELS; i++) {
132         if (asgn[i].rxif[0] == 0) /* end of table content */
133             break;
134         if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
135             break;
136     }
137
138     if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
139         return 0; /* not found */
140
141     return asgn[i].txifidx; /* return interface index */
142 }
143
144 char *get_txname(char *logif_name) {
145
146     int i;
147
148     for (i=0; i<CHANNELS; i++) {
149         if (asgn[i].rxif[0] == 0) /* end of table content */
150             break;
151         if (strcmp(asgn[i].rxif, logif_name) == 0) /* found device name */
152             break;
153     }
154
155     if ((i == CHANNELS) || (asgn[i].rxif[0] == 0))
156         return 0; /* not found */
157
158     return asgn[i].txif; /* return interface name */
159 }
160
161 int add_assignment(char *mode, int socket, char *txname, char *rxname,
162                    int verbose) {
163
164     struct ifreq ifr;
165     int i;
166
167     /* find free entry */
168     for (i=0; i<CHANNELS; i++) {
169         if (asgn[i].txif[0] == 0)
170             break;
171     }
172
173     if (i == CHANNELS) {
174         fprintf(stderr, "Assignment table exceeded!\n");
175         return 1;
176     }
177
178     if (strlen(txname) >= IFNAMSIZ) {
179         fprintf(stderr, "write-if interface name '%s' too long!", txname);
180         return 1;
181     }
182     strcpy(asgn[i].txif, txname);
183
184     if (strlen(rxname) >= IFNAMSIZ) {
185         fprintf(stderr, "log-if interface name '%s' too long!", rxname);
186         return 1;
187     }
188     strcpy(asgn[i].rxif, rxname);
189
190     strcpy(ifr.ifr_name, txname);
191     if (ioctl(socket, SIOCGIFINDEX, &ifr) < 0) {
192         perror("SIOCGIFINDEX");
193         fprintf(stderr, "write-if interface name '%s' is wrong!\n", txname);
194         return 1;
195     }
196     asgn[i].txifidx = ifr.ifr_ifindex;
197
198     if (verbose > 1) /* use -v -v to see this */
199         printf("added %s assignment: log-if=%s write-if=%s write-if-idx=%d\n",
200                mode, asgn[i].rxif, asgn[i].txif, asgn[i].txifidx);
201
202     return 0;
203 }
204
205 int main(int argc, char **argv)
206 {
207     static char buf[BUFSZ], device[BUFSZ], ascframe[BUFSZ];
208     struct sockaddr_can addr;
209     static struct can_frame frame;
210     static struct timeval today_tv, log_tv, diff_tv;
211     struct timespec sleep_ts;
212     int s; /* CAN_RAW socket */
213     FILE *infile = stdin;
214     unsigned long gap = DEFAULT_GAP; 
215     int use_timestamps = 1;
216     static int verbose, opt, loops;
217     int assignments; /* assignments defined on the commandline */
218     int txidx;       /* sendto() interface index */
219     int nbytes, i, j;
220
221     while ((opt = getopt(argc, argv, "I:tg:v")) != -1) {
222         switch (opt) {
223         case 'I':
224             infile = fopen(optarg, "r");
225             if (!infile) {
226                 perror("infile");
227                 return 1;
228             }
229             break;
230
231         case 't':
232             use_timestamps = 0;
233             break;
234
235         case 'g':
236             gap = strtoul(optarg, NULL, 10);
237             break;
238
239         case 'v':
240             verbose++;
241             break;
242
243         default:
244             print_usage(basename(argv[0]));
245             return 1;
246             break;
247         }
248     }
249
250     assignments = argc - optind; /* find real number of user assignments */
251
252     sleep_ts.tv_sec  =  gap / 1000;
253     sleep_ts.tv_nsec = (gap % 1000) * 1000000;
254
255     /* open socket */
256     if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
257         perror("socket");
258         return 1;
259     }
260
261     addr.can_family  = AF_CAN;
262     addr.can_ifindex = 0;
263
264     /* disable unneeded default receive filter on this RAW socket */
265     setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
266
267     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
268         perror("bind");
269         return 1;
270     }
271
272     if (assignments) {
273         /* add & check user assginments from commandline */
274         for (i=0; i<assignments; i++) {
275             if (strlen(argv[optind+i]) >= BUFSZ) {
276                 fprintf(stderr, "Assignment too long!\n");
277                 print_usage(basename(argv[0]));
278                 return 1;
279             }
280             strcpy(buf, argv[optind+i]);
281             for (j=0; j<BUFSZ; j++) { /* find '=' in assignment */
282                 if (buf[j] == '=')
283                     break;
284             }
285             if (buf[j] != '=') {
286                 fprintf(stderr, "'=' missing in assignment!\n");
287                 print_usage(basename(argv[0]));
288                 return 1;
289             }
290             buf[j] = 0; /* cut string in two pieces */
291             if (add_assignment("user", s, &buf[0], &buf[j+1], verbose))
292                 return 1;
293         }
294     }
295
296     if (!fgets(buf, BUFSZ-1, infile)) /* read first frame from logfile */
297         goto out; /* nothing to read */
298
299     if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
300                device, ascframe) != 4)
301         return 1;
302
303     if (use_timestamps) { /* throttle sending due to logfile timestamps */
304
305         gettimeofday(&today_tv, NULL);
306
307         /* omit crazy comparations with negative diff_tv */
308         if (timeval_compare(&today_tv, &log_tv) < 1) {
309             fprintf(stderr, "logfile timestamps newer than time of day!\n");
310             return 1;
311         }
312
313         /* create diff_tv so that log_tv + diff_tv = today_tv */
314         diff_tv.tv_sec  = today_tv.tv_sec  - log_tv.tv_sec;
315         diff_tv.tv_usec = today_tv.tv_usec - log_tv.tv_usec;
316         if (diff_tv.tv_usec < 0)
317             diff_tv.tv_sec--, diff_tv.tv_usec += 1000000;
318     }
319
320     while (1) {
321
322         while ((!use_timestamps) ||
323                (frames_to_send(&today_tv, &diff_tv, &log_tv) < 0)) {
324
325             /* log_tv/device/ascframe are valid here */
326
327             if (strlen(device) >= IFNAMSIZ) {
328                 fprintf(stderr, "log interface name '%s' too long!", device);
329                 return 1;
330             }
331
332             txidx = get_txidx(device); /* get ifindex for sending the frame */
333  
334             if ((!txidx) && (!assignments)) {
335                 /* ifindex not found and no user assignments */
336                 /* => assign this device automatically       */
337                 if (add_assignment("auto", s, device, device, verbose))
338                     return 1;
339                 txidx = get_txidx(device);
340             }
341
342             if (txidx) { /* only send to valid CAN devices */
343
344                 if (parse_canframe(ascframe, &frame)) {
345                     fprintf(stderr, "wrong CAN frame format: '%s'!", ascframe);
346                     return 1;
347                 }
348
349                 addr.can_family  = AF_CAN;
350                 addr.can_ifindex = txidx; /* send via this interface */
351  
352                 nbytes = sendto(s, &frame, sizeof(struct can_frame), 0,
353                                 (struct sockaddr*)&addr, sizeof(addr));
354
355                 if (nbytes != sizeof(struct can_frame)) {
356                     perror("sendto");
357                     return 1;
358                 }
359
360                 if (verbose) {
361                     printf("%s (%s) ", get_txname(device), device);
362                     fprint_long_canframe(stdout, &frame, "\n", 1);
363                 }
364             }
365
366             /* read next frame from logfile */
367             if (!fgets(buf, BUFSZ-1, infile))
368                 goto out; /* nothing to read */
369
370             if (sscanf(buf, "(%ld.%ld) %s %s", &log_tv.tv_sec, &log_tv.tv_usec,
371                        device, ascframe) != 4)
372                 return 1;
373
374             if (use_timestamps) /* save a syscall if possible */
375                 gettimeofday(&today_tv, NULL);
376         }
377
378         if (nanosleep(&sleep_ts, NULL))
379             return 1;
380
381         loops++; /* private statistics */
382         gettimeofday(&today_tv, NULL);
383     }
384
385  out:
386
387     close(s);
388     fclose(infile);
389
390     if (verbose > 1) /* use -v -v to see this */
391         printf("%d loops\n", loops);
392
393     return 0;
394 }