]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - canbusload.c
can-utils: AOSP build clean up
[sojka/can-utils.git] / canbusload.c
1 /*
2  * canbusload.c
3  *
4  * Copyright (c) 2002-2008 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of Volkswagen nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * Alternatively, provided that this notice is retained in full, this
20  * software may be distributed under the terms of the GNU General
21  * Public License ("GPL") version 2, in which case the provisions of the
22  * GPL apply INSTEAD OF those given above.
23  *
24  * The provided data structures and external interfaces from this code
25  * are not restricted to be used by modules with a GPL compatible license.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  *
40  * Send feedback to <linux-can@vger.kernel.org>
41  *
42  */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <unistd.h>
47 #include <string.h>
48 #include <signal.h>
49 #include <ctype.h>
50 #include <libgen.h>
51 #include <time.h>
52
53 #include <sys/time.h>
54 #include <sys/types.h>
55 #include <sys/socket.h>
56 #include <sys/ioctl.h>
57 #include <sys/uio.h>
58 #include <net/if.h>
59
60 #include <linux/can.h>
61 #include <linux/can/raw.h>
62
63 #include "terminal.h"
64
65 #define MAXSOCK 16    /* max. number of CAN interfaces given on the cmdline */
66
67 #define PERCENTRES 5 /* resolution in percent for bargraph */
68 #define NUMBAR (100/PERCENTRES) /* number of bargraph elements */
69
70 extern int optind, opterr, optopt;
71
72 static struct {
73         char devname[IFNAMSIZ+1];
74         unsigned int bitrate;
75         unsigned int recv_frames;
76         unsigned int recv_bits_total;
77         unsigned int recv_bits_payload;
78 } stat[MAXSOCK+1];
79
80 static int  max_devname_len; /* to prevent frazzled device name output */ 
81 static int  max_bitrate_len;
82 static int  currmax;
83 static unsigned char redraw;
84 static unsigned char timestamp;
85 static unsigned char color;
86 static unsigned char bargraph;
87 static unsigned char ignore_bitstuffing;
88 static char *prg;
89
90 void print_usage(char *prg)
91 {
92         fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
93         fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
94         fprintf(stderr, "Options: -t (show current time on the first line)\n");
95         fprintf(stderr, "         -c (colorize lines)\n");
96         fprintf(stderr, "         -b (show bargraph in %d%% resolution)\n", PERCENTRES);
97         fprintf(stderr, "         -r (redraw the terminal - similar to top)\n");
98         fprintf(stderr, "         -i (ignore bitstuffing estimation in bandwith calculation)\n");
99         fprintf(stderr, "\n");
100         fprintf(stderr, "Up to %d CAN interfaces with mandatory bitrate can be specified on the \n", MAXSOCK);
101         fprintf(stderr, "commandline in the form: <ifname>@<bitrate>\n\n");
102         fprintf(stderr, "The bitrate is mandatory as it is needed to know the CAN bus bitrate to\n");
103         fprintf(stderr, "calcultate the bus load percentage based on the received CAN frames.\n");
104         fprintf(stderr, "Due to the bitstuffing estimation the calculated busload may exceed 100%%.\n");
105         fprintf(stderr, "For each given interface the data is presented in one line which contains:\n\n");
106         fprintf(stderr, "(interface) (received CAN frames) (used bits total) (used bits for payload)\n");
107         fprintf(stderr, "\nExample:\n");
108         fprintf(stderr, "\nuser$> canbusload can0@100000 can1@500000 can2@500000 can3@500000 -r -t -b -c\n\n");
109         fprintf(stderr, "%s 2008-05-27 15:18:49\n", prg);
110         fprintf(stderr, " can0@100000   805   74491  36656  74%% |XXXXXXXXXXXXXX......|\n");
111         fprintf(stderr, " can1@500000   796   75140  37728  15%% |XXX.................|\n");
112         fprintf(stderr, " can2@500000     0       0      0   0%% |....................|\n");
113         fprintf(stderr, " can3@500000    47    4633   2424   0%% |....................|\n");
114         fprintf(stderr, "\n");
115 }
116
117 void sigterm(int signo)
118 {
119         exit(0);
120 }
121
122 void printstats(int signo)
123 {
124         int i, j, percent;
125
126         if (redraw)
127                 printf("%s", CSR_HOME);
128
129         if (timestamp) {
130                 time_t currtime;
131                 struct tm now;
132
133                 if (time(&currtime) == (time_t)-1) {
134                         perror("time");
135                         exit(1);
136                 }
137
138                 localtime_r(&currtime, &now);
139
140                 printf("%s %04d-%02d-%02d %02d:%02d:%02d\n",
141                        prg,
142                        now.tm_year + 1900,
143                        now.tm_mon + 1,
144                        now.tm_mday,
145                        now.tm_hour,
146                        now.tm_min,
147                        now.tm_sec);
148         }
149
150         for (i=0; i<currmax; i++) {
151
152                 if (color) {
153                         if (i%2)
154                                 printf("%s", FGRED);
155                         else
156                                 printf("%s", FGBLUE);
157                 }
158
159                 if (stat[i].bitrate)
160                         percent = (stat[i].recv_bits_total*100)/stat[i].bitrate;
161                 else
162                         percent = 0;
163
164                 printf(" %*s@%-*d %5d %7d %6d %3d%%",
165                        max_devname_len, stat[i].devname,
166                        max_bitrate_len, stat[i].bitrate,
167                        stat[i].recv_frames,
168                        stat[i].recv_bits_total,
169                        stat[i].recv_bits_payload,
170                        percent);
171
172                 if (bargraph) {
173
174                         printf(" |");
175
176                         if (percent > 100)
177                                 percent = 100;
178
179                         for (j=0; j < NUMBAR; j++){
180                                 if (j < percent/PERCENTRES)
181                                         printf("X");
182                                 else
183                                         printf(".");
184                         }
185             
186                         printf("|");
187                 }
188         
189                 if (color)
190                         printf("%s", ATTRESET);
191
192                 printf("\n");
193
194                 stat[i].recv_frames = 0;
195                 stat[i].recv_bits_total = 0;
196                 stat[i].recv_bits_payload = 0;
197         }
198
199         printf("\n");
200         fflush(stdout);
201
202         alarm(1);
203 }
204
205 int main(int argc, char **argv)
206 {
207         fd_set rdfs;
208         int s[MAXSOCK];
209
210         int opt;
211         char *ptr, *nptr;
212         struct sockaddr_can addr;
213         struct can_frame frame;
214         int nbytes, i;
215         struct ifreq ifr;
216         sigset_t sigmask, savesigmask;
217
218         signal(SIGTERM, sigterm);
219         signal(SIGHUP, sigterm);
220         signal(SIGINT, sigterm);
221
222         signal(SIGALRM, printstats);
223
224         prg = basename(argv[0]);
225
226         while ((opt = getopt(argc, argv, "rtbcih?")) != -1) {
227                 switch (opt) {
228                 case 'r':
229                         redraw = 1;
230                         break;
231
232                 case 't':
233                         timestamp = 1;
234                         break;
235
236                 case 'b':
237                         bargraph = 1;
238                         break;
239
240                 case 'c':
241                         color = 1;
242                         break;
243
244                 case 'i':
245                         ignore_bitstuffing = 1;
246                         break;
247
248                 default:
249                         print_usage(prg);
250                         exit(1);
251                         break;
252                 }
253         }
254
255         if (optind == argc) {
256                 print_usage(prg);
257                 exit(0);
258         }
259         
260         currmax = argc - optind; /* find real number of CAN devices */
261
262         if (currmax > MAXSOCK) {
263                 printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
264                 return 1;
265         }
266
267         for (i=0; i < currmax; i++) {
268
269                 ptr = argv[optind+i];
270
271                 nbytes = strlen(ptr);
272                 if (nbytes >= IFNAMSIZ+sizeof("@1000000")+1) {
273                         printf("name of CAN device '%s' is too long!\n", ptr);
274                         return 1;
275                 }
276
277 #ifdef DEBUG
278                 printf("open %d '%s'.\n", i, ptr);
279 #endif
280
281                 s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
282                 if (s[i] < 0) {
283                         perror("socket");
284                         return 1;
285                 }
286
287                 nptr = strchr(ptr, '@');
288
289                 if (!nptr) {
290                         print_usage(prg);
291                         return 1;
292                 }
293
294                 nbytes = nptr - ptr;  /* interface name is up the first '@' */
295
296                 if (nbytes >= IFNAMSIZ) {
297                         printf("name of CAN device '%s' is too long!\n", ptr);
298                         return 1;
299                 }
300
301                 strncpy(stat[i].devname, ptr, nbytes);
302                 memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
303                 strncpy(ifr.ifr_name, ptr, nbytes);
304
305                 if (nbytes > max_devname_len)
306                         max_devname_len = nbytes; /* for nice printing */
307
308                 stat[i].bitrate = atoi(nptr+1); /* bitrate is placed behind the '@' */
309
310                 if (!stat[i].bitrate || stat[i].bitrate > 1000000) {
311                         printf("invalid bitrate for CAN device '%s'!\n", ptr);
312                         return 1;
313                 }
314
315                 nbytes = strlen(nptr+1);
316                 if (nbytes > max_bitrate_len)
317                         max_bitrate_len = nbytes; /* for nice printing */
318
319
320 #ifdef DEBUG
321                 printf("using interface name '%s'.\n", ifr.ifr_name);
322 #endif
323
324                 if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
325                         perror("SIOCGIFINDEX");
326                         exit(1);
327                 }
328
329                 addr.can_family = AF_CAN;
330                 addr.can_ifindex = ifr.ifr_ifindex;
331
332                 if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
333                         perror("bind");
334                         return 1;
335                 }
336         }
337
338         alarm(1);
339
340         if (redraw)
341                 printf("%s", CLR_SCREEN);
342
343         while (1) {
344
345                 FD_ZERO(&rdfs);
346                 for (i=0; i<currmax; i++)
347                         FD_SET(s[i], &rdfs);
348
349                 savesigmask = sigmask;
350
351                 if (pselect(s[currmax-1]+1, &rdfs, NULL, NULL, NULL, &sigmask) < 0) {
352                         //perror("pselect");
353                         sigmask = savesigmask;
354                         continue;
355                 }
356
357                 for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
358
359                         if (FD_ISSET(s[i], &rdfs)) {
360
361                                 nbytes = read(s[i], &frame, sizeof(struct can_frame));
362
363                                 if (nbytes < 0) {
364                                         perror("read");
365                                         return 1;
366                                 }
367
368                                 if (nbytes < sizeof(struct can_frame)) {
369                                         fprintf(stderr, "read: incomplete CAN frame\n");
370                                         return 1;
371                                 }
372
373                                 stat[i].recv_frames++;
374                                 stat[i].recv_bits_payload += frame.can_dlc*8;
375
376                                 /*
377                                  * Following Ken Tindells *worst* case calculation for stuff-bits
378                                  * (see "Guaranteeing Message Latencies on Controller Area Network" 1st ICC'94)
379                                  * the needed bits on the wire can be calculated as:
380                                  *
381                                  * (34 + 8n)/5 + 47 + 8n for SFF frames (11 bit CAN-ID) => (269 + 48n)/5 
382                                  * (54 + 8n)/5 + 67 + 8n for EFF frames (29 bit CAN-ID) => (389 + 48n)/5 
383                                  *
384                                  * while 'n' is the data length code (number of payload bytes)
385                                  *
386                                  */
387
388                                 if (ignore_bitstuffing) {
389                                         /* calculation without bitstuffing */
390                                         if (frame.can_id & CAN_EFF_FLAG)
391                                                 stat[i].recv_bits_total += 67 + frame.can_dlc*8;
392                                         else
393                                                 stat[i].recv_bits_total += 47 + frame.can_dlc*8;
394                                 } else {
395                                         /* needed bits including estimated worst case stuff bits */
396                                         if (frame.can_id & CAN_EFF_FLAG)
397                                                 stat[i].recv_bits_total += (389 + frame.can_dlc*48)/5;
398                                         else
399                                                 stat[i].recv_bits_total += (269 + frame.can_dlc*48)/5;
400                                 }
401                         }
402                 }
403         }
404
405         for (i=0; i<currmax; i++)
406                 close(s[i]);
407
408         return 0;
409 }