connectivity/networking/conn_mgr/main.html · connectivity/networking/conn_mgr/main.rst 공식 원문 ↗

Zephyr 3.7.0 · Connectivity · Networking

Connection Manager

Network technology와 무관한 API로 여러 interface의 IP readiness와 association 수명주기를 감시하고 제어합니다.

Official pathconnectivity/networking/conn_mgr/main.html
Source fileconnectivity/networking/conn_mgr/main.rst
Source versionZephyr 3.7.0
TranslationFull · reviewed

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

Part 1

요약·해설

Ready iface 판정과 L4 event, 초기 알림 누락 방지, association·disassociation, timeout·persistence 및 자동 동작을 한 흐름으로 설명합니다.

Monitoring

Ready · IPv4 · IPv6

Control

Bind · Connect · Disconnect

Policy

Timeout · Persistence · Automation

Part 2

접을 수 있는 영어 원문 전체

영어 원문 전체 펼치기
원문 SHA-256 253ABAF27669029330CE6B524E4A9DAF16771BE09CDCB236AE43BB0897D12D1C
.. _conn_mgr_overview:

Overview
########

Connection Manager is a collection of optional Zephyr features that aim to allow applications to monitor and control connectivity (access to IP-capable networks) with minimal concern for the specifics of underlying network technologies.

Using Connection Manager, applications can use a single abstract API to control network association and monitor Internet access, and avoid excessive use of technology-specific boilerplate.

This allows an application to potentially support several very different connectivity technologies (for example, Wi-Fi and LTE) with a single codebase.

Applications can also use Connection Manager to generically manage and use multiple connectivity technologies simultaneously.

Structure
=========

Connection Manager is split into the following two subsystems:

* :ref:`Connectivity monitoring <conn_mgr_monitoring>` (header file :file:`include/zephyr/net/conn_mgr_monitoring.h`) monitors all available :ref:`Zephyr network interfaces (ifaces) <net_if_interface>` and triggers :ref:`network management <net_mgmt_interface>` events indicating when IP connectivity is gained or lost.

* :ref:`Connectivity control <conn_mgr_control>` (header file :file:`include/zephyr/net/conn_mgr_connectivity.h`) provides an abstract API for controlling iface network association.

.. _conn_mgr_integration_diagram_simple:

.. figure:: ../../../../../connectivity/networking/conn_mgr/figures/integration_diagram_simplified.svg
    :alt: A simplified view of how Connection Manager integrates with Zephyr and the application.
    :figclass: align-center

    A simplified view of how Connection Manager integrates with Zephyr and the application.

    See :ref:`here <conn_mgr_integration_diagram_detailed>` for a more detailed version.

.. _conn_mgr_monitoring:

Connectivity monitoring
#######################

Connectivity monitoring tracks all available ifaces (whether or not they support :ref:`Connectivity control <conn_mgr_control>`) as they transition through various :ref:`operational states <net_if_interface_state_management>` and acquire or lose assigned IP addresses.

Each available iface is considered ready if it meets the following criteria:

* The iface is admin-up

  * This means the iface has been instructed to become operational-up (ready for use). This is done by a call to :c:func:`net_if_up`.

* The iface is oper-up

  * This means the interface is completely ready for use; It is online, and if applicable, has associated with a network.
  * See :ref:`net_if_interface_state_management` for details.

* The iface has at least one assigned IP address

  * Both IPv4 and IPv6 addresses are acceptable.
    This condition is met as soon as one or both of these is assigned.
  * See :ref:`net_if_interface` for details on iface IP assignment.

* The iface has not been ignored

  * Ignored ifaces are always treated as unready.
  * See :ref:`conn_mgr_monitoring_ignoring_ifaces` for more details.

.. note::

   Typically, iface state and IP assignment are updated either by the iface's :ref:`L2 implementation <net_l2_interface>` or bound :ref:`connectivity implementation <conn_mgr_impl>`.

   See :ref:`conn_mgr_impl_guidelines_iface_state_reporting` for details.

A ready iface ceases to be ready the moment any of the above conditions is lost.

When at least one iface is ready, the :c:macro:`NET_EVENT_L4_CONNECTED` :ref:`network management <net_mgmt_interface>` event is triggered, and IP connectivity is said to be ready.

Afterwards, ifaces can become ready or unready without firing additional events, so long as there always remains at least one ready iface.

