zbus: Add message bus subsystem to Zephyr
Add zbus message bus as a Zephyr subsystem. No message bus or communication abstraction other than the usual (message queues, mailboxes, etc.) enabled developers to implement event-driven systems in Zephyr quickly. Zbus would fill that gap by providing the community with a lightweight and flexible message bus. The implementation tries to be closest as possible to the existing ones. We use the claim/finish approach, and the API for publishing and reading channels are similar in message queues. Zbus is about channels, messages, and observers. Signed-off-by: Rodrigo Peixoto <rodrigopex@gmail.com>
This commit is contained in:
parent
47d09c04af
commit
b8ecbfaa57
|
@ -29,4 +29,5 @@ OS Services
|
|||
usb/index.rst
|
||||
virtualization/index.rst
|
||||
rtio/index.rst
|
||||
zbus/index.rst
|
||||
misc.rst
|
||||
|
|
3
doc/services/zbus/images/zbus_anatomy.svg
generated
Normal file
3
doc/services/zbus/images/zbus_anatomy.svg
generated
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 223 KiB |
3
doc/services/zbus/images/zbus_operations.svg
generated
Normal file
3
doc/services/zbus/images/zbus_operations.svg
generated
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 103 KiB |
3
doc/services/zbus/images/zbus_overview.svg
generated
Normal file
3
doc/services/zbus/images/zbus_overview.svg
generated
Normal file
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 71 KiB |
387
doc/services/zbus/index.rst
Normal file
387
doc/services/zbus/index.rst
Normal file
|
@ -0,0 +1,387 @@
|
|||
.. _zbus:
|
||||
|
||||
Zephyr message bus (zbus)
|
||||
#########################
|
||||
|
||||
The :dfn:`Zephyr message bus - Zbus` is a lightweight and flexible message bus enabling a simple way for threads to talk to one another.
|
||||
|
||||
.. contents::
|
||||
:local:
|
||||
:depth: 2
|
||||
|
||||
Concepts
|
||||
********
|
||||
|
||||
Threads can broadcast messages to all interested observers using zbus. Many-to-many communication is possible. The bus implements message-passing and publish/subscribe communication paradigms that enable threads to communicate synchronously or asynchronously through shared memory. The communication through zbus is channel-based, where threads publish and read to and from using messages. Additionally, threads can observe channels and receive notifications from the bus when the channels are modified. :numref:`zbus common` shows an example of a typical application using zbus in which the application logic (hardware independent) talks to other threads via message bus. Note that the threads are decoupled from each other because they only use zbus' channels and do not need to know each other to talk.
|
||||
|
||||
|
||||
.. _zbus common:
|
||||
.. figure:: images/zbus_overview.svg
|
||||
:alt: zbus usage overview
|
||||
:width: 75%
|
||||
|
||||
A typical zbus application architecture.
|
||||
|
||||
:numref:`zbus anatomy` illustrates zbus' anatomy. The bus comprises:
|
||||
|
||||
* Set of channels that consists of a unique identifier, its control metadata information, and the message itself;
|
||||
* :dfn:`Virtual distributed event dispatcher` (VDED), the bus logic responsible for sending notifications to the observers. The VDED logic runs inside the publishing action in the same thread context, giving the bus an idea of a distributed execution. When a thread publishes to a channel, it also propagates the notifications to the observers;
|
||||
* Threads (subscribers) and callbacks (listeners) publishing, reading, and receiving notifications from the bus.
|
||||
|
||||
.. _zbus anatomy:
|
||||
.. figure:: images/zbus_anatomy.svg
|
||||
:alt: Zbus anatomy
|
||||
:width: 70%
|
||||
|
||||
Zbus internals details.
|
||||
|
||||
The bus makes the publish, read, and subscribe actions available over channels. Publishing and reading are available in all RTOS contexts except inside an Interrupt Service Routine (ISR). The publish and read operations were designed to be simple and fast; the procedure is a mutex locking followed by a memory copy to and from a shared memory region. Zbus observers' registration can be:
|
||||
|
||||
* Static, defined in compile time. It is not possible to remove at runtime, but it is possible to suppress it by calling the :c:func:`zbus_obs_set_enable`;
|
||||
* Dynamic, it can be added and removed to and from a channel at runtime.
|
||||
|
||||
|
||||
For illustration purposes, suppose a usual sensor-based solution in :numref:`zbus operations`. When the timer is triggered, it pushes an action to a workqueue that publishes to the ``Start trigger`` channel. As the sensor thread subscribed to the ``Start trigger`` channel, it starts to fetch the sensor data. Notice the event dispatcher executes the blink callback because it also listens to the ``Start trigger`` channel. When the sensor data is ready, the sensor thread publishes it to the ``Sensor data`` channel. The core thread as a ``Sensor data`` channel subscriber process the sensor data and stores it in a internal sample buffer. It repeats until the sample buffer is full; when it happens, the core thread aggregates the sample buffer information, prepares a package, and publishes that to the ``Payload`` channel. The Lora thread receives that because it is a ``Payload`` channel subscriber and sends the payload to the cloud. When the transmission is completed, the Lora thread publishes to the ``Transmission done`` channel. The blink callback will be executed again since it listens to the ``Transmission done`` channel.
|
||||
|
||||
|
||||
|
||||
.. _zbus operations:
|
||||
.. figure:: images/zbus_operations.svg
|
||||
:alt: Zbus sensor-based application
|
||||
:width: 80%
|
||||
|
||||
Zbus sensor-based application.
|
||||
|
||||
This way of implementing the solution gives us certain flexibility enabling us to change things independently. For example, suppose we would like to change the trigger from a timer to a button press. We can do that, and the change does not affect other parts of the system. Suppose, again, we would like to change the communication interface from LoRa to Bluetooth; for that, we only need to change the LoRa thread. No other change is needed to make that work. Thus, the developer would do that for every block of the image. Based on that, there is a sign zbus promotes decoupling in the system architecture.
|
||||
|
||||
Another important aspect of using zbus is the reuse of system modules. If a module, code portion with a set of well-defined behaviors, only uses zbus channels and not hardware interfaces, it can easily be reused in other solutions. For that, the new solution must implement the interfaces (set of channels) the module needs to work. That indicates zbus could improve the module reuse.
|
||||
|
||||
The last important note is the zbus solution reach. We can count on many different ways of using zbus to enable the developer to be as free as possible to create what they need with it. Messages can be dynamic or static allocated, notifications can be synchronous or asynchronous, the developer can control the channel in so many different ways claiming the channel, developers can add their metadata information to a channel by using the user-data field, the discretionary use of a validator enables the systems to be accurate over message format, and so on. Those characteristics increase the solutions that can be done with zbus and make it a good fit as an open-source community tool.
|
||||
|
||||
Limitations
|
||||
===========
|
||||
|
||||
Based on the fact that developers can use zbus to solve many different problems, some challenges arise. Zbus will not solve every problem, so it is necessary to analyze the situation to be sure zbus is applicable. For instance, based on the zbus benchmark, it would not be well suited to a high-speed stream of bytes between threads. The `Pipe` kernel object solves this kind of need.
|
||||
|
||||
Delivery guarantees
|
||||
-------------------
|
||||
|
||||
Zbus always delivers the messages to the listeners. However, there are no message delivery guarantees for subscribers because zbus only sends the notification, but the message reading depends on the subscriber's implementation. It is possible to increase the delivery rate by following design tips:
|
||||
|
||||
* Keep the listeners quick-as-possible (deal with them as ISRs). If some processing is needed, consider submitting a work to a work-queue;
|
||||
* Try to give producers a high priority to avoid losses;
|
||||
* Leave spare CPU for observers to consume data produced;
|
||||
* Consider using message queues or pipes for intensive byte transfers.
|
||||
|
||||
|
||||
Message delivery sequence
|
||||
-------------------------
|
||||
|
||||
The listeners (synchronous observers) will follow the channel definition sequence as the notification and message consumption sequence. However, the subscribers, as they have an asynchronous nature, all will receive the notification as the channel definition sequence but only will consume the data when they execute again, so the delivery respects the order, but the priority assigned to the subscribers will define the reaction sequence. All the listeners (static o dynamic) will receive the message before subscribers receive the notification. The sequence of delivery is: (i) static listeners; (ii) runtime listeners; (iii) static subscribers; at last (iv) runtime subscribers.
|
||||
|
||||
Implementation
|
||||
**************
|
||||
|
||||
Zbus operation depends on channels and observers. Therefore, it is necessary to determine its message and observers list during the channel definition. A message is a regular C struct; the observer can be a subscriber (asynchronous) or a listener (synchronous). Channels can have a ``validator function`` that enables a channel to accept only valid messages.
|
||||
|
||||
The following code defines and initializes a regular channel and its dependencies. This channel exchanges accelerometer data, for example.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
struct acc_msg {
|
||||
int x;
|
||||
int y;
|
||||
int z;
|
||||
};
|
||||
|
||||
ZBUS_CHAN_DEFINE(acc_chan, /* Name */
|
||||
struct acc_msg, /* Message type */
|
||||
|
||||
NULL, /* Validator */
|
||||
NULL, /* User Data */
|
||||
ZBUS_OBSERVERS(my_listener, my_subscriber), /* observers */
|
||||
ZBUS_MSG_INIT(.x = 0, .y = 0, .z = 0) /* Initial value {0} */
|
||||
);
|
||||
|
||||
void listener_callback_example(const struct zbus_channel *chan)
|
||||
{
|
||||
const struct acc_msg *acc;
|
||||
if (&acc_chan == chan) {
|
||||
acc = zbus_chan_const_msg(chan); // Direct message access
|
||||
LOG_DBG("From listener -> Acc x=%d, y=%d, z=%d", acc->x, acc->y, acc->z);
|
||||
}
|
||||
}
|
||||
|
||||
ZBUS_LISTENER_DEFINE(my_listener, listener_callback_example);
|
||||
|
||||
ZBUS_SUBSCRIBER_DEFINE(my_subscriber, 4);
|
||||
void subscriber_task(void)
|
||||
{
|
||||
const struct zbus_channel *chan;
|
||||
|
||||
while (!zbus_sub_wait(&my_subscriber, &chan, K_FOREVER)) {
|
||||
struct acc_msg acc = {0};
|
||||
|
||||
if (&acc_chan == chan) {
|
||||
// Indirect message access
|
||||
zbus_chan_read(&acc_chan, &acc, K_NO_WAIT);
|
||||
LOG_DBG("From subscriber -> Acc x=%d, y=%d, z=%d", acc.x, acc.y, acc.z);
|
||||
}
|
||||
}
|
||||
}
|
||||
K_THREAD_DEFINE(subscriber_task_id, 512, subscriber_task, NULL, NULL, NULL, 3, 0, 0);
|
||||
|
||||
|
||||
.. note::
|
||||
It is unnecessary to claim/lock a channel before accessing the message inside the listener since the event dispatcher calls listeners with the notifying channel already locked. Subscribers, however, must claim/lock that or use regular read operations to access the message after being notified.
|
||||
|
||||
The following code defines and initializes a :dfn:`hard channel` and its dependencies. Only valid messages can be published to a :dfn:`hard channel`. It is possible because a ``Validator function`` passed to the channel's definition. In this example, only messages with ``move`` equal to 0, -1, and 1 are valid. Publish function will discard all other values to ``move``.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
struct control_msg {
|
||||
int move;
|
||||
};
|
||||
|
||||
bool control_validator(const void* msg, size_t msg_size) {
|
||||
const struct control_msg* cm = msg;
|
||||
bool is_valid = (cm->move == -1) || (cm->move == 0) || (cm->move == 1);
|
||||
return is_valid;
|
||||
}
|
||||
|
||||
static int message_count = 0;
|
||||
|
||||
ZBUS_CHAN_DEFINE(control_chan, /* Name */
|
||||
struct control_msg, /* Message type */
|
||||
|
||||
control_validator, /* Validator */
|
||||
&message_count, /* User data */
|
||||
ZBUS_OBSERVERS_EMPTY, /* observers */
|
||||
ZBUS_MSG_INIT(.move = 0) /* Initial value {.move=0} */
|
||||
);
|
||||
|
||||
The following sections describe in detail how to use zbus features.
|
||||
|
||||
|
||||
Publishing to a channel
|
||||
=======================
|
||||
|
||||
Messages are published to a channel in zbus by calling :c:func:`zbus_chan_pub`. For example, the following code builds on the examples above and publishes to channel ``acc_chan``. The code is trying to publish the message ``acc1`` to channel ``acc_chan``, and it will wait up to one second for the message to be published. Otherwise, the operation fails.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
struct acc_msg acc1 = {.x = 1, .y = 1, .z = 1};
|
||||
zbus_chan_pub(&acc_chan, &acc1, K_SECONDS(1));
|
||||
|
||||
.. warning::
|
||||
Do not use this function inside an ISR.
|
||||
|
||||
Reading from a channel
|
||||
======================
|
||||
|
||||
Messages are read from a channel in zbus by calling :c:func:`zbus_chan_read`. So, for example, the following code tries to read the channel ``acc_chan``, which will wait up to 500 milliseconds to read the message. Otherwise, the operation fails.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
struct acc_msg acc = {0};
|
||||
zbus_chan_read(&acc_chan, &acc, K_MSEC(500));
|
||||
|
||||
.. warning::
|
||||
Do not use this function inside an ISR.
|
||||
|
||||
Forcing channel notification
|
||||
============================
|
||||
|
||||
It is possible to force zbus to notify a channel's observers by calling :c:func:`zbus_chan_notify`. For example, the following code builds on the examples above and forces a notification for the channel ``acc_chan``. Note this can send events with no message, which does not require any data exchange.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
zbus_chan_notify(&acc_chan, K_NO_WAIT);
|
||||
|
||||
.. warning::
|
||||
Do not use this function inside an ISR.
|
||||
|
||||
Declaring channels and observers
|
||||
================================
|
||||
|
||||
For accessing channels or observers from files other than its defining files, it is necessary to declare them by calling :c:macro:`ZBUS_CHAN_DECLARE` and :c:macro:`ZBUS_OBS_DECLARE`. It is possible to declare more than one channel or observer at the same call. The following code builds on the examples above and displays the defined channels and observers.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
ZBUS_OBS_DECLARE(my_listener, my_subscriber);
|
||||
ZBUS_CHAN_DECLARE(acc_chan, version_chan);
|
||||
|
||||
|
||||
Iterating over channels and observers
|
||||
=====================================
|
||||
|
||||
There is an iterator mechanism in zbus that enables the developer to execute some procedure per channel and observer. The sequence executed is sorted by channel or observer name.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
int count;
|
||||
|
||||
bool print_channel_data_iterator(const struct zbus_channel *chan)
|
||||
{
|
||||
LOG_DBG("%d - Channel %s:", count, zbus_chan_name(chan));
|
||||
LOG_DBG(" Message size: %d", zbus_chan_msg_size(chan));
|
||||
++count;
|
||||
LOG_DBG(" Observers:");
|
||||
for (struct zbus_observer **obs = chan->observers; *obs != NULL; ++obs) {
|
||||
LOG_DBG(" - %s", zbus_obs_name(*obs));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool print_observer_data_iterator(const struct zbus_observer *obs)
|
||||
{
|
||||
LOG_DBG("%d - %s %s", count, ((obs->queue != NULL) ? "Subscriber" : "Listener"), zbus_obs_name(obs));
|
||||
++count;
|
||||
return true;
|
||||
}
|
||||
void main(void)
|
||||
{
|
||||
LOG_DBG("Channel list:");
|
||||
count = 0;
|
||||
zbus_iterate_over_channels(print_channel_data_iterator);
|
||||
|
||||
LOG_DBG("Observers list:");
|
||||
count = 0;
|
||||
zbus_iterate_over_observers(print_observer_data_iterator);
|
||||
}
|
||||
|
||||
The code will log the following output:
|
||||
|
||||
.. code-block:: console
|
||||
|
||||
D: Channel list:
|
||||
D: 0 - Channel acc_chan:
|
||||
D: Message size: 12
|
||||
D: Observers:
|
||||
D: - my_listener
|
||||
D: - my_subscriber
|
||||
D: 1 - Channel version_chan:
|
||||
D: Message size: 4
|
||||
D: Observers:
|
||||
D: Observers list:
|
||||
D: 0 - Listener my_listener
|
||||
D: 1 - Subscriber my_subscriber
|
||||
|
||||
|
||||
Advanced channel control
|
||||
========================
|
||||
|
||||
Zbus was designed to be as flexible and extensible as possible. Thus there are some features designed to provide some control and extensibility to the bus.
|
||||
|
||||
Listeners message access
|
||||
------------------------
|
||||
|
||||
For performance purposes, listeners can access the receiving channel message directly since they already have the mutex lock for it. To access the channel's message, the listener should use the ``zbus_chan_const_msg`` because the channel passed as an argument to the listener function is a constant pointer to the channel. The const pointer ensures that the message will be kept unchanged during the notification process.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
void listener_callback_example(const struct zbus_channel *chan)
|
||||
{
|
||||
const struct acc_msg *acc;
|
||||
if (&acc_chan == chan) {
|
||||
acc = zbus_chan_const_msg(chan); // Use this
|
||||
// instead of zbus_chan_read(chan, &acc, K_MSEC(200))
|
||||
// or zbus_chan_msg(chan)
|
||||
|
||||
LOG_DBG("From listener -> Acc x=%d, y=%d, z=%d", acc->x, acc->y, acc->z);
|
||||
}
|
||||
}
|
||||
|
||||
User Data
|
||||
---------
|
||||
|
||||
There is a possibility of injecting data into the channel's metadata by passing the ``user_data`` pointer to the channel's definition macro. The ``user_data`` field enables others to access the data. Note that it needs to be set individually for each channel.
|
||||
|
||||
Claim and finish a channel
|
||||
--------------------------
|
||||
|
||||
To take more control over channels, two function were added :c:func:`zbus_chan_claim` and :c:func:`zbus_chan_finish`. With these functions, it is possible to access the channel's metadata safely. When a channel is claimed, no actions are available to that channel. After finishing the channel, all the actions are available again.
|
||||
|
||||
.. warning::
|
||||
Never change the fields of the channel struct directly. It may cause zbus behavior inconsistencies and concurrency issues.
|
||||
|
||||
The following code builds on the examples above and claims the ``acc_chan`` to set the ``user_data`` to the channel. Suppose we would like to count how many times the channels exchange messages. We defined the ``user_data`` to have the 32 bits integer. This code could be added to the listener code described above.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
|
||||
int *message_counting = (int *) zbus_chan_user_data(acc_chan);
|
||||
*message_counting += 1;
|
||||
zbus_chan_finish(&acc_chan);
|
||||
}
|
||||
|
||||
.. warning::
|
||||
Do not use these functions inside an ISR.
|
||||
|
||||
|
||||
Runtime observer registration
|
||||
-----------------------------
|
||||
|
||||
It is possible to add observers to channels in runtime. This feature uses the object pool pattern technique in which the dynamic nodes are pre-allocated and can be used and recycled. Therefore, it is necessary to set the pool size by changing the feature :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE` to enable this feature. Furthermore, it uses memory slabs. When necessary, turn on the :kconfig:option:`CONFIG_MEM_SLAB_TRACE_MAX_UTILIZATION` configuration to track the maximum usage of the pool. The following example illustrates the runtime registration usage.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
ZBUS_LISTENER_DEFINE(my_listener, callback);
|
||||
// ...
|
||||
void thread_entry(void) {
|
||||
// ...
|
||||
/* Adding the observer to channel chan1 */
|
||||
zbus_chan_add_obs(&chan1, &my_listener);
|
||||
/* Removing the observer from channel chan1 */
|
||||
zbus_chan_rm_obs(&chan1, &my_listener);
|
||||
|
||||
|
||||
Zbus can only use a limited number of dynamic observers. The configuration option :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE` represents the size of the runtime observers pool (memory slab). Change that to fit the solution needs. Use the :c:func:`k_mem_slab_num_used_get` to verify how many runtime observers slots are available. The function :c:func:`k_mem_slab_max_used_get` will provide information regarding the maximum number of used slots count reached during the execution. Use that to set the appropriate pool size avoiding waste. The following code illustrates how to use that.
|
||||
|
||||
.. code-block:: c
|
||||
|
||||
extern struct k_mem_slab _zbus_runtime_obs_pool;
|
||||
uint32_t slots_available = k_mem_slab_num_free_get(&_zbus_runtime_obs_pool);
|
||||
uint32_t max_usage = k_mem_slab_max_used_get(&_zbus_runtime_obs_pool);
|
||||
|
||||
|
||||
.. warning::
|
||||
Do not use ``_zbus_runtime_obs_pool`` memory slab directly. It may lead to inconsistencies.
|
||||
|
||||
Samples
|
||||
*******
|
||||
|
||||
For a complete overview of zbus usage, take a look at the samples. There are the following samples available:
|
||||
|
||||
* :ref:`zbus-hello-world-sample` illustrates the code used above in action;
|
||||
* :ref:`zbus-work-queue-sample` shows how to define and use different kinds of observers. Note there is an example of using a work queue instead of executing the listener as an execution option;
|
||||
* :ref:`zbus-dyn-channel-sample` demonstrates how to use dynamically allocated exchanging data in zbus;
|
||||
* :ref:`zbus-uart-bridge-sample` shows an example of sending the operation of the channel to a host via serial;
|
||||
* :ref:`zbus-remote-mock-sample` illustrates how to implement an external mock (on the host) to send and receive messages to and from the bus.
|
||||
* :ref:`zbus-runtime-obs-registration-sample` illustrates a way of using the runtime observer registration feature;
|
||||
* :ref:`zbus-benchmark-sample` implements a benchmark with different combinations of inputs.
|
||||
|
||||
Suggested Uses
|
||||
**************
|
||||
|
||||
Use zbus to transfer data (messages) between threads in one-to-one, one-to-many, and many-to-many synchronously or asynchronously.
|
||||
|
||||
.. note::
|
||||
Zbus can be used to transfer streams from the producer to the consumer. However, this can increase zbus' communication latency. So maybe consider a Pipe a good alternative for this communication topology.
|
||||
|
||||
Configuration Options
|
||||
*********************
|
||||
|
||||
For enabling zbus, it is necessary to enable the :kconfig:option:`CONFIG_ZBUS` option.
|
||||
|
||||
Related configuration options:
|
||||
|
||||
* :kconfig:option:`CONFIG_ZBUS_CHANNEL_NAME`
|
||||
* :kconfig:option:`CONFIG_ZBUS_OBSERVER_NAME`
|
||||
* :kconfig:option:`CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS`
|
||||
* :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE`
|
||||
|
||||
API Reference
|
||||
*************
|
||||
|
||||
.. doxygengroup:: zbus_apis
|
615
include/zephyr/zbus/zbus.h
Normal file
615
include/zephyr/zbus/zbus.h
Normal file
|
@ -0,0 +1,615 @@
|
|||
/*
|
||||
* Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#ifndef ZEPHYR_INCLUDE_ZBUS_H_
|
||||
#define ZEPHYR_INCLUDE_ZBUS_H_
|
||||
|
||||
#include <string.h>
|
||||
|
||||
#include <zephyr/kernel.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Zbus API
|
||||
* @defgroup zbus_apis Zbus APIs
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Type used to represent a channel.
|
||||
*
|
||||
* Every channel has a zbus_channel structure associated used to control the channel
|
||||
* access and usage.
|
||||
*/
|
||||
struct zbus_channel {
|
||||
#if defined(CONFIG_ZBUS_CHANNEL_NAME) || defined(__DOXYGEN__)
|
||||
/** Channel name. */
|
||||
const char *const name;
|
||||
#endif
|
||||
/** Message size. Represents the channel's message size. */
|
||||
const uint16_t message_size;
|
||||
|
||||
/** User data available to extend zbus features. The channel must be claimed before
|
||||
* using this field.
|
||||
*/
|
||||
void *const user_data;
|
||||
|
||||
/** Message reference. Represents the message's reference that points to the actual
|
||||
* shared memory region.
|
||||
*/
|
||||
void *const message;
|
||||
|
||||
/** Message validator. Stores the reference to the function to check the message
|
||||
* validity before actually performing the publishing. No invalid messages can be
|
||||
* published. Every message is valid when this field is empty.
|
||||
*/
|
||||
bool (*const validator)(const void *msg, size_t msg_size);
|
||||
|
||||
/** Access control mutex. Points to the mutex used to avoid race conditions
|
||||
* for accessing the channel.
|
||||
*/
|
||||
struct k_mutex *mutex;
|
||||
#if (CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0) || defined(__DOXYGEN__)
|
||||
/** Dynamic channel observer list. Represents the channel's observers list, it can be empty
|
||||
* or have listeners and subscribers mixed in any sequence. It can be changed in runtime.
|
||||
*/
|
||||
sys_slist_t *runtime_observers;
|
||||
#endif /* CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE */
|
||||
|
||||
/** Channel observer list. Represents the channel's observers list, it can be empty or
|
||||
* have listeners and subscribers mixed in any sequence.
|
||||
*/
|
||||
const struct zbus_observer *const *observers;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Type used to represent an observer.
|
||||
*
|
||||
* Every observer has an representation structure containing the relevant information.
|
||||
* An observer is a code portion interested in some channel. The observer can be notified
|
||||
* synchronously or asynchronously and it is called listener and subscriber respectively.
|
||||
* The observer can be enabled or disabled during runtime by change the enabled boolean
|
||||
* field of the structure. The listeners have a callback function that is executed by the
|
||||
* bus with the index of the changed channel as argument when the notification is sent.
|
||||
* The subscribers have a message queue where the bus enqueues the index of the changed
|
||||
* channel when a notification is sent.
|
||||
*
|
||||
* @see zbus_obs_set_enable function to properly change the observer's enabled field.
|
||||
*
|
||||
*/
|
||||
struct zbus_observer {
|
||||
#if defined(CONFIG_ZBUS_OBSERVER_NAME) || defined(__DOXYGEN__)
|
||||
/** Observer name. */
|
||||
const char *const name;
|
||||
#endif
|
||||
/** Enabled flag. Indicates if observer is receiving notification. */
|
||||
bool enabled;
|
||||
/** Observer message queue. It turns the observer into a subscriber. */
|
||||
struct k_msgq *const queue;
|
||||
|
||||
/** Observer callback function. It turns the observer into a listener. */
|
||||
void (*const callback)(const struct zbus_channel *chan);
|
||||
};
|
||||
|
||||
/** @cond INTERNAL_HIDDEN */
|
||||
|
||||
#if defined(CONFIG_ZBUS_ASSERT_MOCK)
|
||||
#define _ZBUS_ASSERT(_cond, _fmt, ...) \
|
||||
do { \
|
||||
if (!(_cond)) { \
|
||||
printk("ZBUS ASSERT: "); \
|
||||
printk(_fmt, ##__VA_ARGS__); \
|
||||
printk("\n"); \
|
||||
return -EFAULT; \
|
||||
} \
|
||||
} while (0)
|
||||
#else
|
||||
#define _ZBUS_ASSERT(_cond, _fmt, ...) __ASSERT(_cond, _fmt, ##__VA_ARGS__)
|
||||
#endif
|
||||
|
||||
#if defined(CONFIG_ZBUS_CHANNEL_NAME)
|
||||
#define ZBUS_CHANNEL_NAME_INIT(_name) .name = #_name,
|
||||
#else
|
||||
#define ZBUS_CHANNEL_NAME_INIT(_name)
|
||||
#endif
|
||||
|
||||
#if defined(CONFIG_ZBUS_OBSERVER_NAME)
|
||||
#define ZBUS_OBSERVER_NAME_INIT(_name) .name = #_name,
|
||||
#define _ZBUS_OBS_NAME(_obs) (_obs)->name
|
||||
#else
|
||||
#define ZBUS_OBSERVER_NAME_INIT(_name)
|
||||
#define _ZBUS_OBS_NAME(_obs) ""
|
||||
#endif
|
||||
|
||||
#if CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0
|
||||
#define ZBUS_RUNTIME_OBSERVERS_LIST_DECL(_slist_name) static sys_slist_t _slist_name
|
||||
#define ZBUS_RUNTIME_OBSERVERS_LIST_INIT(_slist_name) .runtime_observers = &_slist_name,
|
||||
#else
|
||||
#define ZBUS_RUNTIME_OBSERVERS_LIST_DECL(_slist_name)
|
||||
#define ZBUS_RUNTIME_OBSERVERS_LIST_INIT(_slist_name) /* No runtime observers */
|
||||
#endif
|
||||
|
||||
#if defined(CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS)
|
||||
#define _ZBUS_STRUCT_DECLARE(_type, _name) STRUCT_SECTION_ITERABLE(_type, _name)
|
||||
#else
|
||||
#define _ZBUS_STRUCT_DECLARE(_type, _name) struct _type _name
|
||||
#endif /* CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS */
|
||||
|
||||
#define _ZBUS_OBS_EXTERN(_name) extern struct zbus_observer _name
|
||||
|
||||
#define _ZBUS_CHAN_EXTERN(_name) extern const struct zbus_channel _name
|
||||
|
||||
#define ZBUS_REF(_value) &(_value)
|
||||
|
||||
k_timeout_t _zbus_timeout_remainder(uint64_t end_ticks);
|
||||
/** @endcond */
|
||||
|
||||
/**
|
||||
* @def ZBUS_OBS_DECLARE
|
||||
* This macro list the observers to be used in a file. Internally, it declares the observers with
|
||||
* the extern statement. Note it is only necessary when the observers are declared outside the file.
|
||||
*/
|
||||
#define ZBUS_OBS_DECLARE(...) FOR_EACH(_ZBUS_OBS_EXTERN, (;), __VA_ARGS__)
|
||||
|
||||
/**
|
||||
* @def ZBUS_CHAN_DECLARE
|
||||
* This macro list the channels to be used in a file. Internally, it declares the channels with the
|
||||
* extern statement. Note it is only necessary when the channels are declared outside the file.
|
||||
*/
|
||||
#define ZBUS_CHAN_DECLARE(...) FOR_EACH(_ZBUS_CHAN_EXTERN, (;), __VA_ARGS__)
|
||||
|
||||
/**
|
||||
* @def ZBUS_OBSERVERS_EMPTY
|
||||
* This macro indicates the channel has no observers.
|
||||
*/
|
||||
#define ZBUS_OBSERVERS_EMPTY
|
||||
|
||||
/**
|
||||
* @def ZBUS_OBSERVERS
|
||||
* This macro indicates the channel has listed observers. Note the sequence of observer notification
|
||||
* will follow the same as listed.
|
||||
*/
|
||||
#define ZBUS_OBSERVERS(...) __VA_ARGS__
|
||||
|
||||
/**
|
||||
* @brief Zbus channel definition.
|
||||
*
|
||||
* This macro defines a channel.
|
||||
*
|
||||
* @param _name The channel's name.
|
||||
* @param _type The Message type. It must be a struct or union.
|
||||
* @param _validator The validator function.
|
||||
* @param _user_data A pointer to the user data.
|
||||
*
|
||||
* @see struct zbus_channel
|
||||
* @param _observers The observers list. The sequence indicates the priority of the observer. The
|
||||
* first the highest priority.
|
||||
* @param _init_val The message initialization.
|
||||
*/
|
||||
#define ZBUS_CHAN_DEFINE(_name, _type, _validator, _user_data, _observers, _init_val) \
|
||||
static _type _CONCAT(_zbus_message_, _name) = _init_val; \
|
||||
static K_MUTEX_DEFINE(_CONCAT(_zbus_mutex_, _name)); \
|
||||
ZBUS_RUNTIME_OBSERVERS_LIST_DECL(_CONCAT(_runtime_observers_, _name)); \
|
||||
FOR_EACH_NONEMPTY_TERM(_ZBUS_OBS_EXTERN, (;), _observers) \
|
||||
static const struct zbus_observer *const _CONCAT(_zbus_observers_, _name)[] = { \
|
||||
FOR_EACH_NONEMPTY_TERM(ZBUS_REF, (,), _observers) NULL}; \
|
||||
const _ZBUS_STRUCT_DECLARE(zbus_channel, _name) = { \
|
||||
ZBUS_CHANNEL_NAME_INIT(_name) /* Name */ \
|
||||
.message_size = sizeof(_type), /* Message size */ \
|
||||
.user_data = _user_data, /* User data */ \
|
||||
.message = &_CONCAT(_zbus_message_, _name), /* Reference to the message */\
|
||||
.validator = (_validator), /* Validator function */ \
|
||||
.mutex = &_CONCAT(_zbus_mutex_, _name), /* Channel's Mutex */ \
|
||||
ZBUS_RUNTIME_OBSERVERS_LIST_INIT( \
|
||||
_CONCAT(_runtime_observers_, _name)) /* Runtime observer list */ \
|
||||
.observers = _CONCAT(_zbus_observers_, _name)} /* Static observer list */
|
||||
|
||||
/**
|
||||
* @brief Initialize a message.
|
||||
*
|
||||
* This macro initializes a message by passing the values to initialize the message struct
|
||||
* or union.
|
||||
*
|
||||
* @param[in] _val Variadic with the initial values. ``ZBUS_INIT(0)`` means ``{0}``, as
|
||||
* ZBUS_INIT(.a=10, .b=30) means ``{.a=10, .b=30}``.
|
||||
*/
|
||||
#define ZBUS_MSG_INIT(_val, ...) \
|
||||
{ \
|
||||
_val, ##__VA_ARGS__ \
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Define and initialize a subscriber.
|
||||
*
|
||||
* This macro defines an observer of subscriber type. It defines a message queue where the
|
||||
* subscriber will receive the notification asynchronously, and initialize the ``struct
|
||||
* zbus_observer`` defining the subscriber.
|
||||
*
|
||||
* @param[in] _name The subscriber's name.
|
||||
* @param[in] _queue_size The notification queue's size.
|
||||
*/
|
||||
#define ZBUS_SUBSCRIBER_DEFINE(_name, _queue_size) \
|
||||
K_MSGQ_DEFINE(_zbus_observer_queue_##_name, sizeof(const struct zbus_channel *), \
|
||||
_queue_size, sizeof(const struct zbus_channel *)); \
|
||||
_ZBUS_STRUCT_DECLARE(zbus_observer, \
|
||||
_name) = {ZBUS_OBSERVER_NAME_INIT(_name) /* Name field */ \
|
||||
.enabled = true, \
|
||||
.queue = &_zbus_observer_queue_##_name, .callback = NULL}
|
||||
|
||||
/**
|
||||
* @brief Define and initialize a listener.
|
||||
*
|
||||
* This macro defines an observer of listener type. This macro establishes the callback where the
|
||||
* listener will be notified synchronously, and initialize the ``struct zbus_observer`` defining the
|
||||
* listener.
|
||||
*
|
||||
* @param[in] _name The listener's name.
|
||||
* @param[in] _cb The callback function.
|
||||
*/
|
||||
#define ZBUS_LISTENER_DEFINE(_name, _cb) \
|
||||
_ZBUS_STRUCT_DECLARE(zbus_observer, \
|
||||
_name) = {ZBUS_OBSERVER_NAME_INIT(_name) /* Name field */ \
|
||||
.enabled = true, \
|
||||
.queue = NULL, .callback = (_cb)}
|
||||
|
||||
/**
|
||||
*
|
||||
* @brief Publish to a channel
|
||||
*
|
||||
* This routine publishes a message to a channel.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
* @param msg Reference to the message where the publish function copies the channel's
|
||||
* message data from.
|
||||
* @param timeout Waiting period to publish the channel,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Channel published.
|
||||
* @retval -ENOMSG The message is invalid based on the validator function or some of the
|
||||
* observers could not receive the notification.
|
||||
* @retval -EBUSY The channel is busy.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -EFAULT A parameter is incorrect, the notification could not be sent to one or more
|
||||
* observer, or the function context is invalid (inside an ISR). The function only returns this
|
||||
* value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_chan_pub(const struct zbus_channel *chan, const void *msg, k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Read a channel
|
||||
*
|
||||
* This routine reads a message from a channel.
|
||||
*
|
||||
* @param[in] chan The channel's reference.
|
||||
* @param[out] msg Reference to the message where the read function copies the channel's
|
||||
* message data to.
|
||||
* @param[in] timeout Waiting period to read the channel,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Channel read.
|
||||
* @retval -EBUSY The channel is busy.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -EFAULT A parameter is incorrect, or the function context is invalid (inside an ISR). The
|
||||
* function only returns this value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_chan_read(const struct zbus_channel *chan, void *msg, k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Claim a channel
|
||||
*
|
||||
* This routine claims a channel. During the claiming period the channel is blocked for publishing,
|
||||
* reading, notifying or claiming again. Finishing is the only available action.
|
||||
*
|
||||
* @warning After calling this routine, the channel cannot be used by other
|
||||
* thread until the zbus_chan_finish routine is performed.
|
||||
*
|
||||
* @warning This routine should only be called once before a zbus_chan_finish.
|
||||
*
|
||||
* @param[in] chan The channel's reference.
|
||||
* @param[in] timeout Waiting period to claim the channel,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Channel claimed.
|
||||
* @retval -EBUSY The channel is busy.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -EFAULT A parameter is incorrect, or the function context is invalid (inside an ISR). The
|
||||
* function only returns this value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_chan_claim(const struct zbus_channel *chan, k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Finish a channel claim.
|
||||
*
|
||||
* This routine finishes a channel claim. After calling this routine with success, the channel will
|
||||
* be able to be used by other thread.
|
||||
*
|
||||
* @warning This routine must only be used after a zbus_chan_claim.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
*
|
||||
* @retval 0 Channel finished.
|
||||
* @retval -EPERM The channel was claimed by other thread.
|
||||
* @retval -EINVAL The channel's mutex is not locked.
|
||||
* @retval -EFAULT A parameter is incorrect, or the function context is invalid (inside an ISR). The
|
||||
* function only returns this value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_chan_finish(const struct zbus_channel *chan);
|
||||
|
||||
/**
|
||||
* @brief Force a channel notification.
|
||||
*
|
||||
* This routine forces the event dispatcher to notify the channel's observers even if the message
|
||||
* has no changes. Note this function could be useful after claiming/finishing actions.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
* @param timeout Waiting period to notify the channel,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Channel notified.
|
||||
* @retval -EPERM The current thread does not own the channel.
|
||||
* @retval -EBUSY The channel's mutex returned without waiting.
|
||||
* @retval -EAGAIN Timeout to acquiring the channel's mutex.
|
||||
* @retval -EFAULT A parameter is incorrect, the notification could not be sent to one or more
|
||||
* observer, or the function context is invalid (inside an ISR). The function only returns this
|
||||
* value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_chan_notify(const struct zbus_channel *chan, k_timeout_t timeout);
|
||||
|
||||
#if defined(CONFIG_ZBUS_CHANNEL_NAME) || defined(__DOXYGEN__)
|
||||
|
||||
/**
|
||||
* @brief Get the channel's name.
|
||||
*
|
||||
* This routine returns the channel's name reference.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
*
|
||||
* @return Channel's name reference.
|
||||
*/
|
||||
static inline const char *zbus_chan_name(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
return chan->name;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Get the reference for a channel message directly.
|
||||
*
|
||||
* This routine returns the reference of a channel message.
|
||||
*
|
||||
* @warning This function must only be used directly for acquired (locked by mutex) channels. This
|
||||
* can be done inside a listener for the receiving channel or after claim a channel.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
*
|
||||
* @return Channel's message reference.
|
||||
*/
|
||||
static inline void *zbus_chan_msg(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
return chan->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get a constant reference for a channel message directly.
|
||||
*
|
||||
* This routine returns a constant reference of a channel message. This should be used
|
||||
* inside listeners to access the message directly. In this way zbus prevents the listener of
|
||||
* changing the notifying channel's message during the notification process.
|
||||
*
|
||||
* @warning This function must only be used directly for acquired (locked by mutex) channels. This
|
||||
* can be done inside a listener for the receiving channel or after claim a channel.
|
||||
*
|
||||
* @param chan The channel's constant reference.
|
||||
*
|
||||
* @return A constant channel's message reference.
|
||||
*/
|
||||
static inline const void *zbus_chan_const_msg(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
return chan->message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the channel's message size.
|
||||
*
|
||||
* This routine returns the channel's message size.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
*
|
||||
* @return Channel's message size.
|
||||
*/
|
||||
static inline uint16_t zbus_chan_msg_size(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
return chan->message_size;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get the channel's user data.
|
||||
*
|
||||
* This routine returns the channel's user data.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
*
|
||||
* @return Channel's user data.
|
||||
*/
|
||||
static inline void *zbus_chan_user_data(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
return chan->user_data;
|
||||
}
|
||||
|
||||
#if (CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0) || defined(__DOXYGEN__)
|
||||
|
||||
/**
|
||||
* @brief Add an observer to a channel.
|
||||
*
|
||||
* This routine adds an observer to the channel.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
* @param obs The observer's reference to be added.
|
||||
* @param timeout Waiting period to add an observer,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Observer added to the channel.
|
||||
* @retval -EALREADY The observer is already present in the channel's runtime observers list.
|
||||
* @retval -ENOMEM Returned without waiting.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -EINVAL Some parameter is invalid.
|
||||
*/
|
||||
int zbus_chan_add_obs(const struct zbus_channel *chan, const struct zbus_observer *obs,
|
||||
k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Remove an observer from a channel.
|
||||
*
|
||||
* This routine removes an observer to the channel.
|
||||
*
|
||||
* @param chan The channel's reference.
|
||||
* @param obs The observer's reference to be removed.
|
||||
* @param timeout Waiting period to remove an observer,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Observer removed to the channel.
|
||||
* @retval -EINVAL Invalid data supplied.
|
||||
* @retval -EBUSY Returned without waiting.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -ENODATA no observer found in channel's runtime observer list.
|
||||
* @retval -ENOMEM Returned without waiting.
|
||||
*/
|
||||
int zbus_chan_rm_obs(const struct zbus_channel *chan, const struct zbus_observer *obs,
|
||||
k_timeout_t timeout);
|
||||
|
||||
/**
|
||||
* @brief Get zbus runtime observers pool.
|
||||
*
|
||||
* This routine returns a reference of the runtime observers pool.
|
||||
*
|
||||
* @return Reference of runtime observers pool.
|
||||
*/
|
||||
struct k_mem_slab *zbus_runtime_obs_pool(void);
|
||||
|
||||
/** @cond INTERNAL_HIDDEN */
|
||||
|
||||
struct zbus_observer_node {
|
||||
sys_snode_t node;
|
||||
const struct zbus_observer *obs;
|
||||
};
|
||||
|
||||
/** @endcond */
|
||||
|
||||
#endif /* CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE */
|
||||
|
||||
/**
|
||||
* @brief Change the observer state.
|
||||
*
|
||||
* This routine changes the observer state. A channel when disabled will not receive
|
||||
* notifications from the event dispatcher.
|
||||
*
|
||||
* @param[in] obs The observer's reference.
|
||||
* @param[in] enabled State to be. When false the observer stops to receive notifications.
|
||||
*
|
||||
* @retval 0 Observer set enable.
|
||||
* @retval -EFAULT A parameter is incorrect, or the function context is invalid (inside an ISR). The
|
||||
* function only returns this value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
static inline int zbus_obs_set_enable(struct zbus_observer *obs, bool enabled)
|
||||
{
|
||||
_ZBUS_ASSERT(obs != NULL, "obs is required");
|
||||
|
||||
obs->enabled = enabled;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#if defined(CONFIG_ZBUS_OBSERVER_NAME) || defined(__DOXYGEN__)
|
||||
|
||||
/**
|
||||
* @brief Get the observer's name.
|
||||
*
|
||||
* This routine returns the observer's name reference.
|
||||
*
|
||||
* @param obs The observer's reference.
|
||||
*
|
||||
* @return The observer's name reference.
|
||||
*/
|
||||
static inline const char *zbus_obs_name(const struct zbus_observer *obs)
|
||||
{
|
||||
__ASSERT(obs != NULL, "obs is required");
|
||||
|
||||
return obs->name;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Wait for a channel notification.
|
||||
*
|
||||
* This routine makes the subscriber to wait a notification. The notification comes as a channel
|
||||
* reference.
|
||||
*
|
||||
* @param[in] sub The subscriber's reference.
|
||||
* @param[out] chan The notification channel's reference.
|
||||
* @param[in] timeout Waiting period for a notification arrival,
|
||||
* or one of the special values K_NO_WAIT and K_FOREVER.
|
||||
*
|
||||
* @retval 0 Notification received.
|
||||
* @retval -ENOMSG Returned without waiting.
|
||||
* @retval -EAGAIN Waiting period timed out.
|
||||
* @retval -EINVAL The observer is not a subscriber.
|
||||
* @retval -EFAULT A parameter is incorrect, or the function context is invalid (inside an ISR). The
|
||||
* function only returns this value when the CONFIG_ZBUS_ASSERT_MOCK is enabled.
|
||||
*/
|
||||
int zbus_sub_wait(const struct zbus_observer *sub, const struct zbus_channel **chan,
|
||||
k_timeout_t timeout);
|
||||
|
||||
#if defined(CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS) || defined(__DOXYGEN__)
|
||||
/**
|
||||
*
|
||||
* @brief Iterate over channels.
|
||||
*
|
||||
* Enables the developer to iterate over the channels giving to this function an
|
||||
* iterator_func which is called for each channel. If the iterator_func returns false all
|
||||
* the iteration stops.
|
||||
*
|
||||
* @retval true Iterator executed for all channels.
|
||||
* @retval false Iterator could not be executed. Some iterate returned false.
|
||||
*/
|
||||
bool zbus_iterate_over_channels(bool (*iterator_func)(const struct zbus_channel *chan));
|
||||
|
||||
/**
|
||||
*
|
||||
* @brief Iterate over observers.
|
||||
*
|
||||
* Enables the developer to iterate over the observers giving to this function an
|
||||
* iterator_func which is called for each observer. If the iterator_func returns false all
|
||||
* the iteration stops.
|
||||
*
|
||||
* @retval true Iterator executed for all channels.
|
||||
* @retval false Iterator could not be executed. Some iterate returned false.
|
||||
*/
|
||||
bool zbus_iterate_over_observers(bool (*iterator_func)(const struct zbus_observer *obs));
|
||||
|
||||
#endif /* CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS */
|
||||
/**
|
||||
* @}
|
||||
*/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* ZEPHYR_INCLUDE_ZBUS_H_ */
|
|
@ -32,3 +32,4 @@ add_subdirectory_ifdef(CONFIG_DEMAND_PAGING demand_paging)
|
|||
add_subdirectory(modbus)
|
||||
add_subdirectory(sd)
|
||||
add_subdirectory(rtio)
|
||||
add_subdirectory_ifdef(CONFIG_ZBUS zbus)
|
||||
|
|
|
@ -72,4 +72,6 @@ source "subsys/demand_paging/Kconfig"
|
|||
|
||||
source "subsys/rtio/Kconfig"
|
||||
|
||||
source "subsys/zbus/Kconfig"
|
||||
|
||||
endmenu
|
||||
|
|
14
subsys/zbus/CMakeLists.txt
Normal file
14
subsys/zbus/CMakeLists.txt
Normal file
|
@ -0,0 +1,14 @@
|
|||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
zephyr_library()
|
||||
|
||||
zephyr_library_sources(zbus.c)
|
||||
|
||||
if(CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE GREATER 0)
|
||||
zephyr_library_sources(zbus_runtime_observers.c)
|
||||
endif()
|
||||
|
||||
if(CONFIG_ZBUS_STRUCTS_ITERABLE_ACCESS)
|
||||
zephyr_library_sources(zbus_iterable_sections.c)
|
||||
zephyr_linker_sources(DATA_SECTIONS zbus.ld)
|
||||
endif()
|
43
subsys/zbus/Kconfig
Normal file
43
subsys/zbus/Kconfig
Normal file
|
@ -0,0 +1,43 @@
|
|||
# Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
menuconfig ZBUS
|
||||
bool "Zbus support"
|
||||
help
|
||||
Enables support for Zephyr message bus.
|
||||
|
||||
if ZBUS
|
||||
|
||||
config ZBUS_STRUCTS_ITERABLE_ACCESS
|
||||
bool "Zbus iterable sections support."
|
||||
depends on !XTENSA && !ARCH_POSIX
|
||||
default y
|
||||
|
||||
config ZBUS_CHANNEL_NAME
|
||||
bool "Channel name field"
|
||||
|
||||
config ZBUS_OBSERVER_NAME
|
||||
bool "Observer name field"
|
||||
|
||||
config ZBUS_RUNTIME_OBSERVERS_POOL_SIZE
|
||||
int "The size of the runtime observers pool."
|
||||
default 0
|
||||
help
|
||||
When the size is bigger than zero this feature will be enabled. It applies the Object Pool Pattern,
|
||||
where the objects in the pool are pre-allocated and can be used and recycled after use. The
|
||||
technique avoids dynamic allocation and allows the code to increase the number of observers by
|
||||
only changing a configuration.
|
||||
|
||||
config ZBUS_ASSERT_MOCK
|
||||
bool "Zbus assert mock for test purposes."
|
||||
help
|
||||
This configuration enables the developer to change the _ZBUS_ASSERT behavior. When this configuration is
|
||||
enabled, _ZBUS_ASSERT returns -EFAULT instead of assert. It makes it more straightforward to test invalid
|
||||
parameters.
|
||||
|
||||
|
||||
module = ZBUS
|
||||
module-str = zbus
|
||||
source "subsys/logging/Kconfig.template.log_config"
|
||||
|
||||
endif # ZBUS
|
204
subsys/zbus/zbus.c
Normal file
204
subsys/zbus/zbus.c
Normal file
|
@ -0,0 +1,204 @@
|
|||
/*
|
||||
* Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/sys/printk.h>
|
||||
#include <zephyr/zbus/zbus.h>
|
||||
LOG_MODULE_REGISTER(zbus, CONFIG_ZBUS_LOG_LEVEL);
|
||||
|
||||
k_timeout_t _zbus_timeout_remainder(uint64_t end_ticks)
|
||||
{
|
||||
int64_t now_ticks = sys_clock_tick_get();
|
||||
|
||||
return K_TICKS((k_ticks_t)MAX(end_ticks - now_ticks, 0));
|
||||
}
|
||||
|
||||
#if (CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0)
|
||||
static inline void _zbus_notify_runtime_listeners(const struct zbus_channel *chan)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
struct zbus_observer_node *obs_nd, *tmp;
|
||||
|
||||
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->runtime_observers, obs_nd, tmp, node) {
|
||||
|
||||
__ASSERT(obs_nd != NULL, "observer node is NULL");
|
||||
|
||||
if (obs_nd->obs->enabled && (obs_nd->obs->callback != NULL)) {
|
||||
obs_nd->obs->callback(chan);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static inline int _zbus_notify_runtime_subscribers(const struct zbus_channel *chan,
|
||||
uint64_t end_ticks)
|
||||
{
|
||||
__ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
int last_error = 0, err;
|
||||
struct zbus_observer_node *obs_nd, *tmp;
|
||||
|
||||
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->runtime_observers, obs_nd, tmp, node) {
|
||||
|
||||
__ASSERT(obs_nd != NULL, "observer node is NULL");
|
||||
|
||||
if (obs_nd->obs->enabled && (obs_nd->obs->queue != NULL)) {
|
||||
err = k_msgq_put(obs_nd->obs->queue, &chan,
|
||||
_zbus_timeout_remainder(end_ticks));
|
||||
|
||||
_ZBUS_ASSERT(err == 0,
|
||||
"could not deliver notification to observer %s. Error code %d",
|
||||
_ZBUS_OBS_NAME(obs_nd->obs), err);
|
||||
|
||||
if (err) {
|
||||
last_error = err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return last_error;
|
||||
}
|
||||
#endif /* CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE */
|
||||
|
||||
static int _zbus_notify_observers(const struct zbus_channel *chan, uint64_t end_ticks)
|
||||
{
|
||||
int last_error = 0, err;
|
||||
/* Notify static listeners */
|
||||
for (const struct zbus_observer *const *obs = chan->observers; *obs != NULL; ++obs) {
|
||||
if ((*obs)->enabled && ((*obs)->callback != NULL)) {
|
||||
(*obs)->callback(chan);
|
||||
}
|
||||
}
|
||||
|
||||
#if CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0
|
||||
_zbus_notify_runtime_listeners(chan);
|
||||
#endif /* CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE */
|
||||
|
||||
/* Notify static subscribers */
|
||||
for (const struct zbus_observer *const *obs = chan->observers; *obs != NULL; ++obs) {
|
||||
if ((*obs)->enabled && ((*obs)->queue != NULL)) {
|
||||
err = k_msgq_put((*obs)->queue, &chan, _zbus_timeout_remainder(end_ticks));
|
||||
_ZBUS_ASSERT(err == 0, "could not deliver notification to observer %s.",
|
||||
_ZBUS_OBS_NAME(*obs));
|
||||
if (err) {
|
||||
LOG_ERR("Observer %s at %p could not be notified. Error code %d",
|
||||
_ZBUS_OBS_NAME(*obs), *obs, err);
|
||||
last_error = err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE > 0
|
||||
err = _zbus_notify_runtime_subscribers(chan, end_ticks);
|
||||
if (err) {
|
||||
last_error = err;
|
||||
}
|
||||
#endif /* CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE */
|
||||
return last_error;
|
||||
}
|
||||
|
||||
int zbus_chan_pub(const struct zbus_channel *chan, const void *msg, k_timeout_t timeout)
|
||||
{
|
||||
int err;
|
||||
uint64_t end_ticks = sys_clock_timeout_end_calc(timeout);
|
||||
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
_ZBUS_ASSERT(msg != NULL, "msg is required");
|
||||
|
||||
if (chan->validator != NULL && !chan->validator(msg, chan->message_size)) {
|
||||
return -ENOMSG;
|
||||
}
|
||||
|
||||
err = k_mutex_lock(chan->mutex, timeout);
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
memcpy(chan->message, msg, chan->message_size);
|
||||
|
||||
err = _zbus_notify_observers(chan, end_ticks);
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
int zbus_chan_read(const struct zbus_channel *chan, void *msg, k_timeout_t timeout)
|
||||
{
|
||||
int err;
|
||||
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
_ZBUS_ASSERT(msg != NULL, "msg is required");
|
||||
|
||||
err = k_mutex_lock(chan->mutex, timeout);
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
memcpy(msg, chan->message, chan->message_size);
|
||||
|
||||
return k_mutex_unlock(chan->mutex);
|
||||
}
|
||||
|
||||
int zbus_chan_notify(const struct zbus_channel *chan, k_timeout_t timeout)
|
||||
{
|
||||
int err;
|
||||
uint64_t end_ticks = sys_clock_timeout_end_calc(timeout);
|
||||
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
err = k_mutex_lock(chan->mutex, timeout);
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
err = _zbus_notify_observers(chan, end_ticks);
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
int zbus_chan_claim(const struct zbus_channel *chan, k_timeout_t timeout)
|
||||
{
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
int err = k_mutex_lock(chan->mutex, timeout);
|
||||
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int zbus_chan_finish(const struct zbus_channel *chan)
|
||||
{
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
int err = k_mutex_unlock(chan->mutex);
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
int zbus_sub_wait(const struct zbus_observer *sub, const struct zbus_channel **chan,
|
||||
k_timeout_t timeout)
|
||||
{
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "zbus cannot be used inside ISRs");
|
||||
_ZBUS_ASSERT(sub != NULL, "sub is required");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
|
||||
if (sub->queue == NULL) {
|
||||
return -EINVAL;
|
||||
}
|
||||
|
||||
return k_msgq_get(sub->queue, chan, timeout);
|
||||
}
|
2
subsys/zbus/zbus.ld
Normal file
2
subsys/zbus/zbus.ld
Normal file
|
@ -0,0 +1,2 @@
|
|||
ITERABLE_SECTION_RAM(zbus_channel, 4)
|
||||
ITERABLE_SECTION_RAM(zbus_observer, 4)
|
27
subsys/zbus/zbus_iterable_sections.c
Normal file
27
subsys/zbus/zbus_iterable_sections.c
Normal file
|
@ -0,0 +1,27 @@
|
|||
/*
|
||||
* Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/zbus/zbus.h>
|
||||
LOG_MODULE_DECLARE(zbus, CONFIG_ZBUS_LOG_LEVEL);
|
||||
|
||||
bool zbus_iterate_over_channels(bool (*iterator_func)(const struct zbus_channel *chan))
|
||||
{
|
||||
STRUCT_SECTION_FOREACH(zbus_channel, chan) {
|
||||
if (!(*iterator_func)(chan)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool zbus_iterate_over_observers(bool (*iterator_func)(const struct zbus_observer *obs))
|
||||
{
|
||||
STRUCT_SECTION_FOREACH(zbus_observer, obs) {
|
||||
if (!(*iterator_func)(obs)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
106
subsys/zbus/zbus_runtime_observers.c
Normal file
106
subsys/zbus/zbus_runtime_observers.c
Normal file
|
@ -0,0 +1,106 @@
|
|||
/*
|
||||
* Copyright (c) 2022 Rodrigo Peixoto <rodrigopex@gmail.com>
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/zbus/zbus.h>
|
||||
|
||||
LOG_MODULE_DECLARE(zbus, CONFIG_ZBUS_LOG_LEVEL);
|
||||
|
||||
K_MEM_SLAB_DEFINE_STATIC(_zbus_runtime_obs_pool, sizeof(struct zbus_observer_node),
|
||||
CONFIG_ZBUS_RUNTIME_OBSERVERS_POOL_SIZE, 4);
|
||||
|
||||
struct k_mem_slab *zbus_runtime_obs_pool(void)
|
||||
{
|
||||
return &_zbus_runtime_obs_pool;
|
||||
}
|
||||
|
||||
int zbus_chan_add_obs(const struct zbus_channel *chan, const struct zbus_observer *obs,
|
||||
k_timeout_t timeout)
|
||||
{
|
||||
int err;
|
||||
struct zbus_observer_node *obs_nd, *tmp;
|
||||
uint64_t end_ticks = sys_clock_timeout_end_calc(timeout);
|
||||
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "ISR blocked");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
_ZBUS_ASSERT(obs != NULL, "obs is required");
|
||||
|
||||
/* Check if the observer is already a static observer */
|
||||
for (const struct zbus_observer *const *static_obs = chan->observers; *static_obs != NULL;
|
||||
++static_obs) {
|
||||
if (*static_obs == obs) {
|
||||
return -EEXIST;
|
||||
}
|
||||
}
|
||||
|
||||
err = k_mutex_lock(chan->mutex, timeout);
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Check if the observer is already a runtime observer */
|
||||
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->runtime_observers, obs_nd, tmp, node) {
|
||||
if (obs_nd->obs == obs) {
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return -EALREADY;
|
||||
}
|
||||
}
|
||||
|
||||
err = k_mem_slab_alloc(&_zbus_runtime_obs_pool, (void **)&obs_nd,
|
||||
_zbus_timeout_remainder(end_ticks));
|
||||
|
||||
if (err) {
|
||||
LOG_ERR("Could not allocate memory on runtime observers pool\n");
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
obs_nd->obs = obs;
|
||||
|
||||
sys_slist_append(chan->runtime_observers, &obs_nd->node);
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int zbus_chan_rm_obs(const struct zbus_channel *chan, const struct zbus_observer *obs,
|
||||
k_timeout_t timeout)
|
||||
{
|
||||
int err;
|
||||
struct zbus_observer_node *obs_nd, *tmp;
|
||||
struct zbus_observer_node *prev_obs_nd = NULL;
|
||||
|
||||
_ZBUS_ASSERT(!k_is_in_isr(), "ISR blocked");
|
||||
_ZBUS_ASSERT(chan != NULL, "chan is required");
|
||||
_ZBUS_ASSERT(obs != NULL, "obs is required");
|
||||
|
||||
err = k_mutex_lock(chan->mutex, timeout);
|
||||
if (err) {
|
||||
return err;
|
||||
}
|
||||
|
||||
SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->runtime_observers, obs_nd, tmp, node) {
|
||||
if (obs_nd->obs == obs) {
|
||||
sys_slist_remove(chan->runtime_observers, &prev_obs_nd->node,
|
||||
&obs_nd->node);
|
||||
|
||||
k_mem_slab_free(&_zbus_runtime_obs_pool, (void **)&obs_nd);
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
prev_obs_nd = obs_nd;
|
||||
}
|
||||
|
||||
k_mutex_unlock(chan->mutex);
|
||||
|
||||
return -ENODATA;
|
||||
}
|
Loading…
Reference in a new issue