services/zbus/index.html · services/zbus/index.rst 공식 원문 ↗

Zephyr 3.7.0 · Services · Software Bus

Zephyr bus (zbus)

Thread와 callback을 many-to-many channel contract로 분리해 synchronous·asynchronous message를 전달합니다.

Official pathservices/zbus/index.html
Source fileservices/zbus/index.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

본문 기준: Zephyr 3.7.0 LTS3 · 이후 유지보수 패치는 별도입니다.

Part 1

요약·해설

세 observer type, VDED delivery timing, HLP priority boost, delivery guarantee, channel control, pool sizing과 66개 API를 설명합니다.

Model

Channel · observer · VDED

Delivery

Sync callback · async reference · async copy

Control

Validator · claim · mask · runtime obs

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 53B7FC88C4724540CB7E299B621E26985CBA0238E6CEF959BEA6A7991A33E236
.. _zbus:

Zephyr bus (zbus)
#################

..
   Note to documentation authors: the diagrams included in this documentation page were designed
   using the following Figma library:
   https://www.figma.com/community/file/1292866458780627559/zbus-diagram-assets


The :dfn:`Zephyr bus - zbus` is a lightweight and flexible software bus enabling a simple way for
threads to talk to one another in a many-to-many way.

.. contents::
    :local:
    :depth: 2

Concepts
********
Threads can send messages to one or more observers using zbus. It makes the many-to-many
communication 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. Threads (or callbacks) use channels to exchange
messages. Additionally, besides other actions, threads can publish and observe channels. When a
thread publishes a message on a channel, the bus will make the message available to all the
published channel's observers. Based on the observer's type, it can access the message directly,
receive a copy of it, or even receive only a reference of the published channel.

The figure below shows an example of a typical application using zbus in which the application logic
(hardware independent) talks to other threads via software 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.


.. figure:: ../../../../services/zbus/images/zbus_overview.svg
    :alt: zbus usage overview
    :width: 75%

    A typical zbus application architecture.

The bus comprises:

* Set of channels that consists of the control metadata information, and the message itself;
* :dfn:`Virtual Distributed Event Dispatcher` (VDED), the bus logic responsible for sending
  notifications/messages 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 message subscribers) and callbacks (listeners) publishing, reading, and
  receiving notifications from the bus.

.. figure:: ../../../../services/zbus/images/zbus_anatomy.svg
    :alt: ZBus anatomy
    :width: 70%

    ZBus anatomy.

The bus makes the publish, read, claim, finish, notify, and subscribe actions available over
channels. Publishing, reading, claiming, and finishing are available in all RTOS thread contexts,
including ISRs. The publish and read operations are simple and fast; the procedure is channel
locking followed by a memory copy to and from a shared memory region and then a channel unlocking.
Another essential aspect of zbus is the observers. There are three types of observers:

.. figure:: ../../../../services/zbus/images/zbus_type_of_observers.svg
    :alt: ZBus observers type
    :width: 70%

    ZBus observers.

* Listeners, a callback that the event dispatcher executes every time an observed channel is
  published or notified;
* Subscriber, a thread-based observer that relies internally on a message queue where the event
  dispatcher puts a changed channel's reference every time an observed channel is published or
  notified. Note this kind of observer does not receive the message itself. It should read the
  message from the channel after receiving the notification;
* Message subscribers, a thread-based observer that relies internally on a FIFO where the event
  dispatcher puts a copy of the message every time an observed channel is published or notified.

Channel observation structures define the relationship between a channel and its observers. For
every observation, a pair channel/observer. Developers can statically allocate observation using the
:c:macro:`ZBUS_CHAN_DEFINE` or :c:macro:`ZBUS_CHAN_ADD_OBS`. There are also runtime observers,
enabling developers to create runtime observations. It is possible to disable an observer entirely
or observations individually.  The event dispatcher will ignore disabled observers and observations.

.. figure:: ../../../../services/zbus/images/zbus_observation_mask.svg
    :alt: ZBus observation mask.
    :width: 75%

    ZBus observation mask.

The above figure illustrates some states, from (a) to (d), for channels from ``C1`` to ``C5``,
``Subscriber 1``, and the observations. The last two are in orange to indicate they are dynamically
allocated (runtime observation). (a) shows that the observer and all observations are enabled. (b)
shows the observer is disabled, so the event dispatcher will ignore it. (c) shows the observer
enabled. However, there is one static observervation disabled. The event dispatcher will only stop
sending notifications from channel ``C3``.  In (d), the event dispatcher will stop sending
notifications from channels ``C3`` and ``C5`` to ``Subscriber 1``.


Suppose a usual sensor-based solution is in the figure below for illustration purposes. When
triggered, the timer publishes to the ``Trigger`` channel. As the sensor thread subscribed to the
``Trigger`` channel, it receives the sensor data. Notice the VDED executes the ``Blink`` because it
also listens to the ``Trigger`` channel. When the sensor data is ready, the sensor thread publishes
it to the ``Sensor data`` channel. The core thread receives the message as a ``Sensor data`` channel
message subscriber, processes the sensor data, and stores it in an 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 message subscriber and sends the payload to
the cloud. When it completes the transmission, the Lora thread publishes to the ``Transmission
done`` channel. The VDED executes the ``Blink`` again since it listens to the ``Transmission done``
channel.

.. figure:: ../../../../services/zbus/images/zbus_operations.svg
    :alt: ZBus sensor-based application
    :width: 85%

    ZBus sensor-based application.

This way of implementing the solution makes the application more flexible, enabling us to change
things independently. For example, we want 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. Likewise, we would like to
change the communication interface from LoRa to Bluetooth; we only need to change the LoRa thread.
No other change is required in order 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 code portion with
well-defined behaviors (we call that module) only uses zbus channels and not hardware interfaces, it
can easily be reused in other solutions. 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 ways of using zbus to
enable the developer to be as free as possible to create what they need. For example, 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.


.. _Virtual Distributed Event Dispatcher:

Virtual Distributed Event Dispatcher
====================================

The VDED execution always happens in the publisher's context. It can be a thread or an ISR. Be
careful with publications inside ISR because the scheduler won't preempt the VDED. Use that wisely.
The basic description of the execution is as follows:


* The channel lock is acquired;
* The channel receives the new message via direct copy (by a raw :c:func:`memcpy`);
* The event dispatcher logic executes the listeners, sends a copy of the message to the message
  subscribers, and pushes the channel's reference to the subscribers' notification message queue in
  the same sequence they appear on the channel observers' list. The listeners can perform non-copy
  quick access to the constant message reference directly (via the :c:func:`zbus_chan_const_msg`
  function) since the channel is still locked;
* At last, the publishing function unlocks the channel.


To illustrate the VDED execution, consider the example illustrated below. We have four threads in
ascending priority ``S1``, ``MS2``, ``MS1``, and ``T1`` (the highest priority); two listeners,
``L1`` and ``L2``; and channel A. Supposing ``L1``, ``L2``, ``MS1``, ``MS2``, and ``S1`` observer
channel A.

.. figure:: ../../../../services/zbus/images/zbus_publishing_process_example_scenario.svg
    :alt: ZBus example scenario
    :width: 45%

    ZBus VDED execution example scenario.


The following code implements channel A. Note the ``struct a_msg`` is illustrative only.