When there are no longer any ready ifaces left, the :c:macro:`NET_EVENT_L4_DISCONNECTED` :ref:`network management <net_mgmt_interface>` event is triggered, and IP connectivity is said to be unready.

.. note::

   Connection Manager also fires the following more specific ``CONNECTED`` / ``DISCONNECTED`` events:

   - :c:macro:`NET_EVENT_L4_IPV4_CONNECTED`
   - :c:macro:`NET_EVENT_L4_IPV4_DISCONNECTED`
   - :c:macro:`NET_EVENT_L4_IPV6_CONNECTED`
   - :c:macro:`NET_EVENT_L4_IPV6_DISCONNECTED`

   These are similar to :c:macro:`NET_EVENT_L4_CONNECTED` and :c:macro:`NET_EVENT_L4_DISCONNECTED`, but specifically track whether IPv4- and IPv6-capable ifaces are ready.

.. _conn_mgr_monitoring_usage:

Usage
=====

Connectivity monitoring is enabled if the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER` Kconfig option is enabled.

To receive connectivity updates, create and register a listener for the :c:macro:`NET_EVENT_L4_CONNECTED` and :c:macro:`NET_EVENT_L4_DISCONNECTED` :ref:`network management <net_mgmt_interface>` events:

.. code-block:: c

   /* Callback struct where the callback will be stored */
   struct net_mgmt_event_callback l4_callback;

   /* Callback handler */
   static void l4_event_handler(struct net_mgmt_event_callback *cb,
                                uint32_t event, struct net_if *iface)
   {
           if (event == NET_EVENT_L4_CONNECTED) {
                   LOG_INF("Network connectivity gained!");
           } else if (event == NET_EVENT_L4_DISCONNECTED) {
                   LOG_INF("Network connectivity lost!");
           }

           /* Otherwise, it's some other event type we didn't register for. */
   }

   /* Call this before Connection Manager monitoring initializes */
   static void my_application_setup(void)
   {
           /* Configure the callback struct to respond to (at least) the L4_CONNECTED
            * and L4_DISCONNECTED events.
            *
            *
            * Note that the callback may also be triggered for events other than those specified here!
            * (See the net_mgmt documentation)
            */
           net_mgmt_init_event_callback(
                   &l4_callback, l4_event_handler,
                   NET_EVENT_L4_CONNECTED | NET_EVENT_L4_DISCONNECTED
           );

           /* Register the callback */
           net_mgmt_add_event_callback(&l4_callback);
   }

See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events.

.. note::
   To avoid missing initial connectivity events, you should register your listener(s) before Connection Manager monitoring initializes.
   See :ref:`conn_mgr_monitoring_missing_notifications` for strategies to ensure this.

.. _conn_mgr_monitoring_missing_notifications:

Avoiding missed notifications
=============================

Connectivity monitoring may trigger events immediately upon initialization.

If your application registers its event listeners after connectivity monitoring initializes, it is possible to miss this first wave of events, and not be informed the first time network connectivity is gained.

If this is a concern, your application should :ref:`register its event listeners <conn_mgr_monitoring_usage>` before connectivity monitoring initializes.

Connectivity monitoring initializes using the :c:macro:`SYS_INIT` ``APPLICATION`` initialization priority specified by the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER_MONITOR_PRIORITY` Kconfig option.

You can register your callbacks before this initialization by using :c:macro:`SYS_INIT` with an earlier initialization priority than this value, for instance priority 0:

.. code-block:: C

   static int my_application_setup(void)
   {
	   /* Register callbacks here */
	   return 0;
   }

   SYS_INIT(my_application_setup, APPLICATION, 0);

If this is not feasible, you can instead request that connectivity monitoring resend the latest connectivity events at any time by calling :c:func:`conn_mgr_mon_resend_status`:

.. code-block:: C

   static void my_late_application_setup(void)
   {
     /* Register callbacks here */

     /* Once done, request that events be re-triggered */
     conn_mgr_mon_resend_status();
   }

.. _conn_mgr_monitoring_ignoring_ifaces:

Ignoring ifaces
===============

Applications can request that ifaces be ignored by Connection Manager by calling :c:func:`conn_mgr_ignore_iface` with the iface to be ignored.

Alternatively, an entire :ref:`L2 implementation <net_l2_interface>` can be ignored by calling :c:func:`conn_mgr_ignore_l2`.

