From: Bartosz Golaszewski Date: Wed, 22 Feb 2017 10:47:52 +0000 (+0100) Subject: core: new gpiod_chip_open() flavor X-Git-Url: http://git.maquefel.me/?a=commitdiff_plain;h=6d33670b9517ae4584ce0432aa8dc693d2acb246;p=qemu-gpiodev%2Flibgpiod.git core: new gpiod_chip_open() flavor Implement gpiod_chip_open_by_label() which allows to find and open a GPIO chip by its in-kernel label. Signed-off-by: Bartosz Golaszewski --- diff --git a/include/gpiod.h b/include/gpiod.h index b629322..0cb5d1a 100644 --- a/include/gpiod.h +++ b/include/gpiod.h @@ -870,6 +870,14 @@ struct gpiod_chip * gpiod_chip_open_by_name(const char *name) GPIOD_API; */ struct gpiod_chip * gpiod_chip_open_by_number(unsigned int num) GPIOD_API; +/** + * @brief Open a gpiochip by label. + * @param label Label of the gpiochip to open. + * @return GPIO chip handle or NULL if the chip with given label was not found + * or an error occured. + */ +struct gpiod_chip * gpiod_chip_open_by_label(const char *label) GPIOD_API; + /** * @brief Open a gpiochip based on the best guess what the path is. * @param descr String describing the gpiochip. diff --git a/src/lib/core.c b/src/lib/core.c index 9ad5d05..9b54128 100644 --- a/src/lib/core.c +++ b/src/lib/core.c @@ -960,6 +960,30 @@ struct gpiod_chip * gpiod_chip_open_by_number(unsigned int num) return chip; } +struct gpiod_chip * gpiod_chip_open_by_label(const char *label) +{ + struct gpiod_chip_iter *iter; + struct gpiod_chip *chip; + + iter = gpiod_chip_iter_new(); + if (!iter) + return NULL; + + gpiod_foreach_chip(iter, chip) { + if (gpiod_chip_iter_err(iter)) + goto out; + + if (strcmp(label, gpiod_chip_label(chip)) == 0) { + gpiod_chip_iter_free_noclose(iter); + return chip; + } + } + +out: + gpiod_chip_iter_free(iter); + return NULL; +} + struct gpiod_chip * gpiod_chip_open_lookup(const char *descr) { if (is_unsigned_int(descr)) diff --git a/tests/unit/tests-chip.c b/tests/unit/tests-chip.c index bfba6f7..0690e4a 100644 --- a/tests/unit/tests-chip.c +++ b/tests/unit/tests-chip.c @@ -80,6 +80,29 @@ GU_DEFINE_TEST(chip_open_lookup, "gpiod_chip_open_lookup()", GU_LINES_UNNAMED, { 8 }); +static void chip_open_by_label_good(void) +{ + GU_CLEANUP(gu_close_chip) struct gpiod_chip *chip = NULL; + + chip = gpiod_chip_open_by_label("gpio-mockup-D"); + GU_ASSERT_NOT_NULL(chip); + GU_ASSERT_STR_EQ(gpiod_chip_name(chip), gu_chip_name(3)); +} +GU_DEFINE_TEST(chip_open_by_label_good, + "chip_open_by_label() good", + GU_LINES_UNNAMED, { 4, 4, 4, 4, 4 }); + +static void chip_open_by_label_bad(void) +{ + GU_CLEANUP(gu_close_chip) struct gpiod_chip *chip = NULL; + + chip = gpiod_chip_open_by_label("nonexistent_gpio_chip"); + GU_ASSERT_NULL(chip); +} +GU_DEFINE_TEST(chip_open_by_label_bad, + "chip_open_by_label() bad", + GU_LINES_UNNAMED, { 4, 4, 4, 4, 4 }); + static void chip_name(void) { GU_CLEANUP(gu_close_chip) struct gpiod_chip *chip0 = NULL;