Updated new 'cangen' and 'candump' in the trunk.
[profile/ivi/can-utils.git] / cangen.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * cangen.c - CAN frames generator for testing purposes
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 <stdlib.h>
50 #include <stdint.h>
51 #include <unistd.h>
52 #include <string.h>
53 #include <signal.h>
54 #include <ctype.h>
55 #include <libgen.h>
56 #include <time.h>
57 #include <errno.h>
58
59 #include <sys/time.h>
60 #include <sys/types.h>
61 #include <sys/socket.h>
62 #include <sys/ioctl.h>
63 #include <sys/uio.h>
64 #include <net/if.h>
65
66 #include <linux/can.h>
67 #include <linux/can/raw.h>
68 #include "lib.h"
69
70 #define DEFAULT_GAP 200 /* ms */
71
72 #define MODE_RANDOM     0
73 #define MODE_INCREMENT  1
74 #define MODE_FIX        2
75
76 extern int optind, opterr, optopt;
77
78 static volatile int running = 1;
79 static unsigned long long enobufs_count;
80
81 void print_usage(char *prg)
82 {
83     fprintf(stderr, "\n%s: generate CAN frames\n\n", prg);
84     fprintf(stderr, "Usage: %s [options] <CAN interface>\n", prg);
85     fprintf(stderr, "Options: -g <ms>       (gap in milli seconds "
86             "- default: %d ms)\n", DEFAULT_GAP);
87     fprintf(stderr, "         -e            (generate extended frame mode "
88             "(EFF) CAN frames)\n");
89     fprintf(stderr, "         -I <mode>     (CAN ID"
90             " generation mode - see below)\n");
91     fprintf(stderr, "         -L <mode>     (CAN data length code (dlc)"
92             " generation mode - see below)\n");
93     fprintf(stderr, "         -D <mode>     (CAN data (payload)"
94             " generation mode - see below)\n");
95     fprintf(stderr, "         -i            (ignore -ENOBUFS return values on"
96             " write() syscalls)\n");
97     fprintf(stderr, "         -x            (disable local loopback of "
98             "generated CAN frames)\n");
99     fprintf(stderr, "         -v            (increment verbose level for "
100             "printing sent CAN frames)\n\n");
101     fprintf(stderr, "Generation modes:\n");
102     fprintf(stderr, "'r'        => random values (default)\n");
103     fprintf(stderr, "'i'        => increment values\n");
104     fprintf(stderr, "<hexvalue> => fix value using <hexvalue>\n\n");
105     fprintf(stderr, "When incrementing the CAN data the data length code "
106             "minimum is set to 1.\n\n");
107     fprintf(stderr, "Examples:\n");
108     fprintf(stderr, "%s vcan0 -g 4 -I 42A -L 1 -D i -v -v   ", prg);
109     fprintf(stderr, "(fixed CAN ID and length, inc. data)\n");
110     fprintf(stderr, "%s vcan0 -e -L i -v -v -v              ", prg);
111     fprintf(stderr, "(generate EFF frames, incr. length)\n");
112     fprintf(stderr, "%s vcan0 -D 11223344DEADBEEF -L 8      ", prg);
113     fprintf(stderr, "(fixed CAN data payload and length)\n");
114     fprintf(stderr, "%s vcan0 -g 0 -i -x                    ", prg);
115     fprintf(stderr, "(full load test ignoring -ENOBUFS)\n");
116     fprintf(stderr, "%s vcan0                               ", prg);
117     fprintf(stderr, "(my favourite default :)\n\n");
118 }
119
120 void sigterm(int signo)
121 {
122     running = 0;
123 }
124
125 int main(int argc, char **argv)
126 {
127     unsigned long gap = DEFAULT_GAP; 
128     unsigned char ignore_enobufs = 0;
129     unsigned char extended = 0;
130     unsigned char id_mode = MODE_RANDOM;
131     unsigned char data_mode = MODE_RANDOM;
132     unsigned char dlc_mode = MODE_RANDOM;
133     unsigned char loopback_disable = 0;
134     unsigned char verbose = 0;
135     uint64_t incdata = 0;
136
137     int opt;
138     int s; /* socket */
139
140     struct sockaddr_can addr;
141     static struct can_frame frame;
142     int nbytes;
143     int i;
144     struct ifreq ifr;
145
146     struct timespec ts;
147
148     signal(SIGTERM, sigterm);
149     signal(SIGHUP, sigterm);
150     signal(SIGINT, sigterm);
151
152     while ((opt = getopt(argc, argv, "ig:eI:L:D:xvh?")) != -1) {
153         switch (opt) {
154
155         case 'i':
156             ignore_enobufs = 1;
157             break;
158
159         case 'g':
160             gap = strtoul(optarg, NULL, 10);
161             break;
162
163         case 'e':
164             extended = 1;
165             break;
166
167         case 'I':
168             if (optarg[0] == 'r') {
169                 id_mode = MODE_RANDOM;
170             } else if (optarg[0] == 'i') {
171                 id_mode = MODE_INCREMENT;
172             } else {
173                 id_mode = MODE_FIX;
174                 frame.can_id = strtoul(optarg, NULL, 16);
175             }
176             break;
177
178         case 'L':
179             if (optarg[0] == 'r') {
180                 dlc_mode = MODE_RANDOM;
181             } else if (optarg[0] == 'i') {
182                 dlc_mode = MODE_INCREMENT;
183             } else {
184                 dlc_mode = MODE_FIX;
185                 frame.can_dlc = atoi(optarg)%9;
186             }
187             break;
188
189         case 'D':
190             if (optarg[0] == 'r') {
191                 data_mode = MODE_RANDOM;
192             } else if (optarg[0] == 'i') {
193                 data_mode = MODE_INCREMENT;
194             } else {
195                 data_mode = MODE_FIX;
196                 incdata = strtoull(optarg, NULL, 16);
197                 for (i=0; i<8 ;i++)
198                     frame.data[i] = (incdata >> (7-i)*8) & 0xFFULL;
199             }
200             break;
201
202         case 'v':
203             verbose++;
204             break;
205
206         case 'x':
207             loopback_disable = 1;
208             break;
209
210         case '?':
211         case 'h':
212         default:
213             print_usage(basename(argv[0]));
214             return 1;
215             break;
216         }
217     }
218
219     if (optind == argc) {
220         print_usage(basename(argv[0]));
221         return 1;
222     }
223
224     ts.tv_sec = gap / 1000;
225     ts.tv_nsec = (gap % 1000) * 1000000;
226
227
228     if (id_mode == MODE_FIX) {
229
230         /* recognize obviously missing commandline option */
231         if ((frame.can_id > 0x7FF) && !extended) {
232             printf("The given CAN-ID is greater than 0x7FF and "
233                    "the '-e' option is not set.\n");
234             return 1;
235         }
236
237         if (extended)
238             frame.can_id &= CAN_EFF_MASK;
239         else
240             frame.can_id &= CAN_SFF_MASK;
241     }
242
243     if (extended)
244             frame.can_id |=  CAN_EFF_FLAG;
245
246     if ((data_mode == MODE_INCREMENT) && !frame.can_dlc)
247         frame.can_dlc = 1; /* min dlc value for incr. data */
248
249     if (strlen(argv[optind]) >= IFNAMSIZ) {
250         printf("Name of CAN device '%s' is too long!\n\n", argv[optind]);
251         return 1;
252     }
253
254     if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
255         perror("socket");
256         return 1;
257     }
258
259     addr.can_family = AF_CAN;
260
261     strcpy(ifr.ifr_name, argv[optind]);
262     if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
263         perror("SIOCGIFINDEX");
264         return 1;
265     }
266     addr.can_ifindex = ifr.ifr_ifindex;
267
268     /* disable default receive filter on this RAW socket */
269     /* This is obsolete as we do not read from the socket at all, but for */
270     /* this reason we can remove the receive list in the Kernel to save a */
271     /* little (really a very little!) CPU usage.                          */
272     setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
273
274     if (loopback_disable) {
275         int loopback = 0;
276
277         setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
278                    &loopback, sizeof(loopback));
279     }
280
281     if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
282         perror("bind");
283         return 1;
284     }
285
286     while (running) {
287
288         if (id_mode == MODE_RANDOM) {
289
290             frame.can_id = random();
291
292             if (extended) {
293                 frame.can_id &= CAN_EFF_MASK;
294                 frame.can_id |= CAN_EFF_FLAG;
295             } else
296                 frame.can_id &= CAN_SFF_MASK;
297         }
298
299         if (dlc_mode == MODE_RANDOM) {
300
301             frame.can_dlc = random() & 0xF;
302
303             if (frame.can_dlc & 8)
304                 frame.can_dlc = 8; /* for about 50% of the frames */
305
306             if ((data_mode == MODE_INCREMENT) && !frame.can_dlc)
307                 frame.can_dlc = 1; /* min dlc value for incr. data */
308         }
309
310         if (data_mode == MODE_RANDOM) {
311
312             /* that's what the 64 bit alignment of data[] is for ... :) */
313             *(unsigned long*)(&frame.data[0]) = random();
314             *(unsigned long*)(&frame.data[4]) = random();
315         }
316
317         if (verbose) {
318
319             printf("  %s  ", argv[optind]);
320
321             if (verbose > 1)
322                 fprint_long_canframe(stdout, &frame, "\n", (verbose > 2)?1:0);
323             else
324                 fprint_canframe(stdout, &frame, "\n", 1);
325         }
326
327         nbytes = write(s, &frame, sizeof(struct can_frame));
328         if (nbytes < 0) {
329             if (errno != ENOBUFS) {
330                 perror("write");
331                 return 1;
332             }
333             if (!ignore_enobufs) {
334                 perror("write");
335                 return 1;
336             }
337             enobufs_count++;
338
339         } else if (nbytes < sizeof(struct can_frame)) {
340             fprintf(stderr, "write: incomplete CAN frame\n");
341             return 1;
342         }
343
344         if (gap) /* gap == 0 => performance test :-] */
345             if (nanosleep(&ts, NULL))
346                 return 1;
347                     
348         if (id_mode == MODE_INCREMENT) {
349
350             frame.can_id++;
351
352             if (extended) {
353                 frame.can_id &= CAN_EFF_MASK;
354                 frame.can_id |= CAN_EFF_FLAG;
355             } else
356                 frame.can_id &= CAN_SFF_MASK;
357         }
358
359         if (dlc_mode == MODE_INCREMENT) {
360
361             frame.can_dlc++;
362             frame.can_dlc %= 9;
363
364             if ((data_mode == MODE_INCREMENT) && !frame.can_dlc)
365                 frame.can_dlc = 1; /* min dlc value for incr. data */
366         }
367
368         if (data_mode == MODE_INCREMENT) {
369
370             incdata++;
371
372             for (i=0; i<8 ;i++)
373                 frame.data[i] = (incdata >> i*8) & 0xFFULL;
374         }
375     }
376
377     if (enobufs_count)
378         printf("\nCounted %llu ENOBUFS return values on write().\n\n",
379                enobufs_count);
380
381     close(s);
382
383     return 0;
384 }