From 28238d03ad156eb3f31c27849c94d0aa5b5619b6 Mon Sep 17 00:00:00 2001 From: James Roy Date: Wed, 6 Nov 2024 21:02:21 +0800 Subject: [PATCH] devicetree: Add DT_HAS_ALIAS macro Add 'DT_HAS_ALIAS' macro to verify node alias existence. Signed-off-by: James Roy --- doc/build/dts/api-usage.rst | 2 ++ include/zephyr/devicetree.h | 7 +++++++ tests/lib/devicetree/api/src/main.c | 2 ++ 3 files changed, 11 insertions(+) diff --git a/doc/build/dts/api-usage.rst b/doc/build/dts/api-usage.rst index c53ece8ee6a..5b96349590a 100644 --- a/doc/build/dts/api-usage.rst +++ b/doc/build/dts/api-usage.rst @@ -50,6 +50,8 @@ By alias :zephyr:code-sample:`blinky`, which uses the ``led0`` alias) that need to refer to *some* device of a particular type ("the board's user LED") but don't care which one is used. + You may also use :c:macro:`DT_HAS_ALIAS()` to verify whether an alias + node exists. By instance number This is done primarily by device drivers, as instance numbers are a way to diff --git a/include/zephyr/devicetree.h b/include/zephyr/devicetree.h index 3a26a1dd355..1adc7602f10 100644 --- a/include/zephyr/devicetree.h +++ b/include/zephyr/devicetree.h @@ -235,6 +235,13 @@ */ #define DT_ALIAS(alias) DT_CAT(DT_N_ALIAS_, alias) +/** + * @brief Test if the devicetree has a given alias + * @param alias_name lowercase-and-underscores devicetree alias name + * @return 1 if the alias exists and refers to a node, 0 otherwise + */ +#define DT_HAS_ALIAS(alias_name) DT_NODE_EXISTS(DT_ALIAS(alias_name)) + /** * @brief Get a node identifier for an instance of a compatible * diff --git a/tests/lib/devicetree/api/src/main.c b/tests/lib/devicetree/api/src/main.c index d4dd12cf733..4b39c4571a8 100644 --- a/tests/lib/devicetree/api/src/main.c +++ b/tests/lib/devicetree/api/src/main.c @@ -127,6 +127,8 @@ ZTEST(devicetree_api, test_path_props) ZTEST(devicetree_api, test_alias_props) { + zassert_equal(DT_HAS_ALIAS(test_alias), 1, ""); + zassert_equal(DT_HAS_ALIAS(test_alias_none), 0, ""); zassert_equal(DT_NUM_REGS(TEST_ALIAS), 1, ""); zassert_equal(DT_REG_ADDR(TEST_ALIAS), 0xdeadbeef, ""); zassert_equal(DT_REG_SIZE(TEST_ALIAS), 0x1000, "");