xref: /btstack/doc/manual/docs-template/how_to.md (revision 01f72e3df45a7cedc261ee0c559b7ee1149f5d69)
1#
2
3BTstack implements a set of Bluetooth protocols and profiles. To connect to other Bluetooth devices or to provide a Bluetooth services, BTstack has to be properly configured.
4
5The configuration of BTstack is done both at compile time as well as at run time:
6
7- compile time configuration:
8    - adjust *btstack_config.h* - this file describes the system configuration, used functionality, and also the memory configuration
9    - add necessary source code files to your project
10
11- run time configuration of:
12    - Bluetooth chipset
13    - run loop
14    - HCI transport layer
15    - provided services
16    - packet handlers
17
18In the following, we provide an overview of the configuration
19that is necessary to setup BTstack. From the point when the run loop
20is executed, the application runs as a finite
21state machine, which processes events received from BTstack. BTstack
22groups events logically and provides them via packet handlers.
23We provide their overview here. For the case that there is a need to inspect the data exchanged
24between BTstack and the Bluetooth chipset, we describe how to configure
25packet logging mechanism. Finally, we provide an overview on power management in Bluetooth in general and how to save energy in BTstack.
26
27## Configuration in btstack_config.h {#sec:btstackConfigHowTo}
28The file *btstack_config.h* contains three parts:
29
30- \#define HAVE_* directives [listed here](#sec:haveDirectives). These directives describe available system properties, similar to config.h in a autoconf setup.
31- \#define ENABLE_* directives [listed here](#sec:enableDirectives). These directives list enabled properties, most importantly ENABLE_CLASSIC and ENABLE_BLE.
32- other #define directives for BTstack configuration, most notably static memory, [see next section](#sec:memoryConfigurationHowTo) and [NVM configuration](#sec:nvmConfiguration).
33
34<!-- a name "lst:platformConfiguration"></a-->
35<!-- -->
36
37### HAVE_* directives {#sec:haveDirectives}
38System properties:
39
40\#define | Description
41-----------------------------------|-------------------------------------
42HAVE_MALLOC                        | Use dynamic memory
43HAVE_AES128                        | Use platform AES128 engine - not needed usually
44HAVE_BTSTACK_STDIN                 | STDIN is available for CLI interface
45HAVE_MBEDTLS_ECC_P256              | mbedTLS provides NIST P-256 operations e.g. for LE Secure Connections
46
47Embedded platform properties:
48
49\#define                           | Description
50-----------------------------------|------------------------------------
51HAVE_EMBEDDED_TIME_MS              | System provides time in milliseconds
52HAVE_EMBEDDED_TICK                 | System provides tick interrupt
53
54FreeRTOS platform properties:
55
56\#define                           | Description
57-----------------------------------|------------------------------------
58HAVE_FREERTOS_INCLUDE_PREFIX       | FreeRTOS headers are in 'freertos' folder (e.g. ESP32's esp-idf)
59
60POSIX platform properties:
61
62\#define                            | Description
63-----------------------------------|------------------------------------
64HAVE_POSIX_B300_MAPPED_TO_2000000  | Workaround to use serial port with 2 mbps
65HAVE_POSIX_B600_MAPPED_TO_3000000  | Workaround to use serial port with 3 mpbs
66HAVE_POSIX_FILE_IO                 | POSIX File i/o used for hci dump
67HAVE_POSIX_TIME                    | System provides time function
68LINK_KEY_PATH                      | Path to stored link keys
69LE_DEVICE_DB_PATH                  | Path to stored LE device information
70<!-- a name "lst:btstackFeatureConfiguration"></a-->
71<!-- -->
72
73### ENABLE_* directives {#sec:enableDirectives}
74BTstack properties:
75
76\#define                         | Description
77---------------------------------|---------------------------------------------
78ENABLE_CLASSIC                   | Enable Classic related code in HCI and L2CAP
79ENABLE_BLE                       | Enable BLE related code in HCI and L2CAP
80ENABLE_EHCILL                    | Enable eHCILL low power mode on TI CC256x/WL18xx chipsets
81ENABLE_H5                        | Enable support for SLIP mode in `btstack_uart.h` drivers for HCI H5 ('Three-Wire Mode')
82ENABLE_LOG_DEBUG                 | Enable log_debug messages
83ENABLE_LOG_ERROR                 | Enable log_error messages
84ENABLE_LOG_INFO                  | Enable log_info messages
85ENABLE_SCO_OVER_HCI              | Enable SCO over HCI for chipsets (if supported)
86ENABLE_SCO_OVER_PCM              | Enable SCO ofer PCM/I2S for chipsets (if supported)
87ENABLE_HFP_WIDE_BAND_SPEECH      | Enable support for mSBC codec used in HFP profile for Wide-Band Speech
88ENABLE_HFP_AT_MESSAGES           | Enable `HFP_SUBEVENT_AT_MESSAGE_SENT` and `HFP_SUBEVENT_AT_MESSAGE_RECEIVED` events
89ENABLE_LE_PERIPHERAL             | Enable support for LE Peripheral Role in HCI and Security Manager
90ENBALE_LE_CENTRAL                | Enable support for LE Central Role in HCI and Security Manager
91ENABLE_LE_SECURE_CONNECTIONS     | Enable LE Secure Connections
92ENABLE_LE_PROACTIVE_AUTHENTICATION | Enable automatic encryption for bonded devices on re-connect
93ENABLE_GATT_CLIENT_PAIRING       | Enable GATT Client to start pairing and retry operation on security error
94ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS | Use [micro-ecc library](https://github.com/kmackay/micro-ecc) for ECC operations
95ENABLE_LE_DATA_CHANNELS          | Enable LE Data Channels in credit-based flow control mode
96ENABLE_LE_DATA_LENGTH_EXTENSION  | Enable LE Data Length Extension support
97ENABLE_LE_SIGNED_WRITE           | Enable LE Signed Writes in ATT/GATT
98ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION | Enable address resolution for resolvable private addresses in Controller
99ENABLE_CROSS_TRANSPORT_KEY_DERIVATION | Enable Cross-Transport Key Derivation (CTKD) for Secure Connections
100ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE | Enable L2CAP Enhanced Retransmission Mode. Mandatory for AVRCP Browsing
101ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL | Enable HCI Controller to Host Flow Control, see below
102ENABLE_ATT_DELAYED_RESPONSE      | Enable support for delayed ATT operations, see [GATT Server](profiles/#sec:GATTServerProfile)
103ENABLE_BCM_PCM_WBS               | Enable support for Wide-Band Speech codec in BCM controller, requires ENABLE_SCO_OVER_PCM
104ENABLE_CC256X_ASSISTED_HFP       | Enable support for Assisted HFP mode in CC256x Controller, requires ENABLE_SCO_OVER_PCM
105ENABLE_CC256X_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND | Enable workaround for bug in CC256x Flow Control during baud rate change, see chipset docs.
106ENABLE_CYPRESS_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND | Enable workaround for bug in CYW2070x Flow Control during baud rate change, similar to CC256x.
107ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS | Force HCI to fragment ACL-LE packets to fit into over-the-air packet
108ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD | Enable use of explicit delete field in TLV Flash implemenation - required when flash value cannot be overwritten with zero
109ENABLE_CONTROLLER_WARM_BOOT      | Enable stack startup without power cycle (if supported/possible)
110ENABLE_SEGGER_RTT                | Use SEGGER RTT for console output and packet log, see [additional options](#sec:rttConfiguration)
111ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL | Disable calls to control Connectable Mode by L2CAP
112ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY | Let application trigger sending IO Capabilities (Negative) Reply
113ENABLE_CLASSIC_OOB_PAIRING       | Enable support for classic Out-of-Band (OOB) pairing
114ENABLE_A2DP_SOURCE_EXPLICIT_CONFIG | Let application configure stream endpoint (skip auto-config of SBC endpoint)
115ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION | allow accept or reject of stream start on A2DP_SUBEVENT_START_STREAM_REQUESTED
116
117
118Notes:
119
120- ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS: Only some Bluetooth 4.2+ controllers (e.g., EM9304, ESP32) support the necessary HCI commands for ECC. Other reason to enable the ECC software implementations are if the Host is much faster or if the micro-ecc library is already provided (e.g., ESP32, WICED, or if the ECC HCI Commands are unreliable.
121
122### HCI Controller to Host Flow Control
123In general, BTstack relies on flow control of the HCI transport, either via Hardware CTS/RTS flow control for UART or regular USB flow control. If this is not possible, e.g on an SoC, BTstack can use HCI Controller to Host Flow Control by defining ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL. If enabled, the HCI Transport implementation must be able to buffer the specified packets. In addition, it also need to be able to buffer a few HCI Events. Using a low number of host buffers might result in less throughput.
124
125Host buffer configuration for HCI Controller to Host Flow Control:
126
127\#define         | Description
128------------------|------------
129HCI_HOST_ACL_PACKET_NUM | Max number of ACL packets
130HCI_HOST_ACL_PACKET_LEN | Max size of HCI Host ACL packets
131HCI_HOST_SCO_PACKET_NUM | Max number of ACL packets
132HCI_HOST_SCO_PACKET_LEN | Max size of HCI Host SCO packets
133
134
135### Memory configuration directives {#sec:memoryConfigurationHowTo}
136
137The structs for services, active connections and remote devices can be
138allocated in two different manners:
139
140-   statically from an individual memory pool, whose maximal number of
141    elements is defined in the btstack_config.h file. To initialize the static
142    pools, you need to call at runtime *btstack_memory_init* function. An example
143    of memory configuration for a single SPP service with a minimal
144    L2CAP MTU is shown in Listing {@lst:memoryConfigurationSPP}.
145
146-   dynamically using the *malloc/free* functions, if HAVE_MALLOC is
147    defined in btstack_config.h file.
148
149For each HCI connection, a buffer of size HCI_ACL_PAYLOAD_SIZE is reserved. For fast data transfer, however, a large ACL buffer of 1021 bytes is recommend. The large ACL buffer is required for 3-DH5 packets to be used.
150
151<!-- a name "lst:memoryConfiguration"></a-->
152<!-- -->
153
154\#define | Description
155--------|------------
156HCI_ACL_PAYLOAD_SIZE | Max size of HCI ACL payloads
157MAX_NR_BNEP_CHANNELS | Max number of BNEP channels
158MAX_NR_BNEP_SERVICES | Max number of BNEP services
159MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES | Max number of link key entries cached in RAM
160MAX_NR_GATT_CLIENTS | Max number of GATT clients
161MAX_NR_HCI_CONNECTIONS | Max number of HCI connections
162MAX_NR_HFP_CONNECTIONS | Max number of HFP connections
163MAX_NR_L2CAP_CHANNELS |  Max number of L2CAP connections
164MAX_NR_L2CAP_SERVICES |  Max number of L2CAP services
165MAX_NR_RFCOMM_CHANNELS | Max number of RFOMMM connections
166MAX_NR_RFCOMM_MULTIPLEXERS | Max number of RFCOMM multiplexers, with one multiplexer per HCI connection
167MAX_NR_RFCOMM_SERVICES | Max number of RFCOMM services
168MAX_NR_SERVICE_RECORD_ITEMS | Max number of SDP service records
169MAX_NR_SM_LOOKUP_ENTRIES | Max number of items in Security Manager lookup queue
170MAX_NR_WHITELIST_ENTRIES | Max number of items in GAP LE Whitelist to connect to
171MAX_NR_LE_DEVICE_DB_ENTRIES | Max number of items in LE Device DB
172
173
174The memory is set up by calling *btstack_memory_init* function:
175
176    btstack_memory_init();
177
178<!-- a name "lst:memoryConfigurationSPP"></a-->
179<!-- -->
180
181Here's the memory configuration for a basic SPP server.
182
183    #define HCI_ACL_PAYLOAD_SIZE 52
184    #define MAX_NR_HCI_CONNECTIONS 1
185    #define MAX_NR_L2CAP_SERVICES  2
186    #define MAX_NR_L2CAP_CHANNELS  2
187    #define MAX_NR_RFCOMM_MULTIPLEXERS 1
188    #define MAX_NR_RFCOMM_SERVICES 1
189    #define MAX_NR_RFCOMM_CHANNELS 1
190    #define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES  3
191
192Listing: Memory configuration for a basic SPP server. {#lst:memoryConfigurationSPP}
193
194In this example, the size of ACL packets is limited to the minimum of 52 bytes, resulting in an L2CAP MTU of 48 bytes. Only a singleHCI connection can be established at any time. On it, two L2CAP services are provided, which can be active at the same time. Here, these two can be RFCOMM and SDP. Then, memory for one RFCOMM multiplexer is reserved over which one connection can be active. Finally, up to three link keys can be cached in RAM.
195
196<!-- -->
197
198### Non-volatile memory (NVM) directives {#sec:nvmConfiguration}
199
200If implemented, bonding information is stored in Non-volatile memory. For Classic, a single link keys and its type is stored. For LE, the bonding information contains various values (long term key, random number, EDIV, signing counter, identity, ...) Often, this is implemented using Flash memory. Then, the number of stored entries are limited by:
201
202<!-- a name "lst:nvmDefines"></a-->
203<!-- -->
204
205\#define                  | Description
206--------------------------|------------
207NVM_NUM_LINK_KEYS         | Max number of Classic Link Keys that can be stored
208NVM_NUM_DEVICE_DB_ENTRIES | Max number of LE Device DB entries that can be stored
209NVN_NUM_GATT_SERVER_CCC   | Max number of 'Client Characteristic Configuration' values that can be stored by GATT Server
210
211
212### SEGGER Real Time Transfer (RTT) directives {#sec:rttConfiguration}
213
214[SEGGER RTT](https://www.segger.com/products/debug-probes/j-link/technology/about-real-time-transfer/) improves on the use of an UART for debugging with higher throughput and less overhead. In addition, it allows for direct logging in PacketLogger/BlueZ format via the provided JLinkRTTLogger tool.
215
216When enabled with `ENABLE_SEGGER_RTT` and `hci_dump_init()` can be called with an `hci_dunp_segger_stdout_get_instance()` for textual output and `hci_dump_segger_binary_get_instance()` for binary output. With the latter, you can select `HCI_DUMP_BLUEZ` or `HCI_DUMP_PACKETLOGGER`, format. For RTT, the following directives are used to configure the up channel:
217
218\#define                         | Default                        | Description
219---------------------------------|--------------------------------|------------------------
220SEGGER_RTT_PACKETLOG_MODE        | SEGGER_RTT_MODE_NO_BLOCK_SKIP  | SEGGER_RTT_MODE_NO_BLOCK_SKIP to skip messages if buffer is full, or, SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL to block
221SEGGER_RTT_PACKETLOG_CHANNEL     | 1                              | Channel to use for packet log. Channel 0 is used for terminal
222SEGGER_RTT_PACKETLOG_BUFFER_SIZE | 1024                           | Size of outgoing ring buffer. Increase if you cannot block but get 'message skipped' warnings.
223
224## Run-time configuration
225
226To allow code-reuse with different platforms
227as well as with new ports, the low-level initialization of BTstack and
228the hardware configuration has been extracted to the various
229*platforms/PLATFORM/main.c* files. The examples only contain the
230platform-independent Bluetooth logic. But let’s have a look at the
231common init code.
232
233Listing [below](#lst:btstackInit) shows a minimal platform setup for an
234embedded system with a Bluetooth chipset connected via UART.
235
236~~~~ {#lst:btstackInit .c caption="{Minimal platform setup for an embedded system}"}
237
238    int main(){
239      // ... hardware init: watchdoch, IOs, timers, etc...
240
241      // setup BTstack memory pools
242      btstack_memory_init();
243
244      // select embedded run loop
245      btstack_run_loop_init(btstack_run_loop_embedded_get_instance());
246
247      // enable logging
248      hci_dump_init(hci_dump_embedded_stdout_get_instance());
249
250
251      // init HCI
252      hci_transport_t     * transport = hci_transport_h4_instance();
253      hci_init(transport, NULL);
254
255      // setup example
256      btstack_main(argc, argv);
257
258      // go
259      btstack_run_loop_execute();
260    }
261
262~~~~
263
264First, BTstack’s memory pools are set up. Then, the standard run loop
265implementation for embedded systems is selected.
266
267The call to *hci_dump_init* configures BTstack to output all Bluetooth
268packets and its own debug and error message using printf with BTstack's
269millisecond tiomestamps.s as tim.
270The Python
271script *tools/create_packet_log.py* can be used to convert the console
272output into a Bluetooth PacketLogger format that can be opened by the OS
273X PacketLogger tool as well as by Wireshark for further inspection. When
274asking for help, please always include a log created with HCI dump.
275
276The *hci_init* function sets up HCI to use the HCI H4 Transport
277implementation. It doesn’t provide a special transport configuration nor
278a special implementation for a particular Bluetooth chipset. It makes
279use of the *remote_device_db_memory* implementation that allows for
280re-connects without a new pairing but doesn’t persist the bonding
281information.
282
283Finally, it calls *btstack_main()* of the actual example before
284executing the run loop.
285
286
287## Source tree structure {#sec:sourceTreeHowTo}
288
289The source tree has been organized to easily setup new projects.
290
291Path                | Description
292--------------------|---------------
293chipset             | Support for individual Bluetooth Controller chipsets
294doc                 | Sources for BTstack documentation
295example             | Example applications available for all ports
296platform            | Support for special OSs and/or MCU architectures
297port                | Complete port for a MCU + Chipset combinations
298src                 | Bluetooth stack implementation
299test                | Unit and PTS tests
300tool                | Helper tools for BTstack
301
302The core of BTstack, including all protocol and profiles, is in *src/*.
303
304Support for a particular platform is provided by the *platform/* subfolder. For most embedded ports, *platform/embedded/* provides *btstack_run_loop_embedded* and the *hci_transport_h4_embedded* implementation that require *hal_cpu.h*, *hal_led.h*, and *hal_uart_dma.h* plus *hal_tick.h* or *hal_time_ms* to be implemented by the user.
305
306To accommodate a particular Bluetooth chipset, the *chipset/* subfolders provide various btstack_chipset_* implementations.
307Please have a look at the existing ports in *port/*.
308
309## Run loop configuration {#sec:runLoopHowTo}
310
311To initialize BTstack you need to [initialize the memory](#sec:memoryConfigurationHowTo)
312and [the run loop](#sec:runLoopHowTo) respectively, then setup HCI and all needed higher
313level protocols.
314
315BTstack uses the concept of a run loop to handle incoming data and to schedule work.
316The run loop handles events from two different types of sources: data
317sources and timers. Data sources represent communication interfaces like
318an UART or an USB driver. Timers are used by BTstack to implement
319various Bluetooth-related timeouts. They can also be used to handle
320periodic events. In addition, most implementations also allow to trigger a poll
321of the data sources from interrupt context, or, execute a function from a different
322thread.
323
324Data sources and timers are represented by the *btstack_data_source_t* and
325*btstack_timer_source_t* structs respectively. Each of these structs contain
326at least a linked list node and a pointer to a callback function. All active timers
327and data sources are kept in link lists. While the list of data sources
328is unsorted, the timers are sorted by expiration timeout for efficient
329processing. Data sources need to be configured upon what event they are called back.
330They can be configured to be polled (*DATA_SOURCE_CALLBACK_POLL*), on read ready (*DATA_SOURCE_CALLBACK_READ*),
331or on write ready (*DATA_SOURCE_CALLBACK_WRITE*).
332
333Timers are single shot: a timer will be removed from the timer list
334before its event handler callback is executed. If you need a periodic
335timer, you can re-register the same timer source in the callback
336function, as shown in Listing [PeriodicTimerHandler]. Note that BTstack
337expects to get called periodically to keep its time, see Section
338[on time abstraction](#sec:timeAbstractionPorting) for more on the
339tick hardware abstraction.
340
341BTstack provides different run loop implementations that implement the *btstack_run_loop_t* interface:
342
343- CoreFoundation: implementation for iOS and OS X applications
344- Embedded: the main implementation for embedded systems, especially without an RTOS.
345- FreeRTOS: implementation to run BTstack on a dedicated FreeRTOS thread
346- POSIX: implementation for POSIX systems based on the select() call.
347- Qt: implementation for the Qt applications
348- WICED: implementation for the Broadcom WICED SDK RTOS abstraction that wraps FreeRTOS or ThreadX.
349- Windows: implementation for Windows based on Event objects and WaitForMultipleObjects() call.
350
351Depending on the platform, data sources are either polled (embedded, FreeRTOS), or the platform provides a way
352to wait for a data source to become ready for read or write (CoreFoundation, POSIX, Qt, Windows), or,
353are not used as the HCI transport driver and the run loop is implemented in a different way (WICED).
354In any case, the callbacks must be explicitly enabled with the *btstack_run_loop_enable_data_source_callbacks(..)* function.
355
356In your code, you'll have to configure the run loop before you start it
357as shown in Listing [listing:btstackInit]. The application can register
358data sources as well as timers, e.g., for periodical sampling of sensors, or
359for communication over the UART.
360
361The run loop is set up by calling *btstack_run_loop_init* function and providing
362an instance of the actual run loop. E.g. for the embedded platform, it is:
363
364<!-- -->
365
366    btstack_run_loop_init(btstack_run_loop_embedded_get_instance());
367
368If the run loop allows to trigger polling of data sources from interrupt context,
369*btstack_run_loop_poll_data_sources_from_irq*.
370
371On multi-threaded environments, e.g., FreeRTOS, POSIX, WINDOWS,
372*btstack_run_loop_execute_code_on_main_thread* can be used to schedule a callback on the main loop.
373
374The complete Run loop API is provided [here](appendix/apis/#sec:runLoopAPIAppendix).
375
376
377### Run Loop Embedded
378
379In the embedded run loop implementation, data sources are constantly polled and
380the system is put to sleep if no IRQ happens during the poll of all data sources.
381
382The complete run loop cycle looks like this: first, the callback
383function of all registered data sources are called in a round robin way.
384Then, the callback functions of timers that are ready are executed.
385Finally, it will be checked if another run loop iteration has been
386requested by an interrupt handler. If not, the run loop will put the MCU
387into sleep mode.
388
389Incoming data over the UART, USB, or timer ticks will generate an
390interrupt and wake up the microcontroller. In order to avoid the
391situation where a data source becomes ready just before the run loop
392enters sleep mode, an interrupt-driven data source has to call the
393*btstack_run_loop_poll_data_sources_from_irq* function. The call to
394*btstack_run_loop_poll_data_sources_from_irq* sets an
395internal flag that is checked in the critical section just before
396entering sleep mode causing another run loop cycle.
397
398To enable the use of timers, make sure that you defined HAVE_EMBEDDED_TICK or HAVE_EMBEDDED_TIME_MS in the
399config file.
400
401While there is no threading, *btstack_run_loop_poll_data_sources_from_irq* allows to reduce stack size by
402scheduling a continuation.
403
404### Run Loop FreeRTOS
405
406The FreeRTOS run loop is used on a dedicated FreeRTOS thread and it uses a FreeRTOS queue to schedule callbacks on the run loop.
407In each iteration:
408
409- all data sources are polled
410- all scheduled callbacks are executed
411- all expired timers are called
412- finally, it gets the next timeout. It then waits for a 'trigger' or the next timeout, if set.
413
414It supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
415
416
417### Run Loop POSIX
418
419The data sources are standard File Descriptors. In the run loop execute implementation,
420select() call is used to wait for file descriptors to become ready to read or write,
421while waiting for the next timeout.
422
423To enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
424
425It supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
426
427
428### Run loop CoreFoundation (OS X/iOS)
429
430This run loop directly maps BTstack's data source and timer source with CoreFoundation objects.
431It supports ready to read and write similar to the POSIX implementation. The call to
432*btstack_run_loop_execute()* then just calls *CFRunLoopRun()*.
433
434To enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
435
436It currently only supports *btstack_run_loop_execute_code_on_main_thread*.
437
438
439### Run Lop Qt
440
441This run loop directly maps BTstack's data source and timer source with Qt Core objects.
442It supports ready to read and write similar to the POSIX implementation.
443
444To enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
445
446It supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
447
448
449### Run loop Windows
450
451The data sources are Event objects. In the run loop implementation WaitForMultipleObjects() call
452is all is used to wait for the Event object to become ready while waiting for the next timeout.
453
454It supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
455
456
457### Run loop WICED
458
459WICED SDK API does not provide asynchronous read and write to the UART and no direct way to wait for
460one or more peripherals to become ready. Therefore, BTstack does not provide direct support for data sources.
461Instead, the run loop provides a message queue that allows to schedule functions calls on its thread via
462*btstack_run_loop_wiced_execute_code_on_main_thread()*.
463
464The HCI transport H4 implementation then uses two lightweight threads to do the
465blocking read and write operations. When a read or write is complete on
466the helper threads, a callback to BTstack is scheduled.
467
468It currently only supports *btstack_run_loop_execute_code_on_main_thread*.
469
470
471## HCI Transport configuration
472
473The HCI initialization has to adapt BTstack to the used platform. The first
474call is to *hci_init()* and requires information about the HCI Transport to use.
475The arguments are:
476
477-   *HCI Transport implementation*: On embedded systems, a Bluetooth
478    module can be connected via USB or an UART port. On embedded, BTstack implements HCI UART Transport Layer (H4) and H4 with eHCILL support, a lightweight low-power variant by Texas Instruments. For POSIX, there is an implementation for HCI H4, HCI H5 and H2 libUSB, and for WICED HCI H4 WICED.
479    These are accessed by linking the appropriate file, e.g.,
480    [platform/embedded/hci_transport_h4_embedded.c]()
481    and then getting a pointer to HCI Transport implementation.
482    For more information on adapting HCI Transport to different
483    environments, see [here](porting/#sec:hciTransportPorting).
484
485<!-- -->
486
487    hci_transport_t * transport = hci_transport_h4_instance();
488
489-   *HCI Transport configuration*: As the configuration of the UART used
490    in the H4 transport interface are not standardized, it has to be
491    provided by the main application to BTstack. In addition to the
492    initial UART baud rate, the main baud rate can be specified. The HCI
493    layer of BTstack will change the init baud rate to the main one
494    after the basic setup of the Bluetooth module. A baud rate change
495    has to be done in a coordinated way at both HCI and hardware level.
496    For example, on the CC256x, the HCI command to change the baud rate
497    is sent first, then it is necessary to wait for the confirmation event
498    from the Bluetooth module. Only now, can the UART baud rate changed.
499
500<!-- -->
501
502    hci_uart_config_t* config = &hci_uart_config;
503
504After these are ready, HCI is initialized like this:
505
506    hci_init(transport, config);
507
508
509In addition to these, most UART-based Bluetooth chipset require some
510special logic for correct initialization that is not covered by the
511Bluetooth specification. In particular, this covers:
512
513- setting the baudrate
514- setting the BD ADDR for devices without an internal persistent storage
515- upload of some firmware patches.
516
517This is provided by the various *btstack_chipset_t* implementation in the *chipset/* subfolders.
518As an example, the *bstack_chipset_cc256x_instance* function returns a pointer to a chipset struct
519suitable for the CC256x chipset.
520
521<!-- -->
522
523    btstack_chipset_t * chipset = btstack_chipset_cc256x_instance();
524    hci_set_chipset(chipset);
525
526
527In some setups, the hardware setup provides explicit control of Bluetooth power and sleep modes.
528In this case, a *btstack_control_t* struct can be set with *hci_set_control*.
529
530Finally, the HCI implementation requires some form of persistent storage for link keys generated
531during either legacy pairing or the Secure Simple Pairing (SSP). This commonly requires platform
532specific code to access the MCU’s EEPROM of Flash storage. For the
533first steps, BTstack provides a (non) persistent store in memory.
534For more see [here](porting/#sec:persistentStoragePorting).
535
536<!-- -->
537
538    btstack_link_key_db_t * link_key_db = &btstack_link_key_db_memory_instance();
539    btstack_set_link_key_db(link_key_db);
540
541
542The higher layers only rely on BTstack and are initialized by calling
543the respective *\*_init* function. These init functions register
544themselves with the underlying layer. In addition, the application can
545register packet handlers to get events and data as explained in the
546following section.
547
548
549## Services {#sec:servicesHowTo}
550
551One important construct of BTstack is *service*. A service represents a
552server side component that handles incoming connections. So far, BTstack
553provides L2CAP, BNEP, and RFCOMM services. An L2CAP service handles incoming
554connections for an L2CAP channel and is registered with its protocol
555service multiplexer ID (PSM). Similarly, an RFCOMM service handles
556incoming RFCOMM connections and is registered with the RFCOMM channel
557ID. Outgoing connections require no special registration, they are
558created by the application when needed.
559
560
561## Packet handlers configuration {#sec:packetHandlersHowTo}
562
563
564After the hardware and BTstack are set up, the run loop is entered. From
565now on everything is event driven. The application calls BTstack
566functions, which in turn may send commands to the Bluetooth module. The
567resulting events are delivered back to the application. Instead of
568writing a single callback handler for each possible event (as it is done
569in some other Bluetooth stacks), BTstack groups events logically and
570provides them over a single generic interface. Appendix
571[Events and Errors](generated/appendix/#sec:eventsAndErrorsAppendix)
572summarizes the parameters and event
573codes of L2CAP and RFCOMM events, as well as possible errors and the
574corresponding error codes.
575
576Here is summarized list of packet handlers that an application might
577use:
578
579-   HCI event handler - allows to observer HCI, GAP, and general BTstack events.
580
581-   L2CAP packet handler - handles LE Connection parameter requeset updates
582
583-   L2CAP service packet handler - handles incoming L2CAP connections,
584    i.e., channels initiated by the remote.
585
586-   L2CAP channel packet handler - handles outgoing L2CAP connections,
587    i.e., channels initiated internally.
588
589-   RFCOMM service packet handler - handles incoming RFCOMM connections,
590    i.e., channels initiated by the remote.
591
592-   RFCOMM channel packet handler - handles outgoing RFCOMM connections,
593    i.e., channels initiated internally.
594
595These handlers are registered with the functions listed in Table
596{@tbl:registeringFunction}.
597
598
599Packet Handler                 | Registering Function
600-------------------------------|--------------------------------------
601HCI packet handler             | hci_add_event_handler
602L2CAP packet handler           | l2cap_register_packet_handler
603L2CAP service packet handler   | l2cap_register_service
604L2CAP channel packet handler   | l2cap_create_channel
605RFCOMM service packet handler  | rfcomm_register_service and rfcomm_register_service_with_initial_credits
606RFCOMM channel packet handler  | rfcomm_create_channel and rfcomm_create_channel_with_initial_credits
607
608
609Table: Functions for registering packet handlers. {#tbl:registeringFunction}
610
611HCI, GAP, and general BTstack events are delivered to the packet handler
612specified by *hci_add_event_handler* function. In L2CAP,
613BTstack discriminates incoming and outgoing connections, i.e., event and
614data packets are delivered to different packet handlers. Outgoing
615connections are used access remote services, incoming connections are
616used to provide services. For incoming connections, the packet handler
617specified by *l2cap_register_service* is used. For outgoing
618connections, the handler provided by *l2cap_create_channel*
619is used. RFCOMM and BNEP are similar.
620
621The application can register a single shared packet handler for all
622protocols and services, or use separate packet handlers for each
623protocol layer and service. A shared packet handler is often used for
624stack initialization and connection management.
625
626Separate packet handlers can be used for each L2CAP service and outgoing
627connection. For example, to connect with a Bluetooth HID keyboard, your
628application could use three packet handlers: one to handle HCI events
629during discovery of a keyboard registered by
630*l2cap_register_packet_handler*; one that will be registered to an
631outgoing L2CAP channel to connect to keyboard and to receive keyboard
632data registered by *l2cap_create_channel*; after that
633keyboard can reconnect by itself. For this, you need to register L2CAP
634services for the HID Control and HID Interrupt PSMs using
635*l2cap_register_service*. In this call, you’ll also specify
636a packet handler to accept and receive keyboard data.
637
638All events names have the form MODULE_EVENT_NAME now, e.g., *gap_event_-advertising_report*.
639To facilitate working with
640events and get rid of manually calculating offsets into packets, BTstack provides
641auto-generated getters for all fields of all events in *src/hci_event.h*. All
642functions are defined as static inline, so they are not wasting any program memory
643if not used. If used, the memory footprint should be identical to accessing the
644field directly via offsets into the packet. For example, to access fields address_type
645and address from the *gap_event_advertising_report* event use following getters:
646
647<!-- -->
648    uint8_t address type = gap_event_advertising_report_get_address_type(event);
649    bd_addr_t address;
650    gap_event_advertising_report_get_address(event, address);
651
652
653## Bluetooth HCI Packet Logs {#sec:packetlogsHowTo}
654
655If things don't work as expected, having a look at the data exchanged
656between BTstack and the Bluetooth chipset often helps.
657
658For this, BTstack provides a configurable packet logging mechanism via hci_dump.h and the following implementations:
659
660    void hci_dump_init(const hci_dump_t * hci_dump_implementation);
661
662Platform | File                         | Description
663---------|------------------------------|------------
664POSIX    | `hci_dump_posix_fs.c`        | HCI log file for Apple PacketLogger and Wireshark
665POSIX    | `hci_dump_posix_stdout.c`    | Console output via printf
666Embedded | `hci_dump_embedded_stdout.c` | Console output via printf
667Embedded | `hci_dump_segger_stdout.c`   | Console output via SEGGER RTT
668Embedded | `hci_dump_segger_binary.c`   | HCI log file for Apple PacketLogger via SEGGER RTT
669
670
671On POSIX systems, you can call *hci_dump_init* with a *hci_dump_posix_fs_get_instance()* and
672configure the path and output format with *hci_dump_posix_fs_open(const char * path, hci_dump_format_t format)*
673where format can be *HCI_DUMP_BLUEZ* or *HCI_DUMP_PACKETLOGGER*.
674The resulting file can be analyzed with Wireshark or the Apple's PacketLogger tool.
675
676On embedded systems without a file system, you either log to an UART console via printf or use SEGGER RTT.
677For printf output you pass *hci_dump_embedded_stdout_get_instance()* to *hci_dump_init()*.
678With RTT, you can choose between textual output similar to printf, and binary output.
679For textual output, you can provide the *hci_dump_segger_stdout_get_instance()*.
680
681It will log all HCI packets to the UART console via printf or RTT Terminal.
682If you capture the console output, incl. your own debug messages, you can use
683the create_packet_log.py tool in the tools folder to convert a text output into a
684PacketLogger file.
685
686For less overhead and higher logging speed, you can directly log in binary format by
687passing *hci_dump_segger_rtt_binary_get_instance()* and selecting the output format by
688calling *hci_dump_segger_rtt_binary_open(hci_dump_format_t format)* with the same format as above.
689
690
691In addition to the HCI packets, you can also enable BTstack's debug information by adding
692
693    #define ENABLE_LOG_INFO
694    #define ENABLE_LOG_ERROR
695
696to the btstack_config.h and recompiling your application.
697
698## Bluetooth Power Control {#sec:powerControl}
699
700In most BTstack examples, the device is set to be discoverable and connectable. In this mode, even when there's no active connection, the Bluetooth Controller will periodically activate its receiver in order to listen for inquiries or connecting requests from another device.
701The ability to be discoverable requires more energy than the ability to be connected. Being discoverable also announces the device to anybody in the area. Therefore, it is a good idea to pause listening for inquiries when not needed. Other devices that have your Bluetooth address can still connect to your device.
702
703To enable/disable discoverability, you can call:
704
705    /**
706     * @brief Allows to control if device is discoverable. OFF by default.
707     */
708    void gap_discoverable_control(uint8_t enable);
709
710If you don't need to become connected from other devices for a longer period of time, you can also disable the listening to connection requests.
711
712To enable/disable connectability, you can call:
713
714    /**
715     * @brief Override page scan mode. Page scan mode enabled by l2cap when services are registered
716     * @note Might be used to reduce power consumption while Bluetooth module stays powered but no (new)
717     *       connections are expected
718     */
719    void gap_connectable_control(uint8_t enable);
720
721For Bluetooth Low Energy, the radio is periodically used to broadcast advertisements that are used for both discovery and connection establishment.
722
723To enable/disable advertisements, you can call:
724
725    /**
726     * @brief Enable/Disable Advertisements. OFF by default.
727     * @param enabled
728     */
729    void gap_advertisements_enable(int enabled);
730
731If a Bluetooth Controller is neither discoverable nor connectable, it does not need to periodically turn on its radio and it only needs to respond to commands from the Host. In this case, the Bluetooth Controller is free to enter some kind of deep sleep where the power consumption is minimal.
732
733Finally, if that's not sufficient for your application, you could request BTstack to shutdown the Bluetooth Controller. For this, the "on" and "off" functions in the btstack_control_t struct must be implemented. To shutdown the Bluetooth Controller, you can call:
734
735    /**
736     * @brief Requests the change of BTstack power mode.
737     */
738    int  hci_power_control(HCI_POWER_MODE mode);
739
740with mode set to *HCI_POWER_OFF*. When needed later, Bluetooth can be started again via by calling it with mode *HCI_POWER_ON*, as seen in all examples.
741