services/device_mgmt/mcumgr_callbacks.html · services/device_mgmt/mcumgr_callbacks.rst 공식 원문 ↗

Zephyr 3.7.0 · Device Management

MCUmgr Callback

Management command 전후에 application policy를 연결하고 요청을 허용·거부하거나 data를 수정합니다.

Official pathservices/device_mgmt/mcumgr_callbacks.html
Source fileservices/device_mgmt/mcumgr_callbacks.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

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

Part 1

요약·해설

Notification hook 활성화, 같은 group event의 bitmask 등록, 두 error return 방식과 Zephyr 3.2 이전 API migration을 설명합니다.

Registration

mgmt_callback_register()

Dispatch

Group + event bitmask

Policy

Allow · deny · rewrite

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 E364C499BEA94F7983FE10F855C069CC4F292656AB6D3BEFDF2FE539AEC67363
.. _mcumgr_callbacks:

MCUmgr Callbacks
################

Overview
********

MCUmgr has a customisable callback/notification system that allows application
(and module) code to receive callbacks for MCUmgr events that they are
interested in and react to them or return a status code to the calling function
that provides control over if the action should be allowed or not. An example
of this is with the fs_mgmt group, whereby file access can be gated, the
callback allows the application to inspect the request path and allow or deny
access to said file, or it can rewrite the provided path to a different path
for transparent file redirection support.

Implementation
**************

Enabling
========

The base callback/notification system can be enabled using
:kconfig:option:`CONFIG_MCUMGR_MGMT_NOTIFICATION_HOOKS` which will compile the
registration and notification system into the code. This will not provide any
callbacks by default as the callbacks that are supported by a build must also
be selected by enabling the Kconfig's for the required callbacks (see
:ref:`mcumgr_cb_events` for further details). A callback function with the
:c:type:`mgmt_cb` type definition can then be declared and registered by
calling :c:func:`mgmt_callback_register` for the desired event inside of a
:c:struct`mgmt_callback` structure. Handlers are called in the order that they
were registered.

With the system enabled, a basic handler can be set up and defined in
application code as per:

.. code-block:: c

    #include <zephyr/kernel.h>
    #include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
    #include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>

    struct mgmt_callback my_callback;

    enum mgmt_cb_return my_function(uint32_t event, enum mgmt_cb_return prev_status,
                                    int32_t *rc, uint16_t *group, bool *abort_more,
                                    void *data, size_t data_size)
    {
        if (event == MGMT_EVT_OP_CMD_DONE) {
            /* This is the event we registered for */
        }

        /* Return OK status code to continue with acceptance to underlying handler */
        return MGMT_CB_OK;
    }

    int main()
    {
        my_callback.callback = my_function;
        my_callback.event_id = MGMT_EVT_OP_CMD_DONE;
        mgmt_callback_register(&my_callback);
    }

This code registers a handler for the :c:enumerator:`MGMT_EVT_OP_CMD_DONE`
event, which will be called after a MCUmgr command has been processed and
output generated, note that this requires that
:kconfig:option:`CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS` be enabled to receive
this callback.

Multiple callbacks can be setup to use a single function as a common callback,
and many different functions can be used for each event by registering each
group once, or all notifications for a whole group can be enabled by using one
of the ``MGMT_EVT_OP_*_ALL`` events, alternatively a handler can setup for
every notification by using :c:enumerator:`MGMT_EVT_OP_ALL`. When setting up
handlers, events can be combined that are in the same group only, for example
5 img_mgmt callbacks can be setup with a single registration call, but to also
setup a callback for an os_mgmt callback, this must be done as a separate
registration. Group IDs are numerical increments, event IDs are bitmask values,
hence the restriction.

As an example, the following registration is allowed, which will register for 3
SMP events with a single callback function in a single registration:

.. code-block:: c

    my_callback.callback = my_function;
    my_callback.event_id = (MGMT_EVT_OP_CMD_RECV |
                            MGMT_EVT_OP_CMD_STATUS |
                            MGMT_EVT_OP_CMD_DONE);
    mgmt_callback_register(&my_callback);

