iio: iio_generic_buffer: Cleanup when receiving signals
[linux-2.6-block.git] / tools / iio / iio_generic_buffer.c
1 /* Industrialio buffer test code.
2  *
3  * Copyright (c) 2008 Jonathan Cameron
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published by
7  * the Free Software Foundation.
8  *
9  * This program is primarily intended as an example application.
10  * Reads the current buffer setup from sysfs and starts a short capture
11  * from the specified device, pretty printing the result after appropriate
12  * conversion.
13  *
14  * Command line parameters
15  * generic_buffer -n <device_name> -t <trigger_name>
16  * If trigger name is not specified the program assumes you want a dataready
17  * trigger associated with the device and goes looking for it.
18  *
19  */
20
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <dirent.h>
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <errno.h>
27 #include <sys/stat.h>
28 #include <sys/dir.h>
29 #include <linux/types.h>
30 #include <string.h>
31 #include <poll.h>
32 #include <endian.h>
33 #include <getopt.h>
34 #include <inttypes.h>
35 #include <stdbool.h>
36 #include <signal.h>
37 #include "iio_utils.h"
38
39 /**
40  * enum autochan - state for the automatic channel enabling mechanism
41  */
42 enum autochan {
43         AUTOCHANNELS_DISABLED,
44         AUTOCHANNELS_ENABLED,
45         AUTOCHANNELS_ACTIVE,
46 };
47
48 /**
49  * size_from_channelarray() - calculate the storage size of a scan
50  * @channels:           the channel info array
51  * @num_channels:       number of channels
52  *
53  * Has the side effect of filling the channels[i].location values used
54  * in processing the buffer output.
55  **/
56 int size_from_channelarray(struct iio_channel_info *channels, int num_channels)
57 {
58         int bytes = 0;
59         int i = 0;
60
61         while (i < num_channels) {
62                 if (bytes % channels[i].bytes == 0)
63                         channels[i].location = bytes;
64                 else
65                         channels[i].location = bytes - bytes % channels[i].bytes
66                                                + channels[i].bytes;
67
68                 bytes = channels[i].location + channels[i].bytes;
69                 i++;
70         }
71
72         return bytes;
73 }
74
75 void print1byte(uint8_t input, struct iio_channel_info *info)
76 {
77         /*
78          * Shift before conversion to avoid sign extension
79          * of left aligned data
80          */
81         input >>= info->shift;
82         input &= info->mask;
83         if (info->is_signed) {
84                 int8_t val = (int8_t)(input << (8 - info->bits_used)) >>
85                              (8 - info->bits_used);
86                 printf("%05f ", ((float)val + info->offset) * info->scale);
87         } else {
88                 printf("%05f ", ((float)input + info->offset) * info->scale);
89         }
90 }
91
92 void print2byte(uint16_t input, struct iio_channel_info *info)
93 {
94         /* First swap if incorrect endian */
95         if (info->be)
96                 input = be16toh(input);
97         else
98                 input = le16toh(input);
99
100         /*
101          * Shift before conversion to avoid sign extension
102          * of left aligned data
103          */
104         input >>= info->shift;
105         input &= info->mask;
106         if (info->is_signed) {
107                 int16_t val = (int16_t)(input << (16 - info->bits_used)) >>
108                               (16 - info->bits_used);
109                 printf("%05f ", ((float)val + info->offset) * info->scale);
110         } else {
111                 printf("%05f ", ((float)input + info->offset) * info->scale);
112         }
113 }
114
115 void print4byte(uint32_t input, struct iio_channel_info *info)
116 {
117         /* First swap if incorrect endian */
118         if (info->be)
119                 input = be32toh(input);
120         else
121                 input = le32toh(input);
122
123         /*
124          * Shift before conversion to avoid sign extension
125          * of left aligned data
126          */
127         input >>= info->shift;
128         input &= info->mask;
129         if (info->is_signed) {
130                 int32_t val = (int32_t)(input << (32 - info->bits_used)) >>
131                               (32 - info->bits_used);
132                 printf("%05f ", ((float)val + info->offset) * info->scale);
133         } else {
134                 printf("%05f ", ((float)input + info->offset) * info->scale);
135         }
136 }
137
138 void print8byte(uint64_t input, struct iio_channel_info *info)
139 {
140         /* First swap if incorrect endian */
141         if (info->be)
142                 input = be64toh(input);
143         else
144                 input = le64toh(input);
145
146         /*
147          * Shift before conversion to avoid sign extension
148          * of left aligned data
149          */
150         input >>= info->shift;
151         input &= info->mask;
152         if (info->is_signed) {
153                 int64_t val = (int64_t)(input << (64 - info->bits_used)) >>
154                               (64 - info->bits_used);
155                 /* special case for timestamp */
156                 if (info->scale == 1.0f && info->offset == 0.0f)
157                         printf("%" PRId64 " ", val);
158                 else
159                         printf("%05f ",
160                                ((float)val + info->offset) * info->scale);
161         } else {
162                 printf("%05f ", ((float)input + info->offset) * info->scale);
163         }
164 }
165
166 /**
167  * process_scan() - print out the values in SI units
168  * @data:               pointer to the start of the scan
169  * @channels:           information about the channels.
170  *                      Note: size_from_channelarray must have been called first
171  *                            to fill the location offsets.
172  * @num_channels:       number of channels
173  **/
174 void process_scan(char *data,
175                   struct iio_channel_info *channels,
176                   int num_channels)
177 {
178         int k;
179
180         for (k = 0; k < num_channels; k++)
181                 switch (channels[k].bytes) {
182                         /* only a few cases implemented so far */
183                 case 1:
184                         print1byte(*(uint8_t *)(data + channels[k].location),
185                                    &channels[k]);
186                         break;
187                 case 2:
188                         print2byte(*(uint16_t *)(data + channels[k].location),
189                                    &channels[k]);
190                         break;
191                 case 4:
192                         print4byte(*(uint32_t *)(data + channels[k].location),
193                                    &channels[k]);
194                         break;
195                 case 8:
196                         print8byte(*(uint64_t *)(data + channels[k].location),
197                                    &channels[k]);
198                         break;
199                 default:
200                         break;
201                 }
202         printf("\n");
203 }
204
205 static int enable_disable_all_channels(char *dev_dir_name, int enable)
206 {
207         const struct dirent *ent;
208         char scanelemdir[256];
209         DIR *dp;
210         int ret;
211
212         snprintf(scanelemdir, sizeof(scanelemdir),
213                  FORMAT_SCAN_ELEMENTS_DIR, dev_dir_name);
214         scanelemdir[sizeof(scanelemdir)-1] = '\0';
215
216         dp = opendir(scanelemdir);
217         if (!dp) {
218                 fprintf(stderr, "Enabling/disabling channels: can't open %s\n",
219                         scanelemdir);
220                 return -EIO;
221         }
222
223         ret = -ENOENT;
224         while (ent = readdir(dp), ent) {
225                 if (iioutils_check_suffix(ent->d_name, "_en")) {
226                         printf("%sabling: %s\n",
227                                enable ? "En" : "Dis",
228                                ent->d_name);
229                         ret = write_sysfs_int(ent->d_name, scanelemdir,
230                                               enable);
231                         if (ret < 0)
232                                 fprintf(stderr, "Failed to enable/disable %s\n",
233                                         ent->d_name);
234                 }
235         }
236
237         if (closedir(dp) == -1) {
238                 perror("Enabling/disabling channels: "
239                        "Failed to close directory");
240                 return -errno;
241         }
242         return 0;
243 }
244
245 void print_usage(void)
246 {
247         fprintf(stderr, "Usage: generic_buffer [options]...\n"
248                 "Capture, convert and output data from IIO device buffer\n"
249                 "  -a         Auto-activate all available channels\n"
250                 "  -c <n>     Do n conversions\n"
251                 "  -e         Disable wait for event (new data)\n"
252                 "  -g         Use trigger-less mode\n"
253                 "  -l <n>     Set buffer length to n samples\n"
254                 "  -n <name>  Set device name (mandatory)\n"
255                 "  -t <name>  Set trigger name\n"
256                 "  -w <n>     Set delay between reads in us (event-less mode)\n");
257 }
258
259 enum autochan autochannels = AUTOCHANNELS_DISABLED;
260 char *dev_dir_name = NULL;
261 char *buf_dir_name = NULL;
262 bool current_trigger_set = false;
263
264 void cleanup(void)
265 {
266         int ret;
267
268         /* Disable trigger */
269         if (dev_dir_name && current_trigger_set) {
270                 /* Disconnect the trigger - just write a dummy name. */
271                 ret = write_sysfs_string("trigger/current_trigger",
272                                          dev_dir_name, "NULL");
273                 if (ret < 0)
274                         fprintf(stderr, "Failed to disable trigger: %s\n",
275                                 strerror(-ret));
276                 current_trigger_set = false;
277         }
278
279         /* Disable buffer */
280         if (buf_dir_name) {
281                 ret = write_sysfs_int("enable", buf_dir_name, 0);
282                 if (ret < 0)
283                         fprintf(stderr, "Failed to disable buffer: %s\n",
284                                 strerror(-ret));
285         }
286
287         /* Disable channels if auto-enabled */
288         if (dev_dir_name && autochannels == AUTOCHANNELS_ACTIVE) {
289                 ret = enable_disable_all_channels(dev_dir_name, 0);
290                 if (ret)
291                         fprintf(stderr, "Failed to disable all channels\n");
292                 autochannels = AUTOCHANNELS_DISABLED;
293         }
294 }
295
296 void sig_handler(int signum)
297 {
298         fprintf(stderr, "Caught signal %d\n", signum);
299         cleanup();
300         exit(-signum);
301 }
302
303 void register_cleanup(void)
304 {
305         struct sigaction sa = { .sa_handler = sig_handler };
306         const int signums[] = { SIGINT, SIGTERM, SIGABRT };
307         int ret, i;
308
309         for (i = 0; i < ARRAY_SIZE(signums); ++i) {
310                 ret = sigaction(signums[i], &sa, NULL);
311                 if (ret) {
312                         perror("Failed to register signal handler");
313                         exit(-1);
314                 }
315         }
316 }
317
318 int main(int argc, char **argv)
319 {
320         unsigned long num_loops = 2;
321         unsigned long timedelay = 1000000;
322         unsigned long buf_len = 128;
323
324         int ret, c, i, j, toread;
325         int fp = -1;
326
327         int num_channels = 0;
328         char *trigger_name = NULL, *device_name = NULL;
329
330         char *data = NULL;
331         ssize_t read_size;
332         int dev_num, trig_num;
333         char *buffer_access = NULL;
334         int scan_size;
335         int noevents = 0;
336         int notrigger = 0;
337         char *dummy;
338
339         struct iio_channel_info *channels;
340
341         register_cleanup();
342
343         while ((c = getopt(argc, argv, "ac:egl:n:t:w:")) != -1) {
344                 switch (c) {
345                 case 'a':
346                         autochannels = AUTOCHANNELS_ENABLED;
347                         break;
348                 case 'c':
349                         errno = 0;
350                         num_loops = strtoul(optarg, &dummy, 10);
351                         if (errno) {
352                                 ret = -errno;
353                                 goto error;
354                         }
355
356                         break;
357                 case 'e':
358                         noevents = 1;
359                         break;
360                 case 'g':
361                         notrigger = 1;
362                         break;
363                 case 'l':
364                         errno = 0;
365                         buf_len = strtoul(optarg, &dummy, 10);
366                         if (errno) {
367                                 ret = -errno;
368                                 goto error;
369                         }
370
371                         break;
372                 case 'n':
373                         device_name = optarg;
374                         break;
375                 case 't':
376                         trigger_name = strdup(optarg);
377                         break;
378                 case 'w':
379                         errno = 0;
380                         timedelay = strtoul(optarg, &dummy, 10);
381                         if (errno) {
382                                 ret = -errno;
383                                 goto error;
384                         }
385                         break;
386                 case '?':
387                         print_usage();
388                         ret = -1;
389                         goto error;
390                 }
391         }
392
393         if (!device_name) {
394                 fprintf(stderr, "Device name not set\n");
395                 print_usage();
396                 return -1;
397         }
398
399         /* Find the device requested */
400         dev_num = find_type_by_name(device_name, "iio:device");
401         if (dev_num < 0) {
402                 fprintf(stderr, "Failed to find the %s\n", device_name);
403                 ret = dev_num;
404                 goto error;
405         }
406
407         printf("iio device number being used is %d\n", dev_num);
408
409         ret = asprintf(&dev_dir_name, "%siio:device%d", iio_dir, dev_num);
410         if (ret < 0) {
411                 ret = -ENOMEM;
412                 goto error;
413         }
414
415         if (!notrigger) {
416                 if (!trigger_name) {
417                         /*
418                          * Build the trigger name. If it is device associated
419                          * its name is <device_name>_dev[n] where n matches
420                          * the device number found above.
421                          */
422                         ret = asprintf(&trigger_name,
423                                        "%s-dev%d", device_name, dev_num);
424                         if (ret < 0) {
425                                 ret = -ENOMEM;
426                                 goto error;
427                         }
428                 }
429
430                 /* Look for this "-devN" trigger */
431                 trig_num = find_type_by_name(trigger_name, "trigger");
432                 if (trig_num < 0) {
433                         /* OK try the simpler "-trigger" suffix instead */
434                         free(trigger_name);
435                         ret = asprintf(&trigger_name,
436                                        "%s-trigger", device_name);
437                         if (ret < 0) {
438                                 ret = -ENOMEM;
439                                 goto error;
440                         }
441                 }
442
443                 trig_num = find_type_by_name(trigger_name, "trigger");
444                 if (trig_num < 0) {
445                         fprintf(stderr, "Failed to find the trigger %s\n",
446                                 trigger_name);
447                         ret = trig_num;
448                         goto error;
449                 }
450
451                 printf("iio trigger number being used is %d\n", trig_num);
452         } else {
453                 printf("trigger-less mode selected\n");
454         }
455
456         /*
457          * Parse the files in scan_elements to identify what channels are
458          * present
459          */
460         ret = build_channel_array(dev_dir_name, &channels, &num_channels);
461         if (ret) {
462                 fprintf(stderr, "Problem reading scan element information\n"
463                         "diag %s\n", dev_dir_name);
464                 goto error;
465         }
466         if (num_channels && autochannels == AUTOCHANNELS_ENABLED) {
467                 fprintf(stderr, "Auto-channels selected but some channels "
468                         "are already activated in sysfs\n");
469                 fprintf(stderr, "Proceeding without activating any channels\n");
470         }
471
472         if (!num_channels && autochannels == AUTOCHANNELS_ENABLED) {
473                 fprintf(stderr,
474                         "No channels are enabled, enabling all channels\n");
475
476                 ret = enable_disable_all_channels(dev_dir_name, 1);
477                 if (ret) {
478                         fprintf(stderr, "Failed to enable all channels\n");
479                         goto error;
480                 }
481
482                 /* This flags that we need to disable the channels again */
483                 autochannels = AUTOCHANNELS_ACTIVE;
484
485                 ret = build_channel_array(dev_dir_name, &channels,
486                                           &num_channels);
487                 if (ret) {
488                         fprintf(stderr, "Problem reading scan element "
489                                 "information\n"
490                                 "diag %s\n", dev_dir_name);
491                         goto error;
492                 }
493                 if (!num_channels) {
494                         fprintf(stderr, "Still no channels after "
495                                 "auto-enabling, giving up\n");
496                         goto error;
497                 }
498         }
499
500         if (!num_channels && autochannels == AUTOCHANNELS_DISABLED) {
501                 fprintf(stderr,
502                         "No channels are enabled, we have nothing to scan.\n");
503                 fprintf(stderr, "Enable channels manually in "
504                         FORMAT_SCAN_ELEMENTS_DIR
505                         "/*_en or pass -a to autoenable channels and "
506                         "try again.\n", dev_dir_name);
507                 ret = -ENOENT;
508                 goto error;
509         }
510
511         /*
512          * Construct the directory name for the associated buffer.
513          * As we know that the lis3l02dq has only one buffer this may
514          * be built rather than found.
515          */
516         ret = asprintf(&buf_dir_name,
517                        "%siio:device%d/buffer", iio_dir, dev_num);
518         if (ret < 0) {
519                 ret = -ENOMEM;
520                 goto error;
521         }
522
523         if (!notrigger) {
524                 printf("%s %s\n", dev_dir_name, trigger_name);
525                 /*
526                  * Set the device trigger to be the data ready trigger found
527                  * above
528                  */
529                 ret = write_sysfs_string_and_verify("trigger/current_trigger",
530                                                     dev_dir_name,
531                                                     trigger_name);
532                 if (ret < 0) {
533                         fprintf(stderr,
534                                 "Failed to write current_trigger file\n");
535                         goto error;
536                 }
537         }
538
539         /* Setup ring buffer parameters */
540         ret = write_sysfs_int("length", buf_dir_name, buf_len);
541         if (ret < 0)
542                 goto error;
543
544         /* Enable the buffer */
545         ret = write_sysfs_int("enable", buf_dir_name, 1);
546         if (ret < 0) {
547                 fprintf(stderr,
548                         "Failed to enable buffer: %s\n", strerror(-ret));
549                 goto error;
550         }
551
552         scan_size = size_from_channelarray(channels, num_channels);
553         data = malloc(scan_size * buf_len);
554         if (!data) {
555                 ret = -ENOMEM;
556                 goto error;
557         }
558
559         ret = asprintf(&buffer_access, "/dev/iio:device%d", dev_num);
560         if (ret < 0) {
561                 ret = -ENOMEM;
562                 goto error;
563         }
564
565         /* Attempt to open non blocking the access dev */
566         fp = open(buffer_access, O_RDONLY | O_NONBLOCK);
567         if (fp == -1) { /* TODO: If it isn't there make the node */
568                 ret = -errno;
569                 fprintf(stderr, "Failed to open %s\n", buffer_access);
570                 goto error;
571         }
572
573         for (j = 0; j < num_loops; j++) {
574                 if (!noevents) {
575                         struct pollfd pfd = {
576                                 .fd = fp,
577                                 .events = POLLIN,
578                         };
579
580                         ret = poll(&pfd, 1, -1);
581                         if (ret < 0) {
582                                 ret = -errno;
583                                 goto error;
584                         } else if (ret == 0) {
585                                 continue;
586                         }
587
588                         toread = buf_len;
589                 } else {
590                         usleep(timedelay);
591                         toread = 64;
592                 }
593
594                 read_size = read(fp, data, toread * scan_size);
595                 if (read_size < 0) {
596                         if (errno == EAGAIN) {
597                                 fprintf(stderr, "nothing available\n");
598                                 continue;
599                         } else {
600                                 break;
601                         }
602                 }
603                 for (i = 0; i < read_size / scan_size; i++)
604                         process_scan(data + scan_size * i, channels,
605                                      num_channels);
606         }
607
608 error:
609         cleanup();
610
611         if (fp >= 0 && close(fp) == -1)
612                 perror("Failed to close buffer");
613         free(buffer_access);
614         free(data);
615         free(buf_dir_name);
616         for (i = num_channels - 1; i >= 0; i--) {
617                 free(channels[i].name);
618                 free(channels[i].generic_name);
619         }
620         free(channels);
621         free(trigger_name);
622         free(dev_dir_name);
623
624         return ret;
625 }