This has the effect of individually ignoring all the ifaces using that :ref:`L2 implementation <net_l2_interface>`.

While ignored, the iface is treated by Connection Manager as though it were unready for network traffic, no matter its actual state.

This may be useful, for instance, if your application has configured one or more ifaces that cannot (or for whatever reason should not) be used to contact the wider Internet.

:ref:`Bulk convenience functions <conn_mgr_control_api_bulk>` optionally skip ignored ifaces.

See :c:func:`conn_mgr_ignore_iface` and :c:func:`conn_mgr_watch_iface` for more details.

.. _conn_mgr_monitoring_api:

Connectivity monitoring API
===========================

Include header file :file:`include/zephyr/net/conn_mgr_monitoring.h` to access these.

.. doxygengroup:: conn_mgr

.. _conn_mgr_control:

Connectivity control
####################

Many network interfaces require a network association procedure to be completed before being usable.

For such ifaces, connectivity control can provide a generic API to request network association (:c:func:`conn_mgr_if_connect`) and disassociation (:c:func:`conn_mgr_if_disconnect`).
Network interfaces implement support for this API by :ref:`binding themselves to a connectivity implementation <conn_mgr_impl_binding>`.

Using this API, applications can associate with networks with minimal technology-specific boilerplate.

Connectivity control also provides the following additional features:

* Standardized :ref:`persistence and timeout <conn_mgr_control_persistence_timeouts>` behaviors during association.
* :ref:`Bulk functions <conn_mgr_control_api_bulk>` for controlling the admin state and network association of all available ifaces simultaneously.
* Optional :ref:`convenience automations <conn_mgr_control_automations>` for common connectivity actions.

.. _conn_mgr_control_operation:

Basic operation
===============

The following sections outline the basic operation of Connection Manager's connectivity control.

.. _conn_mgr_control_operation_binding:

Binding
-------

Before an iface can be commanded to associate or disassociate using Connection Manager, it must first be bound to a :ref:`connectivity implementation <conn_mgr_impl>`.
Binding is performed by the provider of the iface, not by the application (see :ref:`conn_mgr_impl_binding`), and can be thought of as an extension of the iface declaration.

Once an iface is bound, all connectivity commands passed to it (such as :c:func:`conn_mgr_if_connect` or :c:func:`conn_mgr_if_disconnect`) will be routed to the corresponding implementation function in the connectivity implementation.

.. note::

  To avoid inconsistent behavior, all connectivity implementations must adhere to the :ref:`implementation guidelines <conn_mgr_impl_guidelines>`.

.. _conn_mgr_control_operation_connecting:

Connecting
----------

Once a bound iface is admin-up (see :ref:`net_if_interface_state_management`), :c:func:`conn_mgr_if_connect` can be called to cause it to associate with a network.

If association succeeds, the connectivity implementation will mark the iface as operational-up (see :ref:`net_if_interface_state_management`).

If association fails unrecoverably, the :ref:`fatal error event <conn_mgr_control_events_fatal_error>` will be triggered.

You can configure an optional :ref:`timeout <conn_mgr_control_timeouts>` for this process.

.. note::
   The :c:func:`conn_mgr_if_connect` function is intentionally minimalistic, and does not take any kind of configuration.
   Each connectivity implementation should provide a way to pre-configure or automatically configure any required association settings or credentials.
   See :ref:`conn_mgr_impl_guidelines_preconfig` for details.

.. _conn_mgr_control_operation_loss:

Connection loss
---------------

If connectivity is lost due to external factors, the connectivity implementation will mark the iface as operational-down.

Depending on whether :ref:`persistence <conn_mgr_control_persistence>` is set, the iface may then attempt to reconnect.

.. _conn_mgr_control_operation_disconnection:

Manual disconnection
--------------------

The application can also request that connectivity be intentionally abandoned by calling :c:func:`conn_mgr_if_disconnect`.

In this case, the connectivity implementation will disassociate the iface from its network and mark the iface as operational-down (see :ref:`net_if_interface_state_management`).
A new connection attempt will not be initiated, regardless of whether persistence is enabled.

.. _conn_mgr_control_persistence_timeouts:

Timeouts and Persistence
========================

Connection Manager requires that all connectivity implementations support the following standard key features:

* :ref:`Connection timeouts <conn_mgr_control_timeouts>`
* :ref:`Connection persistence <conn_mgr_control_persistence>`

