]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canbusload.c
candump: Added '-u <usecs>' commandline option to delay bridged CAN frames by
[sojka/can-utils.git] / canbusload.c
1 /*
2  *  $Id$
3  */
4
5 /*
6  * canbusload.c
7  *
8  * Copyright (c) 2002-2008 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 <unistd.h>
51 #include <string.h>
52 #include <signal.h>
53 #include <ctype.h>
54 #include <libgen.h>
55 #include <time.h>
56
57 #include <sys/time.h>
58 #include <sys/types.h>
59 #include <sys/socket.h>
60 #include <sys/ioctl.h>
61 #include <sys/uio.h>
62 #include <net/if.h>
63
64 #include <linux/can.h>
65 #include <linux/can/raw.h>
66
67 #include "terminal.h"
68
69 #define MAXSOCK 16    /* max. number of CAN interfaces given on the cmdline */
70
71 #define PERCENTRES 5 /* resolution in percent for bargraph */
72 #define NUMBAR (100/PERCENTRES) /* number of bargraph elements */
73
74 extern int optind, opterr, optopt;
75
76 static struct {
77         char devname[IFNAMSIZ+1];
78         unsigned int bitrate;
79         unsigned int recv_frames;
80         unsigned int recv_bits_total;
81         unsigned int recv_bits_payload;
82 } stat[MAXSOCK+1];
83
84 static int  max_devname_len; /* to prevent frazzled device name output */ 
85 static int  max_bitrate_len;
86 static int  currmax;
87 static unsigned char redraw;
88 static unsigned char timestamp;
89 static unsigned char color;
90 static unsigned char bargraph;
91 static unsigned char ignore_bitstuffing;
92 static char *prg;
93
94 void print_usage(char *prg)
95 {
96         fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
97         fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
98         fprintf(stderr, "Options: -t (show current time on the first line)\n");
99         fprintf(stderr, "         -c (colorize lines)\n");
100         fprintf(stderr, "         -b (show bargraph in %d%% resolution)\n", PERCENTRES);
101         fprintf(stderr, "         -r (redraw the terminal - similar to top)\n");
102         fprintf(stderr, "         -i (ignore bitstuffing estimation in bandwith calculation)\n");
103         fprintf(stderr, "\n");
104         fprintf(stderr, "Up to %d CAN interfaces with mandatory bitrate can be specified on the \n", MAXSOCK);
105         fprintf(stderr, "commandline in the form: <ifname>@<bitrate>\n\n");
106         fprintf(stderr, "The bitrate is mandatory as it is needed to know the CAN bus bitrate to\n");
107         fprintf(stderr, "calcultate the bus load percentage based on the received CAN frames.\n");
108         fprintf(stderr, "Due to the bitstuffing estimation the calculated busload may exceed 100%%.\n");
109         fprintf(stderr, "For each given interface the data is presented in one line which contains:\n\n");
110         fprintf(stderr, "(interface) (received CAN frames) (used bits total) (used bits for payload)\n");
111         fprintf(stderr, "\nExample:\n");
112         fprintf(stderr, "\nuser$> canbusload can0@100000 can1@500000 can2@500000 can3@500000 -r -t -b -c\n\n");
113         fprintf(stderr, "%s 2008-05-27 15:18:49\n", prg);
114         fprintf(stderr, " can0@100000  805  74491  36656  74%%  |XXXXXXXXXXXXXX......|\n");
115         fprintf(stderr, " can1@500000  796  75140  37728  15%%  |XXX.................|\n");
116         fprintf(stderr, " can2@500000    0      0      0   0%%  |....................|\n");
117         fprintf(stderr, " can3@500000   47   4633   2424   0%%  |....................|\n");
118         fprintf(stderr, "\n");
119 }
120
121 void sigterm(int signo)
122 {
123         exit(0);
124 }
125
126 void printstats(int signo)
127 {
128         int i, j, percent;
129
130         if (redraw)
131                 printf("%s", CSR_HOME);
132
133         if (timestamp) {
134                 time_t currtime;
135                 struct tm now;
136
137                 if (time(&currtime) == (time_t)-1) {
138                         perror("time");
139                         exit(1);
140                 }
141
142                 localtime_r(&currtime, &now);
143
144                 printf("%s %04d-%02d-%02d %02d:%02d:%02d\n",
145                        prg,
146                        now.tm_year + 1900,
147                        now.tm_mon + 1,
148                        now.tm_mday,
149                        now.tm_hour,
150                        now.tm_min,
151                        now.tm_sec);
152         }
153
154         for (i=0; i<currmax; i++) {
155
156                 if (color) {
157                         if (i%2)
158                                 printf("%s", FGRED);
159                         else
160                                 printf("%s", FGBLUE);
161                 }
162
163                 if (stat[i].bitrate)
164                         percent = (stat[i].recv_bits_total*100)/stat[i].bitrate;
165                 else
166                         percent = 0;
167
168                 printf(" %*s@%-*d %4d %6d %6d %3d%%",
169                        max_devname_len, stat[i].devname,
170                        max_bitrate_len, stat[i].bitrate,
171                        stat[i].recv_frames,
172                        stat[i].recv_bits_total,
173                        stat[i].recv_bits_payload,
174                        percent);
175
176                 if (bargraph) {
177
178                         printf("  |");
179
180                         if (percent > 100)
181                                 percent = 100;
182
183                         for (j=0; j < NUMBAR; j++){
184                                 if (j < percent/PERCENTRES)
185                                         printf("X");
186                                 else
187                                         printf(".");
188                         }
189             
190                         printf("|");
191                 }
192         
193                 if (color)
194                         printf("%s", ATTRESET);
195
196                 printf("\n");
197
198                 stat[i].recv_frames = 0;
199                 stat[i].recv_bits_total = 0;
200                 stat[i].recv_bits_payload = 0;
201         }
202
203         printf("\n");
204
205         alarm(1);
206 }
207
208 int main(int argc, char **argv)
209 {
210         fd_set rdfs;
211         int s[MAXSOCK];
212
213         int opt;
214         char *ptr, *nptr;
215         struct sockaddr_can addr;
216         struct can_frame frame;
217         int nbytes, i;
218         struct ifreq ifr;
219         sigset_t sigmask, savesigmask;
220
221         signal(SIGTERM, sigterm);
222         signal(SIGHUP, sigterm);
223         signal(SIGINT, sigterm);
224
225         signal(SIGALRM, printstats);
226
227         prg = basename(argv[0]);
228
229         while ((opt = getopt(argc, argv, "rtbcih?")) != -1) {
230                 switch (opt) {
231                 case 'r':
232                         redraw = 1;
233                         break;
234
235                 case 't':
236                         timestamp = 1;
237                         break;
238
239                 case 'b':
240                         bargraph = 1;
241                         break;
242
243                 case 'c':
244                         color = 1;
245                         break;
246
247                 case 'i':
248                         ignore_bitstuffing = 1;
249                         break;
250
251                 default:
252                         print_usage(prg);
253                         exit(1);
254                         break;
255                 }
256         }
257
258         if (optind == argc) {
259                 print_usage(prg);
260                 exit(0);
261         }
262         
263         currmax = argc - optind; /* find real number of CAN devices */
264
265         if (currmax > MAXSOCK) {
266                 printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
267                 return 1;
268         }
269
270         for (i=0; i < currmax; i++) {
271
272                 ptr = argv[optind+i];
273
274                 nbytes = strlen(ptr);
275                 if (nbytes >= IFNAMSIZ+sizeof("@1000000")+1) {
276                         printf("name of CAN device '%s' is too long!\n", ptr);
277                         return 1;
278                 }
279
280 #ifdef DEBUG
281                 printf("open %d '%s'.\n", i, ptr);
282 #endif
283
284                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
285                 if (s[i] < 0) {
286                         perror("socket");
287                         return 1;
288                 }
289
290                 nptr = strchr(ptr, '@');
291
292                 if (!nptr) {
293                         print_usage(prg);
294                         return 1;
295                 }
296
297                 nbytes = nptr - ptr;  /* interface name is up the first '@' */
298
299                 if (nbytes >= IFNAMSIZ) {
300                         printf("name of CAN device '%s' is too long!\n", ptr);
301                         return 1;
302                 }
303
304                 strncpy(stat[i].devname, ptr, nbytes);
305                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
306                 strncpy(ifr.ifr_name, ptr, nbytes);
307
308                 if (nbytes > max_devname_len)
309                         max_devname_len = nbytes; /* for nice printing */
310
311                 stat[i].bitrate = atoi(nptr+1); /* bitrate is placed behind the '@' */
312
313                 if (!stat[i].bitrate || stat[i].bitrate > 1000000) {
314                         printf("invalid bitrate for CAN device '%s'!\n", ptr);
315                         return 1;
316                 }
317
318                 nbytes = strlen(nptr+1);
319                 if (nbytes > max_bitrate_len)
320                         max_bitrate_len = nbytes; /* for nice printing */
321
322
323 #ifdef DEBUG
324                 printf("using interface name '%s'.\n", ifr.ifr_name);
325 #endif
326
327                 if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
328                         perror("SIOCGIFINDEX");
329                         exit(1);
330                 }
331
332                 addr.can_family = AF_CAN;
333                 addr.can_ifindex = ifr.ifr_ifindex;
334
335                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
336                         perror("bind");
337                         return 1;
338                 }
339         }
340
341         alarm(1);
342
343         if (redraw)
344                 printf("%s", CLR_SCREEN);
345
346         while (1) {
347
348                 FD_ZERO(&rdfs);
349                 for (i=0; i<currmax; i++)
350                         FD_SET(s[i], &rdfs);
351
352                 savesigmask = sigmask;
353
354                 if (pselect(s[currmax-1]+1, &rdfs, NULL, NULL, NULL, &sigmask) < 0) {
355                         //perror("pselect");
356                         sigmask = savesigmask;
357                         continue;
358                 }
359
360                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
361
362                         if (FD_ISSET(s[i], &rdfs)) {
363
364                                 nbytes = read(s[i], &frame, sizeof(struct can_frame));
365
366                                 if (nbytes < 0) {
367                                         perror("read");
368                                         return 1;
369                                 }
370
371                                 if (nbytes < sizeof(struct can_frame)) {
372                                         fprintf(stderr, "read: incomplete CAN frame\n");
373                                         return 1;
374                                 }
375
376                                 stat[i].recv_frames++;
377                                 stat[i].recv_bits_payload += frame.can_dlc*8;
378
379                                 /*
380                                  * Following Ken Tindells *worst* case calculation for stuff-bits
381                                  * (see "Guaranteeing Message Latencies on Controller Area Network" 1st ICC'94)
382                                  * the needed bits on the wire can be calculated as:
383                                  *
384                                  * (34 + 8n)/5 + 47 + 8n for SFF frames (11 bit CAN-ID) => (269 + 48n)/5 
385                                  * (54 + 8n)/5 + 67 + 8n for EFF frames (29 bit CAN-ID) => (389 + 48n)/5 
386                                  *
387                                  * while 'n' is the data length code (number of payload bytes)
388                                  *
389                                  */
390
391                                 if (ignore_bitstuffing) {
392                                         /* calculation without bitstuffing */
393                                         if (frame.can_id & CAN_EFF_FLAG)
394                                                 stat[i].recv_bits_total += 67 + frame.can_dlc*8;
395                                         else
396                                                 stat[i].recv_bits_total += 47 + frame.can_dlc*8;
397                                 } else {
398                                         /* needed bits including estimated worst case stuff bits */
399                                         if (frame.can_id & CAN_EFF_FLAG)
400                                                 stat[i].recv_bits_total += (389 + frame.can_dlc*48)/5;
401                                         else
402                                                 stat[i].recv_bits_total += (269 + frame.can_dlc*48)/5;
403                                 }
404                         }
405                 }
406         }
407
408         for (i=0; i<currmax; i++)
409                 close(s[i]);
410
411         return 0;
412 }