.. code-block:: c

    ZBUS_CHAN_DEFINE(a_chan,                       /* Name */
             struct a_msg,                         /* Message type */

             NULL,                                 /* Validator */
             NULL,                                 /* User Data */
             ZBUS_OBSERVERS(L1, L2, MS1, MS2, S1), /* observers */
             ZBUS_MSG_INIT(0)                      /* Initial value {0} */
    );


In the figure below, the letters indicate some action related to the VDED execution. The X-axis
represents the time, and the Y-axis represents the priority of threads. Channel A's message,
represented by a voice balloon, is only one memory portion (shared memory). It appears several times
only as an illustration of the message at that point in time.


.. figure:: ../../../../services/zbus/images/zbus_publishing_process_example.svg
    :alt: ZBus publish processing detail
    :width: 85%

    ZBus VDED execution detail for priority T1 > MS1 > MS2 > S1.



The figure above illustrates the actions performed during the VDED execution when T1 publishes to
channel A. Thus, the table below describes the activities (represented by a letter) of the VDED
execution. The scenario considers the following priorities: T1 > MS1 > MS2 > S1. T1 has the highest
priority.


.. list-table:: VDED execution steps in detail for priority T1 > MS1 > MS2 > S1.
   :widths: 5 65
   :header-rows: 1

   * - Actions
     - Description
   * - a
     - T1 starts and, at some point, publishes to channel A.
   * - b
     - The publishing (VDED) process starts. The VDED locks the channel A.
   * - c
     - The VDED copies the T1 message to the channel A message.

   * - d, e
     - The VDED executes L1 and L2 in the respective sequence. Inside the listeners, usually, there
       is a call to the :c:func:`zbus_chan_const_msg` function, which provides a direct constant
       reference to channel A's message. It is quick, and no copy is needed here.

   * - f, g
     - The VDED copies the message and sends that to MS1 and MS2 sequentially. Notice the threads
       get ready to execute right after receiving the notification. However, they go to a pending
       state because they have less priority than T1.
   * - h
     - The VDED pushes the notification message to the queue of S1. Notice the thread gets ready to
       execute right after receiving the notification. However, it goes to a pending state because
       it cannot access the channel since it is still locked.

   * - i
     - VDED finishes the publishing by unlocking channel A. The MS1 leaves the pending state and
       starts executing.

   * - j
     - MS1 finishes execution. The MS2 leaves the pending state and starts executing.

   * - k
     - MS2 finishes execution. The S1 leaves the pending state and starts executing.

   * - l, m, n
     - The S1 leaves the pending state since channel A is not locked. It gets in the CPU again and
       starts executing. As it did receive a notification from channel A, it performed a channel read
       (as simple as lock, memory copy, unlock), continues its execution and goes out of the CPU.

   * - o
     - S1 finishes its workload.


The figure below illustrates the actions performed during the VDED execution when T1 publishes to
channel A. The scenario considers the following priorities: T1 < MS1 < MS2 < S1.

.. figure:: ../../../../services/zbus/images/zbus_publishing_process_example2.svg
    :alt: ZBus publish processing detail
    :width: 85%

    ZBus VDED execution detail for priority T1 < MS1 < MS2 < S1.

Thus, the table below describes the activities (represented by a letter) of the VDED execution.

.. list-table:: VDED execution steps in detail for priority T1 < MS1 < MS2 < S1.
   :widths: 5 65
   :header-rows: 1

   * - Actions
     - Description
   * - a
     - T1 starts and, at some point, publishes to channel A.
   * - b
     - The publishing (VDED) process starts. The VDED locks the channel A.
   * - c
     - The VDED copies the T1 message to the channel A message.

   * - d, e
     - The VDED executes L1 and L2 in the respective sequence. Inside the listeners, usually, there
       is a call to the :c:func:`zbus_chan_const_msg` function, which provides a direct constant
       reference to channel A's message. It is quick, and no copy is needed here.

   * - f
     - The VDED copies the message and sends that to MS1. MS1 preempts T1 and starts working.
       After that, the T1 regain MCU.

   * - g
     - The VDED copies the message and sends that to MS2. MS2 preempts T1 and starts working.
       After that, the T1 regain MCU.

   * - h
     - The VDED pushes the notification message to the queue of S1.

   * - i
     - VDED finishes the publishing by unlocking channel A.

   * - j, k, l
     - The S1 leaves the pending state since channel A is not locked. It gets in the CPU again and
       starts executing. As it did receive a notification from channel A, it performs a channel read
       (as simple as lock, memory copy, unlock), continues its execution, and goes out the CPU.


HLP priority boost
------------------
ZBus implements the Highest Locker Protocol that relies on the observers' thread priority to
determine a temporary publisher priority. The protocol considers the channel's Highest Observer
Priority (HOP); even if the observer is not waiting for a message on the channel, it is considered
in the calculation. The VDED will elevate the publisher's priority based on the HOP to ensure small
latency and as few preemptions as possible.

.. note::
    The priority boost is enabled by default. To deactivate it, you must set the
    :kconfig:option:`CONFIG_ZBUS_PRIORITY_BOOST` configuration.

.. warning::
    ZBus priority boost does not consider runtime observers on the HOP calculations.

The figure below illustrates the actions performed during the VDED execution when T1 publishes to
channel A. The scenario considers the priority boost feature and the following priorities: T1 < MS1
< MS2 < S1.

.. figure:: ../../../../services/zbus/images/zbus_publishing_process_example_HLP.svg
    :alt: ZBus publishing process details using priority boost.
    :width: 85%

    ZBus VDED execution detail with priority boost enabled and for priority T1 < MS1 < MS2 < S1.

To properly use the priority boost, attaching the observer to a thread is necessary. When the
subscriber is attached to a thread, it assumes its priority, and the priority boost algorithm will
consider the observer's priority. The following code illustrates the thread-attaching function.


.. code-block:: c
   :emphasize-lines: 10

   ZBUS_SUBSCRIBER_DEFINE(s1, 4);
   void s1_thread(void *ptr1, void *ptr2, void *ptr3)
   {
           ARG_UNUSED(ptr1);
           ARG_UNUSED(ptr2);
           ARG_UNUSED(ptr3);

           const struct zbus_channel *chan;

           zbus_obs_attach_to_thread(&s1);

           while (1) {
                   zbus_sub_wait(&s1, &chan, K_FOREVER);

                   /* Subscriber implementation */

           }
   }
   K_THREAD_DEFINE(s1_id, CONFIG_MAIN_STACK_SIZE, s1_thread, NULL, NULL, NULL, 2, 0, 0);

On the above code, the :c:func:`zbus_obs_attach_to_thread` will set the ``s1`` observer with
priority two as the thread has that priority. It is possible to reverse that by detaching the
observer using the :c:func:`zbus_obs_detach_from_thread`. Only enabled observers and observations
will be considered on the channel HOP calculation. Masking a specific observation of a channel will
affect the channel HOP.

In summary, the benefits of the feature are:

* The HLP is more effective for zbus than the mutexes priority inheritance;
* No bounded priority inversion will happen among the publisher and the observers;
* No other threads (that are not involved in the communication) with priority between T1 and S1 can
  preempt T1, avoiding unbounded priority inversion;
* Message subscribers will wait for the VDED to finish the message delivery process. So the VDED
  execution will be faster and more consistent;
* The HLP priority is dynamic and can change in execution;
* ZBus operations can be used inside ISRs;
* The priority boosting feature can be turned off, and plain semaphores can be used as the channel
  lock mechanism;
