1.. _conn_mgr_overview:
2
3Overview
4########
5
6Connection 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.
7
8Using 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.
9
10This allows an application to potentially support several very different connectivity technologies (for example, Wi-Fi and LTE) with a single codebase.
11
12Applications can also use Connection Manager to generically manage and use multiple connectivity technologies simultaneously.
13
14Structure
15=========
16
17Connection Manager is split into the following two subsystems:
18
19* :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.
20
21* :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.
22
23.. _conn_mgr_integration_diagram_simple:
24
25.. figure:: figures/integration_diagram_simplified.svg
26    :alt: A simplified view of how Connection Manager integrates with Zephyr and the application.
27    :figclass: align-center
28
29    A simplified view of how Connection Manager integrates with Zephyr and the application.
30
31    See :ref:`here <conn_mgr_integration_diagram_detailed>` for a more detailed version.
32
33.. _conn_mgr_monitoring:
34
35Connectivity monitoring
36#######################
37
38Connectivity 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.
39
40Each available iface is considered ready if it meets the following criteria:
41
42* The iface is admin-up
43
44  * 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`.
45
46* The iface is oper-up
47
48  * This means the interface is completely ready for use; It is online, and if applicable, has associated with a network.
49  * See :ref:`net_if_interface_state_management` for details.
50
51* The iface has at least one assigned IP address
52
53  * Both IPv4 and IPv6 addresses are acceptable.
54    This condition is met as soon as one or both of these is assigned.
55  * See :ref:`net_if_interface` for details on iface IP assignment.
56
57* The iface has not been ignored
58
59  * Ignored ifaces are always treated as unready.
60  * See :ref:`conn_mgr_monitoring_ignoring_ifaces` for more details.
61
62.. note::
63
64   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>`.
65
66   See :ref:`conn_mgr_impl_guidelines_iface_state_reporting` for details.
67
68A ready iface ceases to be ready the moment any of the above conditions is lost.
69
70When 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.
71
72Afterwards, ifaces can become ready or unready without firing additional events, so long as there always remains at least one ready iface.
73
74When 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.
75
76.. note::
77
78   Connection Manager also fires the following more specific ``CONNECTED`` / ``DISCONNECTED`` events:
79
80   - :c:macro:`NET_EVENT_L4_IPV4_CONNECTED`
81   - :c:macro:`NET_EVENT_L4_IPV4_DISCONNECTED`
82   - :c:macro:`NET_EVENT_L4_IPV6_CONNECTED`
83   - :c:macro:`NET_EVENT_L4_IPV6_DISCONNECTED`
84
85   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.
86
87.. _conn_mgr_monitoring_usage:
88
89Usage
90=====
91
92Connectivity monitoring is enabled if the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER` Kconfig option is enabled.
93
94To 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:
95
96.. code-block:: c
97
98   /* Callback struct where the callback will be stored */
99   struct net_mgmt_event_callback l4_callback;
100
101   /* Callback handler */
102   static void l4_event_handler(struct net_mgmt_event_callback *cb,
103                                uint32_t event, struct net_if *iface)
104   {
105           if (event == NET_EVENT_L4_CONNECTED) {
106                   LOG_INF("Network connectivity gained!");
107           } else if (event == NET_EVENT_L4_DISCONNECTED) {
108                   LOG_INF("Network connectivity lost!");
109           }
110
111           /* Otherwise, it's some other event type we didn't register for. */
112   }
113
114   /* Call this before Connection Manager monitoring initializes */
115   static void my_application_setup(void)
116   {
117           /* Configure the callback struct to respond to (at least) the L4_CONNECTED
118            * and L4_DISCONNECTED events.
119            *
120            *
121            * Note that the callback may also be triggered for events other than those specified here!
122            * (See the net_mgmt documentation)
123            */
124           net_mgmt_init_event_callback(
125                   &l4_callback, l4_event_handler,
126                   NET_EVENT_L4_CONNECTED | NET_EVENT_L4_DISCONNECTED
127           );
128
129           /* Register the callback */
130           net_mgmt_add_event_callback(&l4_callback);
131   }
132
133See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events.
134
135.. note::
136   To avoid missing initial connectivity events, you should register your listener(s) before Connection Manager monitoring initializes.
137   See :ref:`conn_mgr_monitoring_missing_notifications` for strategies to ensure this.
138
139.. _conn_mgr_monitoring_missing_notifications:
140
141Avoiding missed notifications
142=============================
143
144Connectivity monitoring may trigger events immediately upon initialization.
145
146If 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.
147
148If this is a concern, your application should :ref:`register its event listeners <conn_mgr_monitoring_usage>` before connectivity monitoring initializes.
149
150Connectivity monitoring initializes using the :c:macro:`SYS_INIT` ``APPLICATION`` initialization priority specified by the :kconfig:option:`CONFIG_NET_CONNECTION_MANAGER_MONITOR_PRIORITY` Kconfig option.
151
152You 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:
153
154.. code-block:: C
155
156   static int my_application_setup(void)
157   {
158	   /* Register callbacks here */
159	   return 0;
160   }
161
162   SYS_INIT(my_application_setup, APPLICATION, 0);
163
164If 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`:
165
166.. code-block:: C
167
168   static void my_late_application_setup(void)
169   {
170     /* Register callbacks here */
171
172     /* Once done, request that events be re-triggered */
173     conn_mgr_mon_resend_status();
174   }
175
176.. _conn_mgr_monitoring_ignoring_ifaces:
177
178Ignoring ifaces
179===============
180
181Applications can request that ifaces be ignored by Connection Manager by calling :c:func:`conn_mgr_ignore_iface` with the iface to be ignored.
182
183Alternatively, an entire :ref:`L2 implementation <net_l2_interface>` can be ignored by calling :c:func:`conn_mgr_ignore_l2`.
184
185This has the effect of individually ignoring all the ifaces using that :ref:`L2 implementation <net_l2_interface>`.
186
187While ignored, the iface is treated by Connection Manager as though it were unready for network traffic, no matter its actual state.
188
189This 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.
190
191:ref:`Bulk convenience functions <conn_mgr_control_api_bulk>` optionally skip ignored ifaces.
192
193See :c:func:`conn_mgr_ignore_iface` and :c:func:`conn_mgr_watch_iface` for more details.
194
195.. _conn_mgr_monitoring_api:
196
197Connectivity monitoring API
198===========================
199
200Include header file :file:`include/zephyr/net/conn_mgr_monitoring.h` to access these.
201
202.. doxygengroup:: conn_mgr
203
204.. _conn_mgr_control:
205
206Connectivity control
207####################
208
209Many network interfaces require a network association procedure to be completed before being usable.
210
211For 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`).
212Network interfaces implement support for this API by :ref:`binding themselves to a connectivity implementation <conn_mgr_impl_binding>`.
213
214Using this API, applications can associate with networks with minimal technology-specific boilerplate.
215
216Connectivity control also provides the following additional features:
217
218* Standardized :ref:`persistence and timeout <conn_mgr_control_persistence_timeouts>` behaviors during association.
219* :ref:`Bulk functions <conn_mgr_control_api_bulk>` for controlling the admin state and network association of all available ifaces simultaneously.
220* Optional :ref:`convenience automations <conn_mgr_control_automations>` for common connectivity actions.
221
222.. _conn_mgr_control_operation:
223
224Basic operation
225===============
226
227The following sections outline the basic operation of Connection Manager's connectivity control.
228
229.. _conn_mgr_control_operation_binding:
230
231Binding
232-------
233
234Before 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>`.
235Binding 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.
236
237Once 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.
238
239.. note::
240
241  To avoid inconsistent behavior, all connectivity implementations must adhere to the :ref:`implementation guidelines <conn_mgr_impl_guidelines>`.
242
243.. _conn_mgr_control_operation_connecting:
244
245Connecting
246----------
247
248Once 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.
249
250If association succeeds, the connectivity implementation will mark the iface as operational-up (see :ref:`net_if_interface_state_management`).
251
252If association fails unrecoverably, the :ref:`fatal error event <conn_mgr_control_events_fatal_error>` will be triggered.
253
254You can configure an optional :ref:`timeout <conn_mgr_control_timeouts>` for this process.
255
256.. note::
257   The :c:func:`conn_mgr_if_connect` function is intentionally minimalistic, and does not take any kind of configuration.
258   Each connectivity implementation should provide a way to pre-configure or automatically configure any required association settings or credentials.
259   See :ref:`conn_mgr_impl_guidelines_preconfig` for details.
260
261.. _conn_mgr_control_operation_loss:
262
263Connection loss
264---------------
265
266If connectivity is lost due to external factors, the connectivity implementation will mark the iface as operational-down.
267
268Depending on whether :ref:`persistence <conn_mgr_control_persistence>` is set, the iface may then attempt to reconnect.
269
270.. _conn_mgr_control_operation_disconnection:
271
272Manual disconnection
273--------------------
274
275The application can also request that connectivity be intentionally abandoned by calling :c:func:`conn_mgr_if_disconnect`.
276
277In 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`).
278A new connection attempt will not be initiated, regardless of whether persistence is enabled.
279
280.. _conn_mgr_control_persistence_timeouts:
281
282Timeouts and Persistence
283========================
284
285Connection Manager requires that all connectivity implementations support the following standard key features:
286
287* :ref:`Connection timeouts <conn_mgr_control_timeouts>`
288* :ref:`Connection persistence <conn_mgr_control_persistence>`
289
290These features describe how ifaces should behave during connect and disconnect events.
291You can individually set them for each iface.
292
293.. note::
294   It is left to connectivity implementations to successfully and accurately implement these two features as described below.
295   See :ref:`conn_mgr_impl_timeout_persistence` for more details from the connectivity implementation perspective.
296
297.. _conn_mgr_control_timeouts:
298
299Connection Timeouts
300-------------------
301
302When :c:func:`conn_mgr_if_connect` is called on an iface, a connection attempt begins.
303
304The connection attempt continues indefinitely until it succeeds, unless a timeout has been specified for the iface (using :c:func:`conn_mgr_if_set_timeout`).
305
306In that case, the connection attempt will be abandoned if the timeout elapses before it succeeds.
307If this happens, the :ref:`timeout event<conn_mgr_control_events_timeout>` is raised.
308
309.. _conn_mgr_control_persistence:
310
311Connection Persistence
312----------------------
313
314Each iface also has a connection persistence setting that you can enable or disable by setting the :c:enumerator:`CONN_MGR_IF_PERSISTENT` flag with :c:func:`conn_mgr_binding_set_flag`.
315
316This setting specifies how the iface should handle unintentional connection loss.
317
318If persistence is enabled, any unintentional connection loss will initiate a new connection attempt, with a new timeout if applicable.
319
320Otherwise, the iface will not attempt to reconnect.
321
322.. note::
323   Persistence not does affect connection attempt behavior.
324   Only the timeout setting affects this.
325
326   For instance, if a connection attempt on an iface times out, the iface will not attempt to reconnect, even if it is persistent.
327
328   Conversely, if there is not a specified timeout, the iface will try to connect forever until it succeeds, even if it is not persistent.
329
330   See :ref:`conn_mgr_impl_tp_persistence_during_connect` for the equivalent implementation guideline.
331
332.. _conn_mgr_control_events:
333
334Control events
335==============
336
337Connectivity control triggers :ref:`network management <net_mgmt_interface>` events to inform the application of important state changes.
338
339See :ref:`conn_mgr_impl_guidelines_trigger_events` for the corresponding connectivity implementation guideline.
340
341.. _conn_mgr_control_events_fatal_error:
342
343Fatal Error
344-----------
345
346The :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).
347
348Handlers of this event will be passed a pointer to the iface for which the fatal error occurred.
349Individual connectivity implementations may also pass an application-specific data pointer.
350
351.. _conn_mgr_control_events_timeout:
352
353Timeout
354-------
355
356The :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>`.
357
358Handlers of this event will be passed a pointer to the iface that timed out attempting to associate.
359
360.. _conn_mgr_control_events_listening:
361
362Listening for control events
363----------------------------
364
365You can listen for control events as follows:
366
367.. code-block:: c
368
369   /* Declare a net_mgmt callback struct to store the callback */
370   struct net_mgmt_event_callback my_conn_evt_callback;
371
372   /* Declare a handler to receive control events */
373   static void my_conn_evt_handler(struct net_mgmt_event_callback *cb,
374                                   uint32_t event, struct net_if *iface)
375   {
376           if (event == NET_EVENT_CONN_IF_TIMEOUT) {
377                   /* Timeout occurred, handle it */
378           } else if (event == NET_EVENT_CONN_IF_FATAL_ERROR) {
379                   /* Fatal error occurred, handle it */
380           }
381
382           /* Otherwise, it's some other event type we didn't register for. */
383   }
384
385   int main()
386   {
387           /* Configure the callback struct to respond to (at least) the CONN_IF_TIMEOUT
388            * and CONN_IF_FATAL_ERROR events.
389            *
390            * Note that the callback may also be triggered for events other than those specified here!
391            * (See the net_mgmt documentation)
392            */
393
394           net_mgmt_init_event_callback(
395                   &conn_mgr_conn_callback, conn_mgr_conn_handler,
396                       NET_EVENT_CONN_IF_TIMEOUT | NET_EVENT_CONN_IF_FATAL_ERROR
397           );
398
399           /* Register the callback */
400           net_mgmt_add_event_callback(&conn_mgr_conn_callback);
401           return 0;
402   }
403
404See :ref:`net_mgmt_listening` for more details on listening for net_mgmt events.
405
406.. _conn_mgr_control_automations:
407
408Automated behaviors
409===================
410
411There are a few actions related to connectivity that are (by default at least) performed automatically for the user.
412
413.. _conn_mgr_control_automations_auto_up:
414
415.. topic:: Automatic admin-up
416
417   In Zephyr, ifaces are automatically taken admin-up (see :ref:`net_if_interface_state_management` for details on iface states) during initialization.
418
419   Applications can disable this behavior by setting the :c:enumerator:`NET_IF_NO_AUTO_START` interface flag with :c:func:`net_if_flag_set`.
420
421.. _conn_mgr_control_automations_auto_connect:
422
423.. topic:: Automatic connect
424
425   By default, Connection Manager will automatically connect any :ref:`bound <conn_mgr_impl_binding>` iface that becomes admin-up.
426
427   Applications can disable this by setting the :c:enumerator:`CONN_MGR_IF_NO_AUTO_CONNECT` connectivity flag with :c:func:`conn_mgr_if_set_flag`.
428
429.. _conn_mgr_control_automations_auto_down:
430
431.. topic:: Automatic admin-down
432
433   By default, Connection Manager will automatically take any bound iface admin-down if it has given up on associating.
434
435   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_NO_AUTO_DOWN` connectivity flag with :c:func:`conn_mgr_if_set_flag`.
436
437.. _conn_mgr_control_api:
438
439Connectivity control API
440========================
441
442Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these.
443
444.. doxygengroup:: conn_mgr_connectivity
445
446.. _conn_mgr_control_api_bulk:
447
448Bulk API
449--------
450
451Connectivity control provides several bulk functions allowing all ifaces to be controlled at once.
452
453You can restrict these functions to operate only on non-:ref:`ignored <conn_mgr_monitoring_ignoring_ifaces>` ifaces if desired.
454
455Include header file :file:`include/zephyr/net/conn_mgr_connectivity.h` to access these.
456
457.. doxygengroup:: conn_mgr_connectivity_bulk
458