From 14e277affd93e4bbf55408fb2b4b8d145377630c Mon Sep 17 00:00:00 2001 From: Bartosz Golaszewski Date: Fri, 6 Jan 2017 16:21:09 +0100 Subject: [PATCH] gpioget: use tools-common Signed-off-by: Bartosz Golaszewski --- gpioget.c | 74 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/gpioget.c b/gpioget.c index c32bc87..7f09e7b 100644 --- a/gpioget.c +++ b/gpioget.c @@ -9,43 +9,71 @@ */ #include "gpiod.h" +#include "tools-common.h" #include #include +#include + +static const struct option longopts[] = { + { "help", no_argument, NULL, 'h' }, + { "active-low", no_argument, NULL, 'l' }, + { 0 }, +}; + +static const char *const shortopts = "hl"; int main(int argc, char **argv) { + bool active_low = false; + int value, optc, opti; unsigned int offset; char *device, *end; - int value; - if (argc < 2) { - fprintf(stderr, "%s: gpiochip must be specified\n", argv[0]); - return EXIT_FAILURE; - } + set_progname(argv[0]); - if (argc < 3) { - fprintf(stderr, - "%s: gpio line offset must be specified\n", argv[0]); - return EXIT_FAILURE; + for (;;) { + optc = getopt_long(argc, argv, shortopts, longopts, &opti); + if (optc < 0) + break; + + switch (optc) { + case 'h': + printf("Usage: %s [CHIP NAME/NUMBER] [LINE OFFSET] \n", + get_progname()); + printf("List all GPIO chips\n"); + printf("Options:\n"); + printf(" -h, --help:\t\tdisplay this message and exit\n"); + printf(" -l, --active-low:\tset the line active state to low\n"); + exit(EXIT_SUCCESS); + case 'l': + active_low = true; + break; + case '?': + die("try %s --help", get_progname()); + default: + abort(); + } } - device = argv[1]; + argc -= optind; + argv += optind; + + if (argc < 1) + die("gpiochip must be specified"); + + if (argc < 2) + die("gpio line offset must be specified"); + + device = argv[0]; /* FIXME Handle negative numbers. */ - offset = strtoul(argv[2], &end, 10); - if (*end != '\0') { - fprintf(stderr, - "%s: invalid GPIO offset: %s\n", argv[0], argv[2]); - return EXIT_FAILURE; - } + offset = strtoul(argv[1], &end, 10); + if (*end != '\0') + die("invalid GPIO offset: %s", argv[1]); - value = gpiod_simple_get_value(device, offset, false); - if (value < 0) { - fprintf(stderr, - "%s: error reading GPIO value: %s\n", - argv[0], strerror(-value)); - return EXIT_FAILURE; - } + value = gpiod_simple_get_value(device, offset, active_low); + if (value < 0) + die_perror("error reading GPIO value"); printf("%d\n", value); -- 2.30.2