* The Highest Locker Protocol's major disadvantage, the Inheritance-related Priority Inversion, is
  acceptable in the zbus scenario since it will ensure a small bus latency.


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 and message subscribers. 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 item 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.

.. warning::
   ZBus uses :zephyr_file:`include/zephyr/net/buf.h` (network buffers) to exchange data with message
   subscribers. Thus, choose carefully the configurations
   :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE` and
   :kconfig:option:`CONFIG_HEAP_MEM_POOL_SIZE`. They are crucial to a proper VDED execution
   (delivery guarantee) considering message subscribers. If you want to keep an isolated pool for a
   specific set of channels, you can use
   :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION` with a dedicated pool. Look
   at the :zephyr:code-sample:`zbus-msg-subscriber` to see the isolation in action.

.. warning::
   Subscribers will receive only the reference of the changing channel. A data loss may be perceived
   if the channel is published twice before the subscriber reads it. The second publication
   overwrites the value from the first. Thus, the subscriber will receive two notifications, but
   only the last data is there.


.. _zbus delivery sequence:

Message delivery sequence
-------------------------

The message delivery will follow the precedence:

#. Observers defined in a channel using the :c:macro:`ZBUS_CHAN_DEFINE` (following the definition
   sequence);
#. Observers defined using the :c:macro:`ZBUS_CHAN_ADD_OBS` based on the sequence priority
   (parameter of the macro);
#. The latest is the runtime observers in the addition sequence using the
   :c:func:`zbus_chan_add_obs`.

.. note::
    The VDED will ignore all disabled observers or observations.

Usage
*****

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), a message subscriber (asynchronous), or a listener
(synchronous).

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,
                            my_msg_subscriber),          /* observers */
             ZBUS_MSG_INIT(.x = 0, .y = 0, .z = 0)       /* Initial value */
    );

    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_LISTENER_DEFINE(my_listener2, listener_callback_example);

    ZBUS_CHAN_ADD_OBS(acc_chan, my_listener2, 3);

    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);

    ZBUS_MSG_SUBSCRIBER_DEFINE(my_msg_subscriber);
    static void msg_subscriber_task(void *ptr1, void *ptr2, void *ptr3)
    {
            ARG_UNUSED(ptr1);
            ARG_UNUSED(ptr2);
            ARG_UNUSED(ptr3);
            const struct zbus_channel *chan;

            struct acc_msg acc = {0};

            while (!zbus_sub_wait_msg(&my_msg_subscriber, &chan, &acc, K_FOREVER)) {
                    if (&acc_chan == chan) {
                            LOG_INF("From msg subscriber -> Acc x=%d, y=%d, z=%d", acc.x, acc.y, acc.z);
                    }
            }
    }
    K_THREAD_DEFINE(msg_subscriber_task_id, 1024, msg_subscriber_task, NULL, NULL, NULL, 3, 0, 0);



It is possible to add static observers to a channel using the :c:macro:`ZBUS_CHAN_ADD_OBS`. We call
that a post-definition static observer. The command enables us to indicate an initialization
priority that affects the observers' initialization order. The sequence priority param only affects
the post-definition static observers. There is no possibility to overwrite the message delivery
sequence of the static observers.

.. 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.


Channels can have a `validator function` that enables a channel to accept only valid messages.
Publish attempts invalidated by hard channels will return immediately with an error code. This
allows original creators of a channel to exert some authority over other developers/publishers who
may want to piggy-back on their channels. 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` was 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 */
    );

The following sections describe in detail how to use zbus features.


.. _publishing to a channel:

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. As can be inferred from the code
sample, it's OK to use stack allocated messages since VDED copies the data internally.

.. code-block:: c

	struct acc_msg acc1 = {.x = 1, .y = 1, .z = 1};
	zbus_chan_pub(&acc_chan, &acc1, K_SECONDS(1));

.. warning::
    Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.

.. _reading from a channel:

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::
    Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.

.. warning::
   Choose the timeout of :c:func:`zbus_chan_read` after receiving a notification from
   :c:func:`zbus_sub_wait` carefully because the channel will always be unavailable during the VDED
   execution. Using ``K_NO_WAIT`` for reading is highly likely to return a timeout error if there
   are more than one subscriber. For example, consider the VDED illustration again and notice how
   ``S1`` read attempts would definitely fail with K_NO_WAIT. For more details, check
   the `Virtual Distributed Event Dispatcher`_ section.

Notifying a channel
===================

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. See the code example under `Claim and finish a channel`_ where this may become useful.

.. code-block:: c

    zbus_chan_notify(&acc_chan, K_NO_WAIT);

.. warning::
    Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.

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`. In other
words, zbus channel definitions and declarations with the same channel names in different files
would point to the same (global) channel. Thus, developers should be careful about existing
channels, and naming new channels or linking will fail. It is possible to declare more than one
channel or observer on 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
=====================================

ZBus subsystem also implements :ref:`Iterable Sections <iterable_sections_api>` for channels and
observers, for which there are supporting APIs like :c:func:`zbus_iterate_over_channels`,
:c:func:`zbus_iterate_over_channels_with_user_data`, :c:func:`zbus_iterate_over_observers` and
:c:func:`zbus_iterate_over_observers_with_user_data`. This feature enables developers to call a
procedure over all declared channels, where the procedure parameter is a :c:struct:`zbus_channel`.
The execution sequence is in the alphabetical name order of the channels (see :ref:`Iterable
Sections <iterable_sections_api>` documentation for details). ZBus also implements this feature for
:c:struct:`zbus_observer`.

.. code-block:: c

   static bool print_channel_data_iterator(const struct zbus_channel *chan, void *user_data)
   {
         int *count = user_data;

         LOG_INF("%d - Channel %s:", *count, zbus_chan_name(chan));
         LOG_INF("      Message size: %d", zbus_chan_msg_size(chan));
         LOG_INF("      Observers:");

         ++(*count);

         struct zbus_channel_observation *observation;

         for (int16_t i = *chan->observers_start_idx, limit = *chan->observers_end_idx; i < limit;
               ++i) {
               STRUCT_SECTION_GET(zbus_channel_observation, i, &observation);

               LOG_INF("      - %s", observation->obs->name);
         }

         struct zbus_observer_node *obs_nd, *tmp;

         SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->observers, obs_nd, tmp, node) {
               LOG_INF("      - %s", obs_nd->obs->name);
         }

         return true;
   }

   static bool print_observer_data_iterator(const struct zbus_observer *obs, void *user_data)
   {
         int *count = user_data;

         LOG_INF("%d - %s %s", *count, obs->queue ? "Subscriber" : "Listener", zbus_obs_name(obs));

         ++(*count);

         return true;
   }

   int main(void)
   {
         int count = 0;

         LOG_INF("Channel list:");

         zbus_iterate_over_channels_with_user_data(print_channel_data_iterator, &count);

         count = 0;

         LOG_INF("Observers list:");

         zbus_iterate_over_observers_with_user_data(print_observer_data_iterator, &count);

         return 0;
   }


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


