xref: /nrf52832-nimble/packages/NimBLE-latest/docs/ble_setup/ble_sync_cb.rst (revision 042d53a763ad75cb1465103098bb88c245d95138)
1Respond to *sync* and *reset* events
2------------------------------------
3
4sync
5~~~~
6
7The NimBLE stack is inoperable while the host and controller are out of
8sync. In a combined host-controller app, the sync happens immediately at
9startup. When the host and controller are separate, sync typically
10occurs in under a second after the application starts. An application
11learns when sync is achieved by configuring the host's *sync callback*:
12``ble_hs_cfg.sync_cb``. The host calls the sync callback whenever sync
13is acquired. The sync callback has the following form:
14
15.. code-block:: cpp
16
17    typedef void ble_hs_sync_fn(void);
18
19Because the NimBLE stack begins in the unsynced state, the application
20should delay all BLE operations until the sync callback has been called.
21
22reset
23~~~~~
24
25Another event indicated by the host is a *controller reset*. The NimBLE
26stack resets itself when a catastrophic error occurs, such as loss of
27communication between the host and controller. Upon resetting, the host
28drops all BLE connections and loses sync with the controller. After a
29reset, the application should refrain from using the host until sync is
30again signaled via the sync callback.
31
32An application learns of a host reset by configuring the host's *reset
33callback*: ``ble_hs_cfg.reset_cb``. This callback has the following
34form:
35
36.. code-block:: cpp
37
38    typedef void ble_hs_reset_fn(int reason);
39
40The ``reason`` parameter is a :doc:`NimBLE host return
41code <../ble_hs/ble_hs_return_codes>`.
42
43Example
44~~~~~~~
45
46The following example demonstrates the configuration of the sync and
47reset callbacks.
48
49.. code-block:: cpp
50
51    #include "sysinit/sysinit.h"
52    #include "console/console.h"
53    #include "host/ble_hs.h"
54
55    static void
56    on_sync(void)
57    {
58        /* Begin advertising, scanning for peripherals, etc. */
59    }
60
61    static void
62    on_reset(int reason)
63    {
64        console_printf("Resetting state; reason=%d\n", reason);
65    }
66
67    int
68    main(void)
69    {
70        /* Initialize all packages. */
71        sysinit();
72
73        ble_hs_cfg.sync_cb = on_sync;
74        ble_hs_cfg.reset_cb = on_reset;
75
76        /* As the last thing, process events from default event queue. */
77        while (1) {
78            os_eventq_run(os_eventq_dflt_get());
79        }
80    }
81