gpio: store reflect the label to userspace
[deliverable/linux.git] / tools / gpio / lsgpio.c
CommitLineData
6d591c46
LW
1/*
2 * lsgpio - example on how to list the GPIO lines on a system
3 *
4 * Copyright (C) 2015 Linus Walleij
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published by
8 * the Free Software Foundation.
9 *
10 * Usage:
11 * lsgpio <-n device-name>
12 */
13
14#include <unistd.h>
15#include <stdlib.h>
16#include <stdbool.h>
17#include <stdio.h>
18#include <dirent.h>
19#include <errno.h>
20#include <string.h>
21#include <poll.h>
22#include <fcntl.h>
23#include <getopt.h>
24#include <sys/ioctl.h>
25#include <linux/gpio.h>
26
27#include "gpio-utils.h"
28
29int list_device(const char *device_name)
30{
31 struct gpiochip_info cinfo;
32 char *chrdev_name;
33 int fd;
34 int ret;
35
36 ret = asprintf(&chrdev_name, "/dev/%s", device_name);
37 if (ret < 0)
38 return -ENOMEM;
39
40 fd = open(chrdev_name, 0);
41 if (fd == -1) {
42 ret = -errno;
43 fprintf(stderr, "Failed to open %s\n", chrdev_name);
44 goto free_chrdev_name;
45 }
46
47 /* Inspect this GPIO chip */
48 ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &cinfo);
49 if (ret == -1) {
50 ret = -errno;
51 fprintf(stderr, "Failed to retrieve GPIO fd\n");
52 if (close(fd) == -1)
53 perror("Failed to close GPIO character device file");
54
55 goto free_chrdev_name;
56 }
df4878e9
LW
57 fprintf(stdout, "GPIO chip: %s, \"%s\", %u GPIO lines\n",
58 cinfo.name, cinfo.label, cinfo.lines);
6d591c46
LW
59
60 if (close(fd) == -1) {
61 ret = -errno;
62 goto free_chrdev_name;
63 }
64
65free_chrdev_name:
66 free(chrdev_name);
67
68 return ret;
69
70}
71
72void print_usage(void)
73{
74 fprintf(stderr, "Usage: lsgpio [options]...\n"
75 "List GPIO chips, lines and states\n"
76 " -n <name> List GPIOs on a named device\n"
77 " -? This helptext\n"
78 );
79}
80
81int main(int argc, char **argv)
82{
83 const char *device_name;
84 int ret;
85 int c;
86
87 while ((c = getopt(argc, argv, "n:")) != -1) {
88 switch (c) {
89 case 'n':
90 device_name = optarg;
91 break;
92 case '?':
93 print_usage();
94 return -1;
95 }
96 }
97
98 if (device_name)
99 ret = list_device(device_name);
100 else {
101 const struct dirent *ent;
102 DIR *dp;
103
104 /* List all GPIO devices one at a time */
105 dp = opendir("/dev");
106 if (!dp) {
107 ret = -errno;
108 goto error_out;
109 }
110
111 ret = -ENOENT;
112 while (ent = readdir(dp), ent) {
113 if (check_prefix(ent->d_name, "gpiochip")) {
114 ret = list_device(ent->d_name);
115 if (ret)
116 break;
117 }
118 }
119
120 ret = 0;
121 if (closedir(dp) == -1) {
122 perror("scanning devices: Failed to close directory");
123 ret = -errno;
124 }
125 }
126error_out:
127 return ret;
128}
This page took 0.028823 seconds and 5 git commands to generate.