.. _Claim and finish a channel:

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 channel locked for it. To access the channel's message, the listener should use the
:c:func:`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 return type tells developers not to modify the
message.

.. 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
---------
It is possible to pass custom data into the channel's ``user_data`` for various purposes, such as
writing channel metadata. That can be achieved by passing a pointer to the channel definition
macro's ``user_data`` field, which will then be accessible by others. Note that ``user_data`` is
individual for each channel. Also, note that ``user_data`` access is not thread-safe. For
thread-safe access to ``user_data``, see the next section.


Claim and finish a channel
--------------------------

To take more control over channels, two functions 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 scheduling issues.

.. warning::
    Only use this function inside an ISR with a :c:macro:`K_NO_WAIT` timeout.

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);
    }

The following code has the exact behavior of the code in :ref:`publishing to a channel`.

.. code-block:: c

    if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
            struct acc_msg *acc1 = (struct acc_msg *) zbus_chan_msg(&acc_chan);
            acc1.x = 1;
            acc1.y = 1;
            acc1.z = 1;
            zbus_chan_finish(&acc_chan);
            zbus_chan_notify(&acc_chan, K_SECONDS(1));
    }

The following code has the exact behavior of the code in :ref:`reading from a channel`.

.. code-block:: c

    if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
            const struct acc_msg *acc1 = (const struct acc_msg *) zbus_chan_const_msg(&acc_chan);
            // access the acc_msg fields directly.
            zbus_chan_finish(&acc_chan);
    }


Runtime observer registration
-----------------------------

It is possible to add observers to channels in runtime. This feature uses the heap to allocate the
nodes dynamically. The heap size limits the number of dynamic observers zbus can create. Therefore,
set the :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS` to enable the feature. It is possible to
adjust the heap size by changing the configuration :kconfig:option:`CONFIG_HEAP_MEM_POOL_SIZE`. 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, K_NO_WAIT);
            /* Removing the observer from channel chan1 */
            zbus_chan_rm_obs(&chan1, &my_listener, K_NO_WAIT);


Samples
*******

For a complete overview of zbus usage, take a look at the samples. There are the following samples
available:

* :zephyr:code-sample:`zbus-hello-world` illustrates the code used above in action;
* :zephyr:code-sample:`zbus-work-queue` 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;
* :zephyr:code-sample:`zbus-msg-subscriber` illustrates how to use message subscribers;
* :zephyr:code-sample:`zbus-dyn-channel` demonstrates how to use dynamically allocated exchanging
  data in zbus;
* :zephyr:code-sample:`zbus-uart-bridge` shows an example of sending the operation of the channel to
  a host via serial;
* :zephyr:code-sample:`zbus-remote-mock` illustrates how to implement an external mock (on the host)
  to send and receive messages to and from the bus;
* :zephyr:code-sample:`zbus-priority-boost` illustrates zbus priority boost feature with a priority
  inversion scenario;
* :zephyr:code-sample:`zbus-runtime-obs-registration` illustrates a way of using the runtime
  observer registration feature;
* :zephyr:code-sample:`zbus-confirmed-channel` implements a way of implement confirmed channel only
  with subscribers;
* :zephyr:code-sample:`zbus-benchmark` 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. Choosing the proper observer type is crucial. Use subscribers for
scenarios that can tolerate message losses and duplications; when they cannot, use message
subscribers (if you need a thread) or listeners (if you need to be lean and fast). In addition to
the listener, another asynchronous message processing mechanism (like :ref:`message queues
<message_queues_v2>`) may be necessary to retain the pending message until it gets processed.

.. 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_PRIORITY_BOOST` zbus Highest Locker Protocol implementation;
* :kconfig:option:`CONFIG_ZBUS_CHANNELS_SYS_INIT_PRIORITY` determine the :c:macro:`SYS_INIT`
  priority used by zbus to organize the channels observations by channel;
* :kconfig:option:`CONFIG_ZBUS_CHANNEL_NAME` enables the name of channels to be available inside the
  channels metadata. The log uses this information to show the channels' names;
* :kconfig:option:`CONFIG_ZBUS_OBSERVER_NAME` enables the name of observers to be available inside
  the channels metadata;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER` enables the message subscriber observer type;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_DYNAMIC` uses the heap to allocate message
  buffers;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_STATIC` uses the stack to allocate message
  buffers;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE` the available number of message
  buffers to be used simultaneously;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION` enables the developer to isolate
  a pool for the message subscriber for a set of channels;
* :kconfig:option:`CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_STATIC_DATA_SIZE` the biggest message of zbus
  channels to be transported into a message buffer;
* :kconfig:option:`CONFIG_ZBUS_RUNTIME_OBSERVERS` enables the runtime observer registration.

API Reference
*************

.. doxygengroup:: zbus_apis

Part 3

한국어 전문 번역

Zephyr bus(zbus)는 thread들이 서로 직접 reference를 알지 않고도 many-to-many로 통신하게 하는 가볍고 유연한 software bus입니다.

Concepts

Thread는 zbus channel에 message를 publish하고 하나 이상의 observer가 이를 받습니다. Shared memory 위 message-passing과 publish/subscribe를 결합해 synchronous 또는 asynchronous 통신을 제공합니다.

Communication unit은 channel입니다. Publisher가 channel에 message를 쓰면 observer type에 따라 shared message를 직접 읽거나, message copy를 받거나, 바뀐 channel reference만 notification으로 받습니다.

일반적인 zbus application architecture
일반적인 zbus application architecture · Zephyr 3.7.0 official SVG · SHA-256 F8657425AD0FCBAB22185D95D01DE5004C4DE8A46255E14C7DF02A11525B3153

Application logic은 hardware-independent channel interface로만 연결되므로 producer와 consumer가 서로를 몰라도 됩니다. Timer를 button으로, LoRa를 Bluetooth로 바꿔도 같은 channel contract를 유지하면 다른 module은 수정하지 않습니다.

Bus는 control metadata와 shared message를 가진 channel 집합, observer delivery를 수행하는 VDED(Virtual Distributed Event Dispatcher), publish·read·notification을 사용하는 thread와 callback으로 구성됩니다. VDED는 publisher의 thread 또는 ISR context 안에서 분산 실행됩니다.

Channel, VDED와 observer로 구성된 zbus anatomy
Channel, VDED와 observer로 구성된 zbus anatomy · Zephyr 3.7.0 official SVG · SHA-256 29C6487FA9CF9697BEA0A4887BA2A0184FEB83AF0C8EF72FAF4130673EC698F0

Channel action은 publish, read, claim, finish, notify, subscribe입니다. Publish와 read는 channel lock, shared memory memcpy, unlock의 짧은 경로입니다. Publish·read·claim·finish는 ISR을 포함한 RTOS context에서 사용할 수 있지만 ISR timeout은 K_NO_WAIT이어야 합니다.

Listener, subscriber와 message subscriber 비교
Listener, subscriber와 message subscriber 비교 · Zephyr 3.7.0 official SVG · SHA-256 EF837AAD30EE0D3D7A37E42CCD071A1FF396B37EE86801FF1218216D8AD3D5A0
  • Listener: Channel publish·notify 때마다 VDED가 publisher context에서 synchronous callback으로 실행합니다.
  • Subscriber: 내부 message queue로 changed channel reference만 받습니다. Notification 뒤 channel을 다시 read해야 하므로 중간 publish가 덮어쓸 수 있습니다.
  • Message subscriber: 내부 FIFO와 network buffer로 published message copy를 받아 loss 없는 asynchronous thread 처리를 지원합니다.

