1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Industrialio buffer test code.
4 * Copyright (c) 2008 Jonathan Cameron
6 * This program is primarily intended as an example application.
7 * Reads the current buffer setup from sysfs and starts a short capture
8 * from the specified device, pretty printing the result after appropriate
11 * Command line parameters
12 * generic_buffer -n <device_name> -t <trigger_name>
13 * If trigger name is not specified the program assumes you want a dataready
14 * trigger associated with the device and goes looking for it.
25 #include <linux/types.h>
33 #include <sys/ioctl.h>
34 #include <linux/iio/buffer.h>
35 #include "iio_utils.h"
38 * enum autochan - state for the automatic channel enabling mechanism
41 AUTOCHANNELS_DISABLED,
47 * size_from_channelarray() - calculate the storage size of a scan
48 * @channels: the channel info array
49 * @num_channels: number of channels
51 * Has the side effect of filling the channels[i].location values used
52 * in processing the buffer output.
54 static unsigned int size_from_channelarray(struct iio_channel_info *channels, int num_channels)
56 unsigned int bytes = 0;
59 while (i < num_channels) {
60 if (bytes % channels[i].bytes == 0)
61 channels[i].location = bytes;
63 channels[i].location = bytes - bytes % channels[i].bytes
66 bytes = channels[i].location + channels[i].bytes;
73 static void print1byte(uint8_t input, struct iio_channel_info *info)
76 * Shift before conversion to avoid sign extension
77 * of left aligned data
79 input >>= info->shift;
81 if (info->is_signed) {
82 int8_t val = (int8_t)(input << (8 - info->bits_used)) >>
83 (8 - info->bits_used);
84 printf("%05f ", ((float)val + info->offset) * info->scale);
86 printf("%05f ", ((float)input + info->offset) * info->scale);
90 static void print2byte(uint16_t input, struct iio_channel_info *info)
92 /* First swap if incorrect endian */
94 input = be16toh(input);
96 input = le16toh(input);
99 * Shift before conversion to avoid sign extension
100 * of left aligned data
102 input >>= info->shift;
104 if (info->is_signed) {
105 int16_t val = (int16_t)(input << (16 - info->bits_used)) >>
106 (16 - info->bits_used);
107 printf("%05f ", ((float)val + info->offset) * info->scale);
109 printf("%05f ", ((float)input + info->offset) * info->scale);
113 static void print4byte(uint32_t input, struct iio_channel_info *info)
115 /* First swap if incorrect endian */
117 input = be32toh(input);
119 input = le32toh(input);
122 * Shift before conversion to avoid sign extension
123 * of left aligned data
125 input >>= info->shift;
127 if (info->is_signed) {
128 int32_t val = (int32_t)(input << (32 - info->bits_used)) >>
129 (32 - info->bits_used);
130 printf("%05f ", ((float)val + info->offset) * info->scale);
132 printf("%05f ", ((float)input + info->offset) * info->scale);
136 static void print8byte(uint64_t input, struct iio_channel_info *info)
138 /* First swap if incorrect endian */
140 input = be64toh(input);
142 input = le64toh(input);
145 * Shift before conversion to avoid sign extension
146 * of left aligned data
148 input >>= info->shift;
150 if (info->is_signed) {
151 int64_t val = (int64_t)(input << (64 - info->bits_used)) >>
152 (64 - info->bits_used);
153 /* special case for timestamp */
154 if (info->scale == 1.0f && info->offset == 0.0f)
155 printf("%" PRId64 " ", val);
158 ((float)val + info->offset) * info->scale);
160 printf("%05f ", ((float)input + info->offset) * info->scale);
165 * process_scan() - print out the values in SI units
166 * @data: pointer to the start of the scan
167 * @channels: information about the channels.
168 * Note: size_from_channelarray must have been called first
169 * to fill the location offsets.
170 * @num_channels: number of channels
172 static void process_scan(char *data, struct iio_channel_info *channels,
177 for (k = 0; k < num_channels; k++)
178 switch (channels[k].bytes) {
179 /* only a few cases implemented so far */
181 print1byte(*(uint8_t *)(data + channels[k].location),
185 print2byte(*(uint16_t *)(data + channels[k].location),
189 print4byte(*(uint32_t *)(data + channels[k].location),
193 print8byte(*(uint64_t *)(data + channels[k].location),
202 static int enable_disable_all_channels(char *dev_dir_name, int buffer_idx, int enable)
204 const struct dirent *ent;
205 char scanelemdir[256];
209 snprintf(scanelemdir, sizeof(scanelemdir),
210 FORMAT_SCAN_ELEMENTS_DIR, dev_dir_name, buffer_idx);
211 scanelemdir[sizeof(scanelemdir)-1] = '\0';
213 dp = opendir(scanelemdir);
215 fprintf(stderr, "Enabling/disabling channels: can't open %s\n",
221 while (ent = readdir(dp), ent) {
222 if (iioutils_check_suffix(ent->d_name, "_en")) {
223 printf("%sabling: %s\n",
224 enable ? "En" : "Dis",
226 ret = write_sysfs_int(ent->d_name, scanelemdir,
229 fprintf(stderr, "Failed to enable/disable %s\n",
234 if (closedir(dp) == -1) {
235 perror("Enabling/disabling channels: "
236 "Failed to close directory");
242 static void print_usage(void)
244 fprintf(stderr, "Usage: generic_buffer [options]...\n"
245 "Capture, convert and output data from IIO device buffer\n"
246 " -a Auto-activate all available channels\n"
247 " -A Force-activate ALL channels\n"
248 " -b <n> The buffer which to open (by index), default 0\n"
249 " -c <n> Do n conversions, or loop forever if n < 0\n"
250 " -e Disable wait for event (new data)\n"
251 " -g Use trigger-less mode\n"
252 " -l <n> Set buffer length to n samples\n"
253 " --device-name -n <name>\n"
254 " --device-num -N <num>\n"
255 " Set device by name or number (mandatory)\n"
256 " --trigger-name -t <name>\n"
257 " --trigger-num -T <num>\n"
258 " Set trigger by name or number\n"
259 " -w <n> Set delay between reads in us (event-less mode)\n");
262 static enum autochan autochannels = AUTOCHANNELS_DISABLED;
263 static char *dev_dir_name = NULL;
264 static char *buf_dir_name = NULL;
265 static int buffer_idx = 0;
266 static bool current_trigger_set = false;
268 static void cleanup(void)
272 /* Disable trigger */
273 if (dev_dir_name && current_trigger_set) {
274 /* Disconnect the trigger - just write a dummy name. */
275 ret = write_sysfs_string("trigger/current_trigger",
276 dev_dir_name, "NULL");
278 fprintf(stderr, "Failed to disable trigger: %s\n",
280 current_trigger_set = false;
285 ret = write_sysfs_int("enable", buf_dir_name, 0);
287 fprintf(stderr, "Failed to disable buffer: %s\n",
291 /* Disable channels if auto-enabled */
292 if (dev_dir_name && autochannels == AUTOCHANNELS_ACTIVE) {
293 ret = enable_disable_all_channels(dev_dir_name, buffer_idx, 0);
295 fprintf(stderr, "Failed to disable all channels\n");
296 autochannels = AUTOCHANNELS_DISABLED;
300 static void sig_handler(int signum)
302 fprintf(stderr, "Caught signal %d\n", signum);
307 static void register_cleanup(void)
309 struct sigaction sa = { .sa_handler = sig_handler };
310 const int signums[] = { SIGINT, SIGTERM, SIGABRT };
313 for (i = 0; i < ARRAY_SIZE(signums); ++i) {
314 ret = sigaction(signums[i], &sa, NULL);
316 perror("Failed to register signal handler");
322 static const struct option longopts[] = {
323 { "device-name", 1, 0, 'n' },
324 { "device-num", 1, 0, 'N' },
325 { "trigger-name", 1, 0, 't' },
326 { "trigger-num", 1, 0, 'T' },
330 int main(int argc, char **argv)
332 long long num_loops = 2;
333 unsigned long timedelay = 1000000;
334 unsigned long buf_len = 128;
337 unsigned long long j;
338 unsigned long toread;
344 int num_channels = 0;
345 char *trigger_name = NULL, *device_name = NULL;
349 int dev_num = -1, trig_num = -1;
350 char *buffer_access = NULL;
351 unsigned int scan_size;
355 bool force_autochannels = false;
357 struct iio_channel_info *channels = NULL;
361 while ((c = getopt_long(argc, argv, "aAb:c:egl:n:N:t:T:w:?", longopts,
365 autochannels = AUTOCHANNELS_ENABLED;
368 autochannels = AUTOCHANNELS_ENABLED;
369 force_autochannels = true;
373 buffer_idx = strtoll(optarg, &dummy, 10);
378 if (buffer_idx < 0) {
386 num_loops = strtoll(optarg, &dummy, 10);
401 buf_len = strtoul(optarg, &dummy, 10);
409 device_name = strdup(optarg);
413 dev_num = strtoul(optarg, &dummy, 10);
420 trigger_name = strdup(optarg);
424 trig_num = strtoul(optarg, &dummy, 10);
430 timedelay = strtoul(optarg, &dummy, 10);
443 /* Find the device requested */
444 if (dev_num < 0 && !device_name) {
445 fprintf(stderr, "Device not set\n");
449 } else if (dev_num >= 0 && device_name) {
450 fprintf(stderr, "Only one of --device-num or --device-name needs to be set\n");
454 } else if (dev_num < 0) {
455 dev_num = find_type_by_name(device_name, "iio:device");
457 fprintf(stderr, "Failed to find the %s\n", device_name);
462 printf("iio device number being used is %d\n", dev_num);
464 ret = asprintf(&dev_dir_name, "%siio:device%d", iio_dir, dev_num);
467 /* Fetch device_name if specified by number */
469 device_name = malloc(IIO_MAX_NAME_LENGTH);
474 ret = read_sysfs_string("name", dev_dir_name, device_name);
476 fprintf(stderr, "Failed to read name of device %d\n", dev_num);
482 printf("trigger-less mode selected\n");
483 } else if (trig_num >= 0) {
485 ret = asprintf(&trig_dev_name, "%strigger%d", iio_dir, trig_num);
489 trigger_name = malloc(IIO_MAX_NAME_LENGTH);
490 ret = read_sysfs_string("name", trig_dev_name, trigger_name);
493 fprintf(stderr, "Failed to read trigger%d name from\n", trig_num);
496 printf("iio trigger number being used is %d\n", trig_num);
500 * Build the trigger name. If it is device associated
501 * its name is <device_name>_dev[n] where n matches
502 * the device number found above.
504 ret = asprintf(&trigger_name,
505 "%s-dev%d", device_name, dev_num);
512 /* Look for this "-devN" trigger */
513 trig_num = find_type_by_name(trigger_name, "trigger");
515 /* OK try the simpler "-trigger" suffix instead */
517 ret = asprintf(&trigger_name,
518 "%s-trigger", device_name);
525 trig_num = find_type_by_name(trigger_name, "trigger");
527 fprintf(stderr, "Failed to find the trigger %s\n",
533 printf("iio trigger number being used is %d\n", trig_num);
537 * Parse the files in scan_elements to identify what channels are
540 ret = build_channel_array(dev_dir_name, buffer_idx, &channels, &num_channels);
542 fprintf(stderr, "Problem reading scan element information\n"
543 "diag %s\n", dev_dir_name);
546 if (num_channels && autochannels == AUTOCHANNELS_ENABLED &&
547 !force_autochannels) {
548 fprintf(stderr, "Auto-channels selected but some channels "
549 "are already activated in sysfs\n");
550 fprintf(stderr, "Proceeding without activating any channels\n");
553 if ((!num_channels && autochannels == AUTOCHANNELS_ENABLED) ||
554 (autochannels == AUTOCHANNELS_ENABLED && force_autochannels)) {
555 fprintf(stderr, "Enabling all channels\n");
557 ret = enable_disable_all_channels(dev_dir_name, buffer_idx, 1);
559 fprintf(stderr, "Failed to enable all channels\n");
563 /* This flags that we need to disable the channels again */
564 autochannels = AUTOCHANNELS_ACTIVE;
566 ret = build_channel_array(dev_dir_name, buffer_idx, &channels,
569 fprintf(stderr, "Problem reading scan element "
571 "diag %s\n", dev_dir_name);
575 fprintf(stderr, "Still no channels after "
576 "auto-enabling, giving up\n");
581 if (!num_channels && autochannels == AUTOCHANNELS_DISABLED) {
583 "No channels are enabled, we have nothing to scan.\n");
584 fprintf(stderr, "Enable channels manually in "
585 FORMAT_SCAN_ELEMENTS_DIR
586 "/*_en or pass -a to autoenable channels and "
587 "try again.\n", dev_dir_name, buffer_idx);
593 * Construct the directory name for the associated buffer.
594 * As we know that the lis3l02dq has only one buffer this may
595 * be built rather than found.
597 ret = asprintf(&buf_dir_name,
598 "%siio:device%d/buffer%d", iio_dir, dev_num, buffer_idx);
604 if (stat(buf_dir_name, &st)) {
605 fprintf(stderr, "Could not stat() '%s', got error %d: %s\n",
606 buf_dir_name, errno, strerror(errno));
611 if (!S_ISDIR(st.st_mode)) {
612 fprintf(stderr, "File '%s' is not a directory\n", buf_dir_name);
618 printf("%s %s\n", dev_dir_name, trigger_name);
620 * Set the device trigger to be the data ready trigger found
623 ret = write_sysfs_string_and_verify("trigger/current_trigger",
628 "Failed to write current_trigger file\n");
633 ret = asprintf(&buffer_access, "/dev/iio:device%d", dev_num);
639 /* Attempt to open non blocking the access dev */
640 fd = open(buffer_access, O_RDONLY | O_NONBLOCK);
641 if (fd == -1) { /* TODO: If it isn't there make the node */
643 fprintf(stderr, "Failed to open %s\n", buffer_access);
647 /* specify for which buffer index we want an FD */
650 ret = ioctl(fd, IIO_BUFFER_GET_FD_IOCTL, &buf_fd);
651 if (ret == -1 || buf_fd == -1) {
653 if (ret == -ENODEV || ret == -EINVAL)
655 "Device does not have this many buffers\n");
657 fprintf(stderr, "Failed to retrieve buffer fd\n");
662 /* Setup ring buffer parameters */
663 ret = write_sysfs_int("length", buf_dir_name, buf_len);
667 /* Enable the buffer */
668 ret = write_sysfs_int("enable", buf_dir_name, 1);
671 "Failed to enable buffer '%s': %s\n",
672 buf_dir_name, strerror(-ret));
676 scan_size = size_from_channelarray(channels, num_channels);
678 size_t total_buf_len = scan_size * buf_len;
680 if (scan_size > 0 && total_buf_len / scan_size != buf_len) {
682 perror("Integer overflow happened when calculate scan_size * buf_len");
686 data = malloc(total_buf_len);
693 * This check is being done here for sanity reasons, however it
694 * should be omitted under normal operation.
695 * If this is buffer0, we check that we get EBUSY after this point.
697 if (buffer_idx == 0) {
699 read_size = read(fd, data, 1);
700 if (read_size > -1 || errno != EBUSY) {
702 perror("Reading from '%s' should not be possible after ioctl()");
707 /* close now the main chardev FD and let the buffer FD work */
709 perror("Failed to close character device file");
712 for (j = 0; j < num_loops || num_loops < 0; j++) {
714 struct pollfd pfd = {
719 ret = poll(&pfd, 1, -1);
723 } else if (ret == 0) {
733 read_size = read(buf_fd, data, toread * scan_size);
735 if (errno == EAGAIN) {
736 fprintf(stderr, "nothing available\n");
742 for (i = 0; i < read_size / scan_size; i++)
743 process_scan(data + scan_size * i, channels,
750 if (fd >= 0 && close(fd) == -1)
751 perror("Failed to close character device");
752 if (buf_fd >= 0 && close(buf_fd) == -1)
753 perror("Failed to close buffer");
757 for (i = num_channels - 1; i >= 0; i--) {
758 free(channels[i].name);
759 free(channels[i].generic_name);