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 		"  -A         Force-activate ALL channels\n"
251 		"  -c <n>     Do n conversions, or loop forever if n < 0\n"
252 		"  -e         Disable wait for event (new data)\n"
253 		"  -g         Use trigger-less mode\n"
254 		"  -l <n>     Set buffer length to n samples\n"
255 		"  --device-name -n <name>\n"
256 		"  --device-num -N <num>\n"
257 		"        Set device by name or number (mandatory)\n"
258 		"  --trigger-name -t <name>\n"
259 		"  --trigger-num -T <num>\n"
260 		"        Set trigger by name or number\n"
261 		"  -w <n>     Set delay between reads in us (event-less mode)\n");
262 }
263 
264 enum autochan autochannels = AUTOCHANNELS_DISABLED;
265 char *dev_dir_name = NULL;
266 char *buf_dir_name = NULL;
267 bool current_trigger_set = false;
268 
269 void cleanup(void)
270 {
271 	int ret;
272 
273 	/* Disable trigger */
274 	if (dev_dir_name && current_trigger_set) {
275 		/* Disconnect the trigger - just write a dummy name. */
276 		ret = write_sysfs_string("trigger/current_trigger",
277 					 dev_dir_name, "NULL");
278 		if (ret < 0)
279 			fprintf(stderr, "Failed to disable trigger: %s\n",
280 				strerror(-ret));
281 		current_trigger_set = false;
282 	}
283 
284 	/* Disable buffer */
285 	if (buf_dir_name) {
286 		ret = write_sysfs_int("enable", buf_dir_name, 0);
287 		if (ret < 0)
288 			fprintf(stderr, "Failed to disable buffer: %s\n",
289 				strerror(-ret));
290 	}
291 
292 	/* Disable channels if auto-enabled */
293 	if (dev_dir_name && autochannels == AUTOCHANNELS_ACTIVE) {
294 		ret = enable_disable_all_channels(dev_dir_name, 0);
295 		if (ret)
296 			fprintf(stderr, "Failed to disable all channels\n");
297 		autochannels = AUTOCHANNELS_DISABLED;
298 	}
299 }
300 
301 void sig_handler(int signum)
302 {
303 	fprintf(stderr, "Caught signal %d\n", signum);
304 	cleanup();
305 	exit(-signum);
306 }
307 
308 void register_cleanup(void)
309 {
310 	struct sigaction sa = { .sa_handler = sig_handler };
311 	const int signums[] = { SIGINT, SIGTERM, SIGABRT };
312 	int ret, i;
313 
314 	for (i = 0; i < ARRAY_SIZE(signums); ++i) {
315 		ret = sigaction(signums[i], &sa, NULL);
316 		if (ret) {
317 			perror("Failed to register signal handler");
318 			exit(-1);
319 		}
320 	}
321 }
322 
323 static const struct option longopts[] = {
324 	{ "device-name",	1, 0, 'n' },
325 	{ "device-num",		1, 0, 'N' },
326 	{ "trigger-name",	1, 0, 't' },
327 	{ "trigger-num",	1, 0, 'T' },
328 	{ },
329 };
330 
331 int main(int argc, char **argv)
332 {
333 	unsigned long long num_loops = 2;
334 	unsigned long timedelay = 1000000;
335 	unsigned long buf_len = 128;
336 
337 	ssize_t i;
338 	unsigned long long j;
339 	unsigned long toread;
340 	int ret, c;
341 	int fp = -1;
342 
343 	int num_channels = 0;
344 	char *trigger_name = NULL, *device_name = NULL;
345 
346 	char *data = NULL;
347 	ssize_t read_size;
348 	int dev_num = -1, trig_num = -1;
349 	char *buffer_access = NULL;
350 	int scan_size;
351 	int noevents = 0;
352 	int notrigger = 0;
353 	char *dummy;
354 	bool force_autochannels = false;
355 
356 	struct iio_channel_info *channels = NULL;
357 
358 	register_cleanup();
359 
360 	while ((c = getopt_long(argc, argv, "aAc:egl:n:N:t:T:w:?", longopts,
361 				NULL)) != -1) {
362 		switch (c) {
363 		case 'a':
364 			autochannels = AUTOCHANNELS_ENABLED;
365 			break;
366 		case 'A':
367 			autochannels = AUTOCHANNELS_ENABLED;
368 			force_autochannels = true;
369 			break;
370 		case 'c':
371 			errno = 0;
372 			num_loops = strtoll(optarg, &dummy, 10);
373 			if (errno) {
374 				ret = -errno;
375 				goto error;
376 			}
377 
378 			break;
379 		case 'e':
380 			noevents = 1;
381 			break;
382 		case 'g':
383 			notrigger = 1;
384 			break;
385 		case 'l':
386 			errno = 0;
387 			buf_len = strtoul(optarg, &dummy, 10);
388 			if (errno) {
389 				ret = -errno;
390 				goto error;
391 			}
392 
393 			break;
394 		case 'n':
395 			device_name = strdup(optarg);
396 			break;
397 		case 'N':
398 			errno = 0;
399 			dev_num = strtoul(optarg, &dummy, 10);
400 			if (errno) {
401 				ret = -errno;
402 				goto error;
403 			}
404 			break;
405 		case 't':
406 			trigger_name = strdup(optarg);
407 			break;
408 		case 'T':
409 			errno = 0;
410 			trig_num = strtoul(optarg, &dummy, 10);
411 			if (errno)
412 				return -errno;
413 			break;
414 		case 'w':
415 			errno = 0;
416 			timedelay = strtoul(optarg, &dummy, 10);
417 			if (errno) {
418 				ret = -errno;
419 				goto error;
420 			}
421 			break;
422 		case '?':
423 			print_usage();
424 			ret = -1;
425 			goto error;
426 		}
427 	}
428 
429 	/* Find the device requested */
430 	if (dev_num < 0 && !device_name) {
431 		fprintf(stderr, "Device not set\n");
432 		print_usage();
433 		ret = -1;
434 		goto error;
435 	} else if (dev_num >= 0 && device_name) {
436 		fprintf(stderr, "Only one of --device-num or --device-name needs to be set\n");
437 		print_usage();
438 		ret = -1;
439 		goto error;
440 	} else if (dev_num < 0) {
441 		dev_num = find_type_by_name(device_name, "iio:device");
442 		if (dev_num < 0) {
443 			fprintf(stderr, "Failed to find the %s\n", device_name);
444 			ret = dev_num;
445 			goto error;
446 		}
447 	}
448 	printf("iio device number being used is %d\n", dev_num);
449 
450 	ret = asprintf(&dev_dir_name, "%siio:device%d", iio_dir, dev_num);
451 	if (ret < 0)
452 		return -ENOMEM;
453 	/* Fetch device_name if specified by number */
454 	if (!device_name) {
455 		device_name = malloc(IIO_MAX_NAME_LENGTH);
456 		if (!device_name) {
457 			ret = -ENOMEM;
458 			goto error;
459 		}
460 		ret = read_sysfs_string("name", dev_dir_name, device_name);
461 		if (ret < 0) {
462 			fprintf(stderr, "Failed to read name of device %d\n", dev_num);
463 			goto error;
464 		}
465 	}
466 
467 	if (notrigger) {
468 		printf("trigger-less mode selected\n");
469 	} else if (trig_num >= 0) {
470 		char *trig_dev_name;
471 		ret = asprintf(&trig_dev_name, "%strigger%d", iio_dir, trig_num);
472 		if (ret < 0) {
473 			return -ENOMEM;
474 		}
475 		trigger_name = malloc(IIO_MAX_NAME_LENGTH);
476 		ret = read_sysfs_string("name", trig_dev_name, trigger_name);
477 		free(trig_dev_name);
478 		if (ret < 0) {
479 			fprintf(stderr, "Failed to read trigger%d name from\n", trig_num);
480 			return ret;
481 		}
482 		printf("iio trigger number being used is %d\n", trig_num);
483 	} else {
484 		if (!trigger_name) {
485 			/*
486 			 * Build the trigger name. If it is device associated
487 			 * its name is <device_name>_dev[n] where n matches
488 			 * the device number found above.
489 			 */
490 			ret = asprintf(&trigger_name,
491 				       "%s-dev%d", device_name, dev_num);
492 			if (ret < 0) {
493 				ret = -ENOMEM;
494 				goto error;
495 			}
496 		}
497 
498 		/* Look for this "-devN" trigger */
499 		trig_num = find_type_by_name(trigger_name, "trigger");
500 		if (trig_num < 0) {
501 			/* OK try the simpler "-trigger" suffix instead */
502 			free(trigger_name);
503 			ret = asprintf(&trigger_name,
504 				       "%s-trigger", device_name);
505 			if (ret < 0) {
506 				ret = -ENOMEM;
507 				goto error;
508 			}
509 		}
510 
511 		trig_num = find_type_by_name(trigger_name, "trigger");
512 		if (trig_num < 0) {
513 			fprintf(stderr, "Failed to find the trigger %s\n",
514 				trigger_name);
515 			ret = trig_num;
516 			goto error;
517 		}
518 
519 		printf("iio trigger number being used is %d\n", trig_num);
520 	}
521 
522 	/*
523 	 * Parse the files in scan_elements to identify what channels are
524 	 * present
525 	 */
526 	ret = build_channel_array(dev_dir_name, &channels, &num_channels);
527 	if (ret) {
528 		fprintf(stderr, "Problem reading scan element information\n"
529 			"diag %s\n", dev_dir_name);
530 		goto error;
531 	}
532 	if (num_channels && autochannels == AUTOCHANNELS_ENABLED &&
533 	    !force_autochannels) {
534 		fprintf(stderr, "Auto-channels selected but some channels "
535 			"are already activated in sysfs\n");
536 		fprintf(stderr, "Proceeding without activating any channels\n");
537 	}
538 
539 	if ((!num_channels && autochannels == AUTOCHANNELS_ENABLED) ||
540 	    (autochannels == AUTOCHANNELS_ENABLED && force_autochannels)) {
541 		fprintf(stderr, "Enabling all channels\n");
542 
543 		ret = enable_disable_all_channels(dev_dir_name, 1);
544 		if (ret) {
545 			fprintf(stderr, "Failed to enable all channels\n");
546 			goto error;
547 		}
548 
549 		/* This flags that we need to disable the channels again */
550 		autochannels = AUTOCHANNELS_ACTIVE;
551 
552 		ret = build_channel_array(dev_dir_name, &channels,
553 					  &num_channels);
554 		if (ret) {
555 			fprintf(stderr, "Problem reading scan element "
556 				"information\n"
557 				"diag %s\n", dev_dir_name);
558 			goto error;
559 		}
560 		if (!num_channels) {
561 			fprintf(stderr, "Still no channels after "
562 				"auto-enabling, giving up\n");
563 			goto error;
564 		}
565 	}
566 
567 	if (!num_channels && autochannels == AUTOCHANNELS_DISABLED) {
568 		fprintf(stderr,
569 			"No channels are enabled, we have nothing to scan.\n");
570 		fprintf(stderr, "Enable channels manually in "
571 			FORMAT_SCAN_ELEMENTS_DIR
572 			"/*_en or pass -a to autoenable channels and "
573 			"try again.\n", dev_dir_name);
574 		ret = -ENOENT;
575 		goto error;
576 	}
577 
578 	/*
579 	 * Construct the directory name for the associated buffer.
580 	 * As we know that the lis3l02dq has only one buffer this may
581 	 * be built rather than found.
582 	 */
583 	ret = asprintf(&buf_dir_name,
584 		       "%siio:device%d/buffer", iio_dir, dev_num);
585 	if (ret < 0) {
586 		ret = -ENOMEM;
587 		goto error;
588 	}
589 
590 	if (!notrigger) {
591 		printf("%s %s\n", dev_dir_name, trigger_name);
592 		/*
593 		 * Set the device trigger to be the data ready trigger found
594 		 * above
595 		 */
596 		ret = write_sysfs_string_and_verify("trigger/current_trigger",
597 						    dev_dir_name,
598 						    trigger_name);
599 		if (ret < 0) {
600 			fprintf(stderr,
601 				"Failed to write current_trigger file\n");
602 			goto error;
603 		}
604 	}
605 
606 	/* Setup ring buffer parameters */
607 	ret = write_sysfs_int("length", buf_dir_name, buf_len);
608 	if (ret < 0)
609 		goto error;
610 
611 	/* Enable the buffer */
612 	ret = write_sysfs_int("enable", buf_dir_name, 1);
613 	if (ret < 0) {
614 		fprintf(stderr,
615 			"Failed to enable buffer: %s\n", strerror(-ret));
616 		goto error;
617 	}
618 
619 	scan_size = size_from_channelarray(channels, num_channels);
620 	data = malloc(scan_size * buf_len);
621 	if (!data) {
622 		ret = -ENOMEM;
623 		goto error;
624 	}
625 
626 	ret = asprintf(&buffer_access, "/dev/iio:device%d", dev_num);
627 	if (ret < 0) {
628 		ret = -ENOMEM;
629 		goto error;
630 	}
631 
632 	/* Attempt to open non blocking the access dev */
633 	fp = open(buffer_access, O_RDONLY | O_NONBLOCK);
634 	if (fp == -1) { /* TODO: If it isn't there make the node */
635 		ret = -errno;
636 		fprintf(stderr, "Failed to open %s\n", buffer_access);
637 		goto error;
638 	}
639 
640 	for (j = 0; j < num_loops || num_loops < 0; j++) {
641 		if (!noevents) {
642 			struct pollfd pfd = {
643 				.fd = fp,
644 				.events = POLLIN,
645 			};
646 
647 			ret = poll(&pfd, 1, -1);
648 			if (ret < 0) {
649 				ret = -errno;
650 				goto error;
651 			} else if (ret == 0) {
652 				continue;
653 			}
654 
655 			toread = buf_len;
656 		} else {
657 			usleep(timedelay);
658 			toread = 64;
659 		}
660 
661 		read_size = read(fp, data, toread * scan_size);
662 		if (read_size < 0) {
663 			if (errno == EAGAIN) {
664 				fprintf(stderr, "nothing available\n");
665 				continue;
666 			} else {
667 				break;
668 			}
669 		}
670 		for (i = 0; i < read_size / scan_size; i++)
671 			process_scan(data + scan_size * i, channels,
672 				     num_channels);
673 	}
674 
675 error:
676 	cleanup();
677 
678 	if (fp >= 0 && close(fp) == -1)
679 		perror("Failed to close buffer");
680 	free(buffer_access);
681 	free(data);
682 	free(buf_dir_name);
683 	for (i = num_channels - 1; i >= 0; i--) {
684 		free(channels[i].name);
685 		free(channels[i].generic_name);
686 	}
687 	free(channels);
688 	free(trigger_name);
689 	free(device_name);
690 	free(dev_dir_name);
691 
692 	return ret;
693 }
694