Channel observation은 channel/observer 한 쌍의 관계입니다. ZBUS_CHAN_DEFINE 또는 ZBUS_CHAN_ADD_OBS로 static allocation하고 runtime observer API로 dynamic 관계를 만들 수 있습니다. Observer 전체 또는 observation 하나만 disable/mask할 수 있으며 VDED는 disabled 관계를 건너뜁니다.

Observer와 channel observation mask 상태
Observer와 channel observation mask 상태 · Zephyr 3.7.0 official SVG · SHA-256 70AFF4E6AB83E921B55FDD2EFCE94890D7CE562A1A7BC29526C4E4DB7C763940

그림 (a)는 observer와 모든 observation이 enabled입니다. (b)는 observer 전체 disabled라 C1~C5 notification을 모두 무시합니다. (c)는 C3 static observation만 mask합니다. (d)는 C3 static 관계와 C5 runtime 관계를 mask해 Subscriber 1에 두 channel의 notification을 보내지 않습니다.

Sensor 예에서는 timer가 Trigger를 publish하고 sensor thread와 Blink listener가 반응합니다. Sensor thread는 Sensor data를 publish하고 core message subscriber가 sample buffer를 채웁니다. Buffer가 가득 차면 Payload를 publish해 LoRa thread가 cloud로 전송하고 Transmission done을 publish하면 Blink가 다시 실행됩니다.

Sensor, core, LoRa와 blink module의 channel pipeline
Sensor, core, LoRa와 blink module의 channel pipeline · Zephyr 3.7.0 official SVG · SHA-256 A52CADA9F0B18969CEF20A9EC44F9565E969FEB4EC3854954B0D21CF73410928

Channel interface만 유지하면 trigger source, transport와 processing module을 독립 교체할 수 있어 architecture decoupling과 module reuse가 좋아집니다. Hardware interface가 아닌 channel set에만 의존하는 module은 새 solution이 같은 channel contract를 제공하기만 하면 재사용할 수 있습니다.

Message는 static 또는 dynamic allocation, notification은 sync 또는 async로 설계할 수 있습니다. Claim으로 channel을 직접 제어하고, user data로 metadata를 붙이고, validator로 허용 message format을 강제할 수 있습니다.

Virtual Distributed Event Dispatcher

VDED는 항상 publisher context에서 실행됩니다. ISR publish에서는 scheduler가 VDED를 preempt하지 않으므로 observer 수, listener 실행 시간과 buffer allocation을 매우 짧게 유지해야 합니다.

  1. Channel lock을 얻습니다.
  2. 새 message를 raw memcpy로 shared message에 복사합니다.
  3. Observer list 순서대로 listener를 실행하고 message subscriber에 copy를 보내며 subscriber queue에 channel reference를 넣습니다. Listener는 lock이 유지된 동안 zbus_chan_const_msg()로 copy 없이 읽을 수 있습니다.
  4. 마지막에 channel을 unlock합니다.

예제에는 낮은 순서부터 S1, MS2, MS1, 가장 높은 T1 네 thread와 listener L1·L2, channel A가 있습니다. 다섯 observer 모두 channel A를 관찰합니다.

VDED priority example의 channel과 observer 구성
VDED priority example의 channel과 observer 구성 · Zephyr 3.7.0 official SVG · SHA-256 018FBCE2F41570961E81B62F51720223EDB5559922E52414BB8951591C545C6E
ZBUS_CHAN_DEFINE(a_chan,                       /* Name */
         struct a_msg,                         /* Message type */

         NULL,                                 /* Validator */
         NULL,                                 /* User Data */
         ZBUS_OBSERVERS(L1, L2, MS1, MS2, S1), /* observers */
         ZBUS_MSG_INIT(0)                      /* Initial value {0} */
);

첫 timing은 T1 > MS1 > MS2 > S1입니다. Message balloon은 여러 copy가 아니라 channel A의 shared memory 한 곳을 시간축 위치마다 반복 표시한 것입니다.

T1이 가장 높은 priority일 때 VDED 실행
T1이 가장 높은 priority일 때 VDED 실행 · Zephyr 3.7.0 official SVG · SHA-256 3462DD3D7E8DB1E6A6B69A922EFF6020F365827EBC093436607312AE3CBD30DF
동작설명
aT1이 실행을 시작하고 어느 시점에 channel A에 publish합니다.
bVDED publish 과정이 시작되어 channel A를 lock합니다.
cT1 message를 channel A의 shared message 영역으로 복사합니다.
d, eL1, L2를 목록 순서로 실행합니다. Listener는 zbus_chan_const_msg()로 copy 없이 const message reference를 읽습니다.
f, gMessage를 MS1, MS2에 차례로 복사합니다. 두 thread는 ready가 되지만 T1보다 priority가 낮아 pending에 머뭅니다.
hS1 notification queue에 channel reference를 넣습니다. S1은 ready지만 channel이 lock되어 있고 priority도 낮아 대기합니다.
iVDED가 channel A를 unlock해 publish를 끝냅니다. MS1이 pending에서 나와 실행합니다.
jMS1 종료 뒤 MS2가 실행합니다.
kMS2 종료 뒤 S1이 실행합니다.
l, m, nS1이 channel A를 lock·copy·unlock 방식으로 읽고 자신의 처리를 계속한 뒤 CPU를 내놓습니다.
oS1 workload가 끝납니다.

두 번째 timing은 T1 < MS1 < MS2 < S1입니다. Publisher보다 observer thread priority가 높아 VDED가 enqueue/copy할 때마다 T1이 preempt됩니다.

T1이 가장 낮은 priority일 때 VDED 실행
T1이 가장 낮은 priority일 때 VDED 실행 · Zephyr 3.7.0 official SVG · SHA-256 ACCC1BFA7A1F5466FB198392B7AC1F38DACFE6D1E65E0FC3455D87C53B5F4E1C
동작설명
aT1이 실행을 시작하고 channel A에 publish합니다.
bVDED가 시작되어 channel A를 lock합니다.
cT1 message를 channel A message로 복사합니다.
d, eL1, L2가 순서대로 실행되고 const reference로 message를 직접 읽습니다.
fMessage를 MS1에 복사하자 더 높은 priority의 MS1이 T1을 preempt해 처리한 뒤 T1이 CPU를 되찾습니다.
gMS2도 message를 받은 즉시 T1을 preempt해 처리하고 돌아옵니다.
hS1 notification queue에 channel reference를 넣습니다.
iVDED가 channel A를 unlock하고 publish를 마칩니다.
j, k, lS1이 pending에서 나와 CPU를 얻고 channel을 read한 뒤 나머지 처리를 수행합니다.

HLP priority boost

zbus는 Highest Locker Protocol(HLP)을 구현합니다. Channel의 enabled observer에 연결된 thread priority 중 가장 높은 HOP(Highest Observer Priority)를 계산해 publisher를 일시 boost합니다. Observer가 현재 wait 중이 아니어도 계산에 들어갑니다. 목표는 VDED latency와 중간 preemption을 줄이는 것입니다.

HLP priority boost를 적용한 VDED 실행
HLP priority boost를 적용한 VDED 실행 · Zephyr 3.7.0 official SVG · SHA-256 D1C42AF89FB16FB5A4B48E832D131F70A731FA8AF288D8BB78700E92C7E631A9

Observer를 실제 thread에 attach해야 해당 priority가 HOP에 반영됩니다.

