1*503a627eSMilanka Ringwald# 2*503a627eSMilanka Ringwald 3*503a627eSMilanka 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. 4*503a627eSMilanka Ringwald 5*503a627eSMilanka RingwaldThe configuration of BTstack is done both at compile time as well as at run time: 6*503a627eSMilanka Ringwald 7*503a627eSMilanka Ringwald- compile time configuration: 8*503a627eSMilanka Ringwald - adjust *btstack_config.h* - this file describes the system configuration, used functionality, and also the memory configuration 9*503a627eSMilanka Ringwald - add necessary source code files to your project 10*503a627eSMilanka Ringwald 11*503a627eSMilanka Ringwald- run time configuration of: 12*503a627eSMilanka Ringwald - Bluetooth chipset 13*503a627eSMilanka Ringwald - run loop 14*503a627eSMilanka Ringwald - HCI transport layer 15*503a627eSMilanka Ringwald - provided services 16*503a627eSMilanka Ringwald - packet handlers 17*503a627eSMilanka Ringwald 18*503a627eSMilanka RingwaldIn the following, we provide an overview of the configuration 19*503a627eSMilanka Ringwaldthat is necessary to setup BTstack. From the point when the run loop 20*503a627eSMilanka Ringwaldis executed, the application runs as a finite 21*503a627eSMilanka Ringwaldstate machine, which processes events received from BTstack. BTstack 22*503a627eSMilanka Ringwaldgroups events logically and provides them via packet handlers. 23*503a627eSMilanka RingwaldWe provide their overview here. For the case that there is a need to inspect the data exchanged 24*503a627eSMilanka Ringwaldbetween BTstack and the Bluetooth chipset, we describe how to configure 25*503a627eSMilanka Ringwaldpacket logging mechanism. Finally, we provide an overview on power management in Bluetooth in general and how to save energy in BTstack. 26*503a627eSMilanka Ringwald 27*503a627eSMilanka Ringwald## Configuration in btstack_config.h {#sec:btstackConfigHowTo} 28*503a627eSMilanka RingwaldThe file *btstack_config.h* contains three parts: 29*503a627eSMilanka Ringwald 30*503a627eSMilanka Ringwald- \#define HAVE_* directives [listed here](#sec:haveDirectives). These directives describe available system properties, similar to config.h in a autoconf setup. 31*503a627eSMilanka Ringwald- \#define ENABLE_* directives [listed here](#sec:enableDirectives). These directives list enabled properties, most importantly ENABLE_CLASSIC and ENABLE_BLE. 32*503a627eSMilanka Ringwald- other #define directives for BTstack configuration, most notably static memory, [see next section](#sec:memoryConfigurationHowTo) and [NVM configuration](#sec:nvmConfiguration). 33*503a627eSMilanka Ringwald 34*503a627eSMilanka Ringwald<!-- a name "lst:platformConfiguration"></a--> 35*503a627eSMilanka Ringwald<!-- --> 36*503a627eSMilanka Ringwald 37*503a627eSMilanka Ringwald### HAVE_* directives {#sec:haveDirectives} 38*503a627eSMilanka RingwaldSystem properties: 39*503a627eSMilanka Ringwald 40*503a627eSMilanka Ringwald\#define | Description 41*503a627eSMilanka Ringwald-----------------------------------|------------------------------------- 42*503a627eSMilanka RingwaldHAVE_MALLOC | Use dynamic memory 43*503a627eSMilanka RingwaldHAVE_AES128 | Use platform AES128 engine - not needed usually 44*503a627eSMilanka RingwaldHAVE_BTSTACK_STDIN | STDIN is available for CLI interface 45*503a627eSMilanka RingwaldHAVE_MBEDTLS_ECC_P256 | mbedTLS provides NIST P-256 operations e.g. for LE Secure Connections 46*503a627eSMilanka Ringwald 47*503a627eSMilanka RingwaldEmbedded platform properties: 48*503a627eSMilanka Ringwald 49*503a627eSMilanka Ringwald\#define | Description 50*503a627eSMilanka Ringwald-----------------------------------|------------------------------------ 51*503a627eSMilanka RingwaldHAVE_EMBEDDED_TIME_MS | System provides time in milliseconds 52*503a627eSMilanka RingwaldHAVE_EMBEDDED_TICK | System provides tick interrupt 53*503a627eSMilanka Ringwald 54*503a627eSMilanka RingwaldFreeRTOS platform properties: 55*503a627eSMilanka Ringwald 56*503a627eSMilanka Ringwald\#define | Description 57*503a627eSMilanka Ringwald-----------------------------------|------------------------------------ 58*503a627eSMilanka RingwaldHAVE_FREERTOS_INCLUDE_PREFIX | FreeRTOS headers are in 'freertos' folder (e.g. ESP32's esp-idf) 59*503a627eSMilanka Ringwald 60*503a627eSMilanka RingwaldPOSIX platform properties: 61*503a627eSMilanka Ringwald 62*503a627eSMilanka Ringwald\#define | Description 63*503a627eSMilanka Ringwald-----------------------------------|------------------------------------ 64*503a627eSMilanka RingwaldHAVE_POSIX_B300_MAPPED_TO_2000000 | Workaround to use serial port with 2 mbps 65*503a627eSMilanka RingwaldHAVE_POSIX_B600_MAPPED_TO_3000000 | Workaround to use serial port with 3 mpbs 66*503a627eSMilanka RingwaldHAVE_POSIX_FILE_IO | POSIX File i/o used for hci dump 67*503a627eSMilanka RingwaldHAVE_POSIX_TIME | System provides time function 68*503a627eSMilanka RingwaldLINK_KEY_PATH | Path to stored link keys 69*503a627eSMilanka RingwaldLE_DEVICE_DB_PATH | Path to stored LE device information 70*503a627eSMilanka Ringwald<!-- a name "lst:btstackFeatureConfiguration"></a--> 71*503a627eSMilanka Ringwald<!-- --> 72*503a627eSMilanka Ringwald 73*503a627eSMilanka Ringwald### ENABLE_* directives {#sec:enableDirectives} 74*503a627eSMilanka RingwaldBTstack properties: 75*503a627eSMilanka Ringwald 76*503a627eSMilanka Ringwald\#define | Description 77*503a627eSMilanka Ringwald---------------------------------|--------------------------------------------- 78*503a627eSMilanka RingwaldENABLE_CLASSIC | Enable Classic related code in HCI and L2CAP 79*503a627eSMilanka RingwaldENABLE_BLE | Enable BLE related code in HCI and L2CAP 80*503a627eSMilanka RingwaldENABLE_EHCILL | Enable eHCILL low power mode on TI CC256x/WL18xx chipsets 81*503a627eSMilanka RingwaldENABLE_H5 | Enable support for SLIP mode in `btstack_uart.h` drivers for HCI H5 ('Three-Wire Mode') 82*503a627eSMilanka RingwaldENABLE_LOG_DEBUG | Enable log_debug messages 83*503a627eSMilanka RingwaldENABLE_LOG_ERROR | Enable log_error messages 84*503a627eSMilanka RingwaldENABLE_LOG_INFO | Enable log_info messages 85*503a627eSMilanka RingwaldENABLE_SCO_OVER_HCI | Enable SCO over HCI for chipsets (if supported) 86*503a627eSMilanka RingwaldENABLE_SCO_OVER_PCM | Enable SCO ofer PCM/I2S for chipsets (if supported) 87*503a627eSMilanka RingwaldENABLE_HFP_WIDE_BAND_SPEECH | Enable support for mSBC codec used in HFP profile for Wide-Band Speech 88*503a627eSMilanka RingwaldENABLE_HFP_AT_MESSAGES | Enable `HFP_SUBEVENT_AT_MESSAGE_SENT` and `HFP_SUBEVENT_AT_MESSAGE_RECEIVED` events 89*503a627eSMilanka RingwaldENABLE_LE_PERIPHERAL | Enable support for LE Peripheral Role in HCI and Security Manager 90*503a627eSMilanka RingwaldENBALE_LE_CENTRAL | Enable support for LE Central Role in HCI and Security Manager 91*503a627eSMilanka RingwaldENABLE_LE_SECURE_CONNECTIONS | Enable LE Secure Connections 92*503a627eSMilanka RingwaldENABLE_LE_PROACTIVE_AUTHENTICATION | Enable automatic encryption for bonded devices on re-connect 93*503a627eSMilanka RingwaldENABLE_GATT_CLIENT_PAIRING | Enable GATT Client to start pairing and retry operation on security error 94*503a627eSMilanka RingwaldENABLE_MICRO_ECC_FOR_LE_SECURE_CONNECTIONS | Use [micro-ecc library](https://github.com/kmackay/micro-ecc) for ECC operations 95*503a627eSMilanka RingwaldENABLE_LE_DATA_CHANNELS | Enable LE Data Channels in credit-based flow control mode 96*503a627eSMilanka RingwaldENABLE_LE_DATA_LENGTH_EXTENSION | Enable LE Data Length Extension support 97*503a627eSMilanka RingwaldENABLE_LE_SIGNED_WRITE | Enable LE Signed Writes in ATT/GATT 98*503a627eSMilanka RingwaldENABLE_LE_PRIVACY_ADDRESS_RESOLUTION | Enable address resolution for resolvable private addresses in Controller 99*503a627eSMilanka RingwaldENABLE_CROSS_TRANSPORT_KEY_DERIVATION | Enable Cross-Transport Key Derivation (CTKD) for Secure Connections 100*503a627eSMilanka RingwaldENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE | Enable L2CAP Enhanced Retransmission Mode. Mandatory for AVRCP Browsing 101*503a627eSMilanka RingwaldENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL | Enable HCI Controller to Host Flow Control, see below 102*503a627eSMilanka RingwaldENABLE_ATT_DELAYED_RESPONSE | Enable support for delayed ATT operations, see [GATT Server](profiles/#sec:GATTServerProfile) 103*503a627eSMilanka RingwaldENABLE_BCM_PCM_WBS | Enable support for Wide-Band Speech codec in BCM controller, requires ENABLE_SCO_OVER_PCM 104*503a627eSMilanka RingwaldENABLE_CC256X_ASSISTED_HFP | Enable support for Assisted HFP mode in CC256x Controller, requires ENABLE_SCO_OVER_PCM 105*503a627eSMilanka RingwaldENABLE_CC256X_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND | Enable workaround for bug in CC256x Flow Control during baud rate change, see chipset docs. 106*503a627eSMilanka RingwaldENABLE_CYPRESS_BAUDRATE_CHANGE_FLOWCONTROL_BUG_WORKAROUND | Enable workaround for bug in CYW2070x Flow Control during baud rate change, similar to CC256x. 107*503a627eSMilanka RingwaldENABLE_LE_LIMIT_ACL_FRAGMENT_BY_MAX_OCTETS | Force HCI to fragment ACL-LE packets to fit into over-the-air packet 108*503a627eSMilanka RingwaldENABLE_TLV_FLASH_EXPLICIT_DELETE_FIELD | Enable use of explicit delete field in TLV Flash implemenation - required when flash value cannot be overwritten with zero 109*503a627eSMilanka RingwaldENABLE_CONTROLLER_WARM_BOOT | Enable stack startup without power cycle (if supported/possible) 110*503a627eSMilanka RingwaldENABLE_SEGGER_RTT | Use SEGGER RTT for console output and packet log, see [additional options](#sec:rttConfiguration) 111*503a627eSMilanka RingwaldENABLE_EXPLICIT_CONNECTABLE_MODE_CONTROL | Disable calls to control Connectable Mode by L2CAP 112*503a627eSMilanka RingwaldENABLE_EXPLICIT_IO_CAPABILITIES_REPLY | Let application trigger sending IO Capabilities (Negative) Reply 113*503a627eSMilanka RingwaldENABLE_CLASSIC_OOB_PAIRING | Enable support for classic Out-of-Band (OOB) pairing 114*503a627eSMilanka RingwaldENABLE_A2DP_SOURCE_EXPLICIT_CONFIG | Let application configure stream endpoint (skip auto-config of SBC endpoint) 115*503a627eSMilanka Ringwald 116*503a627eSMilanka RingwaldNotes: 117*503a627eSMilanka Ringwald 118*503a627eSMilanka 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. 119*503a627eSMilanka Ringwald 120*503a627eSMilanka Ringwald### HCI Controller to Host Flow Control 121*503a627eSMilanka 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. 122*503a627eSMilanka Ringwald 123*503a627eSMilanka RingwaldHost buffer configuration for HCI Controller to Host Flow Control: 124*503a627eSMilanka Ringwald 125*503a627eSMilanka Ringwald\#define | Description 126*503a627eSMilanka Ringwald------------------|------------ 127*503a627eSMilanka RingwaldHCI_HOST_ACL_PACKET_NUM | Max number of ACL packets 128*503a627eSMilanka RingwaldHCI_HOST_ACL_PACKET_LEN | Max size of HCI Host ACL packets 129*503a627eSMilanka RingwaldHCI_HOST_SCO_PACKET_NUM | Max number of ACL packets 130*503a627eSMilanka RingwaldHCI_HOST_SCO_PACKET_LEN | Max size of HCI Host SCO packets 131*503a627eSMilanka Ringwald 132*503a627eSMilanka Ringwald 133*503a627eSMilanka Ringwald### Memory configuration directives {#sec:memoryConfigurationHowTo} 134*503a627eSMilanka Ringwald 135*503a627eSMilanka RingwaldThe structs for services, active connections and remote devices can be 136*503a627eSMilanka Ringwaldallocated in two different manners: 137*503a627eSMilanka Ringwald 138*503a627eSMilanka Ringwald- statically from an individual memory pool, whose maximal number of 139*503a627eSMilanka Ringwald elements is defined in the btstack_config.h file. To initialize the static 140*503a627eSMilanka Ringwald pools, you need to call at runtime *btstack_memory_init* function. An example 141*503a627eSMilanka Ringwald of memory configuration for a single SPP service with a minimal 142*503a627eSMilanka Ringwald L2CAP MTU is shown in Listing {@lst:memoryConfigurationSPP}. 143*503a627eSMilanka Ringwald 144*503a627eSMilanka Ringwald- dynamically using the *malloc/free* functions, if HAVE_MALLOC is 145*503a627eSMilanka Ringwald defined in btstack_config.h file. 146*503a627eSMilanka Ringwald 147*503a627eSMilanka 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 recommend. The large ACL buffer is required for 3-DH5 packets to be used. 148*503a627eSMilanka Ringwald 149*503a627eSMilanka Ringwald<!-- a name "lst:memoryConfiguration"></a--> 150*503a627eSMilanka Ringwald<!-- --> 151*503a627eSMilanka Ringwald 152*503a627eSMilanka Ringwald\#define | Description 153*503a627eSMilanka Ringwald--------|------------ 154*503a627eSMilanka RingwaldHCI_ACL_PAYLOAD_SIZE | Max size of HCI ACL payloads 155*503a627eSMilanka RingwaldMAX_NR_BNEP_CHANNELS | Max number of BNEP channels 156*503a627eSMilanka RingwaldMAX_NR_BNEP_SERVICES | Max number of BNEP services 157*503a627eSMilanka RingwaldMAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES | Max number of link key entries cached in RAM 158*503a627eSMilanka RingwaldMAX_NR_GATT_CLIENTS | Max number of GATT clients 159*503a627eSMilanka RingwaldMAX_NR_HCI_CONNECTIONS | Max number of HCI connections 160*503a627eSMilanka RingwaldMAX_NR_HFP_CONNECTIONS | Max number of HFP connections 161*503a627eSMilanka RingwaldMAX_NR_L2CAP_CHANNELS | Max number of L2CAP connections 162*503a627eSMilanka RingwaldMAX_NR_L2CAP_SERVICES | Max number of L2CAP services 163*503a627eSMilanka RingwaldMAX_NR_RFCOMM_CHANNELS | Max number of RFOMMM connections 164*503a627eSMilanka RingwaldMAX_NR_RFCOMM_MULTIPLEXERS | Max number of RFCOMM multiplexers, with one multiplexer per HCI connection 165*503a627eSMilanka RingwaldMAX_NR_RFCOMM_SERVICES | Max number of RFCOMM services 166*503a627eSMilanka RingwaldMAX_NR_SERVICE_RECORD_ITEMS | Max number of SDP service records 167*503a627eSMilanka RingwaldMAX_NR_SM_LOOKUP_ENTRIES | Max number of items in Security Manager lookup queue 168*503a627eSMilanka RingwaldMAX_NR_WHITELIST_ENTRIES | Max number of items in GAP LE Whitelist to connect to 169*503a627eSMilanka RingwaldMAX_NR_LE_DEVICE_DB_ENTRIES | Max number of items in LE Device DB 170*503a627eSMilanka Ringwald 171*503a627eSMilanka Ringwald 172*503a627eSMilanka RingwaldThe memory is set up by calling *btstack_memory_init* function: 173*503a627eSMilanka Ringwald 174*503a627eSMilanka Ringwald btstack_memory_init(); 175*503a627eSMilanka Ringwald 176*503a627eSMilanka Ringwald<!-- a name "lst:memoryConfigurationSPP"></a--> 177*503a627eSMilanka Ringwald<!-- --> 178*503a627eSMilanka Ringwald 179*503a627eSMilanka RingwaldHere's the memory configuration for a basic SPP server. 180*503a627eSMilanka Ringwald 181*503a627eSMilanka Ringwald #define HCI_ACL_PAYLOAD_SIZE 52 182*503a627eSMilanka Ringwald #define MAX_NR_HCI_CONNECTIONS 1 183*503a627eSMilanka Ringwald #define MAX_NR_L2CAP_SERVICES 2 184*503a627eSMilanka Ringwald #define MAX_NR_L2CAP_CHANNELS 2 185*503a627eSMilanka Ringwald #define MAX_NR_RFCOMM_MULTIPLEXERS 1 186*503a627eSMilanka Ringwald #define MAX_NR_RFCOMM_SERVICES 1 187*503a627eSMilanka Ringwald #define MAX_NR_RFCOMM_CHANNELS 1 188*503a627eSMilanka Ringwald #define MAX_NR_BTSTACK_LINK_KEY_DB_MEMORY_ENTRIES 3 189*503a627eSMilanka Ringwald 190*503a627eSMilanka RingwaldListing: Memory configuration for a basic SPP server. {#lst:memoryConfigurationSPP} 191*503a627eSMilanka Ringwald 192*503a627eSMilanka 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 cached in RAM. 193*503a627eSMilanka Ringwald 194*503a627eSMilanka Ringwald<!-- --> 195*503a627eSMilanka Ringwald 196*503a627eSMilanka Ringwald### Non-volatile memory (NVM) directives {#sec:nvmConfiguration} 197*503a627eSMilanka Ringwald 198*503a627eSMilanka 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: 199*503a627eSMilanka Ringwald 200*503a627eSMilanka Ringwald<!-- a name "lst:nvmDefines"></a--> 201*503a627eSMilanka Ringwald<!-- --> 202*503a627eSMilanka Ringwald 203*503a627eSMilanka Ringwald\#define | Description 204*503a627eSMilanka Ringwald--------------------------|------------ 205*503a627eSMilanka RingwaldNVM_NUM_LINK_KEYS | Max number of Classic Link Keys that can be stored 206*503a627eSMilanka RingwaldNVM_NUM_DEVICE_DB_ENTRIES | Max number of LE Device DB entries that can be stored 207*503a627eSMilanka RingwaldNVN_NUM_GATT_SERVER_CCC | Max number of 'Client Characteristic Configuration' values that can be stored by GATT Server 208*503a627eSMilanka Ringwald 209*503a627eSMilanka Ringwald 210*503a627eSMilanka Ringwald### SEGGER Real Time Transfer (RTT) directives {#sec:rttConfiguration} 211*503a627eSMilanka Ringwald 212*503a627eSMilanka 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. 213*503a627eSMilanka Ringwald 214*503a627eSMilanka 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: 215*503a627eSMilanka Ringwald 216*503a627eSMilanka Ringwald\#define | Default | Description 217*503a627eSMilanka Ringwald---------------------------------|--------------------------------|------------------------ 218*503a627eSMilanka RingwaldSEGGER_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 219*503a627eSMilanka RingwaldSEGGER_RTT_PACKETLOG_CHANNEL | 1 | Channel to use for packet log. Channel 0 is used for terminal 220*503a627eSMilanka RingwaldSEGGER_RTT_PACKETLOG_BUFFER_SIZE | 1024 | Size of outgoing ring buffer. Increase if you cannot block but get 'message skipped' warnings. 221*503a627eSMilanka Ringwald 222*503a627eSMilanka Ringwald## Run-time configuration 223*503a627eSMilanka Ringwald 224*503a627eSMilanka RingwaldTo allow code-reuse with different platforms 225*503a627eSMilanka Ringwaldas well as with new ports, the low-level initialization of BTstack and 226*503a627eSMilanka Ringwaldthe hardware configuration has been extracted to the various 227*503a627eSMilanka Ringwald*platforms/PLATFORM/main.c* files. The examples only contain the 228*503a627eSMilanka Ringwaldplatform-independent Bluetooth logic. But let’s have a look at the 229*503a627eSMilanka Ringwaldcommon init code. 230*503a627eSMilanka Ringwald 231*503a627eSMilanka RingwaldListing [below](#lst:btstackInit) shows a minimal platform setup for an 232*503a627eSMilanka Ringwaldembedded system with a Bluetooth chipset connected via UART. 233*503a627eSMilanka Ringwald 234*503a627eSMilanka Ringwald~~~~ {#lst:btstackInit .c caption="{Minimal platform setup for an embedded system}"} 235*503a627eSMilanka Ringwald 236*503a627eSMilanka Ringwald int main(){ 237*503a627eSMilanka Ringwald // ... hardware init: watchdoch, IOs, timers, etc... 238*503a627eSMilanka Ringwald 239*503a627eSMilanka Ringwald // setup BTstack memory pools 240*503a627eSMilanka Ringwald btstack_memory_init(); 241*503a627eSMilanka Ringwald 242*503a627eSMilanka Ringwald // select embedded run loop 243*503a627eSMilanka Ringwald btstack_run_loop_init(btstack_run_loop_embedded_get_instance()); 244*503a627eSMilanka Ringwald 245*503a627eSMilanka Ringwald // enable logging 246*503a627eSMilanka Ringwald hci_dump_init(hci_dump_embedded_stdout_get_instance()); 247*503a627eSMilanka Ringwald 248*503a627eSMilanka Ringwald 249*503a627eSMilanka Ringwald // init HCI 250*503a627eSMilanka Ringwald hci_transport_t * transport = hci_transport_h4_instance(); 251*503a627eSMilanka Ringwald hci_init(transport, NULL); 252*503a627eSMilanka Ringwald 253*503a627eSMilanka Ringwald // setup example 254*503a627eSMilanka Ringwald btstack_main(argc, argv); 255*503a627eSMilanka Ringwald 256*503a627eSMilanka Ringwald // go 257*503a627eSMilanka Ringwald btstack_run_loop_execute(); 258*503a627eSMilanka Ringwald } 259*503a627eSMilanka Ringwald 260*503a627eSMilanka Ringwald~~~~ 261*503a627eSMilanka Ringwald 262*503a627eSMilanka RingwaldFirst, BTstack’s memory pools are setup up. Then, the standard run loop 263*503a627eSMilanka Ringwaldimplementation for embedded systems is selected. 264*503a627eSMilanka Ringwald 265*503a627eSMilanka RingwaldThe call to *hci_dump_init* configures BTstack to output all Bluetooth 266*503a627eSMilanka Ringwaldpackets and its own debug and error message using printf with BTstack's 267*503a627eSMilanka Ringwaldmillisecond tiomestamps.s as tim. 268*503a627eSMilanka RingwaldThe Python 269*503a627eSMilanka Ringwaldscript *tools/create_packet_log.py* can be used to convert the console 270*503a627eSMilanka Ringwaldoutput into a Bluetooth PacketLogger format that can be opened by the OS 271*503a627eSMilanka RingwaldX PacketLogger tool as well as by Wireshark for further inspection. When 272*503a627eSMilanka Ringwaldasking for help, please always include a log created with HCI dump. 273*503a627eSMilanka Ringwald 274*503a627eSMilanka RingwaldThe *hci_init* function sets up HCI to use the HCI H4 Transport 275*503a627eSMilanka Ringwaldimplementation. It doesn’t provide a special transport configuration nor 276*503a627eSMilanka Ringwalda special implementation for a particular Bluetooth chipset. It makes 277*503a627eSMilanka Ringwalduse of the *remote_device_db_memory* implementation that allows for 278*503a627eSMilanka Ringwaldre-connects without a new pairing but doesn’t persist the bonding 279*503a627eSMilanka Ringwaldinformation. 280*503a627eSMilanka Ringwald 281*503a627eSMilanka RingwaldFinally, it calls *btstack_main()* of the actual example before 282*503a627eSMilanka Ringwaldexecuting the run loop. 283*503a627eSMilanka Ringwald 284*503a627eSMilanka Ringwald 285*503a627eSMilanka Ringwald## Source tree structure {#sec:sourceTreeHowTo} 286*503a627eSMilanka Ringwald 287*503a627eSMilanka RingwaldThe source tree has been organized to easily setup new projects. 288*503a627eSMilanka Ringwald 289*503a627eSMilanka RingwaldPath | Description 290*503a627eSMilanka Ringwald--------------------|--------------- 291*503a627eSMilanka Ringwaldchipset | Support for individual Bluetooth Controller chipsets 292*503a627eSMilanka Ringwalddoc | Sources for BTstack documentation 293*503a627eSMilanka Ringwaldexample | Example applications available for all ports 294*503a627eSMilanka Ringwaldplatform | Support for special OSs and/or MCU architectures 295*503a627eSMilanka Ringwaldport | Complete port for a MCU + Chipset combinations 296*503a627eSMilanka Ringwaldsrc | Bluetooth stack implementation 297*503a627eSMilanka Ringwaldtest | Unit and PTS tests 298*503a627eSMilanka Ringwaldtool | Helper tools for BTstack 299*503a627eSMilanka Ringwald 300*503a627eSMilanka RingwaldThe core of BTstack, including all protocol and profiles, is in *src/*. 301*503a627eSMilanka Ringwald 302*503a627eSMilanka 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. 303*503a627eSMilanka Ringwald 304*503a627eSMilanka RingwaldTo accommodate a particular Bluetooth chipset, the *chipset/* subfolders provide various btstack_chipset_* implementations. 305*503a627eSMilanka RingwaldPlease have a look at the existing ports in *port/*. 306*503a627eSMilanka Ringwald 307*503a627eSMilanka Ringwald## Run loop configuration {#sec:runLoopHowTo} 308*503a627eSMilanka Ringwald 309*503a627eSMilanka RingwaldTo initialize BTstack you need to [initialize the memory](#sec:memoryConfigurationHowTo) 310*503a627eSMilanka Ringwaldand [the run loop](#sec:runLoopHowTo) respectively, then setup HCI and all needed higher 311*503a627eSMilanka Ringwaldlevel protocols. 312*503a627eSMilanka Ringwald 313*503a627eSMilanka RingwaldBTstack uses the concept of a run loop to handle incoming data and to schedule work. 314*503a627eSMilanka RingwaldThe run loop handles events from two different types of sources: data 315*503a627eSMilanka Ringwaldsources and timers. Data sources represent communication interfaces like 316*503a627eSMilanka Ringwaldan UART or an USB driver. Timers are used by BTstack to implement 317*503a627eSMilanka Ringwaldvarious Bluetooth-related timeouts. They can also be used to handle 318*503a627eSMilanka Ringwaldperiodic events. 319*503a627eSMilanka Ringwald 320*503a627eSMilanka RingwaldData sources and timers are represented by the *btstack_data_source_t* and 321*503a627eSMilanka Ringwald*btstack_timer_source_t* structs respectively. Each of these structs contain 322*503a627eSMilanka Ringwaldat least a linked list node and a pointer to a callback function. All active timers 323*503a627eSMilanka Ringwaldand data sources are kept in link lists. While the list of data sources 324*503a627eSMilanka Ringwaldis unsorted, the timers are sorted by expiration timeout for efficient 325*503a627eSMilanka Ringwaldprocessing. 326*503a627eSMilanka Ringwald 327*503a627eSMilanka RingwaldTimers are single shot: a timer will be removed from the timer list 328*503a627eSMilanka Ringwaldbefore its event handler callback is executed. If you need a periodic 329*503a627eSMilanka Ringwaldtimer, you can re-register the same timer source in the callback 330*503a627eSMilanka Ringwaldfunction, as shown in Listing [PeriodicTimerHandler]. Note that BTstack 331*503a627eSMilanka Ringwaldexpects to get called periodically to keep its time, see Section 332*503a627eSMilanka Ringwald[on time abstraction](#sec:timeAbstractionPorting) for more on the 333*503a627eSMilanka Ringwaldtick hardware abstraction. 334*503a627eSMilanka Ringwald 335*503a627eSMilanka RingwaldBTstack provides different run loop implementations that implement the *btstack_run_loop_t* interface: 336*503a627eSMilanka Ringwald 337*503a627eSMilanka Ringwald- Embedded: the main implementation for embedded systems, especially without an RTOS. 338*503a627eSMilanka Ringwald- FreeRTOS: implementation to run BTstack on a dedicated FreeRTOS thread 339*503a627eSMilanka Ringwald- POSIX: implementation for POSIX systems based on the select() call. 340*503a627eSMilanka Ringwald- CoreFoundation: implementation for iOS and OS X applications 341*503a627eSMilanka Ringwald- WICED: implementation for the Broadcom WICED SDK RTOS abstraction that wraps FreeRTOS or ThreadX. 342*503a627eSMilanka Ringwald- Windows: implementation for Windows based on Event objects and WaitForMultipleObjects() call. 343*503a627eSMilanka Ringwald 344*503a627eSMilanka RingwaldDepending on the platform, data sources are either polled (embedded, FreeRTOS), or the platform provides a way 345*503a627eSMilanka Ringwaldto wait for a data source to become ready for read or write (POSIX, CoreFoundation, Windows), or, 346*503a627eSMilanka Ringwaldare not used as the HCI transport driver and the run loop is implemented in a different way (WICED). 347*503a627eSMilanka RingwaldIn any case, the callbacks must be to explicitly enabled with the *btstack_run_loop_enable_data_source_callbacks(..)* function. 348*503a627eSMilanka Ringwald 349*503a627eSMilanka RingwaldIn your code, you'll have to configure the run loop before you start it 350*503a627eSMilanka Ringwaldas shown in Listing [listing:btstackInit]. The application can register 351*503a627eSMilanka Ringwalddata sources as well as timers, e.g., for periodical sampling of sensors, or 352*503a627eSMilanka Ringwaldfor communication over the UART. 353*503a627eSMilanka Ringwald 354*503a627eSMilanka RingwaldThe run loop is set up by calling *btstack_run_loop_init* function and providing 355*503a627eSMilanka Ringwaldan instance of the actual run loop. E.g. for the embedded platform, it is: 356*503a627eSMilanka Ringwald 357*503a627eSMilanka Ringwald<!-- --> 358*503a627eSMilanka Ringwald 359*503a627eSMilanka Ringwald btstack_run_loop_init(btstack_run_loop_embedded_get_instance()); 360*503a627eSMilanka Ringwald 361*503a627eSMilanka RingwaldThe complete Run loop API is provided [here](appendix/apis/#sec:runLoopAPIAppendix). 362*503a627eSMilanka Ringwald 363*503a627eSMilanka Ringwald### Run loop embedded 364*503a627eSMilanka Ringwald 365*503a627eSMilanka RingwaldIn the embedded run loop implementation, data sources are constantly polled and 366*503a627eSMilanka Ringwaldthe system is put to sleep if no IRQ happens during the poll of all data sources. 367*503a627eSMilanka Ringwald 368*503a627eSMilanka RingwaldThe complete run loop cycle looks like this: first, the callback 369*503a627eSMilanka Ringwaldfunction of all registered data sources are called in a round robin way. 370*503a627eSMilanka RingwaldThen, the callback functions of timers that are ready are executed. 371*503a627eSMilanka RingwaldFinally, it will be checked if another run loop iteration has been 372*503a627eSMilanka Ringwaldrequested by an interrupt handler. If not, the run loop will put the MCU 373*503a627eSMilanka Ringwaldinto sleep mode. 374*503a627eSMilanka Ringwald 375*503a627eSMilanka RingwaldIncoming data over the UART, USB, or timer ticks will generate an 376*503a627eSMilanka Ringwaldinterrupt and wake up the microcontroller. In order to avoid the 377*503a627eSMilanka Ringwaldsituation where a data source becomes ready just before the run loop 378*503a627eSMilanka Ringwaldenters sleep mode, an interrupt-driven data source has to call the 379*503a627eSMilanka Ringwald*btstack_run_loop_embedded_trigger* function. The call to 380*503a627eSMilanka Ringwald*btstack_run_loop_embedded_trigger* sets an 381*503a627eSMilanka Ringwaldinternal flag that is checked in the critical section just before 382*503a627eSMilanka Ringwaldentering sleep mode causing another run loop cycle. 383*503a627eSMilanka Ringwald 384*503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_EMBEDDED_TICK or HAVE_EMBEDDED_TIME_MS in the 385*503a627eSMilanka Ringwaldconfig file. 386*503a627eSMilanka Ringwald 387*503a627eSMilanka Ringwald### Run loop FreeRTOS 388*503a627eSMilanka Ringwald 389*503a627eSMilanka RingwaldThe FreeRTOS run loop is used on a dedicated FreeRTOS thread and it uses a FreeRTOS queue to schedule callbacks on the run loop. 390*503a627eSMilanka RingwaldIn each iteration: 391*503a627eSMilanka Ringwald 392*503a627eSMilanka Ringwald- all data sources are polled 393*503a627eSMilanka Ringwald- all scheduled callbacks are executed 394*503a627eSMilanka Ringwald- all expired timers are called 395*503a627eSMilanka Ringwald- finally, it gets the next timeout. It then waits for a 'trigger' or the next timeout, if set. 396*503a627eSMilanka Ringwald 397*503a627eSMilanka RingwaldTo trigger the run loop, *btstack_run_loop_freertos_trigger* and *btstack_run_loop_freertos_trigger_from_isr* can be called. 398*503a627eSMilanka RingwaldThis causes the data sources to get polled. 399*503a627eSMilanka Ringwald 400*503a627eSMilanka RingwaldAlternatively. *btstack_run_loop_freertos_execute_code_on_main_thread* can be used to schedule a callback on the main loop. 401*503a627eSMilanka RingwaldPlease note that the queue is finite (see *RUN_LOOP_QUEUE_LENGTH* in btstack_run_loop_embedded). 402*503a627eSMilanka Ringwald 403*503a627eSMilanka Ringwald### Run loop POSIX 404*503a627eSMilanka Ringwald 405*503a627eSMilanka RingwaldThe data sources are standard File Descriptors. In the run loop execute implementation, 406*503a627eSMilanka Ringwaldselect() call is used to wait for file descriptors to become ready to read or write, 407*503a627eSMilanka Ringwaldwhile waiting for the next timeout. 408*503a627eSMilanka Ringwald 409*503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file. 410*503a627eSMilanka Ringwald 411*503a627eSMilanka Ringwald### Run loop CoreFoundation (OS X/iOS) 412*503a627eSMilanka Ringwald 413*503a627eSMilanka RingwaldThis run loop directly maps BTstack's data source and timer source with CoreFoundation objects. 414*503a627eSMilanka RingwaldIt supports ready to read and write similar to the POSIX implementation. The call to 415*503a627eSMilanka Ringwald*btstack_run_loop_execute()* then just calls *CFRunLoopRun()*. 416*503a627eSMilanka Ringwald 417*503a627eSMilanka RingwaldTo enable the use of timers, make sure that you defined HAVE_POSIX_TIME in the config file. 418*503a627eSMilanka Ringwald 419*503a627eSMilanka Ringwald### Run loop Windows 420*503a627eSMilanka Ringwald 421*503a627eSMilanka RingwaldThe data sources are Event objects. In the run loop implementation WaitForMultipleObjects() call 422*503a627eSMilanka Ringwaldis all is used to wait for the Event object to become ready while waiting for the next timeout. 423*503a627eSMilanka Ringwald 424*503a627eSMilanka Ringwald 425*503a627eSMilanka Ringwald### Run loop WICED 426*503a627eSMilanka Ringwald 427*503a627eSMilanka RingwaldWICED SDK API does not provide asynchronous read and write to the UART and no direct way to wait for 428*503a627eSMilanka Ringwaldone or more peripherals to become ready. Therefore, BTstack does not provide direct support for data sources. 429*503a627eSMilanka RingwaldInstead, the run loop provides a message queue that allows to schedule functions calls on its thread via 430*503a627eSMilanka Ringwald*btstack_run_loop_wiced_execute_code_on_main_thread()*. 431*503a627eSMilanka Ringwald 432*503a627eSMilanka RingwaldThe HCI transport H4 implementation then uses two lightweight threads to do the 433*503a627eSMilanka Ringwaldblocking read and write operations. When a read or write is complete on 434*503a627eSMilanka Ringwaldthe helper threads, a callback to BTstack is scheduled. 435*503a627eSMilanka Ringwald 436*503a627eSMilanka Ringwald 437*503a627eSMilanka Ringwald## HCI Transport configuration 438*503a627eSMilanka Ringwald 439*503a627eSMilanka RingwaldThe HCI initialization has to adapt BTstack to the used platform. The first 440*503a627eSMilanka Ringwaldcall is to *hci_init()* and requires information about the HCI Transport to use. 441*503a627eSMilanka RingwaldThe arguments are: 442*503a627eSMilanka Ringwald 443*503a627eSMilanka Ringwald- *HCI Transport implementation*: On embedded systems, a Bluetooth 444*503a627eSMilanka 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. 445*503a627eSMilanka Ringwald These are accessed by linking the appropriate file, e.g., 446*503a627eSMilanka Ringwald [platform/embedded/hci_transport_h4_embedded.c]() 447*503a627eSMilanka Ringwald and then getting a pointer to HCI Transport implementation. 448*503a627eSMilanka Ringwald For more information on adapting HCI Transport to different 449*503a627eSMilanka Ringwald environments, see [here](porting/#sec:hciTransportPorting). 450*503a627eSMilanka Ringwald 451*503a627eSMilanka Ringwald<!-- --> 452*503a627eSMilanka Ringwald 453*503a627eSMilanka Ringwald hci_transport_t * transport = hci_transport_h4_instance(); 454*503a627eSMilanka Ringwald 455*503a627eSMilanka Ringwald- *HCI Transport configuration*: As the configuration of the UART used 456*503a627eSMilanka Ringwald in the H4 transport interface are not standardized, it has to be 457*503a627eSMilanka Ringwald provided by the main application to BTstack. In addition to the 458*503a627eSMilanka Ringwald initial UART baud rate, the main baud rate can be specified. The HCI 459*503a627eSMilanka Ringwald layer of BTstack will change the init baud rate to the main one 460*503a627eSMilanka Ringwald after the basic setup of the Bluetooth module. A baud rate change 461*503a627eSMilanka Ringwald has to be done in a coordinated way at both HCI and hardware level. 462*503a627eSMilanka Ringwald For example, on the CC256x, the HCI command to change the baud rate 463*503a627eSMilanka Ringwald is sent first, then it is necessary to wait for the confirmation event 464*503a627eSMilanka Ringwald from the Bluetooth module. Only now, can the UART baud rate changed. 465*503a627eSMilanka Ringwald 466*503a627eSMilanka Ringwald<!-- --> 467*503a627eSMilanka Ringwald 468*503a627eSMilanka Ringwald hci_uart_config_t* config = &hci_uart_config; 469*503a627eSMilanka Ringwald 470*503a627eSMilanka RingwaldAfter these are ready, HCI is initialized like this: 471*503a627eSMilanka Ringwald 472*503a627eSMilanka Ringwald hci_init(transport, config); 473*503a627eSMilanka Ringwald 474*503a627eSMilanka Ringwald 475*503a627eSMilanka RingwaldIn addition to these, most UART-based Bluetooth chipset require some 476*503a627eSMilanka Ringwaldspecial logic for correct initialization that is not covered by the 477*503a627eSMilanka RingwaldBluetooth specification. In particular, this covers: 478*503a627eSMilanka Ringwald 479*503a627eSMilanka Ringwald- setting the baudrate 480*503a627eSMilanka Ringwald- setting the BD ADDR for devices without an internal persistent storage 481*503a627eSMilanka Ringwald- upload of some firmware patches. 482*503a627eSMilanka Ringwald 483*503a627eSMilanka RingwaldThis is provided by the various *btstack_chipset_t* implementation in the *chipset/* subfolders. 484*503a627eSMilanka RingwaldAs an example, the *bstack_chipset_cc256x_instance* function returns a pointer to a chipset struct 485*503a627eSMilanka Ringwaldsuitable for the CC256x chipset. 486*503a627eSMilanka Ringwald 487*503a627eSMilanka Ringwald<!-- --> 488*503a627eSMilanka Ringwald 489*503a627eSMilanka Ringwald btstack_chipset_t * chipset = btstack_chipset_cc256x_instance(); 490*503a627eSMilanka Ringwald hci_set_chipset(chipset); 491*503a627eSMilanka Ringwald 492*503a627eSMilanka Ringwald 493*503a627eSMilanka RingwaldIn some setups, the hardware setup provides explicit control of Bluetooth power and sleep modes. 494*503a627eSMilanka RingwaldIn this case, a *btstack_control_t* struct can be set with *hci_set_control*. 495*503a627eSMilanka Ringwald 496*503a627eSMilanka RingwaldFinally, the HCI implementation requires some form of persistent storage for link keys generated 497*503a627eSMilanka Ringwaldduring either legacy pairing or the Secure Simple Pairing (SSP). This commonly requires platform 498*503a627eSMilanka Ringwaldspecific code to access the MCU’s EEPROM of Flash storage. For the 499*503a627eSMilanka Ringwaldfirst steps, BTstack provides a (non) persistent store in memory. 500*503a627eSMilanka RingwaldFor more see [here](porting/#sec:persistentStoragePorting). 501*503a627eSMilanka Ringwald 502*503a627eSMilanka Ringwald<!-- --> 503*503a627eSMilanka Ringwald 504*503a627eSMilanka Ringwald btstack_link_key_db_t * link_key_db = &btstack_link_key_db_memory_instance(); 505*503a627eSMilanka Ringwald btstack_set_link_key_db(link_key_db); 506*503a627eSMilanka Ringwald 507*503a627eSMilanka Ringwald 508*503a627eSMilanka RingwaldThe higher layers only rely on BTstack and are initialized by calling 509*503a627eSMilanka Ringwaldthe respective *\*_init* function. These init functions register 510*503a627eSMilanka Ringwaldthemselves with the underlying layer. In addition, the application can 511*503a627eSMilanka Ringwaldregister packet handlers to get events and data as explained in the 512*503a627eSMilanka Ringwaldfollowing section. 513*503a627eSMilanka Ringwald 514*503a627eSMilanka Ringwald 515*503a627eSMilanka Ringwald## Services {#sec:servicesHowTo} 516*503a627eSMilanka Ringwald 517*503a627eSMilanka RingwaldOne important construct of BTstack is *service*. A service represents a 518*503a627eSMilanka Ringwaldserver side component that handles incoming connections. So far, BTstack 519*503a627eSMilanka Ringwaldprovides L2CAP, BNEP, and RFCOMM services. An L2CAP service handles incoming 520*503a627eSMilanka Ringwaldconnections for an L2CAP channel and is registered with its protocol 521*503a627eSMilanka Ringwaldservice multiplexer ID (PSM). Similarly, an RFCOMM service handles 522*503a627eSMilanka Ringwaldincoming RFCOMM connections and is registered with the RFCOMM channel 523*503a627eSMilanka RingwaldID. Outgoing connections require no special registration, they are 524*503a627eSMilanka Ringwaldcreated by the application when needed. 525*503a627eSMilanka Ringwald 526*503a627eSMilanka Ringwald 527*503a627eSMilanka Ringwald## Packet handlers configuration {#sec:packetHandlersHowTo} 528*503a627eSMilanka Ringwald 529*503a627eSMilanka Ringwald 530*503a627eSMilanka RingwaldAfter the hardware and BTstack are set up, the run loop is entered. From 531*503a627eSMilanka Ringwaldnow on everything is event driven. The application calls BTstack 532*503a627eSMilanka Ringwaldfunctions, which in turn may send commands to the Bluetooth module. The 533*503a627eSMilanka Ringwaldresulting events are delivered back to the application. Instead of 534*503a627eSMilanka Ringwaldwriting a single callback handler for each possible event (as it is done 535*503a627eSMilanka Ringwaldin some other Bluetooth stacks), BTstack groups events logically and 536*503a627eSMilanka Ringwaldprovides them over a single generic interface. Appendix 537*503a627eSMilanka Ringwald[Events and Errors](generated/appendix/#sec:eventsAndErrorsAppendix) 538*503a627eSMilanka Ringwaldsummarizes the parameters and event 539*503a627eSMilanka Ringwaldcodes of L2CAP and RFCOMM events, as well as possible errors and the 540*503a627eSMilanka Ringwaldcorresponding error codes. 541*503a627eSMilanka Ringwald 542*503a627eSMilanka RingwaldHere is summarized list of packet handlers that an application might 543*503a627eSMilanka Ringwalduse: 544*503a627eSMilanka Ringwald 545*503a627eSMilanka Ringwald- HCI event handler - allows to observer HCI, GAP, and general BTstack events. 546*503a627eSMilanka Ringwald 547*503a627eSMilanka Ringwald- L2CAP packet handler - handles LE Connection parameter requeset updates 548*503a627eSMilanka Ringwald 549*503a627eSMilanka Ringwald- L2CAP service packet handler - handles incoming L2CAP connections, 550*503a627eSMilanka Ringwald i.e., channels initiated by the remote. 551*503a627eSMilanka Ringwald 552*503a627eSMilanka Ringwald- L2CAP channel packet handler - handles outgoing L2CAP connections, 553*503a627eSMilanka Ringwald i.e., channels initiated internally. 554*503a627eSMilanka Ringwald 555*503a627eSMilanka Ringwald- RFCOMM service packet handler - handles incoming RFCOMM connections, 556*503a627eSMilanka Ringwald i.e., channels initiated by the remote. 557*503a627eSMilanka Ringwald 558*503a627eSMilanka Ringwald- RFCOMM channel packet handler - handles outgoing RFCOMM connections, 559*503a627eSMilanka Ringwald i.e., channels initiated internally. 560*503a627eSMilanka Ringwald 561*503a627eSMilanka RingwaldThese handlers are registered with the functions listed in Table 562*503a627eSMilanka Ringwald{@tbl:registeringFunction}. 563*503a627eSMilanka Ringwald 564*503a627eSMilanka Ringwald 565*503a627eSMilanka RingwaldPacket Handler | Registering Function 566*503a627eSMilanka Ringwald-------------------------------|-------------------------------------- 567*503a627eSMilanka RingwaldHCI packet handler | hci_add_event_handler 568*503a627eSMilanka RingwaldL2CAP packet handler | l2cap_register_packet_handler 569*503a627eSMilanka RingwaldL2CAP service packet handler | l2cap_register_service 570*503a627eSMilanka RingwaldL2CAP channel packet handler | l2cap_create_channel 571*503a627eSMilanka RingwaldRFCOMM service packet handler | rfcomm_register_service and rfcomm_register_service_with_initial_credits 572*503a627eSMilanka RingwaldRFCOMM channel packet handler | rfcomm_create_channel and rfcomm_create_channel_with_initial_credits 573*503a627eSMilanka Ringwald 574*503a627eSMilanka Ringwald 575*503a627eSMilanka RingwaldTable: Functions for registering packet handlers. {#tbl:registeringFunction} 576*503a627eSMilanka Ringwald 577*503a627eSMilanka RingwaldHCI, GAP, and general BTstack events are delivered to the packet handler 578*503a627eSMilanka Ringwaldspecified by *hci_add_event_handler* function. In L2CAP, 579*503a627eSMilanka RingwaldBTstack discriminates incoming and outgoing connections, i.e., event and 580*503a627eSMilanka Ringwalddata packets are delivered to different packet handlers. Outgoing 581*503a627eSMilanka Ringwaldconnections are used access remote services, incoming connections are 582*503a627eSMilanka Ringwaldused to provide services. For incoming connections, the packet handler 583*503a627eSMilanka Ringwaldspecified by *l2cap_register_service* is used. For outgoing 584*503a627eSMilanka Ringwaldconnections, the handler provided by *l2cap_create_channel* 585*503a627eSMilanka Ringwaldis used. RFCOMM and BNEP are similar. 586*503a627eSMilanka Ringwald 587*503a627eSMilanka RingwaldThe application can register a single shared packet handler for all 588*503a627eSMilanka Ringwaldprotocols and services, or use separate packet handlers for each 589*503a627eSMilanka Ringwaldprotocol layer and service. A shared packet handler is often used for 590*503a627eSMilanka Ringwaldstack initialization and connection management. 591*503a627eSMilanka Ringwald 592*503a627eSMilanka RingwaldSeparate packet handlers can be used for each L2CAP service and outgoing 593*503a627eSMilanka Ringwaldconnection. For example, to connect with a Bluetooth HID keyboard, your 594*503a627eSMilanka Ringwaldapplication could use three packet handlers: one to handle HCI events 595*503a627eSMilanka Ringwaldduring discovery of a keyboard registered by 596*503a627eSMilanka Ringwald*l2cap_register_packet_handler*; one that will be registered to an 597*503a627eSMilanka Ringwaldoutgoing L2CAP channel to connect to keyboard and to receive keyboard 598*503a627eSMilanka Ringwalddata registered by *l2cap_create_channel*; after that 599*503a627eSMilanka Ringwaldkeyboard can reconnect by itself. For this, you need to register L2CAP 600*503a627eSMilanka Ringwaldservices for the HID Control and HID Interrupt PSMs using 601*503a627eSMilanka Ringwald*l2cap_register_service*. In this call, you’ll also specify 602*503a627eSMilanka Ringwalda packet handler to accept and receive keyboard data. 603*503a627eSMilanka Ringwald 604*503a627eSMilanka RingwaldAll events names have the form MODULE_EVENT_NAME now, e.g., *gap_event_-advertising_report*. 605*503a627eSMilanka RingwaldTo facilitate working with 606*503a627eSMilanka Ringwaldevents and get rid of manually calculating offsets into packets, BTstack provides 607*503a627eSMilanka Ringwaldauto-generated getters for all fields of all events in *src/hci_event.h*. All 608*503a627eSMilanka Ringwaldfunctions are defined as static inline, so they are not wasting any program memory 609*503a627eSMilanka Ringwaldif not used. If used, the memory footprint should be identical to accessing the 610*503a627eSMilanka Ringwaldfield directly via offsets into the packet. For example, to access fields address_type 611*503a627eSMilanka Ringwaldand address from the *gap_event_advertising_report* event use following getters: 612*503a627eSMilanka Ringwald 613*503a627eSMilanka Ringwald<!-- --> 614*503a627eSMilanka Ringwald uint8_t address type = gap_event_advertising_report_get_address_type(event); 615*503a627eSMilanka Ringwald bd_addr_t address; 616*503a627eSMilanka Ringwald gap_event_advertising_report_get_address(event, address); 617*503a627eSMilanka Ringwald 618*503a627eSMilanka Ringwald 619*503a627eSMilanka Ringwald## Bluetooth HCI Packet Logs {#sec:packetlogsHowTo} 620*503a627eSMilanka Ringwald 621*503a627eSMilanka RingwaldIf things don't work as expected, having a look at the data exchanged 622*503a627eSMilanka Ringwaldbetween BTstack and the Bluetooth chipset often helps. 623*503a627eSMilanka Ringwald 624*503a627eSMilanka RingwaldFor this, BTstack provides a configurable packet logging mechanism via hci_dump.h: 625*503a627eSMilanka Ringwald 626*503a627eSMilanka Ringwald void hci_dump_init(const hci_dump_t * hci_dump_implementation); 627*503a627eSMilanka Ringwald 628*503a627eSMilanka RingwaldOn POSIX systems, you can call *hci_dump_init* with a *hci_dump_posix_fs_get_instance()* and 629*503a627eSMilanka Ringwaldconfigure the path and output format with *hci_dump_posix_fs_open(const char * path, hci_dump_format_t format)* 630*503a627eSMilanka Ringwaldwhere format can be *HCI_DUMP_BLUEZ* or *HCI_DUMP_PACKETLOGGER*. 631*503a627eSMilanka RingwaldThe resulting file can be analyzed with Wireshark or the Apple's PacketLogger tool. 632*503a627eSMilanka Ringwald 633*503a627eSMilanka RingwaldOn embedded systems without a file system, you either log to an UART console via printf or use SEGGER RTT. 634*503a627eSMilanka RingwaldFor printf output you pass *hci_dump_embedded_stdout_get_instance()* to *hci_dump_init()*. 635*503a627eSMilanka RingwaldWith RTT, you can choose between textual output similar to printf, and binary output. 636*503a627eSMilanka RingwaldFor textual output, you can provide the *hci_dump_segger_stdout_get_instance()*. 637*503a627eSMilanka Ringwald 638*503a627eSMilanka RingwaldIt will log all HCI packets to the UART console via printf or RTT Terminal. 639*503a627eSMilanka RingwaldIf you capture the console output, incl. your own debug messages, you can use 640*503a627eSMilanka Ringwaldthe create_packet_log.py tool in the tools folder to convert a text output into a 641*503a627eSMilanka RingwaldPacketLogger file. 642*503a627eSMilanka Ringwald 643*503a627eSMilanka RingwaldFor less overhead and higher logging speed, you can directly log in binary format by 644*503a627eSMilanka Ringwaldpassing *hci_dump_segger_rtt_binary_get_instance()* and selecting the output format by 645*503a627eSMilanka Ringwaldcalling *hci_dump_segger_rtt_binary_open(hci_dump_format_t format)* with the same format as above. 646*503a627eSMilanka Ringwald 647*503a627eSMilanka Ringwald 648*503a627eSMilanka RingwaldIn addition to the HCI packets, you can also enable BTstack's debug information by adding 649*503a627eSMilanka Ringwald 650*503a627eSMilanka Ringwald #define ENABLE_LOG_INFO 651*503a627eSMilanka Ringwald #define ENABLE_LOG_ERROR 652*503a627eSMilanka Ringwald 653*503a627eSMilanka Ringwaldto the btstack_config.h and recompiling your application. 654*503a627eSMilanka Ringwald 655*503a627eSMilanka Ringwald## Bluetooth Power Control {#sec:powerControl} 656*503a627eSMilanka Ringwald 657*503a627eSMilanka 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. 658*503a627eSMilanka 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. 659*503a627eSMilanka Ringwald 660*503a627eSMilanka RingwaldTo enable/disable discoverability, you can call: 661*503a627eSMilanka Ringwald 662*503a627eSMilanka Ringwald /** 663*503a627eSMilanka Ringwald * @brief Allows to control if device is discoverable. OFF by default. 664*503a627eSMilanka Ringwald */ 665*503a627eSMilanka Ringwald void gap_discoverable_control(uint8_t enable); 666*503a627eSMilanka Ringwald 667*503a627eSMilanka 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. 668*503a627eSMilanka Ringwald 669*503a627eSMilanka RingwaldTo enable/disable connectability, you can call: 670*503a627eSMilanka Ringwald 671*503a627eSMilanka Ringwald /** 672*503a627eSMilanka Ringwald * @brief Override page scan mode. Page scan mode enabled by l2cap when services are registered 673*503a627eSMilanka Ringwald * @note Might be used to reduce power consumption while Bluetooth module stays powered but no (new) 674*503a627eSMilanka Ringwald * connections are expected 675*503a627eSMilanka Ringwald */ 676*503a627eSMilanka Ringwald void gap_connectable_control(uint8_t enable); 677*503a627eSMilanka Ringwald 678*503a627eSMilanka RingwaldFor Bluetooth Low Energy, the radio is periodically used to broadcast advertisements that are used for both discovery and connection establishment. 679*503a627eSMilanka Ringwald 680*503a627eSMilanka RingwaldTo enable/disable advertisements, you can call: 681*503a627eSMilanka Ringwald 682*503a627eSMilanka Ringwald /** 683*503a627eSMilanka Ringwald * @brief Enable/Disable Advertisements. OFF by default. 684*503a627eSMilanka Ringwald * @param enabled 685*503a627eSMilanka Ringwald */ 686*503a627eSMilanka Ringwald void gap_advertisements_enable(int enabled); 687*503a627eSMilanka Ringwald 688*503a627eSMilanka 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. 689*503a627eSMilanka Ringwald 690*503a627eSMilanka 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: 691*503a627eSMilanka Ringwald 692*503a627eSMilanka Ringwald /** 693*503a627eSMilanka Ringwald * @brief Requests the change of BTstack power mode. 694*503a627eSMilanka Ringwald */ 695*503a627eSMilanka Ringwald int hci_power_control(HCI_POWER_MODE mode); 696*503a627eSMilanka Ringwald 697*503a627eSMilanka 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. 698