net: lwm2m: Add path generation macro

Currently, the Zephyr LwM2M code base is littered with hard-coded
object- and resource IDs, such as

    /* Mark 1st instance of security object as a bootstrap server */
    lwm2m_engine_set_u8("0/0/1", 1);

The purpose of this LoC is extremely opaque without the accompanying
comment. Each use of a resource path requires constantly checking
headers or the object registry to ensure you're not misremembering IDs.

To alleviate this, this commit introduces a variadic LwM2M path
expansion macro which performs preprocessor stringification on each
argument. For instance, "0/0/1" can now be written as

    LWM2M_PATH(LWM2M_OBJECT_SECURITY_ID, 0, SECURITY_BOOTSTRAP_FLAG_ID)

which, while albeit lengthier, avoids the use of hard-coded string
literals, thus making the code much more immediately understandable.

Signed-off-by: Benjamin Lindqvist <benjamin.lindqvist@endian.se>
This commit is contained in:
Benjamin Lindqvist 2020-10-22 13:28:35 +02:00 committed by Jukka Rissanen
commit 1578e70eaf
2 changed files with 47 additions and 0 deletions

View file

@ -26,6 +26,7 @@
#include <kernel.h>
#include <sys/mutex.h>
#include <net/coap.h>
#include <net/lwm2m_path.h>
/**
* @brief LwM2M Objects managed by OMA for LwM2M tech specification. Objects

46
include/net/lwm2m_path.h Normal file
View file

@ -0,0 +1,46 @@
/*
* Copyright (c) 2020 Endian Technologies AB
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ZEPHYR_INCLUDE_NET_LWM2M_PATH_H_
#define ZEPHYR_INCLUDE_NET_LWM2M_PATH_H_
/**
* @brief Generate LwM2M string paths using numeric components.
*
* Accepts at least one and up to four arguments. Each argument will be
* stringified by the pre-processor, so calling this with non-literals will
* likely not do what you want. For example,
*
* #define MY_OBJ_ID 3
* LWM2M_PATH(MY_OBJ_ID, 0, 1)
*
* would evaluate to "3/0/1", while
*
* int x = 3;
* LWM2M_PATH(x, 0, 1)
*
* evalutes to "x/0/1".
*/
#define LWM2M_PATH(...) \
LWM2M_PATH_MACRO(__VA_ARGS__, LWM2M_PATH4, LWM2M_PATH3, \
LWM2M_PATH2, LWM2M_PATH1)(__VA_ARGS__)
/* Internal helper macros for the LWM2M_PATH macro */
#define LWM2M_PATH_VA_NUM_ARGS(...) \
LWM2M_PATH_VA_NUM_ARGS_IMPL(__VA_ARGS__, 5, 4, 3, 2, 1)
#define LWM2M_PATH_VA_NUM_ARGS_IMPL(_1, _2, _3, _4, N, ...) N
#define LWM2M_PATH1(_x) #_x
#define LWM2M_PATH2(_x, _y) #_x "/" #_y
#define LWM2M_PATH3(_x, _y, _z) #_x "/" #_y "/" #_z
#define LWM2M_PATH4(_a, _x, _y, _z) #_a "/" #_x "/" #_y "/" #_z
#define LWM2M_PATH_MACRO(_1, _2, _3, _4, NAME, ...) NAME
#endif /* ZEPHYR_INCLUDE_NET_LWM2M_PATH_H_ */