ZBUS_SUBSCRIBER_DEFINE(s1, 4);
void s1_thread(void *ptr1, void *ptr2, void *ptr3)
{
        ARG_UNUSED(ptr1);
        ARG_UNUSED(ptr2);
        ARG_UNUSED(ptr3);

        const struct zbus_channel *chan;

        zbus_obs_attach_to_thread(&s1);

        while (1) {
                zbus_sub_wait(&s1, &chan, K_FOREVER);

                /* Subscriber implementation */

        }
}
K_THREAD_DEFINE(s1_id, CONFIG_MAIN_STACK_SIZE, s1_thread, NULL, NULL, NULL, 2, 0, 0);

zbus_obs_attach_to_thread(&s1)은 priority 2인 thread와 s1을 연결합니다. zbus_obs_detach_from_thread()로 되돌립니다. Enabled observer·observation만 HOP에 포함되므로 observation mask도 channel HOP를 바꿉니다.

HLP는 mutex priority inheritance보다 zbus publish 경로에 적합하고 publisher-observer 사이 bounded inversion을 줄입니다. 통신과 무관한 중간 priority thread가 publisher를 preempt하지 못하고 message subscriber도 VDED delivery가 끝날 때까지 기다려 latency가 일정해집니다. Priority는 runtime에 바뀔 수 있고 ISR action도 가능하며 feature를 끄면 plain semaphore lock을 쓸 수 있습니다. Inheritance-related priority inversion 가능성은 작은 bus latency를 위해 받아들이는 tradeoff입니다.

Limitations

zbus는 모든 통신 문제에 맞지 않습니다. Benchmark 기준 thread 사이 high-speed byte stream에는 적합하지 않으며 이 경우 kernel Pipe가 더 낫습니다.

Delivery guarantees

Listener와 message subscriber에는 message를 전달하지만 subscriber에는 channel reference notification만 보장합니다. Subscriber가 읽기 전에 같은 channel이 두 번 publish되면 첫 data가 두 번째 값으로 덮어써지고 notification 두 개가 같은 최신 data를 가리킬 수 있습니다.

  • Listener를 ISR처럼 최대한 짧게 유지하고 긴 처리는 work queue로 넘깁니다.
  • Producer priority를 높여 publish 지연과 loss를 줄입니다.
  • Observer가 data를 소비할 CPU 시간을 남깁니다.
  • 집중적인 byte transfer는 message queue 또는 pipe를 고려합니다.

Message subscriber는 include/zephyr/net/buf.h network buffer를 사용합니다. CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE와 CONFIG_HEAP_MEM_POOL_SIZE를 delivery burst에 맞게 정해야 합니다. Channel set별 isolated pool은 CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION과 dedicated pool로 구성합니다.

Message delivery sequence

  1. ZBUS_CHAN_DEFINE 안 observer가 definition 순서대로 먼저 전달됩니다.
  2. ZBUS_CHAN_ADD_OBS의 post-definition static observer가 sequence priority 순서로 전달됩니다.
  3. zbus_chan_add_obs() runtime observer가 추가 순서대로 마지막에 전달됩니다.

Disabled observer 또는 masked observation은 VDED가 무시합니다.

Usage

Channel definition에서 regular C struct/union message type, validator, user data, observer 목록과 initial value를 정합니다. Observer는 asynchronous subscriber, asynchronous message subscriber 또는 synchronous listener입니다.

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,
                        my_msg_subscriber),          /* observers */
         ZBUS_MSG_INIT(.x = 0, .y = 0, .z = 0)       /* Initial value */
);

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_LISTENER_DEFINE(my_listener2, listener_callback_example);

ZBUS_CHAN_ADD_OBS(acc_chan, my_listener2, 3);

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);

ZBUS_MSG_SUBSCRIBER_DEFINE(my_msg_subscriber);
static void msg_subscriber_task(void *ptr1, void *ptr2, void *ptr3)
{
        ARG_UNUSED(ptr1);
        ARG_UNUSED(ptr2);
        ARG_UNUSED(ptr3);
        const struct zbus_channel *chan;

        struct acc_msg acc = {0};

        while (!zbus_sub_wait_msg(&my_msg_subscriber, &chan, &acc, K_FOREVER)) {
                if (&acc_chan == chan) {
                        LOG_INF("From msg subscriber -> Acc x=%d, y=%d, z=%d", acc.x, acc.y, acc.z);
                }
        }
}
K_THREAD_DEFINE(msg_subscriber_task_id, 1024, msg_subscriber_task, NULL, NULL, NULL, 3, 0, 0);

ZBUS_CHAN_ADD_OBS는 channel definition 뒤 static observer를 추가하고 initialization sequence priority를 지정합니다. 이 priority는 post-definition static observer끼리만 적용되며 definition 내부 observer의 delivery 순서를 덮어쓸 수 없습니다.

Listener callback은 VDED가 이미 channel lock을 잡은 상태이므로 다시 claim할 필요가 없습니다. Subscriber는 notification 뒤 regular read 또는 claim으로 message에 접근해야 합니다.

Hard channel은 validator가 message를 허용할 때만 publish합니다. 다음 control channel은 move가 -1, 0, 1일 때만 유효하며 다른 값은 즉시 error로 거절합니다. User data에는 32-bit message counter pointer를 둡니다.

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 */
);

Publishing to a channel

zbus_chan_pub()은 caller message를 internal shared storage로 복사하고 observer에 전달합니다. Stack message도 VDED가 즉시 copy하므로 안전합니다. 예제는 최대 1초 기다립니다.

struct acc_msg acc1 = {.x = 1, .y = 1, .z = 1};
zbus_chan_pub(&acc_chan, &acc1, K_SECONDS(1));

Reading from a channel

zbus_chan_read()은 shared message를 caller buffer로 복사합니다. 예제 timeout은 500 ms입니다.

struct acc_msg acc = {0};
zbus_chan_read(&acc_chan, &acc, K_MSEC(500));

Subscriber가 zbus_sub_wait() notification 직후 읽을 때 K_NO_WAIT은 위험합니다. VDED가 observer delivery를 끝낼 때까지 channel이 lock되어 있고 subscriber가 둘 이상이면 앞선 timing의 S1처럼 즉시 timeout될 가능성이 높습니다.

Notifying a channel

zbus_chan_notify()는 message data를 바꾸지 않고 observer event만 강제로 보냅니다. Claim/finish로 direct update한 뒤 별도 notification할 때 유용합니다.

zbus_chan_notify(&acc_chan, K_NO_WAIT);

Declaring channels and observers

Definition과 다른 file에서 global channel·observer를 사용하려면 ZBUS_CHAN_DECLARE와 ZBUS_OBS_DECLARE로 선언합니다. 같은 이름은 같은 object를 가리키므로 duplicate definition은 link failure를 만듭니다.

ZBUS_OBS_DECLARE(my_listener, my_subscriber);
ZBUS_CHAN_DECLARE(acc_chan, version_chan);

Iterating over channels and observers

Channel과 observer는 iterable section에 등록됩니다. 네 iterate API는 모든 declared object에 procedure를 호출하며 channel 순서는 이름 alphabetical order입니다. Callback이 false를 반환하면 순회를 중단합니다.