The following code is not allowed, and will cause undefined operation, because
it mixes the IMG management group with the OS management group whereby the
group is **not** a bitmask value, only the event is:

.. code-block:: c

    my_callback.callback = my_function;
    my_callback.event_id = (MGMT_EVT_OP_IMG_MGMT_DFU_STARTED |
                            MGMT_EVT_OP_OS_MGMT_RESET);
    mgmt_callback_register(&my_callback);

.. _mcumgr_cb_events:

Events
======

Events can be selected by enabling their corresponding Kconfig option:

 - :kconfig:option:`CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS`
    MCUmgr command status (:c:enumerator:`MGMT_EVT_OP_CMD_RECV`,
    :c:enumerator:`MGMT_EVT_OP_CMD_STATUS`,
    :c:enumerator:`MGMT_EVT_OP_CMD_DONE`)
 - :kconfig:option:`CONFIG_MCUMGR_GRP_FS_FILE_ACCESS_HOOK`
    fs_mgmt file access (:c:enumerator:`MGMT_EVT_OP_FS_MGMT_FILE_ACCESS`)
 - :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_UPLOAD_CHECK_HOOK`
    img_mgmt upload check (:c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_CHUNK`)
 - :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS`
    img_mgmt upload status (:c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_STOPPED`,
    :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_STARTED`,
    :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_PENDING`,
    :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_CONFIRMED`)
 - :kconfig:option:`CONFIG_MCUMGR_GRP_OS_RESET_HOOK`
    os_mgmt reset check (:c:enumerator:`MGMT_EVT_OP_OS_MGMT_RESET`)
 - :kconfig:option:`CONFIG_MCUMGR_GRP_SETTINGS_ACCESS_HOOK`
    settings_mgmt access (:c:enumerator:`MGMT_EVT_OP_SETTINGS_MGMT_ACCESS`)

Actions
=======

Some callbacks expect a return status to either allow or disallow an operation,
an example is the fs_mgmt access hook which allows for access to files to be
allowed or denied. With these handlers, the first non-OK error code returned
by a handler will be returned to the MCUmgr client.

An example of selectively denying file access:

.. code-block:: c

    #include <zephyr/kernel.h>
    #include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
    #include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>
    #include <string.h>

    struct mgmt_callback my_callback;

    enum mgmt_cb_return my_function(uint32_t event, enum mgmt_cb_return prev_status,
                                    int32_t *rc, uint16_t *group, bool *abort_more,
                                    void *data, size_t data_size)
    {
        /* Only run this handler if a previous handler has not failed */
        if (event == MGMT_EVT_OP_FS_MGMT_FILE_ACCESS && prev_status == MGMT_CB_OK) {
            struct fs_mgmt_file_access *fs_data = (struct fs_mgmt_file_access *)data;

            /* Check if this is an upload and deny access if it is, otherwise check
             * the path and deny if is matches a name
             */
            if (fs_data->access == FS_MGMT_FILE_ACCESS_WRITE) {
                /* Return an access denied error code to the client and abort calling
                 * further handlers
                 */
                *abort_more = true;
                *rc = MGMT_ERR_EACCESSDENIED;

                return MGMT_CB_ERROR_RC;
            } else if (strcmp(fs_data->filename, "/lfs1/false_deny.txt") == 0) {
                /* Return a no entry error code to the client, call additional handlers
                 * (which will have failed set to true)
                 */
                *rc = MGMT_ERR_ENOENT;

                return MGMT_CB_ERROR_RC;
            }
        }

        /* Return OK status code to continue with acceptance to underlying handler */
        return MGMT_CB_OK;
    }

    int main()
    {
        my_callback.callback = my_function;
        my_callback.event_id = MGMT_EVT_OP_FS_MGMT_FILE_ACCESS;
        mgmt_callback_register(&my_callback);
    }

This code registers a handler for the
:c:enumerator:`MGMT_EVT_OP_FS_MGMT_FILE_ACCESS` event, which will be called
after a fs_mgmt file read/write command has been received to check if access to
the file should be allowed or not, note that this requires that
:kconfig:option:`CONFIG_MCUMGR_GRP_FS_FILE_ACCESS_HOOK` be enabled to receive
this callback.
Two types of errors can be returned, the ``rc`` parameter can be set to an
:c:enum:`mcumgr_err_t` error code and :c:enumerator:`MGMT_CB_ERROR_RC`
can be returned, or a group error code (introduced with version 2 of the MCUmgr
protocol) can be set by setting the ``group`` value to the group and ``rc``
value to the group error code and returning :c:enumerator:`MGMT_CB_ERROR_ERR`.

MCUmgr Command Callback Usage/Adding New Event Types
====================================================

To add a callback to a MCUmgr command, :c:func:`mgmt_callback_notify` can be
called with the event ID and, optionally, a data struct to pass to the callback
(which can be modified by handlers). If no data needs to be passed back,
``NULL`` can be used instead, and size of the data set to 0.

An example MCUmgr command handler:

.. code-block:: c

    #include <zephyr/kernel.h>
    #include <zcbor_common.h>
    #include <zcbor_encode.h>
    #include <zephyr/mgmt/mcumgr/smp/smp.h>
    #include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
    #include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>

    #define MGMT_EVT_GRP_USER_ONE MGMT_EVT_GRP_USER_CUSTOM_START

    enum user_one_group_events {
        /** Callback on first post, data is test_struct. */
        MGMT_EVT_OP_USER_ONE_FIRST  = MGMT_DEF_EVT_OP_ID(MGMT_EVT_GRP_USER_ONE, 0),

        /** Callback on second post, data is test_struct. */
        MGMT_EVT_OP_USER_ONE_SECOND = MGMT_DEF_EVT_OP_ID(MGMT_EVT_GRP_USER_ONE, 1),

        /** Used to enable all user_one events. */
        MGMT_EVT_OP_USER_ONE_ALL    = MGMT_DEF_EVT_OP_ALL(MGMT_EVT_GRP_USER_ONE),
    };

    struct test_struct {
        uint8_t some_value;
    };

    static int test_command(struct mgmt_ctxt *ctxt)
    {
        int rc;
        int err_rc;
        uint16_t err_group;
        zcbor_state_t *zse = ctxt->cnbe->zs;
        bool ok;
        struct test_struct test_data = {
            .some_value = 8,
        };

        rc = mgmt_callback_notify(MGMT_EVT_OP_USER_ONE_FIRST, &test_data,
                                  sizeof(test_data), &err_rc, &err_group);

        if (rc != MGMT_CB_OK) {
            /* A handler returned a failure code */
            if (rc == MGMT_CB_ERROR_RC) {
                /* The failure code is the RC value */
                return err_rc;
            }

            /* The failure is a group and ID error value */
            ok = smp_add_cmd_err(zse, err_group, (uint16_t)err_rc);
            goto end;
        }

        /* All handlers returned success codes */
        ok = zcbor_tstr_put_lit(zse, "output_value") &&
             zcbor_int32_put(zse, 1234);

    end:
        rc = (ok ? MGMT_ERR_EOK : MGMT_ERR_EMSGSIZE);

        return rc;
    }

If no response is required for the callback, the function call be called and
casted to void.

.. _mcumgr_cb_migration:

Migration
*********

If there is existing code using the previous callback system(s) in Zephyr 3.2
or earlier, then it will need to be migrated to the new system. To migrate
code, the following callback registration functions will need to be migrated
to register for callbacks using :c:func:`mgmt_callback_register` (note that
:kconfig:option:`CONFIG_MCUMGR_MGMT_NOTIFICATION_HOOKS` will need to be set to
enable the new notification system in addition to any migrations):

 * mgmt_evt
    Using :c:enumerator:`MGMT_EVT_OP_CMD_RECV`,
    :c:enumerator:`MGMT_EVT_OP_CMD_STATUS`, or
    :c:enumerator:`MGMT_EVT_OP_CMD_DONE` as drop-in replacements for events of
    the same name, where the provided data is :c:struct:`mgmt_evt_op_cmd_arg`.
    :kconfig:option:`CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS` needs to be set.
 * fs_mgmt_register_evt_cb
    Using :c:enumerator:`MGMT_EVT_OP_FS_MGMT_FILE_ACCESS` where the provided
    data is :c:struct:`fs_mgmt_file_access`. Instead of returning true to allow
    the action or false to deny, a MCUmgr result code needs to be returned,
    :c:enumerator:`MGMT_ERR_EOK` will allow the action, any other return code
    will disallow it and return that code to the client
    (:c:enumerator:`MGMT_ERR_EACCESSDENIED` can be used for an access denied
    error). :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS` needs to be
    set.
 * img_mgmt_register_callbacks
    Using :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_STARTED` if
    ``dfu_started_cb`` was used,
    :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_STOPPED` if ``dfu_stopped_cb`` was
    used, :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_PENDING` if
    ``dfu_pending_cb`` was used or
    :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_CONFIRMED` if ``dfu_confirmed_cb``
    was used. These callbacks do not have any return status.
    :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS` needs to be set.
 * img_mgmt_set_upload_cb
    Using :c:enumerator:`MGMT_EVT_OP_IMG_MGMT_DFU_CHUNK` where the provided
    data is :c:struct:`img_mgmt_upload_check`. Instead of returning true to
    allow the action or false to deny, a MCUmgr result code needs to be
    returned, :c:enumerator:`MGMT_ERR_EOK` will allow the action, any other
    return code will disallow it and return that code to the client
    (:c:enumerator:`MGMT_ERR_EACCESSDENIED` can be used for an access denied
    error). :kconfig:option:`CONFIG_MCUMGR_GRP_IMG_UPLOAD_CHECK_HOOK` needs to
    be set.
 * os_mgmt_register_reset_evt_cb
    Using :c:enumerator:`MGMT_EVT_OP_OS_MGMT_RESET`.  Instead of returning
    true to allow the action or false to deny, a MCUmgr result code needs to be
    returned, :c:enumerator:`MGMT_ERR_EOK` will allow the action, any other
    return code will disallow it and return that code to the client
    (:c:enumerator:`MGMT_ERR_EACCESSDENIED` can be used for an access denied
    error). :kconfig:option:`CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS` needs to
    be set.

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

.. doxygengroup:: mcumgr_callback_api

Part 3

한국어 전문 번역

개요

MCUmgr에는 application과 module code가 관심 있는 MCUmgr event를 callback으로 받고 대응할 수 있는 맞춤형 callback/notification system이 있습니다. Callback은 호출 함수에 status code를 돌려주어 해당 action을 허용할지도 제어할 수 있습니다. 예를 들어 fs_mgmt group에서는 file access를 gate할 수 있습니다. Application은 callback에서 요청 path를 검사해 file access를 허용 또는 거부하거나, 전달된 path를 다른 path로 다시 써서 투명한 file redirection을 구현할 수 있습니다.

구현

활성화

기본 callback/notification system은 CONFIG_MCUMGR_MGMT_NOTIFICATION_HOOKS로 활성화합니다. 이 option을 켜면 registration과 notification system이 code에 compile됩니다. 다만 이것만으로 기본 callback이 생기지는 않습니다. Build에서 지원할 callback에 해당하는 Kconfig도 각각 활성화해야 합니다. 자세한 목록은 아래의 event 절을 참고합니다.

mgmt_cb type으로 callback function을 선언한 다음, 원하는 event를 mgmt_callback structure의 event_id에 넣고 mgmt_callback_register()를 호출해 등록합니다. Handler는 등록한 순서대로 호출됩니다.

System을 활성화한 뒤 application code에 기본 handler를 구성하는 예는 다음과 같습니다.

#include <zephyr/kernel.h>
#include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
#include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>

struct mgmt_callback my_callback;

enum mgmt_cb_return my_function(uint32_t event, enum mgmt_cb_return prev_status,
                                int32_t *rc, uint16_t *group, bool *abort_more,
                                void *data, size_t data_size)
{
    if (event == MGMT_EVT_OP_CMD_DONE) {
        /* This is the event we registered for */
    }

    /* Return OK status code to continue with acceptance to underlying handler */
    return MGMT_CB_OK;
}

int main()
{
    my_callback.callback = my_function;
    my_callback.event_id = MGMT_EVT_OP_CMD_DONE;
    mgmt_callback_register(&my_callback);
}

이 code는 MGMT_EVT_OP_CMD_DONE event용 handler를 등록합니다. 이 event는 MCUmgr command 처리가 끝나고 output이 생성된 뒤 호출됩니다. 이 callback을 받으려면 CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS도 활성화해야 합니다.

여러 callback이 하나의 function을 공통 callback으로 사용할 수 있고, event 하나에 여러 function을 등록할 수도 있습니다. 각 group을 한 번씩 등록하거나 MGMT_EVT_OP_*_ALL event 중 하나로 group 전체 notification을 활성화할 수 있습니다. 모든 notification을 받으려면 MGMT_EVT_OP_ALL을 사용합니다.

한 번의 handler registration에서 결합할 수 있는 event는 같은 group에 속한 것뿐입니다. 예를 들어 img_mgmt callback 5개는 한 번에 등록할 수 있지만 os_mgmt callback까지 함께 받으려면 별도로 등록해야 합니다. Group ID는 순차적인 숫자이고 event ID만 bitmask 값이기 때문에 생기는 제한입니다.

다음 registration은 허용됩니다. 하나의 callback function을 한 번 등록해 SMP event 3개를 받습니다.

my_callback.callback = my_function;
my_callback.event_id = (MGMT_EVT_OP_CMD_RECV |
                        MGMT_EVT_OP_CMD_STATUS |
                        MGMT_EVT_OP_CMD_DONE);
mgmt_callback_register(&my_callback);

다음 code는 허용되지 않으며 동작이 정의되지 않습니다. IMG management group과 OS management group을 섞었기 때문입니다. Bitmask인 것은 event뿐이고 group은 bitmask가 아닙니다.

my_callback.callback = my_function;
my_callback.event_id = (MGMT_EVT_OP_IMG_MGMT_DFU_STARTED |
                        MGMT_EVT_OP_OS_MGMT_RESET);
mgmt_callback_register(&my_callback);

Event

각 event에 대응하는 Kconfig option을 활성화해 사용할 event를 선택합니다.

  • CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS: MCUmgr command status인 MGMT_EVT_OP_CMD_RECV, MGMT_EVT_OP_CMD_STATUS, MGMT_EVT_OP_CMD_DONE
  • CONFIG_MCUMGR_GRP_FS_FILE_ACCESS_HOOK: fs_mgmt file access인 MGMT_EVT_OP_FS_MGMT_FILE_ACCESS
  • CONFIG_MCUMGR_GRP_IMG_UPLOAD_CHECK_HOOK: img_mgmt upload check인 MGMT_EVT_OP_IMG_MGMT_DFU_CHUNK
  • CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS: img_mgmt upload status인 MGMT_EVT_OP_IMG_MGMT_DFU_STOPPED, MGMT_EVT_OP_IMG_MGMT_DFU_STARTED, MGMT_EVT_OP_IMG_MGMT_DFU_PENDING, MGMT_EVT_OP_IMG_MGMT_DFU_CONFIRMED
  • CONFIG_MCUMGR_GRP_OS_RESET_HOOK: os_mgmt reset check인 MGMT_EVT_OP_OS_MGMT_RESET
  • CONFIG_MCUMGR_GRP_SETTINGS_ACCESS_HOOK: settings_mgmt access인 MGMT_EVT_OP_SETTINGS_MGMT_ACCESS

Action

일부 callback은 operation의 허용 또는 거부를 결정하는 return status를 요구합니다. File access를 허용하거나 거부하는 fs_mgmt access hook이 한 예입니다. 이런 handler에서는 처음 반환된 non-OK error code가 MCUmgr client에 전달됩니다.

File access를 선택적으로 거부하는 예는 다음과 같습니다.

#include <zephyr/kernel.h>
#include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
#include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>
#include <string.h>

struct mgmt_callback my_callback;

enum mgmt_cb_return my_function(uint32_t event, enum mgmt_cb_return prev_status,
                                int32_t *rc, uint16_t *group, bool *abort_more,
                                void *data, size_t data_size)
{
    /* Only run this handler if a previous handler has not failed */
    if (event == MGMT_EVT_OP_FS_MGMT_FILE_ACCESS && prev_status == MGMT_CB_OK) {
        struct fs_mgmt_file_access *fs_data = (struct fs_mgmt_file_access *)data;

        /* Check if this is an upload and deny access if it is, otherwise check
         * the path and deny if is matches a name
         */
        if (fs_data->access == FS_MGMT_FILE_ACCESS_WRITE) {
            /* Return an access denied error code to the client and abort calling
             * further handlers
             */
            *abort_more = true;
            *rc = MGMT_ERR_EACCESSDENIED;

            return MGMT_CB_ERROR_RC;
        } else if (strcmp(fs_data->filename, "/lfs1/false_deny.txt") == 0) {
            /* Return a no entry error code to the client, call additional handlers
             * (which will have failed set to true)
             */
            *rc = MGMT_ERR_ENOENT;

            return MGMT_CB_ERROR_RC;
        }
    }

    /* Return OK status code to continue with acceptance to underlying handler */
    return MGMT_CB_OK;
}

int main()
{
    my_callback.callback = my_function;
    my_callback.event_id = MGMT_EVT_OP_FS_MGMT_FILE_ACCESS;
    mgmt_callback_register(&my_callback);
}

이 code는 MGMT_EVT_OP_FS_MGMT_FILE_ACCESS event용 handler를 등록합니다. fs_mgmt file read/write command를 받은 뒤 해당 file access를 허용할지 검사할 때 호출됩니다. Callback을 받으려면 CONFIG_MCUMGR_GRP_FS_FILE_ACCESS_HOOK을 활성화해야 합니다.

두 종류의 error를 반환할 수 있습니다. 첫째, rc parameter에 mcumgr_err_t error code를 넣고 MGMT_CB_ERROR_RC를 반환할 수 있습니다. 둘째, MCUmgr protocol version 2에서 도입한 group error code를 쓸 수 있습니다. 이때 group에 group 값을, rc에 group error code를 넣고 MGMT_CB_ERROR_ERR를 반환합니다.

MCUmgr command에서 callback 사용 및 새 event type 추가

MCUmgr command에 callback을 추가하려면 event ID와 선택적인 data structure를 지정해 mgmt_callback_notify()를 호출합니다. 전달된 data는 handler가 수정할 수 있습니다. 돌려줄 data가 없다면 data 대신 NULL을 사용하고 size를 0으로 지정합니다.

MCUmgr command handler의 예는 다음과 같습니다.

#include <zephyr/kernel.h>
#include <zcbor_common.h>
#include <zcbor_encode.h>
#include <zephyr/mgmt/mcumgr/smp/smp.h>
#include <zephyr/mgmt/mcumgr/mgmt/mgmt.h>
#include <zephyr/mgmt/mcumgr/mgmt/callbacks.h>

#define MGMT_EVT_GRP_USER_ONE MGMT_EVT_GRP_USER_CUSTOM_START

enum user_one_group_events {
    /** Callback on first post, data is test_struct. */
    MGMT_EVT_OP_USER_ONE_FIRST  = MGMT_DEF_EVT_OP_ID(MGMT_EVT_GRP_USER_ONE, 0),

    /** Callback on second post, data is test_struct. */
    MGMT_EVT_OP_USER_ONE_SECOND = MGMT_DEF_EVT_OP_ID(MGMT_EVT_GRP_USER_ONE, 1),

    /** Used to enable all user_one events. */
    MGMT_EVT_OP_USER_ONE_ALL    = MGMT_DEF_EVT_OP_ALL(MGMT_EVT_GRP_USER_ONE),
};

struct test_struct {
    uint8_t some_value;
};

static int test_command(struct mgmt_ctxt *ctxt)
{
    int rc;
    int err_rc;
    uint16_t err_group;
    zcbor_state_t *zse = ctxt->cnbe->zs;
    bool ok;
    struct test_struct test_data = {
        .some_value = 8,
    };

    rc = mgmt_callback_notify(MGMT_EVT_OP_USER_ONE_FIRST, &test_data,
                              sizeof(test_data), &err_rc, &err_group);

    if (rc != MGMT_CB_OK) {
        /* A handler returned a failure code */
        if (rc == MGMT_CB_ERROR_RC) {
            /* The failure code is the RC value */
            return err_rc;
        }

        /* The failure is a group and ID error value */
        ok = smp_add_cmd_err(zse, err_group, (uint16_t)err_rc);
        goto end;
    }

    /* All handlers returned success codes */
    ok = zcbor_tstr_put_lit(zse, "output_value") &&
         zcbor_int32_put(zse, 1234);

end:
    rc = (ok ? MGMT_ERR_EOK : MGMT_ERR_EMSGSIZE);

    return rc;
}

Callback response가 필요하지 않으면 function을 호출한 결과를 void로 cast할 수 있습니다.

Migration

Zephyr 3.2 이하의 이전 callback system을 사용하는 기존 code는 새 system으로 migration해야 합니다. 아래의 옛 callback registration function을 mgmt_callback_register() 기반 등록으로 바꿉니다. 각 migration에 필요한 option뿐 아니라 새 notification system 자체를 위한 CONFIG_MCUMGR_MGMT_NOTIFICATION_HOOKS도 활성화해야 합니다.

  • mgmt_evt: 같은 이름의 옛 event를 MGMT_EVT_OP_CMD_RECV, MGMT_EVT_OP_CMD_STATUS, MGMT_EVT_OP_CMD_DONE으로 바로 대체합니다. 전달 data는 mgmt_evt_op_cmd_arg이며 CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS가 필요합니다.
  • fs_mgmt_register_evt_cb: 전달 data가 fs_mgmt_file_access인 MGMT_EVT_OP_FS_MGMT_FILE_ACCESS를 사용합니다. Action 허용에 true, 거부에 false를 반환하던 방식 대신 MCUmgr result code를 반환합니다. MGMT_ERR_EOK는 허용하고 나머지는 거부하면서 해당 code를 client에 보냅니다. Access denied에는 MGMT_ERR_EACCESSDENIED를 사용할 수 있습니다. 원문에 명시된 필요 option은 CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS입니다.
  • img_mgmt_register_callbacks: dfu_started_cb는 MGMT_EVT_OP_IMG_MGMT_DFU_STARTED, dfu_stopped_cb는 MGMT_EVT_OP_IMG_MGMT_DFU_STOPPED, dfu_pending_cb는 MGMT_EVT_OP_IMG_MGMT_DFU_PENDING, dfu_confirmed_cb는 MGMT_EVT_OP_IMG_MGMT_DFU_CONFIRMED를 사용합니다. 이 callback들은 return status가 없으며 CONFIG_MCUMGR_GRP_IMG_STATUS_HOOKS가 필요합니다.
  • img_mgmt_set_upload_cb: 전달 data가 img_mgmt_upload_check인 MGMT_EVT_OP_IMG_MGMT_DFU_CHUNK를 사용합니다. Boolean 대신 MCUmgr result code를 반환하며 MGMT_ERR_EOK는 허용, 나머지는 거부입니다. Access denied에는 MGMT_ERR_EACCESSDENIED를 사용할 수 있습니다. CONFIG_MCUMGR_GRP_IMG_UPLOAD_CHECK_HOOK이 필요합니다.
  • os_mgmt_register_reset_evt_cb: MGMT_EVT_OP_OS_MGMT_RESET을 사용합니다. Boolean 대신 MCUmgr result code를 반환하며 MGMT_ERR_EOK는 허용, 나머지는 거부입니다. Access denied에는 MGMT_ERR_EACCESSDENIED를 사용할 수 있습니다. 원문에 명시된 필요 option은 CONFIG_MCUMGR_SMP_COMMAND_STATUS_HOOKS입니다.

API Reference

원문의 Doxygen group mcumgr_callback_api에 MCUmgr callback API가 수록됩니다.

Source

출처

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