Debian Codegraph @

examples/find_line_by_name.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 // SPDX-FileCopyrightText: 2023 Kent Gibson <[email protected]>
3
4 /* Minimal example of finding a line with the given name. */
5
6 #include <dirent.h>
7 #include <errno.h>
8 #include <gpiod.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/stat.h>
13
14 static int chip_dir_filter(const struct dirent *entry)
15 {
16 struct stat sb;
17 int ret = 0;
18 char *path;
19
20 if (asprintf(&path, "/dev/%s", entry->d_name) < 0)
21 return 0;
22
23 if ((lstat(path, &sb) == 0) && (!S_ISLNK(sb.st_mode)) &&
24 gpiod_is_gpiochip_device(path))
25 ret = 1;
26
27 free(path);
28
29 return ret;
30 }
31
32 static int all_chip_paths(char ***paths_ptr)
33 {
34 int i, j, num_chips, ret = 0;
35 struct dirent **entries;
36 char **paths;
37
38 num_chips = scandir("/dev/", &entries, chip_dir_filter, versionsort);
39 if (num_chips < 0)
40 return 0;
41
42 paths = calloc(num_chips, sizeof(*paths));
43 if (!paths)
44 return 0;
45
46 for (i = 0; i < num_chips; i++) {
47 if (asprintf(&paths[i], "/dev/%s", entries[i]->d_name) < 0) {
48 for (j = 0; j < i; j++)
49 free(paths[j]);
50
51 free(paths);
52 return 0;
53 }
54 }
55
56 *paths_ptr = paths;
57 ret = num_chips;
58
59 for (i = 0; i < num_chips; i++)
60 free(entries[i]);
61
62 free(entries);
63 return ret;
64 }
65
66 int main(void)
67 {
68 /* Example configuration - customize to suit your situation. */
69 static const char *const line_name = "GPIO19";
70
71 struct gpiod_chip_info *cinfo;
72 int i, num_chips, offset;
73 struct gpiod_chip *chip;
74 char **chip_paths;
75
76 /*
77 * Names are not guaranteed unique, so this finds the first line with
78 * the given name.
79 */
80 num_chips = all_chip_paths(&chip_paths);
81 for (i = 0; i < num_chips; i++) {
82 chip = gpiod_chip_open(chip_paths[i]);
83 if (!chip)
84 continue;
85
86 offset = gpiod_chip_get_line_offset_from_name(chip, line_name);
87 if (offset == -1)
88 goto close_chip;
89
90 cinfo = gpiod_chip_get_info(chip);
91 if (!cinfo)
92 goto close_chip;
93
94 printf("%s: %s %d\n", line_name,
95 gpiod_chip_info_get_name(cinfo), offset);
96
97 return EXIT_SUCCESS;
98
99 close_chip:
100 gpiod_chip_close(chip);
101 }
102
103 printf("line '%s' not found\n", line_name);
104 return EXIT_FAILURE;
105 }