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