xref: /btstack/doc/manual/docs-template/how_to.md (revision f48a558634ae46d89c8e106c8db59c770787ebe7)
1503a627eSMilanka Ringwald#
2503a627eSMilanka Ringwald
3503a627eSMilanka RingwaldBTstack 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.
4503a627eSMilanka Ringwald
5503a627eSMilanka RingwaldThe configuration of BTstack is done both at compile time as well as at run time:
6503a627eSMilanka Ringwald
7503a627eSMilanka Ringwald- compile time configuration:
8503a627eSMilanka Ringwald    - adjust *btstack_config.h* - this file describes the system configuration, used functionality, and also the memory configuration
9503a627eSMilanka Ringwald    - add necessary source code files to your project
10503a627eSMilanka Ringwald
11503a627eSMilanka Ringwald- run time configuration of:
12503a627eSMilanka Ringwald    - Bluetooth chipset
13503a627eSMilanka Ringwald    - run loop
14503a627eSMilanka Ringwald    - HCI transport layer
15503a627eSMilanka Ringwald    - provided services
16503a627eSMilanka Ringwald    - packet handlers
17503a627eSMilanka Ringwald
18503a627eSMilanka RingwaldIn the following, we provide an overview of the configuration
19503a627eSMilanka Ringwaldthat is necessary to setup BTstack. From the point when the run loop
20503a627eSMilanka Ringwaldis executed, the application runs as a finite
21503a627eSMilanka Ringwaldstate machine, which processes events received from BTstack. BTstack
22503a627eSMilanka Ringwaldgroups events logically and provides them via packet handlers.
23503a627eSMilanka RingwaldWe provide their overview here. For the case that there is a need to inspect the data exchanged
24503a627eSMilanka Ringwaldbetween BTstack and the Bluetooth chipset, we describe how to configure
25503a627eSMilanka Ringwaldpacket logging mechanism. Finally, we provide an overview on power management in Bluetooth in general and how to save energy in BTstack.
26503a627eSMilanka Ringwald
27503a627eSMilanka Ringwald## Configuration in btstack_config.h {#sec:btstackConfigHowTo}
28503a627eSMilanka RingwaldThe file *btstack_config.h* contains three parts:
29503a627eSMilanka Ringwald
30503a627eSMilanka Ringwald- \#define HAVE_* directives [listed here](#sec:haveDirectives). These directives describe available system properties, similar to config.h in a autoconf setup.
31503a627eSMilanka Ringwald- \#define ENABLE_* directives [listed here](#sec:enableDirectives). These directives list enabled properties, most importantly ENABLE_CLASSIC and ENABLE_BLE.
32503a627eSMilanka Ringwald- other #define directives for BTstack configuration, most notably static memory, [see next section](#sec:memoryConfigurationHowTo) and [NVM configuration](#sec:nvmConfiguration).
33503a627eSMilanka Ringwald
34503a627eSMilanka Ringwald<!-- a name "lst:platformConfiguration"></a-->
35503a627eSMilanka Ringwald<!-- -->
36503a627eSMilanka Ringwald
37503a627eSMilanka Ringwald### HAVE_* directives {#sec:haveDirectives}
38503a627eSMilanka RingwaldSystem properties:
39503a627eSMilanka Ringwald
404402df42SMatthias Ringwald| \#define              | Description                                                           |
414402df42SMatthias Ringwald|-----------------------|-----------------------------------------------------------------------|
42ff1cb106SMatthias Ringwald| HAVE_AES128           | Use platform AES128 engine                                            |
434402df42SMatthias Ringwald| HAVE_BTSTACK_STDIN    | STDIN is available for CLI interface                                  |
44ff1cb106SMatthias Ringwald| HAVE_LWIP             | lwIP is available                    |
45ff1cb106SMatthias Ringwald| HAVE_MALLOC           | Use dynamic memory                                                    |
464402df42SMatthias Ringwald| HAVE_MBEDTLS_ECC_P256 | mbedTLS provides NIST P-256 operations e.g. for LE Secure Connections |
47503a627eSMilanka Ringwald
48503a627eSMilanka RingwaldEmbedded platform properties:
49503a627eSMilanka Ringwald
504402df42SMatthias Ringwald| \#define                        | Description                          |
514402df42SMatthias Ringwald|---------------------------------|--------------------------------------|
524402df42SMatthias Ringwald| HAVE_EMBEDDED_TIME_MS           | System provides time in milliseconds |
534402df42SMatthias Ringwald| HAVE_EMBEDDED_TICK              | System provides tick interrupt       |
544402df42SMatthias Ringwald| HAVE_HAL_AUDIO                  | Audio HAL is available               |
554402df42SMatthias Ringwald| HAVE_HAL_AUDIO_SINK_STEREO_ONLY | Duplicate samples for mono playback  |
56503a627eSMilanka Ringwald
57503a627eSMilanka RingwaldFreeRTOS platform properties:
58503a627eSMilanka Ringwald
594402df42SMatthias Ringwald| \#define                     | Description                                                      |
604402df42SMatthias Ringwald|------------------------------|------------------------------------------------------------------|
614402df42SMatthias Ringwald| HAVE_FREERTOS_INCLUDE_PREFIX | FreeRTOS headers are in 'freertos' folder (e.g. ESP32's esp-idf) |
62503a627eSMilanka Ringwald
63503a627eSMilanka RingwaldPOSIX platform properties:
64503a627eSMilanka Ringwald
654402df42SMatthias Ringwald| \#define           | Description                          |
664402df42SMatthias Ringwald|--------------------|--------------------------------------|
674402df42SMatthias Ringwald| HAVE_POSIX_FILE_IO | POSIX File i/o used for hci dump     |
684402df42SMatthias Ringwald| HAVE_POSIX_TIME    | System provides time function        |
694402df42SMatthias Ringwald| LINK_KEY_PATH      | Path to stored link keys             |
704402df42SMatthias Ringwald| LE_DEVICE_DB_PATH  | Path to stored LE device information |
714402df42SMatthias Ringwald
72503a627eSMilanka Ringwald<!-- a name "lst:btstackFeatureConfiguration"></a-->
73503a627eSMilanka Ringwald<!-- -->
74503a627eSMilanka Ringwald
7508a78038SMatthias RingwaldChipset properties:
7608a78038SMatthias Ringwald
7708a78038SMatthias Ringwald| \#define               | Description                                           |
7808a78038SMatthias Ringwald|------------------------|-------------------------------------------------------|
79dd1f98b4SMatthias Ringwald| HAVE_BCM_PCM2          | PCM2 is used and requires additional configuration    |
8008a78038SMatthias Ringwald| HAVE_BCM_PCM_NBS_16KHZ | NBS is up/downsampled, use 16 kHz sample rate for NBS |
8108a78038SMatthias Ringwald
82503a627eSMilanka Ringwald### ENABLE_* directives {#sec:enableDirectives}
83503a627eSMilanka RingwaldBTstack properties:
84503a627eSMilanka Ringwald
854402df42SMatthias Ringwald| \#define                                                              | Description                                                                                                                 |
86*f48a5586SMatthias Ringwald|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
874402df42SMatthias Ringwald| ENABLE_CLASSIC                                                        | Enable Classic related code in HCI and L2CAP                                                                                |
884402df42SMatthias Ringwald| ENABLE_BLE                                                            | Enable BLE related code in HCI and L2CAP                                                                                    |
894402df42SMatthias Ringwald| ENABLE_EHCILL                                                         | Enable eHCILL low power mode on TI CC256x/WL18xx chipsets                                                                   |
904402df42SMatthias Ringwald| ENABLE_H5                                                             | Enable support for SLIP mode in `btstack_uart.h` drivers for HCI H5 ('Three-Wire Mode')                                     |
914402df42SMatthias Ringwald| ENABLE_LOG_DEBUG                                                      | Enable log_debug messages                                                                                                   |
924402df42SMatthias Ringwald| ENABLE_LOG_ERROR                                                      | Enable log_error messages                                                                                                   |
934402df42SMatthias Ringwald| ENABLE_LOG_INFO                                                       | Enable log_info messages                                                                                                    |
944402df42SMatthias Ringwald| ENABLE_SCO_OVER_HCI                                                   | Enable SCO over HCI for chipsets (if supported)                                                                             |
954402df42SMatthias Ringwald| ENABLE_SCO_OVER_PCM                                                   | Enable SCO ofer PCM/I2S for chipsets (if supported)                                                                         |
964402df42SMatthias Ringwald| ENABLE_HFP_WIDE_BAND_SPEECH                                           | Enable support for mSBC codec used in HFP profile for Wide-Band Speech                                                      |
974402df42SMatthias Ringwald| ENABLE_HFP_AT_MESSAGES                                                | Enable `HFP_SUBEVENT_AT_MESSAGE_SENT` and `HFP_SUBEVENT_AT_MESSAGE_RECEIVED` events                                         |
984402df42SMatthias Ringwald| ENABLE_LE_PERIPHERAL                                                  | Enable support for LE Peripheral Role in HCI and Security Manager                                                           |
99db3c1f89SMatthias Ringwald| ENABLE_LE_CENTRAL                                                     | Enable support for LE Central Role in HCI and Security Manager                                                              |
1004402df42SMatthias Ringwald| ENABLE_LE_SECURE_CONNECTIONS                                          | Enable LE Secure Connections                                                                                                |
101db88441fSMatthias Ringwald| ENABLE_LE_SECURE_CONNECTIONS_DEBUG_KEY                                | Enable support for LE Secure Connection debug keys for testing                                                              |
1024402df42SMatthias Ringwald| ENABLE_LE_PROACTIVE_AUTHENTICATION                                    | Enable automatic encryption for bonded devices on re-connect                                                                |
1034402df42SMatthias Ringwald| ENABLE_GATT_CLIENT_PAIRING                                            | Enable GATT Client to start pairing and retry operation on security error                                                   |
1044402df42SMatthias Ringwald| ENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS                            | Use [micro-ecc library](https://github.com/kmackay/micro-ecc) for ECC operations                                            |
1054402df42SMatthias Ringwald| ENABLE_LE_DATA_LENGTH_EXTENSION                                       | Enable LE Data Length Extension support                                                                                     |
1065d6688b0SMatthias Ringwald| ENABLE_LE_ENHANCED_CONNECTION_COMPLETE_EVENT                          | Enable LE Enhanced Connection Complete Event v1 & v2                                                                        |
1074402df42SMatthias Ringwald| ENABLE_LE_EXTENDED_ADVERTISING                                        | Enable extended advertising and scanning                                                                                    |
1084402df42SMatthias Ringwald| ENABLE_LE_PERIODIC_ADVERTISING                                        | Enable periodic advertising and scanning                                                                                    |
1094402df42SMatthias Ringwald| ENABLE_LE_SIGNED_WRITE                                                | Enable LE Signed Writes in ATT/GATT                                                                                         |
1104402df42SMatthias Ringwald| ENABLE_LE_PRIVACY_ADDRESS_RESOLUTION                                  | Enable address resolution for resolvable private addresses in Controller                                                    |
1114402df42SMatthias Ringwald| ENABLE_CROSS_TRANSPORT_KEY_DERIVATION                                 | Enable Cross-Transport Key Derivation (CTKD) for Secure Connections                                                         |
1124402df42SMatthias Ringwald| ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE                             | Enable Enhanced Retransmission Mode for L2CAP Channels. Mandatory for AVRCP Browsing                                        |
1134402df42SMatthias Ringwald| ENABLE_L2CAP_LE_CREDIT_BASED_FLOW_CONTROL_MODE                        | Enable LE credit-based flow-control mode for L2CAP channels                                                                 |
1144402df42SMatthias Ringwald| ENABLE_L2CAP_ENHANCED_CREDIT_BASED_FLOW_CONTROL_MODE                  | Enable Enhanced credit-based flow-control mode for L2CAP Channels                                                           |
1154402df42SMatthias Ringwald| ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL                            | Enable HCI Controller to Host Flow Control, see below                                                                       |
1164402df42SMatthias Ringwald| ENABLE_HCI_SERIALIZED_CONTROLLER_OPERATIONS                           | Serialize Inquiry, Remote Name Request, and Create Connection operations                                                    |
1177029d61cSMilanka Ringwald| ENABLE_ATT_DELAYED_RESPONSE                                           | Enable support for delayed ATT operations, see [GATT Server](profiles/#sec:GATTServerProfile)                               |
1184402df42SMatthias Ringwald| ENABLE_BCM_PCM_WBS                                                    | Enable support for Wide-Band Speech codec in BCM controller, requires ENABLE_SCO_OVER_PCM                                   |
1194402df42SMatthias Ringwald| ENABLE_CC256X_ASSISTED_HFP                                            | Enable support for Assisted HFP mode in CC256x Controller, requires ENABLE_SCO_OVER_PCM                                     |
1204402df42SMatthias Ringwald| Enable_RTK_PCM_WBS                                                    | Enable support for Wide-Band Speech codec in Realtek controller, requires ENABLE_SCO_OVER_PCM                               |
1214402df42SMatthias Ringwald| ENABLE_CC256X_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND              | Enable workaround for bug in CC256x Flow Control during baud rate change, see chipset docs.                                 |
1224402df42SMatthias Ringwald| ENABLE_CYPRESS_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND             | Enable workaround for bug in CYW2070x Flow Control during baud rate change, similar to CC256x.                              |
1234402df42SMatthias Ringwald| ENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS                            | Force HCI to fragment ACL-LE packets to fit into over-the-air packet                                                        |
124052e5e42SMatthias Ringwald| ENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD                                | Enable use of explicit delete field in TLV Flash implementation - required when flash value cannot be overwritten with zero |
125052e5e42SMatthias Ringwald| ENABLE_TLV_FLASH_WRITE_ONCE                                           | Enable storing of emtpy tag instead of overwriting existing tag - required when flash value cannot be overwritten at all    |
1264402df42SMatthias Ringwald| ENABLE_CONTROLLER_WARM_BOOT                                           | Enable stack startup without power cycle (if supported/possible)                                                            |
1274402df42SMatthias Ringwald| ENABLE_SEGGER_RTT                                                     | Use SEGGER RTT for console output and packet log, see [additional options](#sec:rttConfiguration)                           |
1284402df42SMatthias Ringwald| ENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL                              | Disable calls to control Connectable Mode by L2CAP                                                                          |
1294402df42SMatthias Ringwald| ENABLE_EXPLICIT_IO_CAPABILITIES_REPLY                                 | Let application trigger sending IO Capabilities (Negative) Reply                                                            |
1304402df42SMatthias Ringwald| ENABLE_EXPLICIT_LINK_KEY_REPLY                                        | Let application trigger sending Link Key (Negative) Response, allows for asynchronous link key lookup                       |
1314402df42SMatthias Ringwald| ENABLE_EXPLICIT_BR_EDR_SECURITY_MANAGER                               | Report BR/EDR Security Manager support in L2CAP Information Response                                                        |
132db3c1f89SMatthias Ringwald| ENABLE_EXPLICIT_DEDICATED_BONDING_DISCONNECT                          | Keep connection after dedicated bonding is complete                                                                         |
1334402df42SMatthias Ringwald| ENABLE_CLASSIC_OOB_PAIRING                                            | Enable support for classic Out-of-Band (OOB) pairing                                                                        |
1344402df42SMatthias Ringwald| ENABLE_A2DP_EXPLICIT_CONFIG                                           | Let application configure stream endpoint (skip auto-config of SBC endpoint)                                                |
1354402df42SMatthias Ringwald| ENABLE_AVDTP_ACCEPTOR_EXPLICIT_START_STREAM_CONFIRMATION              | allow accept or reject of stream start on A2DP_SUBEVENT_START_STREAM_REQUESTED                                              |
136ae35a99cSMatthias Ringwald| ENABLE_LE_WHITELIST_TOUCH_AFTER_RESOLVING_LIST_UPDATE                 | Enable Workaround for Controller bug                                                                                        |
137db3c1f89SMatthias Ringwald| ENABLE_LE_SET_ADV_PARAMS_ON_RANDOM_ADDRESS_CHANGE                     | Send HCI LE Set Advertising Params after HCI LE Set Random Address - workaround for Controller Bug                          |
1384402df42SMatthias Ringwald| ENABLE_CONTROLLER_DUMP_PACKETS                                        | Dump number of packets in Controller per type for debugging                                                                 |
139*f48a5586SMatthias Ringwald| ENABLE_HCI_COMMAND_STATUS_DISCARDED_FOR_FAILED_CONNECTIONS WORKAROUND | Track connection handle for HCI Commands and assume command has failed if disonnect event for connection is received |
140503a627eSMilanka Ringwald
141503a627eSMilanka RingwaldNotes:
142503a627eSMilanka Ringwald
143503a627eSMilanka Ringwald- 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.
144503a627eSMilanka Ringwald
145503a627eSMilanka Ringwald### HCI Controller to Host Flow Control
146503a627eSMilanka RingwaldIn 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.
147503a627eSMilanka Ringwald
148503a627eSMilanka RingwaldHost buffer configuration for HCI Controller to Host Flow Control:
149503a627eSMilanka Ringwald
1504402df42SMatthias Ringwald| \#define                | Description                      |
1514402df42SMatthias Ringwald|-------------------------|----------------------------------|
1524402df42SMatthias Ringwald| HCI_HOST_ACL_PACKET_NUM | Max number of ACL packets        |
1534402df42SMatthias Ringwald| HCI_HOST_ACL_PACKET_LEN | Max size of HCI Host ACL packets |
1544402df42SMatthias Ringwald| HCI_HOST_SCO_PACKET_NUM | Max number of ACL packets        |
1554402df42SMatthias Ringwald| HCI_HOST_SCO_PACKET_LEN | Max size of HCI Host SCO packets |
156503a627eSMilanka Ringwald
157503a627eSMilanka Ringwald### Memory configuration directives {#sec:memoryConfigurationHowTo}
158503a627eSMilanka Ringwald
159503a627eSMilanka RingwaldThe structs for services, active connections and remote devices can be
160503a627eSMilanka Ringwaldallocated in two different manners:
161503a627eSMilanka Ringwald
162503a627eSMilanka Ringwald-   statically from an individual memory pool, whose maximal number of
163503a627eSMilanka Ringwald    elements is defined in the btstack_config.h file. To initialize the static
164503a627eSMilanka Ringwald    pools, you need to call at runtime *btstack_memory_init* function. An example
165503a627eSMilanka Ringwald    of memory configuration for a single SPP service with a minimal
166503a627eSMilanka Ringwald    L2CAP MTU is shown in Listing {@lst:memoryConfigurationSPP}.
167503a627eSMilanka Ringwald
168503a627eSMilanka Ringwald-   dynamically using the *malloc/free* functions, if HAVE_MALLOC is
169503a627eSMilanka Ringwald    defined in btstack_config.h file.
170503a627eSMilanka Ringwald
1718b6f0b06SMatthias RingwaldFor 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 recommended. The large ACL buffer is required for 3-DH5 packets to be used.
172503a627eSMilanka Ringwald
173503a627eSMilanka Ringwald<!-- a name "lst:memoryConfiguration"></a-->
174503a627eSMilanka Ringwald<!-- -->
175503a627eSMilanka Ringwald
1764402df42SMatthias Ringwald| \#define                                  | Description                                                                |
1774402df42SMatthias Ringwald|-------------------------------------------|----------------------------------------------------------------------------|
1784402df42SMatthias Ringwald| HCI_ACL_PAYLOAD_SIZE                      | Max size of HCI ACL payloads                                               |
1796bcf18c2SMatthias Ringwald| HCI_ACL_CHUNK_SIZE_ALIGNMENT              | Alignment of ACL chunk size, can be used to align HCI transport writes     |
1804402df42SMatthias Ringwald| HCI_INCOMING_PRE_BUFFER_SIZE              | Number of bytes reserved before actual data for incoming HCI packets       |
1814402df42SMatthias Ringwald| MAX_NR_BNEP_CHANNELS                      | Max number of BNEP channels                                                |
1824402df42SMatthias Ringwald| MAX_NR_BNEP_SERVICES                      | Max number of BNEP services                                                |
1834402df42SMatthias Ringwald| MAX_NR_GATT_CLIENTS                       | Max number of GATT clients                                                 |
1844402df42SMatthias Ringwald| MAX_NR_HCI_CONNECTIONS                    | Max number of HCI connections                                              |
1854402df42SMatthias Ringwald| MAX_NR_HFP_CONNECTIONS                    | Max number of HFP connections                                              |
1864402df42SMatthias Ringwald| MAX_NR_L2CAP_CHANNELS                     | Max number of L2CAP connections                                            |
1874402df42SMatthias Ringwald| MAX_NR_L2CAP_SERVICES                     | Max number of L2CAP services                                               |
1884402df42SMatthias Ringwald| MAX_NR_RFCOMM_CHANNELS                    | Max number of RFOMMM connections                                           |
1894402df42SMatthias Ringwald| MAX_NR_RFCOMM_MULTIPLEXERS                | Max number of RFCOMM multiplexers, with one multiplexer per HCI connection |
1904402df42SMatthias Ringwald| MAX_NR_RFCOMM_SERVICES                    | Max number of RFCOMM services                                              |
1914402df42SMatthias Ringwald| MAX_NR_SERVICE_RECORD_ITEMS               | Max number of SDP service records                                          |
1924402df42SMatthias Ringwald| MAX_NR_SM_LOOKUP_ENTRIES                  | Max number of items in Security Manager lookup queue                       |
1934402df42SMatthias Ringwald| MAX_NR_WHITELIST_ENTRIES                  | Max number of items in GAP LE Whitelist to connect to                      |
194503a627eSMilanka Ringwald
195503a627eSMilanka RingwaldThe memory is set up by calling *btstack_memory_init* function:
196503a627eSMilanka Ringwald
197503a627eSMilanka Ringwald    btstack_memory_init();
198503a627eSMilanka Ringwald
199503a627eSMilanka Ringwald<!-- a name "lst:memoryConfigurationSPP"></a-->
200503a627eSMilanka Ringwald<!-- -->
201503a627eSMilanka Ringwald
202503a627eSMilanka RingwaldHere's the memory configuration for a basic SPP server.
203503a627eSMilanka Ringwald
204503a627eSMilanka Ringwald    #define HCI_ACL_PAYLOAD_SIZE 52
205503a627eSMilanka Ringwald    #define MAX_NR_HCI_CONNECTIONS 1
206503a627eSMilanka Ringwald    #define MAX_NR_L2CAP_SERVICES  2
207503a627eSMilanka Ringwald    #define MAX_NR_L2CAP_CHANNELS  2
208503a627eSMilanka Ringwald    #define MAX_NR_RFCOMM_MULTIPLEXERS 1
209503a627eSMilanka Ringwald    #define MAX_NR_RFCOMM_SERVICES 1
210503a627eSMilanka Ringwald    #define MAX_NR_RFCOMM_CHANNELS 1
2118b6f0b06SMatthias Ringwald    #define NVM_NUM_LINK_KEYS  3
212503a627eSMilanka Ringwald
213503a627eSMilanka RingwaldListing: Memory configuration for a basic SPP server. {#lst:memoryConfigurationSPP}
214503a627eSMilanka Ringwald
2158b6f0b06SMatthias RingwaldIn 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 stored in persistent memory.
216503a627eSMilanka Ringwald
217503a627eSMilanka Ringwald<!-- -->
218503a627eSMilanka Ringwald
219503a627eSMilanka Ringwald### Non-volatile memory (NVM) directives {#sec:nvmConfiguration}
220503a627eSMilanka Ringwald
221503a627eSMilanka RingwaldIf 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:
222503a627eSMilanka Ringwald
223503a627eSMilanka Ringwald<!-- a name "lst:nvmDefines"></a-->
224503a627eSMilanka Ringwald<!-- -->
225503a627eSMilanka Ringwald
2264402df42SMatthias Ringwald| \#define                  | Description                                                                                  |
2274402df42SMatthias Ringwald|---------------------------|----------------------------------------------------------------------------------------------|
2284402df42SMatthias Ringwald| NVM_NUM_LINK_KEYS         | Max number of Classic Link Keys that can be stored                                           |
2294402df42SMatthias Ringwald| NVM_NUM_DEVICE_DB_ENTRIES | Max number of LE Device DB entries that can be stored                                        |
2304402df42SMatthias Ringwald| NVN_NUM_GATT_SERVER_CCC   | Max number of 'Client Characteristic Configuration' values that can be stored by GATT Server |
231503a627eSMilanka Ringwald
2321b5f4ae3SMatthias Ringwald### HCI Dump Stdout directives {#sec:hciDumpStdout}
2331b5f4ae3SMatthias Ringwald
2341b5f4ae3SMatthias RingwaldAllow to truncate HCI ACL and SCO packets to reduce console output for debugging audio applications.
2351b5f4ae3SMatthias Ringwald
2361b5f4ae3SMatthias Ringwald| \#define                     | Description                               |
2371b5f4ae3SMatthias Ringwald|------------------------------|-------------------------------------------|
2381b5f4ae3SMatthias Ringwald| HCI_DUMP_STDOUT_MAX_SIZE_ACL | Max size of ACL packets to log via stdout |
2391b5f4ae3SMatthias Ringwald| HCI_DUMP_STDOUT_MAX_SIZE_SCO | Max size of SCO packets to log via stdout |
2401b5f4ae3SMatthias Ringwald| HCI_DUMP_STDOUT_MAX_SIZE_ISO | Max size of ISO packets to log via stdout |
241503a627eSMilanka Ringwald
242503a627eSMilanka Ringwald### SEGGER Real Time Transfer (RTT) directives {#sec:rttConfiguration}
243503a627eSMilanka Ringwald
244503a627eSMilanka Ringwald[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.
245503a627eSMilanka Ringwald
246503a627eSMilanka RingwaldWhen 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:
247503a627eSMilanka Ringwald
2484402df42SMatthias Ringwald| \#define                         | Default                       | Description                                                                                                       |
2494402df42SMatthias Ringwald|----------------------------------|-------------------------------|-------------------------------------------------------------------------------------------------------------------|
2504402df42SMatthias Ringwald| SEGGER_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 |
2514402df42SMatthias Ringwald| SEGGER_RTT_PACKETLOG_CHANNEL     | 1                             | Channel to use for packet log. Channel 0 is used for terminal                                                     |
2524402df42SMatthias Ringwald| SEGGER_RTT_PACKETLOG_BUFFER_SIZE | 1024                          | Size of outgoing ring buffer. Increase if you cannot block but get 'message skipped' warnings.                    |
253503a627eSMilanka Ringwald
254503a627eSMilanka Ringwald## Run-time configuration
255503a627eSMilanka Ringwald
256503a627eSMilanka RingwaldTo allow code-reuse with different platforms
257503a627eSMilanka Ringwaldas well as with new ports, the low-level initialization of BTstack and
258503a627eSMilanka Ringwaldthe hardware configuration has been extracted to the various
259503a627eSMilanka Ringwald*platforms/PLATFORM/main.c* files. The examples only contain the
260503a627eSMilanka Ringwaldplatform-independent Bluetooth logic. But let’s have a look at the
261503a627eSMilanka Ringwaldcommon init code.
262503a627eSMilanka Ringwald
263503a627eSMilanka RingwaldListing [below](#lst:btstackInit) shows a minimal platform setup for an
264503a627eSMilanka Ringwaldembedded system with a Bluetooth chipset connected via UART.
265503a627eSMilanka Ringwald
266503a627eSMilanka Ringwald~~~~ {#lst:btstackInit .c caption="{Minimal platform setup for an embedded system}"}
267503a627eSMilanka Ringwald
268503a627eSMilanka Ringwald    int main(){
269503a627eSMilanka Ringwald      // ... hardware init: watchdoch, IOs, timers, etc...
270503a627eSMilanka Ringwald
271503a627eSMilanka Ringwald      // setup BTstack memory pools
272503a627eSMilanka Ringwald      btstack_memory_init();
273503a627eSMilanka Ringwald
274503a627eSMilanka Ringwald      // select embedded run loop
275503a627eSMilanka Ringwald      btstack_run_loop_init(btstack_run_loop_embedded_get_instance());
276503a627eSMilanka Ringwald
277503a627eSMilanka Ringwald      // enable logging
278503a627eSMilanka Ringwald      hci_dump_init(hci_dump_embedded_stdout_get_instance());
279503a627eSMilanka Ringwald
280503a627eSMilanka Ringwald
281503a627eSMilanka Ringwald      // init HCI
282503a627eSMilanka Ringwald      hci_transport_t     * transport = hci_transport_h4_instance();
283503a627eSMilanka Ringwald      hci_init(transport, NULL);
284503a627eSMilanka Ringwald
285503a627eSMilanka Ringwald      // setup example
286503a627eSMilanka Ringwald      btstack_main(argc, argv);
287503a627eSMilanka Ringwald
288503a627eSMilanka Ringwald      // go
289503a627eSMilanka Ringwald      btstack_run_loop_execute();
290503a627eSMilanka Ringwald    }
291503a627eSMilanka Ringwald
292503a627eSMilanka Ringwald~~~~
293503a627eSMilanka Ringwald
2940c599961SMatthias RingwaldFirst, BTstack’s memory pools are set up. Then, the standard run loop
295503a627eSMilanka Ringwaldimplementation for embedded systems is selected.
296503a627eSMilanka Ringwald
297503a627eSMilanka RingwaldThe call to *hci_dump_init* configures BTstack to output all Bluetooth
298503a627eSMilanka Ringwaldpackets and its own debug and error message using printf with BTstack's
299503a627eSMilanka Ringwaldmillisecond tiomestamps.s as tim.
300503a627eSMilanka RingwaldThe Python
301503a627eSMilanka Ringwaldscript *tools/create_packet_log.py* can be used to convert the console
302503a627eSMilanka Ringwaldoutput into a Bluetooth PacketLogger format that can be opened by the OS
303503a627eSMilanka RingwaldX PacketLogger tool as well as by Wireshark for further inspection. When
304503a627eSMilanka Ringwaldasking for help, please always include a log created with HCI dump.
305503a627eSMilanka Ringwald
306503a627eSMilanka RingwaldThe *hci_init* function sets up HCI to use the HCI H4 Transport
307503a627eSMilanka Ringwaldimplementation. It doesn’t provide a special transport configuration nor
308503a627eSMilanka Ringwalda special implementation for a particular Bluetooth chipset. It makes
309503a627eSMilanka Ringwalduse of the *remote_device_db_memory* implementation that allows for
310503a627eSMilanka Ringwaldre-connects without a new pairing but doesn’t persist the bonding
311503a627eSMilanka Ringwaldinformation.
312503a627eSMilanka Ringwald
313503a627eSMilanka RingwaldFinally, it calls *btstack_main()* of the actual example before
314503a627eSMilanka Ringwaldexecuting the run loop.
315503a627eSMilanka Ringwald
316503a627eSMilanka Ringwald
317503a627eSMilanka Ringwald## Source tree structure {#sec:sourceTreeHowTo}
318503a627eSMilanka Ringwald
319503a627eSMilanka RingwaldThe source tree has been organized to easily setup new projects.
320503a627eSMilanka Ringwald
3214402df42SMatthias Ringwald| Path     | Description                                          |
3224402df42SMatthias Ringwald|----------|------------------------------------------------------|
3234402df42SMatthias Ringwald| chipset  | Support for individual Bluetooth Controller chipsets |
3244402df42SMatthias Ringwald| doc      | Sources for BTstack documentation                    |
3254402df42SMatthias Ringwald| example  | Example applications available for all ports         |
3264402df42SMatthias Ringwald| platform | Support for special OSs and/or MCU architectures     |
3274402df42SMatthias Ringwald| port     | Complete port for a MCU + Chipset combinations       |
3284402df42SMatthias Ringwald| src      | Bluetooth stack implementation                       |
3294402df42SMatthias Ringwald| test     | Unit and PTS tests                                   |
3304402df42SMatthias Ringwald| tool     | Helper tools for BTstack                             |
331503a627eSMilanka Ringwald
332503a627eSMilanka RingwaldThe core of BTstack, including all protocol and profiles, is in *src/*.
333503a627eSMilanka Ringwald
334503a627eSMilanka RingwaldSupport 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.
335503a627eSMilanka Ringwald
336503a627eSMilanka RingwaldTo accommodate a particular Bluetooth chipset, the *chipset/* subfolders provide various btstack_chipset_* implementations.
337503a627eSMilanka RingwaldPlease have a look at the existing ports in *port/*.
338503a627eSMilanka Ringwald
339503a627eSMilanka Ringwald## Run loop configuration {#sec:runLoopHowTo}
340503a627eSMilanka Ringwald
341503a627eSMilanka RingwaldTo initialize BTstack you need to [initialize the memory](#sec:memoryConfigurationHowTo)
342503a627eSMilanka Ringwaldand [the run loop](#sec:runLoopHowTo) respectively, then setup HCI and all needed higher
343503a627eSMilanka Ringwaldlevel protocols.
344503a627eSMilanka Ringwald
345503a627eSMilanka RingwaldBTstack uses the concept of a run loop to handle incoming data and to schedule work.
346503a627eSMilanka RingwaldThe run loop handles events from two different types of sources: data
347503a627eSMilanka Ringwaldsources and timers. Data sources represent communication interfaces like
348503a627eSMilanka Ringwaldan UART or an USB driver. Timers are used by BTstack to implement
349503a627eSMilanka Ringwaldvarious Bluetooth-related timeouts. They can also be used to handle
3500c599961SMatthias Ringwaldperiodic events. In addition, most implementations also allow to trigger a poll
3510c599961SMatthias Ringwaldof the data sources from interrupt context, or, execute a function from a different
3520c599961SMatthias Ringwaldthread.
353503a627eSMilanka Ringwald
354503a627eSMilanka RingwaldData sources and timers are represented by the *btstack_data_source_t* and
355503a627eSMilanka Ringwald*btstack_timer_source_t* structs respectively. Each of these structs contain
356503a627eSMilanka Ringwaldat least a linked list node and a pointer to a callback function. All active timers
357503a627eSMilanka Ringwaldand data sources are kept in link lists. While the list of data sources
358503a627eSMilanka Ringwaldis unsorted, the timers are sorted by expiration timeout for efficient
3590c599961SMatthias Ringwaldprocessing. Data sources need to be configured upon what event they are called back.
3600c599961SMatthias RingwaldThey can be configured to be polled (*DATA_SOURCE_CALLBACK_POLL*), on read ready (*DATA_SOURCE_CALLBACK_READ*),
3610c599961SMatthias Ringwaldor on write ready (*DATA_SOURCE_CALLBACK_WRITE*).
362503a627eSMilanka Ringwald
363503a627eSMilanka RingwaldTimers are single shot: a timer will be removed from the timer list
364503a627eSMilanka Ringwaldbefore its event handler callback is executed. If you need a periodic
365503a627eSMilanka Ringwaldtimer, you can re-register the same timer source in the callback
366503a627eSMilanka Ringwaldfunction, as shown in Listing [PeriodicTimerHandler]. Note that BTstack
367503a627eSMilanka Ringwaldexpects to get called periodically to keep its time, see Section
368503a627eSMilanka Ringwald[on time abstraction](#sec:timeAbstractionPorting) for more on the
369503a627eSMilanka Ringwaldtick hardware abstraction.
370503a627eSMilanka Ringwald
371503a627eSMilanka RingwaldBTstack provides different run loop implementations that implement the *btstack_run_loop_t* interface:
372503a627eSMilanka Ringwald
3730c599961SMatthias Ringwald- CoreFoundation: implementation for iOS and OS X applications
374503a627eSMilanka Ringwald- Embedded: the main implementation for embedded systems, especially without an RTOS.
375503a627eSMilanka Ringwald- FreeRTOS: implementation to run BTstack on a dedicated FreeRTOS thread
376503a627eSMilanka Ringwald- POSIX: implementation for POSIX systems based on the select() call.
3770c599961SMatthias Ringwald- Qt: implementation for the Qt applications
378503a627eSMilanka Ringwald- WICED: implementation for the Broadcom WICED SDK RTOS abstraction that wraps FreeRTOS or ThreadX.
379503a627eSMilanka Ringwald- Windows: implementation for Windows based on Event objects and WaitForMultipleObjects() call.
380503a627eSMilanka Ringwald
381503a627eSMilanka RingwaldDepending on the platform, data sources are either polled (embedded, FreeRTOS), or the platform provides a way
3820c599961SMatthias Ringwaldto wait for a data source to become ready for read or write (CoreFoundation, POSIX, Qt, Windows), or,
383503a627eSMilanka Ringwaldare not used as the HCI transport driver and the run loop is implemented in a different way (WICED).
3840c599961SMatthias RingwaldIn any case, the callbacks must be explicitly enabled with the *btstack_run_loop_enable_data_source_callbacks(..)* function.
385503a627eSMilanka Ringwald
386503a627eSMilanka RingwaldIn your code, you'll have to configure the run loop before you start it
387503a627eSMilanka Ringwaldas shown in Listing [listing:btstackInit]. The application can register
388503a627eSMilanka Ringwalddata sources as well as timers, e.g., for periodical sampling of sensors, or
389503a627eSMilanka Ringwaldfor communication over the UART.
390503a627eSMilanka Ringwald
391503a627eSMilanka RingwaldThe run loop is set up by calling *btstack_run_loop_init* function and providing
392503a627eSMilanka Ringwaldan instance of the actual run loop. E.g. for the embedded platform, it is:
393503a627eSMilanka Ringwald
394503a627eSMilanka Ringwald<!-- -->
395503a627eSMilanka Ringwald
396503a627eSMilanka Ringwald    btstack_run_loop_init(btstack_run_loop_embedded_get_instance());
397503a627eSMilanka Ringwald
3980c599961SMatthias RingwaldIf the run loop allows to trigger polling of data sources from interrupt context,
3990c599961SMatthias Ringwald*btstack_run_loop_poll_data_sources_from_irq*.
4000c599961SMatthias Ringwald
4010c599961SMatthias RingwaldOn multi-threaded environments, e.g., FreeRTOS, POSIX, WINDOWS,
4020c599961SMatthias Ringwald*btstack_run_loop_execute_code_on_main_thread* can be used to schedule a callback on the main loop.
4030c599961SMatthias Ringwald
404503a627eSMilanka RingwaldThe complete Run loop API is provided [here](appendix/apis/#sec:runLoopAPIAppendix).
405503a627eSMilanka Ringwald
4060c599961SMatthias Ringwald
4070c599961SMatthias Ringwald### Run Loop Embedded
408503a627eSMilanka Ringwald
409503a627eSMilanka RingwaldIn the embedded run loop implementation, data sources are constantly polled and
410503a627eSMilanka Ringwaldthe system is put to sleep if no IRQ happens during the poll of all data sources.
411503a627eSMilanka Ringwald
412503a627eSMilanka RingwaldThe complete run loop cycle looks like this: first, the callback
413503a627eSMilanka Ringwaldfunction of all registered data sources are called in a round robin way.
414503a627eSMilanka RingwaldThen, the callback functions of timers that are ready are executed.
415503a627eSMilanka RingwaldFinally, it will be checked if another run loop iteration has been
416503a627eSMilanka Ringwaldrequested by an interrupt handler. If not, the run loop will put the MCU
417503a627eSMilanka Ringwaldinto sleep mode.
418503a627eSMilanka Ringwald
419503a627eSMilanka RingwaldIncoming data over the UART, USB, or timer ticks will generate an
420503a627eSMilanka Ringwaldinterrupt and wake up the microcontroller. In order to avoid the
421503a627eSMilanka Ringwaldsituation where a data source becomes ready just before the run loop
422503a627eSMilanka Ringwaldenters sleep mode, an interrupt-driven data source has to call the
4230c599961SMatthias Ringwald*btstack_run_loop_poll_data_sources_from_irq* function. The call to
4240c599961SMatthias Ringwald*btstack_run_loop_poll_data_sources_from_irq* sets an
425503a627eSMilanka Ringwaldinternal flag that is checked in the critical section just before
426503a627eSMilanka Ringwaldentering sleep mode causing another run loop cycle.
427503a627eSMilanka Ringwald
428503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_EMBEDDED_TICK or HAVE_EMBEDDED_TIME_MS in the
429503a627eSMilanka Ringwaldconfig file.
430503a627eSMilanka Ringwald
4310c599961SMatthias RingwaldWhile there is no threading, *btstack_run_loop_poll_data_sources_from_irq* allows to reduce stack size by
4320c599961SMatthias Ringwaldscheduling a continuation.
4330c599961SMatthias Ringwald
4340c599961SMatthias Ringwald### Run Loop FreeRTOS
435503a627eSMilanka Ringwald
436503a627eSMilanka RingwaldThe FreeRTOS run loop is used on a dedicated FreeRTOS thread and it uses a FreeRTOS queue to schedule callbacks on the run loop.
437503a627eSMilanka RingwaldIn each iteration:
438503a627eSMilanka Ringwald
439503a627eSMilanka Ringwald- all data sources are polled
440503a627eSMilanka Ringwald- all scheduled callbacks are executed
441503a627eSMilanka Ringwald- all expired timers are called
442503a627eSMilanka Ringwald- finally, it gets the next timeout. It then waits for a 'trigger' or the next timeout, if set.
443503a627eSMilanka Ringwald
4440c599961SMatthias RingwaldIt supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
445503a627eSMilanka Ringwald
446503a627eSMilanka Ringwald
4470c599961SMatthias Ringwald### Run Loop POSIX
448503a627eSMilanka Ringwald
449503a627eSMilanka RingwaldThe data sources are standard File Descriptors. In the run loop execute implementation,
450503a627eSMilanka Ringwaldselect() call is used to wait for file descriptors to become ready to read or write,
451503a627eSMilanka Ringwaldwhile waiting for the next timeout.
452503a627eSMilanka Ringwald
453503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
454503a627eSMilanka Ringwald
4550c599961SMatthias RingwaldIt supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
4560c599961SMatthias Ringwald
4570c599961SMatthias Ringwald
458503a627eSMilanka Ringwald### Run loop CoreFoundation (OS X/iOS)
459503a627eSMilanka Ringwald
460503a627eSMilanka RingwaldThis run loop directly maps BTstack's data source and timer source with CoreFoundation objects.
461503a627eSMilanka RingwaldIt supports ready to read and write similar to the POSIX implementation. The call to
462503a627eSMilanka Ringwald*btstack_run_loop_execute()* then just calls *CFRunLoopRun()*.
463503a627eSMilanka Ringwald
464503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
465503a627eSMilanka Ringwald
4660c599961SMatthias RingwaldIt currently only supports *btstack_run_loop_execute_code_on_main_thread*.
4670c599961SMatthias Ringwald
4680c599961SMatthias Ringwald
4690c599961SMatthias Ringwald### Run Lop Qt
4700c599961SMatthias Ringwald
4710c599961SMatthias RingwaldThis run loop directly maps BTstack's data source and timer source with Qt Core objects.
4720c599961SMatthias RingwaldIt supports ready to read and write similar to the POSIX implementation.
4730c599961SMatthias Ringwald
4740c599961SMatthias RingwaldTo enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file.
4750c599961SMatthias Ringwald
4760c599961SMatthias RingwaldIt supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
4770c599961SMatthias Ringwald
4780c599961SMatthias Ringwald
479503a627eSMilanka Ringwald### Run loop Windows
480503a627eSMilanka Ringwald
481503a627eSMilanka RingwaldThe data sources are Event objects. In the run loop implementation WaitForMultipleObjects() call
482503a627eSMilanka Ringwaldis all is used to wait for the Event object to become ready while waiting for the next timeout.
483503a627eSMilanka Ringwald
4840c599961SMatthias RingwaldIt supports both *btstack_run_loop_poll_data_sources_from_irq* as well as *btstack_run_loop_execute_code_on_main_thread*.
4850c599961SMatthias Ringwald
486503a627eSMilanka Ringwald
487503a627eSMilanka Ringwald### Run loop WICED
488503a627eSMilanka Ringwald
489503a627eSMilanka RingwaldWICED SDK API does not provide asynchronous read and write to the UART and no direct way to wait for
490503a627eSMilanka Ringwaldone or more peripherals to become ready. Therefore, BTstack does not provide direct support for data sources.
491503a627eSMilanka RingwaldInstead, the run loop provides a message queue that allows to schedule functions calls on its thread via
492503a627eSMilanka Ringwald*btstack_run_loop_wiced_execute_code_on_main_thread()*.
493503a627eSMilanka Ringwald
494503a627eSMilanka RingwaldThe HCI transport H4 implementation then uses two lightweight threads to do the
495503a627eSMilanka Ringwaldblocking read and write operations. When a read or write is complete on
496503a627eSMilanka Ringwaldthe helper threads, a callback to BTstack is scheduled.
497503a627eSMilanka Ringwald
4980c599961SMatthias RingwaldIt currently only supports *btstack_run_loop_execute_code_on_main_thread*.
4990c599961SMatthias Ringwald
500503a627eSMilanka Ringwald
501503a627eSMilanka Ringwald## HCI Transport configuration
502503a627eSMilanka Ringwald
503503a627eSMilanka RingwaldThe HCI initialization has to adapt BTstack to the used platform. The first
504503a627eSMilanka Ringwaldcall is to *hci_init()* and requires information about the HCI Transport to use.
505503a627eSMilanka RingwaldThe arguments are:
506503a627eSMilanka Ringwald
507503a627eSMilanka Ringwald-   *HCI Transport implementation*: On embedded systems, a Bluetooth
508503a627eSMilanka Ringwald    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.
509503a627eSMilanka Ringwald    These are accessed by linking the appropriate file, e.g.,
510503a627eSMilanka Ringwald    [platform/embedded/hci_transport_h4_embedded.c]()
511503a627eSMilanka Ringwald    and then getting a pointer to HCI Transport implementation.
512503a627eSMilanka Ringwald    For more information on adapting HCI Transport to different
5137029d61cSMilanka Ringwald    environments, see [here](porting/#sec:hciTransportPorting).
514503a627eSMilanka Ringwald
515503a627eSMilanka Ringwald<!-- -->
516503a627eSMilanka Ringwald
517503a627eSMilanka Ringwald    hci_transport_t * transport = hci_transport_h4_instance();
518503a627eSMilanka Ringwald
519503a627eSMilanka Ringwald-   *HCI Transport configuration*: As the configuration of the UART used
520503a627eSMilanka Ringwald    in the H4 transport interface are not standardized, it has to be
521503a627eSMilanka Ringwald    provided by the main application to BTstack. In addition to the
522503a627eSMilanka Ringwald    initial UART baud rate, the main baud rate can be specified. The HCI
523503a627eSMilanka Ringwald    layer of BTstack will change the init baud rate to the main one
524503a627eSMilanka Ringwald    after the basic setup of the Bluetooth module. A baud rate change
525503a627eSMilanka Ringwald    has to be done in a coordinated way at both HCI and hardware level.
526503a627eSMilanka Ringwald    For example, on the CC256x, the HCI command to change the baud rate
527503a627eSMilanka Ringwald    is sent first, then it is necessary to wait for the confirmation event
528503a627eSMilanka Ringwald    from the Bluetooth module. Only now, can the UART baud rate changed.
529503a627eSMilanka Ringwald
530503a627eSMilanka Ringwald<!-- -->
531503a627eSMilanka Ringwald
532503a627eSMilanka Ringwald    hci_uart_config_t* config = &hci_uart_config;
533503a627eSMilanka Ringwald
534503a627eSMilanka RingwaldAfter these are ready, HCI is initialized like this:
535503a627eSMilanka Ringwald
536503a627eSMilanka Ringwald    hci_init(transport, config);
537503a627eSMilanka Ringwald
538503a627eSMilanka Ringwald
539503a627eSMilanka RingwaldIn addition to these, most UART-based Bluetooth chipset require some
540503a627eSMilanka Ringwaldspecial logic for correct initialization that is not covered by the
541503a627eSMilanka RingwaldBluetooth specification. In particular, this covers:
542503a627eSMilanka Ringwald
543503a627eSMilanka Ringwald- setting the baudrate
544503a627eSMilanka Ringwald- setting the BD ADDR for devices without an internal persistent storage
545503a627eSMilanka Ringwald- upload of some firmware patches.
546503a627eSMilanka Ringwald
547503a627eSMilanka RingwaldThis is provided by the various *btstack_chipset_t* implementation in the *chipset/* subfolders.
548503a627eSMilanka RingwaldAs an example, the *bstack_chipset_cc256x_instance* function returns a pointer to a chipset struct
549503a627eSMilanka Ringwaldsuitable for the CC256x chipset.
550503a627eSMilanka Ringwald
551503a627eSMilanka Ringwald<!-- -->
552503a627eSMilanka Ringwald
553503a627eSMilanka Ringwald    btstack_chipset_t * chipset = btstack_chipset_cc256x_instance();
554503a627eSMilanka Ringwald    hci_set_chipset(chipset);
555503a627eSMilanka Ringwald
556503a627eSMilanka Ringwald
557503a627eSMilanka RingwaldIn some setups, the hardware setup provides explicit control of Bluetooth power and sleep modes.
558503a627eSMilanka RingwaldIn this case, a *btstack_control_t* struct can be set with *hci_set_control*.
559503a627eSMilanka Ringwald
560503a627eSMilanka RingwaldFinally, the HCI implementation requires some form of persistent storage for link keys generated
561503a627eSMilanka Ringwaldduring either legacy pairing or the Secure Simple Pairing (SSP). This commonly requires platform
562503a627eSMilanka Ringwaldspecific code to access the MCU’s EEPROM of Flash storage. For the
563503a627eSMilanka Ringwaldfirst steps, BTstack provides a (non) persistent store in memory.
5647029d61cSMilanka RingwaldFor more see [here](porting/#sec:persistentStoragePorting).
565503a627eSMilanka Ringwald
566503a627eSMilanka Ringwald<!-- -->
567503a627eSMilanka Ringwald
568503a627eSMilanka Ringwald    btstack_link_key_db_t * link_key_db = &btstack_link_key_db_memory_instance();
569503a627eSMilanka Ringwald    btstack_set_link_key_db(link_key_db);
570503a627eSMilanka Ringwald
571503a627eSMilanka Ringwald
572503a627eSMilanka RingwaldThe higher layers only rely on BTstack and are initialized by calling
573503a627eSMilanka Ringwaldthe respective *\*_init* function. These init functions register
574503a627eSMilanka Ringwaldthemselves with the underlying layer. In addition, the application can
575503a627eSMilanka Ringwaldregister packet handlers to get events and data as explained in the
576503a627eSMilanka Ringwaldfollowing section.
577503a627eSMilanka Ringwald
578503a627eSMilanka Ringwald
579503a627eSMilanka Ringwald## Services {#sec:servicesHowTo}
580503a627eSMilanka Ringwald
581503a627eSMilanka RingwaldOne important construct of BTstack is *service*. A service represents a
582503a627eSMilanka Ringwaldserver side component that handles incoming connections. So far, BTstack
583503a627eSMilanka Ringwaldprovides L2CAP, BNEP, and RFCOMM services. An L2CAP service handles incoming
584503a627eSMilanka Ringwaldconnections for an L2CAP channel and is registered with its protocol
585503a627eSMilanka Ringwaldservice multiplexer ID (PSM). Similarly, an RFCOMM service handles
586503a627eSMilanka Ringwaldincoming RFCOMM connections and is registered with the RFCOMM channel
587503a627eSMilanka RingwaldID. Outgoing connections require no special registration, they are
588503a627eSMilanka Ringwaldcreated by the application when needed.
589503a627eSMilanka Ringwald
590503a627eSMilanka Ringwald
591503a627eSMilanka Ringwald## Packet handlers configuration {#sec:packetHandlersHowTo}
592503a627eSMilanka Ringwald
593503a627eSMilanka Ringwald
594503a627eSMilanka RingwaldAfter the hardware and BTstack are set up, the run loop is entered. From
595503a627eSMilanka Ringwaldnow on everything is event driven. The application calls BTstack
596503a627eSMilanka Ringwaldfunctions, which in turn may send commands to the Bluetooth module. The
597503a627eSMilanka Ringwaldresulting events are delivered back to the application. Instead of
598503a627eSMilanka Ringwaldwriting a single callback handler for each possible event (as it is done
599503a627eSMilanka Ringwaldin some other Bluetooth stacks), BTstack groups events logically and
600503a627eSMilanka Ringwaldprovides them over a single generic interface. Appendix
601503a627eSMilanka Ringwald[Events and Errors](generated/appendix/#sec:eventsAndErrorsAppendix)
602503a627eSMilanka Ringwaldsummarizes the parameters and event
603503a627eSMilanka Ringwaldcodes of L2CAP and RFCOMM events, as well as possible errors and the
604503a627eSMilanka Ringwaldcorresponding error codes.
605503a627eSMilanka Ringwald
606503a627eSMilanka RingwaldHere is summarized list of packet handlers that an application might
607503a627eSMilanka Ringwalduse:
608503a627eSMilanka Ringwald
609503a627eSMilanka Ringwald-   HCI event handler - allows to observer HCI, GAP, and general BTstack events.
610503a627eSMilanka Ringwald
611503a627eSMilanka Ringwald-   L2CAP packet handler - handles LE Connection parameter requeset updates
612503a627eSMilanka Ringwald
613503a627eSMilanka Ringwald-   L2CAP service packet handler - handles incoming L2CAP connections,
614503a627eSMilanka Ringwald    i.e., channels initiated by the remote.
615503a627eSMilanka Ringwald
616503a627eSMilanka Ringwald-   L2CAP channel packet handler - handles outgoing L2CAP connections,
617503a627eSMilanka Ringwald    i.e., channels initiated internally.
618503a627eSMilanka Ringwald
619503a627eSMilanka Ringwald-   RFCOMM service packet handler - handles incoming RFCOMM connections,
620503a627eSMilanka Ringwald    i.e., channels initiated by the remote.
621503a627eSMilanka Ringwald
622503a627eSMilanka Ringwald-   RFCOMM channel packet handler - handles outgoing RFCOMM connections,
623503a627eSMilanka Ringwald    i.e., channels initiated internally.
624503a627eSMilanka Ringwald
625503a627eSMilanka RingwaldThese handlers are registered with the functions listed in Table
626503a627eSMilanka Ringwald{@tbl:registeringFunction}.
627503a627eSMilanka Ringwald
628503a627eSMilanka Ringwald
6294402df42SMatthias Ringwald| Packet Handler                | Registering Function                                                     |
6304402df42SMatthias Ringwald|-------------------------------|--------------------------------------------------------------------------|
6314402df42SMatthias Ringwald| HCI packet handler            | hci_add_event_handler                                                    |
6324402df42SMatthias Ringwald| L2CAP packet handler          | l2cap_register_packet_handler                                            |
6334402df42SMatthias Ringwald| L2CAP service packet handler  | l2cap_register_service                                                   |
6344402df42SMatthias Ringwald| L2CAP channel packet handler  | l2cap_create_channel                                                     |
6354402df42SMatthias Ringwald| RFCOMM service packet handler | rfcomm_register_service and rfcomm_register_service_with_initial_credits |
6364402df42SMatthias Ringwald| RFCOMM channel packet handler | rfcomm_create_channel and rfcomm_create_channel_with_initial_credits     |
637503a627eSMilanka Ringwald
638503a627eSMilanka RingwaldTable: Functions for registering packet handlers. {#tbl:registeringFunction}
639503a627eSMilanka Ringwald
640503a627eSMilanka RingwaldHCI, GAP, and general BTstack events are delivered to the packet handler
641503a627eSMilanka Ringwaldspecified by *hci_add_event_handler* function. In L2CAP,
642503a627eSMilanka RingwaldBTstack discriminates incoming and outgoing connections, i.e., event and
643503a627eSMilanka Ringwalddata packets are delivered to different packet handlers. Outgoing
644503a627eSMilanka Ringwaldconnections are used access remote services, incoming connections are
645503a627eSMilanka Ringwaldused to provide services. For incoming connections, the packet handler
646503a627eSMilanka Ringwaldspecified by *l2cap_register_service* is used. For outgoing
647503a627eSMilanka Ringwaldconnections, the handler provided by *l2cap_create_channel*
648503a627eSMilanka Ringwaldis used. RFCOMM and BNEP are similar.
649503a627eSMilanka Ringwald
650503a627eSMilanka RingwaldThe application can register a single shared packet handler for all
651503a627eSMilanka Ringwaldprotocols and services, or use separate packet handlers for each
652503a627eSMilanka Ringwaldprotocol layer and service. A shared packet handler is often used for
653503a627eSMilanka Ringwaldstack initialization and connection management.
654503a627eSMilanka Ringwald
655503a627eSMilanka RingwaldSeparate packet handlers can be used for each L2CAP service and outgoing
656503a627eSMilanka Ringwaldconnection. For example, to connect with a Bluetooth HID keyboard, your
657503a627eSMilanka Ringwaldapplication could use three packet handlers: one to handle HCI events
658503a627eSMilanka Ringwaldduring discovery of a keyboard registered by
659503a627eSMilanka Ringwald*l2cap_register_packet_handler*; one that will be registered to an
660503a627eSMilanka Ringwaldoutgoing L2CAP channel to connect to keyboard and to receive keyboard
661503a627eSMilanka Ringwalddata registered by *l2cap_create_channel*; after that
662503a627eSMilanka Ringwaldkeyboard can reconnect by itself. For this, you need to register L2CAP
663503a627eSMilanka Ringwaldservices for the HID Control and HID Interrupt PSMs using
664503a627eSMilanka Ringwald*l2cap_register_service*. In this call, you’ll also specify
665503a627eSMilanka Ringwalda packet handler to accept and receive keyboard data.
666503a627eSMilanka Ringwald
667503a627eSMilanka RingwaldAll events names have the form MODULE_EVENT_NAME now, e.g., *gap_event_-advertising_report*.
668503a627eSMilanka RingwaldTo facilitate working with
669503a627eSMilanka Ringwaldevents and get rid of manually calculating offsets into packets, BTstack provides
670503a627eSMilanka Ringwaldauto-generated getters for all fields of all events in *src/hci_event.h*. All
671503a627eSMilanka Ringwaldfunctions are defined as static inline, so they are not wasting any program memory
672503a627eSMilanka Ringwaldif not used. If used, the memory footprint should be identical to accessing the
673503a627eSMilanka Ringwaldfield directly via offsets into the packet. For example, to access fields address_type
674503a627eSMilanka Ringwaldand address from the *gap_event_advertising_report* event use following getters:
675503a627eSMilanka Ringwald
676503a627eSMilanka Ringwald<!-- -->
677503a627eSMilanka Ringwald    uint8_t address type = gap_event_advertising_report_get_address_type(event);
678503a627eSMilanka Ringwald    bd_addr_t address;
679503a627eSMilanka Ringwald    gap_event_advertising_report_get_address(event, address);
680503a627eSMilanka Ringwald
681503a627eSMilanka Ringwald
682503a627eSMilanka Ringwald## Bluetooth HCI Packet Logs {#sec:packetlogsHowTo}
683503a627eSMilanka Ringwald
684503a627eSMilanka RingwaldIf things don't work as expected, having a look at the data exchanged
685503a627eSMilanka Ringwaldbetween BTstack and the Bluetooth chipset often helps.
686503a627eSMilanka Ringwald
6870489de14SMatthias RingwaldFor this, BTstack provides a configurable packet logging mechanism via hci_dump.h and the following implementations:
688503a627eSMilanka Ringwald
689503a627eSMilanka Ringwald    void hci_dump_init(const hci_dump_t * hci_dump_implementation);
690503a627eSMilanka Ringwald
6914402df42SMatthias Ringwald| Platform | File                         | Description                                        |
6924402df42SMatthias Ringwald|----------|------------------------------|----------------------------------------------------|
6934402df42SMatthias Ringwald| POSIX    | `hci_dump_posix_fs.c`        | HCI log file for Apple PacketLogger and Wireshark  |
6944402df42SMatthias Ringwald| POSIX    | `hci_dump_posix_stdout.c`    | Console output via printf                          |
6954402df42SMatthias Ringwald| Embedded | `hci_dump_embedded_stdout.c` | Console output via printf                          |
6964402df42SMatthias Ringwald| Embedded | `hci_dump_segger_stdout.c`   | Console output via SEGGER RTT                      |
6974402df42SMatthias Ringwald| Embedded | `hci_dump_segger_binary.c`   | HCI log file for Apple PacketLogger via SEGGER RTT |
6980489de14SMatthias Ringwald
699503a627eSMilanka RingwaldOn POSIX systems, you can call *hci_dump_init* with a *hci_dump_posix_fs_get_instance()* and
700503a627eSMilanka Ringwaldconfigure the path and output format with *hci_dump_posix_fs_open(const char * path, hci_dump_format_t format)*
701503a627eSMilanka Ringwaldwhere format can be *HCI_DUMP_BLUEZ* or *HCI_DUMP_PACKETLOGGER*.
702503a627eSMilanka RingwaldThe resulting file can be analyzed with Wireshark or the Apple's PacketLogger tool.
703503a627eSMilanka Ringwald
704503a627eSMilanka RingwaldOn embedded systems without a file system, you either log to an UART console via printf or use SEGGER RTT.
705503a627eSMilanka RingwaldFor printf output you pass *hci_dump_embedded_stdout_get_instance()* to *hci_dump_init()*.
706503a627eSMilanka RingwaldWith RTT, you can choose between textual output similar to printf, and binary output.
707503a627eSMilanka RingwaldFor textual output, you can provide the *hci_dump_segger_stdout_get_instance()*.
708503a627eSMilanka Ringwald
709503a627eSMilanka RingwaldIt will log all HCI packets to the UART console via printf or RTT Terminal.
710503a627eSMilanka RingwaldIf you capture the console output, incl. your own debug messages, you can use
711503a627eSMilanka Ringwaldthe create_packet_log.py tool in the tools folder to convert a text output into a
712503a627eSMilanka RingwaldPacketLogger file.
713503a627eSMilanka Ringwald
714503a627eSMilanka RingwaldFor less overhead and higher logging speed, you can directly log in binary format by
715503a627eSMilanka Ringwaldpassing *hci_dump_segger_rtt_binary_get_instance()* and selecting the output format by
716503a627eSMilanka Ringwaldcalling *hci_dump_segger_rtt_binary_open(hci_dump_format_t format)* with the same format as above.
717503a627eSMilanka Ringwald
718503a627eSMilanka Ringwald
719503a627eSMilanka RingwaldIn addition to the HCI packets, you can also enable BTstack's debug information by adding
720503a627eSMilanka Ringwald
721503a627eSMilanka Ringwald    #define ENABLE_LOG_INFO
722503a627eSMilanka Ringwald    #define ENABLE_LOG_ERROR
723503a627eSMilanka Ringwald
724503a627eSMilanka Ringwaldto the btstack_config.h and recompiling your application.
725503a627eSMilanka Ringwald
726503a627eSMilanka Ringwald## Bluetooth Power Control {#sec:powerControl}
727503a627eSMilanka Ringwald
728503a627eSMilanka RingwaldIn 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.
729503a627eSMilanka RingwaldThe 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.
730503a627eSMilanka Ringwald
731503a627eSMilanka RingwaldTo enable/disable discoverability, you can call:
732503a627eSMilanka Ringwald
733503a627eSMilanka Ringwald    /**
734503a627eSMilanka Ringwald     * @brief Allows to control if device is discoverable. OFF by default.
735503a627eSMilanka Ringwald     */
736503a627eSMilanka Ringwald    void gap_discoverable_control(uint8_t enable);
737503a627eSMilanka Ringwald
738503a627eSMilanka RingwaldIf 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.
739503a627eSMilanka Ringwald
740503a627eSMilanka RingwaldTo enable/disable connectability, you can call:
741503a627eSMilanka Ringwald
742503a627eSMilanka Ringwald    /**
743503a627eSMilanka Ringwald     * @brief Override page scan mode. Page scan mode enabled by l2cap when services are registered
744503a627eSMilanka Ringwald     * @note Might be used to reduce power consumption while Bluetooth module stays powered but no (new)
745503a627eSMilanka Ringwald     *       connections are expected
746503a627eSMilanka Ringwald     */
747503a627eSMilanka Ringwald    void gap_connectable_control(uint8_t enable);
748503a627eSMilanka Ringwald
749503a627eSMilanka RingwaldFor Bluetooth Low Energy, the radio is periodically used to broadcast advertisements that are used for both discovery and connection establishment.
750503a627eSMilanka Ringwald
751503a627eSMilanka RingwaldTo enable/disable advertisements, you can call:
752503a627eSMilanka Ringwald
753503a627eSMilanka Ringwald    /**
754503a627eSMilanka Ringwald     * @brief Enable/Disable Advertisements. OFF by default.
755503a627eSMilanka Ringwald     * @param enabled
756503a627eSMilanka Ringwald     */
757503a627eSMilanka Ringwald    void gap_advertisements_enable(int enabled);
758503a627eSMilanka Ringwald
759503a627eSMilanka RingwaldIf 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.
760503a627eSMilanka Ringwald
761503a627eSMilanka RingwaldFinally, 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:
762503a627eSMilanka Ringwald
763503a627eSMilanka Ringwald    /**
764503a627eSMilanka Ringwald     * @brief Requests the change of BTstack power mode.
765503a627eSMilanka Ringwald     */
766503a627eSMilanka Ringwald    int  hci_power_control(HCI_POWER_MODE mode);
767503a627eSMilanka Ringwald
768503a627eSMilanka Ringwaldwith 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.
769