static bool print_channel_data_iterator(const struct zbus_channel *chan, void *user_data)
{
      int *count = user_data;

      LOG_INF("%d - Channel %s:", *count, zbus_chan_name(chan));
      LOG_INF("      Message size: %d", zbus_chan_msg_size(chan));
      LOG_INF("      Observers:");

      ++(*count);

      struct zbus_channel_observation *observation;

      for (int16_t i = *chan->observers_start_idx, limit = *chan->observers_end_idx; i < limit;
            ++i) {
            STRUCT_SECTION_GET(zbus_channel_observation, i, &observation);

            LOG_INF("      - %s", observation->obs->name);
      }

      struct zbus_observer_node *obs_nd, *tmp;

      SYS_SLIST_FOR_EACH_CONTAINER_SAFE(chan->observers, obs_nd, tmp, node) {
            LOG_INF("      - %s", obs_nd->obs->name);
      }

      return true;
}

static bool print_observer_data_iterator(const struct zbus_observer *obs, void *user_data)
{
      int *count = user_data;

      LOG_INF("%d - %s %s", *count, obs->queue ? "Subscriber" : "Listener", zbus_obs_name(obs));

      ++(*count);

      return true;
}

int main(void)
{
      int count = 0;

      LOG_INF("Channel list:");

      zbus_iterate_over_channels_with_user_data(print_channel_data_iterator, &count);

      count = 0;

      LOG_INF("Observers list:");

      zbus_iterate_over_observers_with_user_data(print_observer_data_iterator, &count);

      return 0;
}

예제 output은 두 channel과 두 observer의 이름, message size와 observation 관계를 보여 줍니다.

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

Listeners message access

Listener는 channel lock 안에서 실행되므로 zbus_chan_const_msg()로 message를 직접 읽을 수 있습니다. Const pointer는 notification 중 listener가 shared value를 바꾸지 못하게 합니다.

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

Channel definition의 user_data pointer로 channel별 metadata를 연결할 수 있습니다. 단순 access는 thread-safe하지 않으므로 concurrent update에는 claim/finish를 사용합니다.

Claim and finish a channel

zbus_chan_claim()으로 channel을 독점하면 finish 전까지 publish, read, notify와 다른 claim이 불가능합니다. Struct field를 직접 바꾸면 scheduler와 bus invariant가 깨질 수 있으므로 공개 accessor만 사용하고 모든 성공 claim은 반드시 finish합니다.

다음 listener-side 예제는 user data counter를 안전하게 증가시킵니다.

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);
}

Mutable message pointer를 claim 안에서 수정하고 finish 뒤 notify하면 regular publish와 같은 효과를 냅니다.

if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
        struct acc_msg *acc1 = (struct acc_msg *) zbus_chan_msg(&acc_chan);
        acc1.x = 1;
        acc1.y = 1;
        acc1.z = 1;
        zbus_chan_finish(&acc_chan);
        zbus_chan_notify(&acc_chan, K_SECONDS(1));
}

Const message pointer를 claim 안에서 읽으면 regular read와 같은 보호를 얻습니다.

if (!zbus_chan_claim(&acc_chan, K_MSEC(200))) {
        const struct acc_msg *acc1 = (const struct acc_msg *) zbus_chan_const_msg(&acc_chan);
        // access the acc_msg fields directly.
        zbus_chan_finish(&acc_chan);
}

Runtime observer registration

CONFIG_ZBUS_RUNTIME_OBSERVERS를 켜면 heap node로 observer를 runtime에 추가·제거할 수 있습니다. 가능한 수는 CONFIG_HEAP_MEM_POOL_SIZE에 제한됩니다.