These features describe how ifaces should behave during connect and disconnect events.
You can individually set them for each iface.

.. note::
   It is left to connectivity implementations to successfully and accurately implement these two features as described below.
   See :ref:`conn_mgr_impl_timeout_persistence` for more details from the connectivity implementation perspective.

.. _conn_mgr_control_timeouts:

Connection Timeouts
-------------------

When :c:func:`conn_mgr_if_connect` is called on an iface, a connection attempt begins.

The connection attempt continues indefinitely until it succeeds, unless a timeout has been specified for the iface (using :c:func:`conn_mgr_if_set_timeout`).

In that case, the connection attempt will be abandoned if the timeout elapses before it succeeds.
If this happens, the :ref:`timeout event<conn_mgr_control_events_timeout>` is raised.

.. _conn_mgr_control_persistence:

Connection Persistence
----------------------

Each iface also has a connection persistence setting that you can enable or disable by setting the :c:enumerator:`~conn_mgr_if_flag.CONN_MGR_IF_PERSISTENT` flag with :c:func:`conn_mgr_binding_set_flag`.

This setting specifies how the iface should handle unintentional connection loss.

If persistence is enabled, any unintentional connection loss will initiate a new connection attempt, with a new timeout if applicable.

Otherwise, the iface will not attempt to reconnect.

.. note::
   Persistence not does affect connection attempt behavior.
   Only the timeout setting affects this.

   For instance, if a connection attempt on an iface times out, the iface will not attempt to reconnect, even if it is persistent.

   Conversely, if there is not a specified timeout, the iface will try to connect forever until it succeeds, even if it is not persistent.

   See :ref:`conn_mgr_impl_tp_persistence_during_connect` for the equivalent implementation guideline.

.. _conn_mgr_control_events:

Control events
==============

Connectivity control triggers :ref:`network management <net_mgmt_interface>` events to inform the application of important state changes.

See :ref:`conn_mgr_impl_guidelines_trigger_events` for the corresponding connectivity implementation guideline.

.. _conn_mgr_control_events_fatal_error:

Fatal Error
-----------

The :c:macro:`NET_EVENT_CONN_IF_FATAL_ERROR` event is raised when an iface encounters an error from which it cannot recover (meaning any subsequent attempts to associate are guaranteed to fail, and all such attempts should be abandoned).

Handlers of this event will be passed a pointer to the iface for which the fatal error occurred.
Individual connectivity implementations may also pass an application-specific data pointer.

.. _conn_mgr_control_events_timeout:

Timeout
-------

The :c:macro:`NET_EVENT_CONN_IF_TIMEOUT` event is raised when an :ref:`iface association <conn_mgr_control_operation_connecting>` attempt :ref:`times out <conn_mgr_control_timeouts>`.

Handlers of this event will be passed a pointer to the iface that timed out attempting to associate.

.. _conn_mgr_control_events_listening:

Listening for control events
----------------------------

You can listen for control events as follows:

.. code-block:: c

   /* Declare a net_mgmt callback struct to store the callback */
   struct net_mgmt_event_callback my_conn_evt_callback;

   /* Declare a handler to receive control events */
   static void my_conn_evt_handler(struct net_mgmt_event_callback *cb,
                                   uint32_t event, struct net_if *iface)
   {
           if (event == NET_EVENT_CONN_IF_TIMEOUT) {
                   /* Timeout occurred, handle it */
           } else if (event == NET_EVENT_CONN_IF_FATAL_ERROR) {
                   /* Fatal error occurred, handle it */
           }

           /* Otherwise, it's some other event type we didn't register for. */
   }

   int main()
   {
           /* Configure the callback struct to respond to (at least) the CONN_IF_TIMEOUT
            * and CONN_IF_FATAL_ERROR events.
            *
            * Note that the callback may also be triggered for events other than those specified here!
            * (See the net_mgmt documentation)
            */

           net_mgmt_init_event_callback(
                   &conn_mgr_conn_callback, conn_mgr_conn_handler,
                       NET_EVENT_CONN_IF_TIMEOUT | NET_EVENT_CONN_IF_FATAL_ERROR
           );

           /* Register the callback */
           net_mgmt_add_event_callback(&conn_mgr_conn_callback);
           return 0;
   }

See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events.

.. _conn_mgr_control_automations:

Automated behaviors
===================

There are a few actions related to connectivity that are (by default at least) performed automatically for the user.

