Added tiny tool to measure CAN busload.
[profile/ivi/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 char *prg;
92
93 void print_usage(char *prg)
94 {
95     fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
96     fprintf(stderr, "  (use CTRL-C to terminate %s)\n\n", prg);
97     fprintf(stderr, "Options: -t (show current time on the first line)\n");
98     fprintf(stderr, "         -c (colorize lines)\n");
99     fprintf(stderr, "         -b (show bargraph in %d%% resolution)\n", PERCENTRES);
100     fprintf(stderr, "         -r (redraw the terminal - similar to top)\n");
101     fprintf(stderr, "\n");
102     fprintf(stderr, "Up to %d CAN interfaces with mandatory bitrate can be specified on the \n", MAXSOCK);
103     fprintf(stderr, "commandline in the form: <ifname>@<bitrate>\n\n");
104     fprintf(stderr, "The bitrate is mandatory as it is needed to know the CAN bus bitrate to\n");
105     fprintf(stderr, "calcultate the bus load percentage based on the received CAN frames.\n");
106     fprintf(stderr, "For each given interface the data is presented in one line which contains:\n\n");
107     fprintf(stderr, "(interface) (received CAN frames) (used bits total) (used bits for payload)\n");
108     fprintf(stderr, "\nExample:\n");
109     fprintf(stderr, "\nuser$> canbusload can0@100000 can1@500000 can2@500000 can3@500000 -r -t -b -c\n\n");
110     fprintf(stderr, "%s 2008-05-27 15:18:49\n", prg);
111     fprintf(stderr, " can0@100000  805  74491  36656  74%%  |XXXXXXXXXXXXXX......|\n");
112     fprintf(stderr, " can1@500000  796  75140  37728  15%%  |XXX.................|\n");
113     fprintf(stderr, " can2@500000    0      0      0   0%%  |....................|\n");
114     fprintf(stderr, " can3@500000   47   4633   2424   0%%  |....................|\n");
115     fprintf(stderr, "\n");
116 }
117
118 void sigterm(int signo)
119 {
120     exit(0);
121 }
122
123 void printstats(int signo)
124 {
125     int i, j, percent;
126
127     if (redraw)
128         printf("%s", CSR_HOME);
129
130     if (timestamp) {
131         time_t currtime;
132         struct tm now;
133
134         if (time(&currtime) == (time_t)-1) {
135             perror("time");
136             exit(1);
137         }
138
139         localtime_r(&currtime, &now);
140
141         printf("%s %04d-%02d-%02d %02d:%02d:%02d\n",
142                prg,
143                now.tm_year + 1900,
144                now.tm_mon + 1,
145                now.tm_mday,
146                now.tm_hour,
147                now.tm_min,
148                now.tm_sec);
149     }
150
151     for (i=0; i<currmax; i++) {
152
153         if (color)
154             if (i%2)
155                 printf("%s", FGRED);
156             else
157                 printf("%s", FGBLUE);
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 %4d %6d %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             for (j=0; j < NUMBAR; j++){
177                 if (j < percent/PERCENTRES)
178                     printf("X");
179                 else
180                     printf(".");
181             }
182             
183             printf("|");
184         }
185         
186         if (color)
187             printf("%s", ATTRESET);
188
189         printf("\n");
190
191         stat[i].recv_frames = 0;
192         stat[i].recv_bits_total = 0;
193         stat[i].recv_bits_payload = 0;
194     }
195
196     printf("\n");
197
198     alarm(1);
199 }
200
201 int main(int argc, char **argv)
202 {
203     fd_set rdfs;
204     int s[MAXSOCK];
205
206     int opt;
207     char *ptr, *nptr;
208     struct sockaddr_can addr;
209     struct can_frame frame;
210     int nbytes, i;
211     struct ifreq ifr;
212     sigset_t sigmask, savesigmask;
213
214     signal(SIGTERM, sigterm);
215     signal(SIGHUP, sigterm);
216     signal(SIGINT, sigterm);
217
218     signal(SIGALRM, printstats);
219
220     prg = basename(argv[0]);
221
222     while ((opt = getopt(argc, argv, "rtbch?")) != -1) {
223         switch (opt) {
224         case 'r':
225             redraw = 1;
226             break;
227
228         case 't':
229             timestamp = 1;
230             break;
231
232         case 'b':
233             bargraph = 1;
234             break;
235
236         case 'c':
237             color = 1;
238             break;
239
240         default:
241             print_usage(prg);
242             exit(1);
243             break;
244         }
245     }
246
247     if (optind == argc) {
248         print_usage(prg);
249         exit(0);
250     }
251         
252     currmax = argc - optind; /* find real number of CAN devices */
253
254     if (currmax > MAXSOCK) {
255         printf("More than %d CAN devices given on commandline!\n", MAXSOCK);
256         return 1;
257     }
258
259     for (i=0; i < currmax; i++) {
260
261         ptr = argv[optind+i];
262
263         nbytes = strlen(ptr);
264         if (nbytes >= IFNAMSIZ+sizeof("@1000000")+1) {
265             printf("name of CAN device '%s' is too long!\n", ptr);
266             return 1;
267         }
268
269 #ifdef DEBUG
270         printf("open %d '%s'.\n", i, ptr);
271 #endif
272
273         s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
274         if (s[i] < 0) {
275             perror("socket");
276             return 1;
277         }
278
279         nptr = strchr(ptr, '@');
280
281         if (!nptr) {
282             print_usage(prg);
283             return 1;
284         }
285
286         nbytes = nptr - ptr;  /* interface name is up the first '@' */
287
288         if (nbytes >= IFNAMSIZ) {
289             printf("name of CAN device '%s' is too long!\n", ptr);
290             return 1;
291         }
292
293         strncpy(stat[i].devname, ptr, nbytes);
294         memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
295         strncpy(ifr.ifr_name, ptr, nbytes);
296
297         if (nbytes > max_devname_len)
298             max_devname_len = nbytes; /* for nice printing */
299
300         stat[i].bitrate = atoi(nptr+1); /* bitrate is placed behind the '@' */
301
302         if (!stat[i].bitrate || stat[i].bitrate > 1000000) {
303             printf("invalid bitrate for CAN device '%s'!\n", ptr);
304             return 1;
305         }
306
307         nbytes = strlen(nptr+1);
308         if (nbytes > max_bitrate_len)
309             max_bitrate_len = nbytes; /* for nice printing */
310
311
312 #ifdef DEBUG
313         printf("using interface name '%s'.\n", ifr.ifr_name);
314 #endif
315
316         if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
317             perror("SIOCGIFINDEX");
318             exit(1);
319         }
320
321         addr.can_family = AF_CAN;
322         addr.can_ifindex = ifr.ifr_ifindex;
323
324         if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
325             perror("bind");
326             return 1;
327         }
328     }
329
330     alarm(1);
331
332     if (redraw)
333         printf("%s", CLR_SCREEN);
334
335     while (1) {
336
337         FD_ZERO(&rdfs);
338         for (i=0; i<currmax; i++)
339             FD_SET(s[i], &rdfs);
340
341         savesigmask = sigmask;
342
343         if (pselect(s[currmax-1]+1, &rdfs, NULL, NULL, NULL, &sigmask) < 0) {
344             //perror("pselect");
345             sigmask = savesigmask;
346             continue;
347         }
348
349         for (i=0; i<currmax; i++) {  /* check all CAN RAW sockets */
350
351             if (FD_ISSET(s[i], &rdfs)) {
352
353                 nbytes = read(s[i], &frame, sizeof(struct can_frame));
354
355                 if (nbytes < 0) {
356                     perror("read");
357                     return 1;
358                 }
359
360                 if (nbytes < sizeof(struct can_frame)) {
361                     fprintf(stderr, "read: incomplete CAN frame\n");
362                     return 1;
363                 }
364
365                 stat[i].recv_frames++;
366                 stat[i].recv_bits_payload += frame.can_dlc*8;
367                 stat[i].recv_bits_total += frame.can_dlc*8;
368                 if (frame.can_id & CAN_EFF_FLAG)
369                     stat[i].recv_bits_total += 67;
370                 else
371                     stat[i].recv_bits_total += 47;
372             }
373         }
374     }
375
376     for (i=0; i<currmax; i++)
377         close(s[i]);
378
379     return 0;
380 }