ZBUS_LISTENER_DEFINE(my_listener, callback);
// ...
void thread_entry(void) {
        // ...
        /* Adding the observer to channel chan1 */
        zbus_chan_add_obs(&chan1, &my_listener, K_NO_WAIT);
        /* Removing the observer from channel chan1 */
        zbus_chan_rm_obs(&chan1, &my_listener, K_NO_WAIT);

Samples

  • zbus-hello-world: 위 기본 channel·observer code.
  • zbus-work-queue: 여러 observer와 listener 대신 work queue 사용.
  • zbus-msg-subscriber: Message subscriber와 pool isolation.
  • zbus-dyn-channel: Dynamically allocated message exchange.
  • zbus-uart-bridge: Channel operation을 host serial로 전달.
  • zbus-remote-mock: Host external mock과 bus 양방향 message.
  • zbus-priority-boost: Priority inversion scenario와 HLP.
  • zbus-runtime-obs-registration: Runtime observer 관계.
  • zbus-confirmed-channel: Subscriber만으로 confirmed channel 구현.
  • zbus-benchmark: Input 조합별 성능 측정.

Suggested Uses

Thread 사이 one-to-one, one-to-many, many-to-many data를 sync 또는 async로 전달할 때 사용합니다. Loss·duplicate를 허용할 수 있으면 subscriber, 허용할 수 없고 thread가 필요하면 message subscriber, 가장 lean하고 빠른 synchronous 처리는 listener를 선택합니다. Listener가 긴 처리를 해야 하면 message queue 같은 async mechanism으로 pending work를 보존합니다.

Producer-consumer stream도 만들 수 있지만 zbus latency가 커질 수 있으므로 continuous byte stream은 Pipe를 우선 검토합니다.

Configuration Options

CONFIG_ZBUS로 subsystem을 활성화합니다.

  • CONFIG_ZBUS_PRIORITY_BOOST: Highest Locker Protocol.
  • CONFIG_ZBUS_CHANNELS_SYS_INIT_PRIORITY: Observation을 channel별로 정리하는 SYS_INIT priority.
  • CONFIG_ZBUS_CHANNEL_NAME: Channel name metadata와 log 표시.
  • CONFIG_ZBUS_OBSERVER_NAME: Observer name metadata.
  • CONFIG_ZBUS_MSG_SUBSCRIBER: Message subscriber type.
  • CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_DYNAMIC: Heap message buffer.
  • CONFIG_ZBUS_MSG_SUBSCRIBER_BUF_ALLOC_STATIC: Stack message buffer.
  • CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_SIZE: 동시에 사용할 message buffer 수.
  • CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_POOL_ISOLATION: Channel set 전용 pool.
  • CONFIG_ZBUS_MSG_SUBSCRIBER_NET_BUF_STATIC_DATA_SIZE: Static buffer로 운반할 최대 channel message.
  • CONFIG_ZBUS_RUNTIME_OBSERVERS: Runtime observer registration.

API Reference

아래 66개 symbol은 static definition macro, observer type, channel·observer operation과 metadata structure를 포함합니다.

ZBUS_CHAN_ADD_OBS_WITH_MASK
Channel, observer, initial mask와 sequence priority를 받아 post-definition static observation을 만듭니다.
ZBUS_CHAN_ADD_OBS
Enabled 상태의 post-definition static channel/observer 관계를 sequence priority와 함께 추가합니다.
ZBUS_OBS_DECLARE
다른 source file에서 정의한 observer를 extern으로 선언합니다. 한 번에 여러 이름을 받을 수 있습니다.
ZBUS_CHAN_DECLARE
다른 source file의 global channel을 extern으로 선언합니다.
ZBUS_OBSERVERS_EMPTY
Channel에 static observer가 없음을 definition macro에 전달합니다.
ZBUS_OBSERVERS
Channel definition에 observer 목록을 넣으며 나열 순서가 notification precedence가 됩니다.
ZBUS_CHAN_DEFINE
Name, struct/union message type, validator, user data, observer 목록과 initial value로 channel을 정적으로 정의합니다.
ZBUS_MSG_INIT
Channel의 struct 또는 union message initial value를 지정합니다.
ZBUS_SUBSCRIBER_DEFINE_WITH_ENABLE
Notification channel reference를 받는 message queue 크기와 initial enabled state를 지정해 subscriber를 정의합니다.
ZBUS_SUBSCRIBER_DEFINE
처음부터 enabled인 subscriber와 notification queue를 정의합니다.
ZBUS_LISTENER_DEFINE_WITH_ENABLE
Synchronous callback과 initial enabled state를 가진 listener를 정의합니다.
ZBUS_LISTENER_DEFINE
처음부터 enabled인 listener와 callback을 정의합니다.
ZBUS_MSG_SUBSCRIBER_DEFINE_WITH_ENABLE
Published message copy를 받는 FIFO 기반 message subscriber와 initial state를 정의합니다.
ZBUS_MSG_SUBSCRIBER_DEFINE
처음부터 enabled인 message subscriber와 FIFO를 정의합니다.
zbus_observer_type
Listener, subscriber, message subscriber를 구분하는 observer type enumeration입니다.
zbus_observer_type.ZBUS_OBSERVER_LISTENER_TYPE
Publisher context에서 synchronous callback으로 실행되는 listener type입니다.
zbus_observer_type.ZBUS_OBSERVER_SUBSCRIBER_TYPE
Channel reference notification을 queue로 받는 asynchronous subscriber type입니다.
zbus_observer_type.ZBUS_OBSERVER_MSG_SUBSCRIBER_TYPE
Message copy와 channel reference를 FIFO로 받는 asynchronous message subscriber type입니다.
zbus_chan_pub
Timeout 안에 channel을 lock하고 validator를 통과한 message를 복사한 뒤 VDED로 observer에 전달합니다. 성공 0, invalid/delivery failure -ENOMSG, busy -EBUSY, timeout -EAGAIN입니다.
zbus_chan_read
Timeout 안에 channel message를 caller buffer로 복사합니다. ISR에서는 K_NO_WAIT만 사용합니다.
zbus_chan_claim
Channel을 독점 lock해 publish·read·notify·재claim을 막습니다. 성공 뒤 반드시 한 번 zbus_chan_finish()해야 합니다.
zbus_chan_finish
Claim한 channel lock을 해제해 다른 action을 다시 허용합니다.
zbus_chan_notify
Message 변경 없이도 observer notification을 강제로 실행합니다. Buffer 고갈은 -ENOMEM일 수 있습니다.
zbus_chan_name
Channel metadata에 name support가 활성화됐을 때 name reference를 반환합니다.
zbus_chan_msg
이미 lock된 channel의 mutable message pointer를 직접 얻습니다. Listener 또는 claim 구간에서만 사용합니다.
zbus_chan_const_msg
이미 lock된 channel message의 const pointer를 반환해 listener가 copy 없이 안전하게 읽게 합니다.
zbus_chan_msg_size
Channel message type의 byte 크기를 반환합니다.
zbus_chan_user_data
Channel별 application metadata pointer를 반환합니다. 자체로는 thread-safe하지 않습니다.
zbus_chan_set_msg_sub_pool
Channel의 message subscriber가 사용할 전용 net_buf_pool을 지정합니다.
zbus_chan_add_obs
Heap node를 할당해 runtime observer를 channel에 추가합니다. 중복은 -EALREADY, 부족은 -ENOMEM입니다.
zbus_chan_rm_obs
Channel의 runtime observer 목록에서 observer를 제거합니다. 찾지 못하면 -ENODATA입니다.
zbus_obs_set_enable
Observer 전체 enabled state를 바꿉니다. Disabled observer는 어떤 channel notification도 받지 않습니다.
zbus_obs_is_enabled
Observer enabled state를 output boolean에 돌려줍니다.
zbus_obs_set_chan_notification_mask
특정 channel/observer observation만 mask 또는 unmask합니다. 관계가 없으면 -ESRCH입니다.
zbus_obs_is_chan_notification_masked
특정 observation의 notification mask state를 조회합니다.
zbus_obs_name
Observer metadata name reference를 반환합니다.
zbus_obs_attach_to_thread
현재 thread priority를 observer에 연결해 channel HOP와 priority boost 계산에 포함합니다.
zbus_obs_detach_from_thread
Observer에서 attached thread priority를 제거합니다.
zbus_sub_wait
Subscriber queue에서 channel reference notification을 timeout까지 기다립니다. Message는 이후 channel에서 직접 읽습니다.
zbus_sub_wait_msg
Message subscriber FIFO에서 channel reference와 published message copy를 기다립니다.
zbus_iterate_over_channels
이름의 alphabetical iterable-section 순서로 모든 channel에 callback을 호출하며 false가 나오면 중단합니다.
zbus_iterate_over_channels_with_user_data
User data를 함께 넘기며 모든 channel을 순회합니다.
zbus_iterate_over_observers
모든 observer를 iterable-section 순서로 순회하며 callback false에서 중단합니다.
zbus_iterate_over_observers_with_user_data
User data를 전달하면서 모든 observer를 순회합니다.
zbus_channel_data
Runtime observer range, channel lock, dynamic list와 message subscriber pool 같은 mutable channel state입니다.
zbus_channel_data.observers_start_idx
Iterable section에서 이 channel의 static observation 시작 index입니다.
zbus_channel_data.observers_end_idx
Static observation 범위의 exclusive end index입니다.
zbus_channel_data.sem
Publish·read·claim·notify를 직렬화하는 channel semaphore/lock입니다.
zbus_channel_data.observers
Runtime에 추가한 observer node의 singly linked list입니다.
zbus_channel_data.msg_subscriber_pool
이 channel의 message copy에 사용할 network buffer pool입니다.
zbus_channel
Name, shared message, size, user data, validator와 mutable runtime data를 묶는 channel descriptor입니다.
zbus_channel.name
Optional channel name metadata입니다.
zbus_channel.message
Publisher와 reader가 lock 아래 공유하는 current message storage입니다.
zbus_channel.message_size
Shared message storage의 byte 크기입니다.
zbus_channel.user_data
Application이 channel에 연결한 custom metadata pointer입니다.
zbus_channel.validator
Publish할 message를 검사해 hard channel acceptance를 결정하는 callback입니다.
zbus_channel.data
Mutable zbus_channel_data를 가리킵니다.
zbus_observer_data
Observer enabled flag처럼 runtime에 바뀌는 상태입니다.
zbus_observer_data.enabled
Observer 전체가 notification을 받을지 나타냅니다.
zbus_observer
Observer name, type, state와 listener·subscriber별 delivery endpoint를 묶습니다.
zbus_observer.name
Optional observer name metadata입니다.
zbus_observer.type
Listener, subscriber 또는 message subscriber type입니다.
zbus_observer.data
Mutable observer state pointer입니다.
zbus_observer.queue
Subscriber가 channel reference notification을 받는 message queue입니다.
zbus_observer.callback
Listener를 publisher context에서 실행하는 synchronous callback입니다.
zbus_observer.message_fifo
Message subscriber가 copied message buffer를 받는 FIFO입니다.

Source

출처

영어 원문에는 문단, 문서 지시문, 표, 코드, 코드 심벌, 경로를 그대로 보존했습니다.