.. _conn_mgr_control_automations_auto_up:

.. topic:: Automatic admin-up

   In Zephyr, ifaces are automatically taken admin-up (see :ref:`net_if_interface_state_management` for details on iface states) during initialization.

   Applications can disable this behavior by setting the :c:enumerator:`~net_if_flag.NET_IF_NO_AUTO_START` interface flag with :c:func:`net_if_flag_set`.

.. _conn_mgr_control_automations_auto_connect:

.. topic:: Automatic connect

   By default, Connection Manager will automatically connect any :ref:`bound <conn_mgr_impl_binding>` iface that becomes admin-up.

   Applications can disable this by setting the :c:enumerator:`~conn_mgr_if_flag.CONN_MGR_IF_NO_AUTO_CONNECT` connectivity flag with :c:func:`conn_mgr_if_set_flag`.

.. _conn_mgr_control_automations_auto_down:

.. topic:: Automatic admin-down

   By default, Connection Manager will automatically take any bound iface admin-down if it has given up on associating.

   Applications can disable this for all ifaces by disabling the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER_AUTO_IF_DOWN` Kconfig option, or for individual ifaces by setting the :c:enumerator:`~conn_mgr_if_flag.CONN_MGR_IF_NO_AUTO_DOWN` connectivity flag with :c:func:`conn_mgr_if_set_flag`.

.. _conn_mgr_control_api:

Connectivity control API
========================

Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these.

.. doxygengroup:: conn_mgr_connectivity

.. _conn_mgr_control_api_bulk:

Bulk API
--------

Connectivity control provides several bulk functions allowing all ifaces to be controlled at once.

You can restrict these functions to operate only on non-:ref:`ignored <conn_mgr_monitoring_ignoring_ifaces>` ifaces if desired.

Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these.

.. doxygengroup:: conn_mgr_connectivity_bulk

Part 3

한국어 전문 번역

개요

Connection Manager는 application이 underlying network technology의 세부 사항을 최소한으로만 신경 쓰면서 connectivity, 즉 IP 통신이 가능한 network 접근 상태를 감시하고 제어할 수 있게 하는 선택형 Zephyr feature 모음입니다.

Application은 Connection Manager의 단일 abstract API로 network association을 제어하고 Internet 접근 가능 여부를 감시할 수 있습니다. 따라서 technology-specific boilerplate를 지나치게 반복하지 않아도 됩니다.

이 구조를 사용하면 하나의 codebase가 Wi-Fi와 LTE처럼 서로 매우 다른 여러 connectivity technology를 지원할 수 있습니다.

Application은 여러 connectivity technology를 동시에 사용하고 공통 방식으로 관리할 수도 있습니다.

구조

Connection Manager는 다음 두 subsystem으로 나뉩니다.

  • Connectivity monitoring은 include/zephyr/net/conn_mgr_monitoring.h에 정의됩니다. 사용 가능한 모든 Zephyr network interface(iface)를 감시하고 IP connectivity를 얻거나 잃을 때 network management event를 발생시킵니다.
  • Connectivity control은 include/zephyr/net/conn_mgr_connectivity.h에 정의됩니다. Iface의 network association을 제어하는 abstract API를 제공합니다.
Connection Manager가 Zephyr와 application 사이에 통합되는 단순 구조
Connection Manager가 application에 connectivity monitoring과 connectivity control을 제공하는 단순화된 integration 구조. 더 상세한 구조는 Connectivity Implementations 문서의 도식을 참고하십시오.

Connectivity monitoring

Connectivity monitoring은 Connectivity control 지원 여부와 관계없이 사용 가능한 모든 iface를 추적합니다. 각 iface가 여러 operational state를 오가고 IP address를 할당받거나 잃는 변화를 관찰합니다.

사용 가능한 iface는 다음 조건을 모두 만족할 때 ready로 간주됩니다.

  • Iface가 admin-up 상태여야 합니다.
    • 이는 net_if_up()을 호출해 iface에 operational-up, 즉 사용 준비 상태가 되도록 지시했다는 뜻입니다.
  • Iface가 oper-up 상태여야 합니다.
    • Interface가 완전히 사용 가능하고 online 상태라는 뜻입니다.
    • 필요한 technology라면 network association까지 완료돼야 합니다.
  • Iface에 IP address가 하나 이상 할당돼야 합니다.
    • IPv4와 IPv6 address 모두 허용되며 둘 중 하나만 할당돼도 이 조건을 만족합니다.
    • 구체적인 IP assignment 동작은 network interface 문서를 참고하십시오.
  • Iface가 ignore 상태가 아니어야 합니다.
    • Ignore된 iface는 언제나 unready로 취급합니다.
    • 자세한 내용은 아래의 iface 무시 절을 참고하십시오.

Ready iface는 위 조건 가운데 하나라도 더 이상 충족하지 못하는 순간 unready가 됩니다.

Ready iface가 하나 이상 생기면 NET_EVENT_L4_CONNECTED network management event가 발생하고 IP connectivity가 ready인 것으로 간주됩니다.

그 뒤에도 ready iface가 하나 이상 계속 남아 있는 한, 개별 iface가 ready 또는 unready로 바뀌어도 추가 event는 발생하지 않습니다.

Ready iface가 하나도 남지 않으면 NET_EVENT_L4_DISCONNECTED network management event가 발생하고 IP connectivity는 unready가 됩니다.

사용법

CONFIG_NET_CONNECTION_MANAGER Kconfig option을 켜면 connectivity monitoring이 활성화됩니다.

NET_EVENT_L4_CONNECTED와 NET_EVENT_L4_DISCONNECTED event를 받을 listener를 만들고 등록하는 예는 다음과 같습니다.

/* Callback struct where the callback will be stored */
struct net_mgmt_event_callback l4_callback;

/* Callback handler */
static void l4_event_handler(struct net_mgmt_event_callback *cb,
                             uint32_t event, struct net_if *iface)
{
        if (event == NET_EVENT_L4_CONNECTED) {
                LOG_INF("Network connectivity gained!");
        } else if (event == NET_EVENT_L4_DISCONNECTED) {
                LOG_INF("Network connectivity lost!");
        }

        /* Otherwise, it's some other event type we didn't register for. */
}

/* Call this before Connection Manager monitoring initializes */
static void my_application_setup(void)
{
        /* Configure the callback struct to respond to (at least) the L4_CONNECTED
         * and L4_DISCONNECTED events.
         *
         *
         * Note that the callback may also be triggered for events other than those specified here!
         * (See the net_mgmt documentation)
         */
        net_mgmt_init_event_callback(
                &l4_callback, l4_event_handler,
                NET_EVENT_L4_CONNECTED | NET_EVENT_L4_DISCONNECTED
        );

        /* Register the callback */
        net_mgmt_add_event_callback(&l4_callback);
}

Network management event listener의 자세한 사용법은 net_mgmt event listening 문서를 참고하십시오.

알림 누락 방지

Connectivity monitoring은 초기화 직후 event를 발생시킬 수 있습니다.

Application이 monitoring 초기화 뒤에 event listener를 등록하면 첫 event 묶음을 놓칠 수 있으며, network connectivity를 처음 얻은 시점을 통보받지 못할 수 있습니다.

이 문제가 중요하다면 connectivity monitoring이 초기화되기 전에 event listener를 등록해야 합니다.

CONFIG_NET_CONNECTION_MANAGER_MONITOR_PRIORITY가 지정한 SYS_INIT의 APPLICATION initialization priority로 connectivity monitoring이 초기화됩니다.

이 값보다 이른 initialization priority, 예를 들어 priority 0으로 SYS_INIT을 사용하면 callback을 먼저 등록할 수 있습니다.

static int my_application_setup(void)
{
 /* Register callbacks here */
 return 0;
}

SYS_INIT(my_application_setup, APPLICATION, 0);

이 방식이 어렵다면 listener를 등록한 뒤 conn_mgr_mon_resend_status()를 호출해 connectivity monitoring이 최신 connectivity event를 다시 전송하도록 요청할 수 있습니다.

static void my_late_application_setup(void)
{
  /* Register callbacks here */

  /* Once done, request that events be re-triggered */
  conn_mgr_mon_resend_status();
}

Interface 무시

Application은 무시할 iface를 인자로 conn_mgr_ignore_iface()를 호출해 Connection Manager가 해당 iface를 ignore하도록 요청할 수 있습니다.

또는 conn_mgr_ignore_l2()를 호출해 L2 implementation 전체를 ignore할 수 있습니다.

L2 implementation을 ignore하면 그 L2를 사용하는 모든 iface가 각각 ignore됩니다.

Ignore 상태인 iface는 실제 상태와 관계없이 network traffic에 사용할 준비가 되지 않은 것으로 Connection Manager가 취급합니다.

예를 들어 application이 구성한 iface가 넓은 Internet에 접근할 수 없거나 정책상 접근에 사용하면 안 되는 경우에 유용합니다.

Bulk convenience function은 선택적으로 ignore된 iface를 건너뛸 수 있습니다.

conn_mgr_ignore_iface()와 conn_mgr_watch_iface() API 설명에서 자세한 내용을 확인할 수 있습니다.

Connectivity monitoring API

include/zephyr/net/conn_mgr_monitoring.h header를 include해 이 API에 접근합니다.

Doxygen group conn_mgr가 monitoring API reference를 제공합니다.

Connectivity control

많은 network interface는 사용할 수 있기 전에 network association 절차를 완료해야 합니다.

이러한 iface에 connectivity control은 network association을 요청하는 conn_mgr_if_connect()와 disassociation을 요청하는 conn_mgr_if_disconnect() generic API를 제공합니다. Network interface는 자신을 connectivity implementation에 binding해 이 API를 지원합니다.

Application은 이 API를 통해 technology-specific boilerplate를 최소화하면서 network에 association할 수 있습니다.

Connectivity control은 다음 기능도 제공합니다.

  • Association 도중의 표준화된 persistence와 timeout 동작
  • 사용 가능한 모든 iface의 admin state와 network association을 한 번에 제어하는 bulk function
  • 일반적인 connectivity 작업을 위한 선택형 convenience automation

기본 동작

다음 절은 Connection Manager connectivity control의 기본 동작을 설명합니다.

Binding

Connection Manager 명령으로 iface를 association 또는 disassociation하려면 먼저 connectivity implementation에 binding해야 합니다.

Binding은 application이 아니라 iface provider가 수행하며 iface declaration의 확장으로 볼 수 있습니다.

conn_mgr_if_connect()나 conn_mgr_if_disconnect() 같은 connectivity command를 binding된 iface에 전달하면 connectivity implementation의 대응 implementation function으로 route됩니다.

연결

Binding된 iface가 admin-up이면 conn_mgr_if_connect()을 호출해 network에 association하도록 할 수 있습니다.

Association에 성공하면 connectivity implementation이 iface를 operational-up으로 표시합니다.

복구할 수 없는 association 실패가 발생하면 NET_EVENT_CONN_IF_FATAL_ERROR fatal error event가 발생합니다.

이 과정에 선택형 timeout을 설정할 수 있습니다.

연결 손실

외부 요인으로 connectivity를 잃으면 connectivity implementation이 iface를 operational-down으로 표시합니다.

그 뒤 iface가 다시 연결을 시도할지는 persistence 설정에 따라 결정됩니다.

수동 연결 해제

Application은 conn_mgr_if_disconnect()을 호출해 의도적으로 connectivity를 포기하도록 요청할 수도 있습니다.

이 경우 connectivity implementation은 iface를 network에서 disassociate하고 operational-down으로 표시합니다.

Persistence가 활성화돼 있어도 새 connection attempt를 시작하지 않습니다.

Timeout과 persistence

Connection Manager는 모든 connectivity implementation이 다음 두 핵심 표준 기능을 지원하도록 요구합니다.

  • Connection timeout
  • Connection persistence

두 기능은 connect와 disconnect event가 발생할 때 iface가 어떻게 동작할지 정의하며 iface마다 개별 설정할 수 있습니다.

Connection timeout

conn_mgr_if_connect()을 iface에 호출하면 connection attempt가 시작됩니다.

conn_mgr_if_set_timeout()으로 timeout을 지정하지 않았다면 connection attempt는 성공할 때까지 무기한 계속됩니다.

Timeout을 지정했다면 성공 전에 시간이 만료될 경우 connection attempt를 포기하고 NET_EVENT_CONN_IF_TIMEOUT event를 발생시킵니다.

Connection persistence

각 iface는 conn_mgr_binding_set_flag()로 CONN_MGR_IF_PERSISTENT flag를 설정해 켜거나 끌 수 있는 connection persistence 설정도 가집니다.

이 설정은 의도하지 않은 connection loss를 iface가 어떻게 처리할지 지정합니다.

Persistence가 활성화돼 있으면 의도하지 않은 connection loss가 발생할 때 새 connection attempt를 시작하며, timeout이 설정돼 있다면 새 timeout도 함께 시작합니다.

Persistence가 비활성화돼 있으면 iface는 reconnect를 시도하지 않습니다.

Control event

Connectivity control은 중요한 state change를 application에 알리는 network management event를 발생시킵니다.

Connectivity implementation이 따라야 하는 event 발생 규칙은 implementation guideline을 참고하십시오.

Fatal error

NET_EVENT_CONN_IF_FATAL_ERROR는 iface가 복구 불가능한 error를 만날 때 발생합니다. 이후의 association attempt가 반드시 실패하므로 모든 attempt를 포기해야 하는 경우를 뜻합니다.

Event handler에는 fatal error가 발생한 iface pointer가 전달됩니다. 개별 connectivity implementation은 application-specific data pointer를 추가로 전달할 수도 있습니다.

Timeout event

NET_EVENT_CONN_IF_TIMEOUT은 iface association attempt가 timeout될 때 발생합니다.

Event handler에는 association을 시도하다 timeout된 iface pointer가 전달됩니다.

Control event 수신

다음과 같이 control event listener를 구성할 수 있습니다.

/* Declare a net_mgmt callback struct to store the callback */
struct net_mgmt_event_callback my_conn_evt_callback;

/* Declare a handler to receive control events */
static void my_conn_evt_handler(struct net_mgmt_event_callback *cb,
                                uint32_t event, struct net_if *iface)
{
        if (event == NET_EVENT_CONN_IF_TIMEOUT) {
                /* Timeout occurred, handle it */
        } else if (event == NET_EVENT_CONN_IF_FATAL_ERROR) {
                /* Fatal error occurred, handle it */
        }

        /* Otherwise, it's some other event type we didn't register for. */
}

int main()
{
        /* Configure the callback struct to respond to (at least) the CONN_IF_TIMEOUT
         * and CONN_IF_FATAL_ERROR events.
         *
         * Note that the callback may also be triggered for events other than those specified here!
         * (See the net_mgmt documentation)
         */

        net_mgmt_init_event_callback(
                &conn_mgr_conn_callback, conn_mgr_conn_handler,
                    NET_EVENT_CONN_IF_TIMEOUT | NET_EVENT_CONN_IF_FATAL_ERROR
        );

        /* Register the callback */
        net_mgmt_add_event_callback(&conn_mgr_conn_callback);
        return 0;
}

Network management event listener에 관한 자세한 내용은 net_mgmt 문서를 참고하십시오.

자동 동작

Connectivity와 관련된 몇 가지 동작은 기본적으로 Connection Manager가 사용자를 대신해 자동 수행합니다.

Automatic admin-up

Zephyr는 초기화 도중 iface를 자동으로 admin-up 상태로 만듭니다. Application은 net_if_flag_set()으로 NET_IF_NO_AUTO_START interface flag를 설정해 이 동작을 비활성화할 수 있습니다.

Automatic connect

기본적으로 Connection Manager는 binding된 iface가 admin-up 상태가 되면 자동으로 연결합니다. Application은 conn_mgr_if_set_flag()으로 CONN_MGR_IF_NO_AUTO_CONNECT connectivity flag를 설정해 이를 비활성화할 수 있습니다.

Automatic admin-down

기본적으로 Connection Manager는 association을 포기한 binding iface를 자동으로 admin-down 상태로 만듭니다.

CONFIG_NET_CONNECTION_MANAGER_AUTO_IF_DOWN Kconfig option을 끄면 모든 iface에 대해 이 기능을 비활성화할 수 있습니다. 개별 iface에는 conn_mgr_if_set_flag()으로 CONN_MGR_IF_NO_AUTO_DOWN connectivity flag를 설정합니다.

Connectivity control API

include/zephyr/net/conn_mgr_connectivity.h header를 include해 이 API에 접근합니다.

Doxygen group conn_mgr_connectivity가 connectivity control API reference를 제공합니다.

Bulk API

Connectivity control은 모든 iface를 한 번에 제어하는 여러 bulk function을 제공합니다.

필요하면 이 function이 ignore되지 않은 iface에만 동작하도록 제한할 수 있습니다.

include/zephyr/net/conn_mgr_connectivity.h header를 include해 접근하며 Doxygen group conn_mgr_connectivity_bulk에서 bulk API reference를 확인할 수 있습니다.

Source

출처

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