xref: /btstack/doc/manual/docs-template/protocols.md (revision fe6fb8a2a85b6f18ce013e04580e9909194bffdf)
1#
2
3BTstack is a modular dual-mode Bluetooth stack, supporting both
4Bluetooth Basic Rate/Enhanced Date Rate (BR/EDR) as well as Bluetooth
5Low Energy (LE). The BR/EDR technology, also known as Classic Bluetooth,
6provides a robust wireless connection between devices designed for high
7data rates. In contrast, the LE technology has a lower throughput but
8also lower energy consumption, faster connection setup, and the ability
9to connect to more devices in parallel.
10
11Whether Classic or LE, a Bluetooth device implements one or more
12Bluetooth profiles. A Bluetooth profile specifies how one or more
13Bluetooth protocols are used to achieve its goals. For example, every
14Bluetooth device must implement the Generic Access Profile (GAP), which
15defines how devices find each other and how they establish a connection.
16This profile mainly make use of the Host Controller Interface (HCI)
17protocol, the lowest protocol in the stack hierarchy which implements a
18command interface to the Bluetooth chipset.
19
20In addition to GAP, a popular Classic Bluetooth example would be a
21peripheral devices that can be connected via the Serial Port Profile
22(SPP). SPP basically specifies that a compatible device should provide a
23Service Discovery Protocol (SDP) record containing an RFCOMM channel
24number, which will be used for the actual communication.
25
26Similarly, for every LE device, the Generic Attribute Profile (GATT)
27profile must be implemented in addition to GAP. GATT is built on top of
28the Attribute Protocol (ATT), and defines how one device can interact
29with GATT Services on a remote device.
30
31So far, the most popular use of BTstack is in peripheral devices that
32can be connected via SPP (Android 2.0 or higher) and GATT (Android 4.3
33or higher, and iOS 5 or higher). If higher data rates are required
34between a peripheral and iOS device, the iAP1 and iAP2 protocols of the
35Made for iPhone program can be used instead of GATT. Please contact us
36directly for information on BTstack and MFi.
37
38Figure {@fig:BTstackProtocolArchitecture} depicts Bluetooth protocols
39and profiles that are currently implemented by BTstack.
40In the following, we first explain how the various Bluetooth protocols
41are used in BTstack. In the next chapter, we go over the profiles.
42
43![Architecture of a BTstack-based application.](picts/btstack-protocols.png) {#fig:BTstackProtocolArchitecture}
44
45
46## HCI - Host Controller Interface
47
48The HCI protocol provides a command interface to the Bluetooth chipset.
49In BTstack, the HCI implementation also keeps track of all active
50connections and handles the fragmentation and re-assembly of higher
51layer (L2CAP) packets.
52
53Please note, that an application rarely has to send HCI commands on its
54own. Instead, BTstack provides convenience functions in GAP and higher
55level protocols that use HCI automatically. E.g. to set the name, you
56call *gap_set_local_name()* before powering up. The main use of HCI
57commands in application is during the startup phase to configure special
58features that are not available via the GAP API yet. How to send a
59custom HCI command is explained in the following section.
60
61### Defining custom HCI command templates
62
63Each HCI command is assigned a 2-byte OpCode used to uniquely identify
64different types of commands. The OpCode parameter is divided into two
65fields, called the OpCode Group Field (OGF) and OpCode Command Field
66(OCF), see [Bluetooth Specification](https://www.bluetooth.org/Technical/Specifications/adopted.htm) -
67Core Version 4.0, Volume 2, Part E, Chapter 5.4.
68
69Listing [below](#lst:hciOGFs) shows the OGFs provided by BTstack in file [src/hci.h](GITHUB_URL/src/hci.h):
70
71~~~~ {#lst:hciOGFs .c caption="{HCI OGFs provided by BTstack.}"}
72
73    #define OGF_LINK_CONTROL  0x01
74    #define OGF_LINK_POLICY  0x02
75    #define OGF_CONTROLLER_BASEBAND  0x03
76    #define OGF_INFORMATIONAL_PARAMETERS 0x04
77    #define OGF_LE_CONTROLLER   0x08
78    #define OGF_BTSTACK  0x3d
79    #define OGF_VENDOR  0x3f
80~~~~
81
82For all existing Bluetooth
83commands and their OCFs see [Bluetooth Specification](https://www.bluetooth.org/Technical/Specifications/adopted.htm) -
84Core Version 4.0, Volume 2, Part E, Chapter 7.
85
86In a HCI command packet, the OpCode is followed by parameter total
87length, and the actual parameters. The OpCode of a command can be
88calculated using the OPCODE macro. BTstack provides the *hci_cmd_t*
89struct as a compact format to define HCI command packets, see
90Listing [below](#lst:HCIcmdTemplate), and [src/hci_cmd.h](GITHUB_URL/src/hci_cmd.h)
91file in the source code.
92
93~~~~ {#lst:HCIcmdTemplate .c caption="{HCI command struct.}"}
94
95    // Calculate combined ogf/ocf value.
96    #define OPCODE(ogf, ocf) (ocf | ogf << 10)
97
98    // Compact HCI Command packet description.
99    typedef struct {
100        uint16_t    opcode;
101        const char *format;
102    } hci_cmd_t;
103~~~~
104
105Listing [below](#lst:HCIcmdExample) illustrates the *hci_write_local_name* HCI
106command template from library:
107
108~~~~ {#lst:HCIcmdExample .c caption="{HCI command example.}"}
109
110    // Sets local Bluetooth name
111    const hci_cmd_t hci_write_local_name = {
112        OPCODE(OGF_CONTROLLER_BASEBAND, 0x13), "N"
113        // Local name (UTF-8, Null Terminated, max 248 octets)
114    };
115~~~~
116
117It uses OGF_CONTROLLER_BASEBAND as OGF,
1180x13 as OCF, and has one parameter with format “N” indicating a null
119terminated UTF-8 string. Table {@tbl:hciCmdParamSpecifier} lists the format
120specifiers supported by BTstack. Check for other predefined HCI commands
121and info on their parameters.
122
123  ------------------- ----------------------------------------------------
124   Format Specifier   Description
125        1,2,3,4       one to four byte value
126           A          31 bytes advertising data
127           B          Bluetooth Baseband Address
128           D          8 byte data block
129           E          Extended Inquiry Information 240 octets
130           H          HCI connection handle
131           N          Name up to 248 chars, UTF8 string, null terminated
132           P          16 byte Pairing code, e.g. PIN code or link key
133           S          Service Record (Data Element Sequence)
134  ------------------- ----------------------------------------------------
135
136Table: Supported Format Specifiers of HCI Command Parameter. {#tbl:hciCmdParamSpecifier}
137
138
139### Sending HCI command based on a template {#sec:sendingHCIProtocols}
140
141You can use the *hci_send_cmd* function to send HCI command based on a
142template and a list of parameters. However, it is necessary to check
143that the outgoing packet buffer is empty and that the Bluetooth module
144is ready to receive the next command - most modern Bluetooth modules
145only allow to send a single HCI command. This can be done by calling
146*hci_can_send_command_packet_now()* function, which returns true,
147if it is ok to send.
148
149Listing [below](#lst:HCIcmdExampleLocalName) illustrates how to manually set the
150device name with the HCI Write Local Name command.
151
152~~~~ {#lst:HCIcmdExampleLocalName .c caption="{Sending HCI command example.}"}
153
154    if (hci_can_send_command_packet_now()){
155        hci_send_cmd(&hci_write_local_name, "BTstack Demo");
156    }
157~~~~
158
159Please note, that an application rarely has to send HCI commands on its
160own. Instead, BTstack provides convenience functions in GAP and higher
161level protocols that use HCI automatically.
162
163
164## L2CAP - Logical Link Control and Adaptation Protocol
165
166
167The L2CAP protocol supports higher level protocol multiplexing and
168packet fragmentation. It provides the base for the RFCOMM and BNEP
169protocols. For all profiles that are officially supported by BTstack,
170L2CAP does not need to be used directly. For testing or the development
171of custom protocols, it’s helpful to be able to access and provide L2CAP
172services however.
173
174### Access an L2CAP service on a remote device
175
176L2CAP is based around the concept of channels. A channel is a logical
177connection on top of a baseband connection. Each channel is bound to a
178single protocol in a many-to-one fashion. Multiple channels can be bound
179to the same protocol, but a channel cannot be bound to multiple
180protocols. Multiple channels can share the same baseband connection.
181
182To communicate with an L2CAP service on a remote device, the application
183on a local Bluetooth device initiates the L2CAP layer using the
184*l2cap_init* function, and then creates an outgoing L2CAP channel to
185the PSM of a remote device using the *l2cap_create_channel*
186function. The *l2cap_create_channel* function will initiate
187a new baseband connection if it does not already exist. The packet
188handler that is given as an input parameter of the L2CAP create channel
189function will be assigned to the new outgoing L2CAP channel. This
190handler receives the L2CAP_EVENT_CHANNEL_OPENED and
191L2CAP_EVENT_CHANNEL_CLOSED events and L2CAP data packets, as shown
192in Listing [below](#lst:L2CAPremoteService).
193
194
195~~~~ {#lst:L2CAPremoteService .c caption="{Accessing an L2CAP service on a remote device.}"}
196
197    btstack_packet_handler_t l2cap_packet_handler;
198
199    void l2cap_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
200        bd_addr_t event_addr;
201        switch (packet_type){
202            case HCI_EVENT_PACKET:
203                switch (hci_event_packet_get_type(packet)){
204                    case L2CAP_EVENT_CHANNEL_OPENED:
205                        l2cap_event_channel_opened_get_address(packet, &event_addr);
206                        psm       = l2cap_event_channel_opened_get_psm(packet);
207                        local_cid = l2cap_event_channel_opened_get_local_cid(packet);
208                        handle    = l2cap_event_channel_opened_get_handle(packet);
209                        if (l2cap_event_channel_opened_get_status(packet)) {
210                            printf("Connection failed\n\r");
211                        } else
212                            printf("Connected\n\r");
213                        }
214                        break;
215                    case L2CAP_EVENT_CHANNEL_CLOSED:
216                        break;
217                        ...
218                }
219            case L2CAP_DATA_PACKET:
220                // handle L2CAP data packet
221                break;
222            ...
223        }
224    }
225
226    void create_outgoing_l2cap_channel(bd_addr_t address, uint16_t psm, uint16_t mtu){
227         l2cap_create_channel(NULL, l2cap_packet_handler, remote_bd_addr, psm, mtu);
228    }
229
230    void btstack_setup(){
231        ...
232        l2cap_init();
233    }
234
235~~~~
236
237### Provide an L2CAP service
238
239To provide an L2CAP service, the application on a local Bluetooth device
240must init the L2CAP layer and register the service with
241*l2cap_register_service*. From there on, it can wait for
242incoming L2CAP connections. The application can accept or deny an
243incoming connection by calling the *l2cap_accept_connection*
244and *l2cap_deny_connection* functions respectively.
245
246If a connection is accepted and the incoming L2CAP channel gets successfully
247opened, the L2CAP service can send and receive L2CAP data packets to the connected
248device with *l2cap_send*.
249
250Listing [below](#lst:L2CAPService)
251provides L2CAP service example code.
252
253~~~~ {#lst:L2CAPService .c caption="{Providing an L2CAP service.}"}
254
255    void packet_handler (uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
256        bd_addr_t event_addr;
257        switch (packet_type){
258            case HCI_EVENT_PACKET:
259                switch (hci_event_packet_get_type(packet)){
260                    case L2CAP_EVENT_INCOMING_CONNECTION:
261                        local_cid = l2cap_event_incoming_connection_get_local_cid(packet);
262                        l2cap_accept_connection(local_cid);
263                        break;
264                    case L2CAP_EVENT_CHANNEL_OPENED:
265                        l2cap_event_channel_opened_get_address(packet, &event_addr);
266                        psm       = l2cap_event_channel_opened_get_psm(packet);
267                        local_cid = l2cap_event_channel_opened_get_local_cid(packet);
268                        handle    = l2cap_event_channel_opened_get_handle(packet);
269                        if (l2cap_event_channel_opened_get_status(packet)) {
270                            printf("Connection failed\n\r");
271                        } else
272                            printf("Connected\n\r");
273                        }
274                        break;
275                    case L2CAP_EVENT_CHANNEL_CLOSED:
276                        break;
277                        ...
278                }
279            case L2CAP_DATA_PACKET:
280                // handle L2CAP data packet
281                break;
282            ...
283        }
284    }
285
286    void btstack_setup(){
287        ...
288        l2cap_init();
289        l2cap_register_service(NULL, packet_handler, 0x11,100);
290    }
291
292~~~~
293
294### Sending L2CAP Data {#sec:l2capSendProtocols}
295
296Sending of L2CAP data packets may fail due to a full internal BTstack
297outgoing packet buffer, or if the ACL buffers in the Bluetooth module
298become full, i.e., if the application is sending faster than the packets
299can be transferred over the air.
300
301Instead of directly calling *l2cap_send*, it is recommended to call
302*l2cap_request_can_send_now_event(cahnnel_id)* which will trigger an L2CAP_EVENT_CAN_SEND_NOW
303as soon as possible. It might happen that the event is received via
304packet handler before the *l2cap_request_can_send_now_event* function returns.
305The L2CAP_EVENT_CAN_SEND_NOW indicates a channel ID on which sending is possible.
306
307Please note that the guarantee that a packet can be sent is only valid when the event is received.
308After returning from the packet handler, BTstack might need to send itself.
309
310### LE Data Channels
311
312The full title for LE Data Channels is actually LE Connection-Oriented Channels with LE Credit-Based Flow-Control Mode. In this mode, data is sent as Service Data Units (SDUs) that can be larger than an individual HCI LE ACL packet.
313
314LE Data Channels are similar to Classic L2CAP Channels but also provide a credit-based flow control similar to RFCOMM Channels.
315Unless the LE Data Packet Extension of Bluetooth Core 4.2 specification is used, the maximum packet size for LE ACL packets is 27 bytes. In order to send larger packets, each packet will be split into multiple ACL LE packets and recombined on the receiving side.
316
317Since multiple SDUs can be transmitted at the same time and the individual ACL LE packets can be sent interleaved, BTstack requires a dedicated receive buffer per channel that has to be passed when creating the channel or accepting it. Similarly, when sending SDUs, the data provided to the *l2cap_cbm_send_data* must stay valid until the *L2CAP_EVENT_LE_PACKET_SENT* is received.
318
319When creating an outgoing connection of accepting an incoming, the *initial_credits* allows to provide a fixed number of credits to the remote side. Further credits can be provided anytime with *l2cap_cbm_provide_credits*. If *L2CAP_LE_AUTOMATIC_CREDITS* is used, BTstack automatically provides credits as needed - effectively trading in the flow-control functionality for convenience.
320
321The remainder of the API is similar to the one of L2CAP:
322
323  * *l2cap_cbm_register_service* and *l2cap_cbm_unregister_service* are used to manage local services.
324  * *l2cap_cbm_accept_connection* and *l2cap_cbm_decline_connection* are used to accept or deny an incoming connection request.
325  * *l2cap_cbm_create_channel* creates an outgoing connections.
326  * *l2cap_cbm_can_send_now* checks if a packet can be scheduled for transmission now.
327  * *l2cap_cbm_request_can_send_now_event* requests an *L2CAP_EVENT_LE_CAN_SEND_NOW* event as soon as possible.
328  * *l2cap_cbm_disconnect* closes the connection.
329
330## RFCOMM - Radio Frequency Communication Protocol
331
332The Radio frequency communication (RFCOMM) protocol provides emulation
333of serial ports over the L2CAP protocol and reassembly. It is the base
334for the Serial Port Profile and other profiles used for
335telecommunication like Head-Set Profile, Hands-Free Profile, Object
336Exchange (OBEX) etc.
337
338### No RFCOMM packet boundaries {#sec:noRfcommPacketBoundaries}
339
340As RFCOMM emulates a serial port, it does not preserve packet boundaries.
341
342On most operating systems, RFCOMM/SPP will be modeled as a pipe that allows
343to write a block of bytes. The OS and the Bluetooth Stack are free to buffer
344and chunk this data in any way it seems fit. In your BTstack application, you will
345therefore receive this data in the same order, but there are no guarantees as
346how it might be fragmented into multiple chunks.
347
348If you need to preserve the concept of sending a packet with a specific size
349over RFCOMM, the simplest way is to prefix the data with a 2 or 4 byte length field
350and then reconstruct the packet on the receiving side.
351
352Please note, that due to BTstack's 'no buffers' policy, BTstack will send outgoing RFCOMM data immediately
353and implicitly preserve the packet boundaries, i.e., it will send the data as a single
354RFCOMM packet in a single L2CAP packet, which will arrive in one piece.
355While this will hold between two BTstack instances, it's not a good idea to rely on implementation details
356and rather prefix the data as described.
357
358### RFCOMM flow control {#sec:flowControlProtocols}
359
360RFCOMM has a mandatory credit-based flow-control. This means that two
361devices that established RFCOMM connection, use credits to keep track of
362how many more RFCOMM data packets can be sent to each. If a device has
363no (outgoing) credits left, it cannot send another RFCOMM packet, the
364transmission must be paused. During the connection establishment,
365initial credits are provided. BTstack tracks the number of credits in
366both directions. If no outgoing credits are available, the RFCOMM send
367function will return an error, and you can try later. For incoming data,
368BTstack provides channels and services with and without automatic credit
369management via different functions to create/register them respectively.
370If the management of credits is automatic, the new credits are provided
371when needed relying on ACL flow control - this is only useful if there
372is not much data transmitted and/or only one physical connection is
373used. If the management of credits is manual, credits are provided by
374the application such that it can manage its receive buffers explicitly.
375
376
377### Access an RFCOMM service on a remote device {#sec:rfcommClientProtocols}
378
379To communicate with an RFCOMM service on a remote device, the
380application on a local Bluetooth device initiates the RFCOMM layer using
381the *rfcomm_init* function, and then creates an outgoing RFCOMM channel
382to a given server channel on a remote device using the
383*rfcomm_create_channel* function. The
384*rfcomm_create_channel* function will initiate a new L2CAP
385connection for the RFCOMM multiplexer, if it does not already exist. The
386channel will automatically provide enough credits to the remote side. To
387provide credits manually, you have to create the RFCOMM connection by
388calling *rfcomm_create_channel_with_initial_credits* -
389see Section [on manual credit assignement](#sec:manualCreditsProtocols).
390
391The packet handler that is given as an input parameter of the RFCOMM
392create channel function will be assigned to the new outgoing channel.
393This handler receives the RFCOMM_EVENT_CHANNEL_OPENED and
394RFCOMM_EVENT_CHANNEL_CLOSED events, and RFCOMM data packets, as shown in
395Listing [below](#lst:RFCOMMremoteService).
396
397
398~~~~ {#lst:RFCOMMremoteService .c caption="{RFCOMM handler for outgoing RFCOMM channel.}"}
399
400    void rfcomm_packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
401        switch (packet_type){
402            case HCI_EVENT_PACKET:
403                switch (hci_event_packet_get_type(packet)){
404                    case RFCOMM_EVENT_CHANNEL_OPENED:
405                        if (rfcomm_event_open_channel_complete_get_status(packet)) {
406                            printf("Connection failed\n\r");
407                        } else {
408                            printf("Connected\n\r");
409                        }
410                        break;
411                    case RFCOMM_EVENT_CHANNEL_CLOSED:
412                        break;
413                    ...
414                }
415                break;
416            case RFCOMM_DATA_PACKET:
417                // handle RFCOMM data packets
418                return;
419        }
420    }
421
422    void create_rfcomm_channel(uint8_t packet_type, uint8_t *packet, uint16_t size){
423        rfcomm_create_channel(rfcomm_packet_handler, addr, rfcomm_channel);
424    }
425
426    void btstack_setup(){
427        ...
428        l2cap_init();
429        rfcomm_init();
430    }
431
432
433~~~~
434
435The RFCOMM channel will stay open until either side closes it with rfcomm_disconnect.
436BTstack will close the multiplexer after 60 seconds without an active RFCOMM channel.
437
438### Provide an RFCOMM service {#sec:rfcommServiceProtocols}
439
440To provide an RFCOMM service, the application on a local Bluetooth
441device must first init the L2CAP and RFCOMM layers and then register the
442service with *rfcomm_register_service*. From there on, it
443can wait for incoming RFCOMM connections. The application can accept or
444deny an incoming connection by calling the
445*rfcomm_accept_connection* and *rfcomm_deny_connection* functions respectively.
446If a connection is accepted and the incoming RFCOMM channel gets successfully
447opened, the RFCOMM service can send RFCOMM data packets to the connected
448device with *rfcomm_send* and receive data packets by the
449packet handler provided by the *rfcomm_register_service*
450call.
451
452Listing [below](#lst:RFCOMMService) provides the RFCOMM service example code.
453
454~~~~ {#lst:RFCOMMService .c caption="{Providing an RFCOMM service.}"}
455
456    void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
457        switch (packet_type){
458            case HCI_EVENT_PACKET:
459                switch (hci_event_packet_get_type(packet)){
460                    case RFCOMM_EVENT_INCOMING_CONNECTION:
461                        rfcomm_channel_id = rfcomm_event_incoming_connection_get_rfcomm_cid(packet);
462                        rfcomm_accept_connection(rfcomm_channel_id);
463                        break;
464                    case RFCOMM_EVENT_CHANNEL_OPENED:
465                        if (rfcomm_event_open_channel_complete_get_status(packet)){
466                            printf("RFCOMM channel open failed.");
467                            break;
468                        }
469                        rfcomm_channel_id = rfcomm_event_open_channel_complete_get_rfcomm_cid(packet);
470                        mtu = rfcomm_event_open_channel_complete_get_max_frame_size(packet);
471                        printf("RFCOMM channel open succeeded, max frame size %u.", mtu);
472                        break;
473                    case RFCOMM_EVENT_CHANNEL_CLOSED:
474                        printf("Channel closed.");
475                        break;
476                    ...
477                }
478                break;
479            case RFCOMM_DATA_PACKET:
480                // handle RFCOMM data packets
481                return;
482            ...
483        }
484        ...
485    }
486
487    void btstack_setup(){
488        ...
489        l2cap_init();
490        rfcomm_init();
491        rfcomm_register_service(packet_handler, rfcomm_channel_nr, mtu);
492    }
493
494~~~~
495
496### Slowing down RFCOMM data reception {#sec:manualCreditsProtocols}
497
498RFCOMM’s credit-based flow-control can be used to adapt, i.e., slow down
499the RFCOMM data to your processing speed. For incoming data, BTstack
500provides channels and services with and without automatic credit
501management. If the management of credits is automatic, new credits
502are provided when needed relying on ACL flow control. This is only
503useful if there is not much data transmitted and/or only one physical
504connection is used. See Listing [below](#lst:automaticFlowControl).
505
506~~~~ {#lst:automaticFlowControl .c caption="{RFCOMM service with automatic credit management.}"}
507    void btstack_setup(void){
508        ...
509        // init RFCOMM
510        rfcomm_init();
511        rfcomm_register_service(packet_handler, rfcomm_channel_nr, 100);
512    }
513~~~~
514
515If the management of credits is manual, credits are provided by the
516application such that it can manage its receive buffers explicitly, see
517Listing [below](#lst:explicitFlowControl).
518
519Manual credit management is recommended when received RFCOMM data cannot
520be processed immediately. In the [SPP flow control example](../examples/examples/#sec:sppflowcontrolExample),
521delayed processing of received data is
522simulated with the help of a periodic timer. To provide new credits, you
523call the *rfcomm_grant_credits* function with the RFCOMM channel ID
524and the number of credits as shown in Listing [below](#lst:NewCredits).
525
526~~~~ {#lst:explicitFlowControl .c caption="{RFCOMM service with manual credit management.}"}
527    void btstack_setup(void){
528        ...
529        // init RFCOMM
530        rfcomm_init();
531        // reserved channel, mtu=100, 1 credit
532        rfcomm_register_service_with_initial_credits(packet_handler, rfcomm_channel_nr, 100, 1);
533    }
534~~~~
535
536~~~~ {#lst:NewCredits .c caption="{Granting RFCOMM credits.}"}
537    void processing(){
538        // process incoming data packet
539        ...
540        // provide new credit
541        rfcomm_grant_credits(rfcomm_channel_id, 1);
542    }
543~~~~
544
545Please note that providing single credits effectively reduces the credit-based
546(sliding window) flow control to a stop-and-wait flow-control that
547limits the data throughput substantially. On the plus side, it allows
548for a minimal memory footprint. If possible, multiple RFCOMM buffers
549should be used to avoid pauses while the sender has to wait for a new
550credit.
551
552### Sending RFCOMM data {#sec:rfcommSendProtocols}
553
554Outgoing packets, both commands and data, are not queued in BTstack.
555This section explains the consequences of this design decision for
556sending data and why it is not as bad as it sounds.
557
558Independent from the number of output buffers, packet generation has to
559be adapted to the remote receiver and/or maximal link speed. Therefore,
560a packet can only be generated when it can get sent. With this
561assumption, the single output buffer design does not impose additional
562restrictions. In the following, we show how this is used for adapting
563the RFCOMM send rate.
564
565When there is a need to send a packet, call *rcomm_request_can_send_now*
566and wait for the reception of the RFCOMM_EVENT_CAN_SEND_NOW event
567to send the packet, as shown in Listing [below](#lst:rfcommRequestCanSendNow).
568
569Please note that the guarantee that a packet can be sent is only valid when the event is received.
570After returning from the packet handler, BTstack might need to send itself.
571
572~~~~ {#lst:rfcommRequestCanSendNow .c caption="{Preparing and sending data.}"}
573    void prepare_data(uint16_t rfcomm_channel_id){
574        ...
575        // prepare data in data_buffer
576        rfcomm_request_can_send_now_event(rfcomm_channel_id);
577    }
578
579    void send_data(uint16_t rfcomm_channel_id){
580        rfcomm_send(rfcomm_channel_id,  data_buffer, data_len);
581        // packet is handed over to BTstack, we can prepare the next one
582        prepare_data(rfcomm_channel_id);
583    }
584
585    void packet_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
586        switch (packet_type){
587            case HCI_EVENT_PACKET:
588                switch (hci_event_packet_get_type(packet)){
589                    ...
590                    case RFCOMM_EVENT_CAN_SEND_NOW:
591                        rfcomm_channel_id = rfcomm_event_can_send_now_get_rfcomm_cid(packet);
592                        send_data(rfcomm_channel_id);
593                        break;
594                    ...
595                }
596                ...
597            }
598        }
599    }
600
601~~~~
602
603### Optimized sending of RFCOMM data
604
605When sending RFCOMM data via *rfcomm_send*, BTstack needs to copy the data
606from the user provided buffer into the outgoing buffer. This requires both
607an additional buffer for the user data as well requires a copy operation.
608
609To avoid this, it is possible to directly write the user data into the outgoing buffer.
610
611When get the RFCOMM_CAN_SEND_NOW event, you call *rfcomm_reserve_packet_buffer* to
612lock the buffer for your send operation. Then, you can ask how many bytes you can send
613with *rfcomm_get_max_frame_size* and get a pointer to BTstack's buffer with
614*rfcomm_get_outgoing_buffer*. Now, you can fill that buffer and finally send the
615data with *rfcomm_send_prepared*.
616
617
618## SDP - Service Discovery Protocol
619
620The SDP protocol allows to announce services and discover services
621provided by a remote Bluetooth device.
622
623### Create and announce SDP records
624
625BTstack contains a complete SDP server and allows to register SDP
626records. An SDP record is a list of SDP Attribute *{ID, Value}* pairs
627that are stored in a Data Element Sequence (DES). The Attribute ID is a
62816-bit number, the value can be of other simple types like integers or
629strings or can itself contain other DES.
630
631To create an SDP record for an SPP service, you can call
632*spp_create_sdp_record* from with a pointer to a buffer to store the
633record, the server channel number, and a record name.
634
635For other types of records, you can use the other functions in, using
636the data element *de_* functions. Listing [sdpCreate] shows how an SDP
637record containing two SDP attributes can be created. First, a DES is
638created and then the Service Record Handle and Service Class ID List
639attributes are added to it. The Service Record Handle attribute is added
640by calling the *de_add_number* function twice: the first time to add
6410x0000 as attribute ID, and the second time to add the actual record
642handle (here 0x1000) as attribute value. The Service Class ID List
643attribute has ID 0x0001, and it requires a list of UUIDs as attribute
644value. To create the list, *de_push_sequence* is called, which “opens”
645a sub-DES. The returned pointer is used to add elements to this sub-DES.
646After adding all UUIDs, the sub-DES is “closed” with
647*de_pop_sequence*.
648
649To register an SDP record, you call *sdp_register_service* with a pointer to it.
650The SDP record can be stored in FLASH since BTstack only stores the pointer.
651Please note that the buffer needs to persist (e.g. global storage, dynamically
652allocated from the heap or in FLASH) and cannot be used to create another SDP
653record.
654
655### Query remote SDP service {#sec:querySDPProtocols}
656
657BTstack provides an SDP client to query SDP services of a remote device.
658The SDP Client API is shown in [here](../appendix/apis/#sec:sdpAPIAppendix). The
659*sdp_client_query* function initiates an L2CAP connection to the
660remote SDP server. Upon connect, a *Service Search Attribute* request
661with a *Service Search Pattern* and a *Attribute ID List* is sent. The
662result of the *Service Search Attribute* query contains a list of
663*Service Records*, and each of them contains the requested attributes.
664These records are handled by the SDP parser. The parser delivers
665SDP_PARSER_ATTRIBUTE_VALUE and SDP_PARSER_COMPLETE events via a
666registered callback. The SDP_PARSER_ATTRIBUTE_VALUE event delivers
667the attribute value byte by byte.
668
669On top of this, you can implement specific SDP queries. For example,
670BTstack provides a query for RFCOMM service name and channel number.
671This information is needed, e.g., if you want to connect to a remote SPP
672service. The query delivers all matching RFCOMM services, including its
673name and the channel number, as well as a query complete event via a
674registered callback, as shown in Listing [below](#lst:SDPClientRFCOMM).
675
676
677~~~~ {#lst:SDPClientRFCOMM .c caption="{Searching RFCOMM services on a remote device.}"}
678
679    bd_addr_t remote = {0x04,0x0C,0xCE,0xE4,0x85,0xD3};
680
681    void packet_handler (void * connection, uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){
682        if (packet_type != HCI_EVENT_PACKET) return;
683
684        uint8_t event = packet[0];
685        switch (event) {
686            case BTSTACK_EVENT_STATE:
687                // bt stack activated, get started
688                if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING){
689                      sdp_client_query_rfcomm_channel_and_name_for_uuid(remote, 0x0003);
690                }
691                break;
692            default:
693                break;
694        }
695    }
696
697    static void btstack_setup(){
698       ...
699        // init L2CAP
700        l2cap_init();
701        l2cap_register_packet_handler(packet_handler);
702    }
703
704    void handle_query_rfcomm_event(sdp_query_event_t * event, void * context){
705        sdp_client_query_rfcomm_service_event_t * ve;
706
707        switch (event->type){
708            case SDP_EVENT_QUERY_RFCOMM_SERVICE:
709                ve = (sdp_client_query_rfcomm_service_event_t*) event;
710                printf("Service name: '%s', RFCOMM port %u\n", ve->service_name, ve->channel_nr);
711                break;
712            case SDP_EVENT_QUERY_COMPLETE:
713                report_found_services();
714                printf("Client query response done with status %d. \n", ce->status);
715                break;
716        }
717    }
718
719    int main(void){
720        hw_setup();
721        btstack_setup();
722
723        // register callback to receive matching RFCOMM Services and
724        // query complete event
725        sdp_client_query_rfcomm_register_callback(handle_query_rfcomm_event, NULL);
726
727        // turn on!
728        hci_power_control(HCI_POWER_ON);
729        // go!
730        btstack_run_loop_execute();
731        return 0;
732    }
733~~~~
734
735## BNEP - Bluetooth Network Encapsulation Protocol
736
737The BNEP protocol is used to transport control and data packets over
738standard network protocols such as TCP, IPv4 or IPv6. It is built on top
739of L2CAP, and it specifies a minimum L2CAP MTU of 1691 bytes.
740
741### Receive BNEP events
742
743To receive BNEP events, please register a packet handler with
744*bnep_register_packet_handler*.
745
746### Access a BNEP service on a remote device {#sec:bnepClientProtocols}
747
748To connect to a remote BNEP service, you need to know its UUID. The set
749of available UUIDs can be queried by a SDP query for the PAN profile.
750Please see section on [PAN profile](../profiles/#sec:panProfiles) for details.
751With the remote UUID, you can create a connection using the *bnep_connect*
752function. You’ll receive a *BNEP_EVENT_CHANNEL_OPENED* on success or
753failure.
754
755After the connection was opened successfully, you can send and receive
756Ethernet packets. Before sending an Ethernet frame with *bnep_send*,
757*bnep_can_send_packet_now* needs to return true. Ethernet frames
758are received via the registered packet handler with packet type
759*BNEP_DATA_PACKET*.
760
761BTstack BNEP implementation supports both network protocol filter and
762multicast filters with *bnep_set_net_type_filter* and
763*bnep_set_multicast_filter* respectively.
764
765Finally, to close a BNEP connection, you can call *bnep_disconnect*.
766
767### Provide BNEP service {#sec:bnepServiceProtocols}
768
769To provide a BNEP service, call *bnep_register_service* with the
770provided service UUID and a max frame size.
771
772A *BNEP_EVENT_INCOMING_CONNECTION* event will mark that an incoming
773connection is established. At this point you can start sending and
774receiving Ethernet packets as described in the previous section.
775
776### Sending Ethernet packets
777
778Similar to L2CAP and RFOMM, directly sending an Ethernet packet via BNEP might fail,
779if the outgoing packet buffer or the ACL buffers in the Bluetooth module are full.
780
781When there's a need to send an Ethernet packet, call *bnep_request_can_send_now*
782and send the packet when the BNEP_EVENT_CAN_SEND_NOW event
783gets received.
784
785
786## ATT - Attribute Protocol
787
788The ATT protocol is used by an ATT client to read and write attribute
789values stored on an ATT server. In addition, the ATT server can notify
790the client about attribute value changes. An attribute has a handle, a
791type, and a set of properties.
792
793The Generic Attribute (GATT) profile is built upon ATT and provides
794higher level organization of the ATT attributes into GATT Services and
795GATT Characteristics. In BTstack, the complete ATT client functionality
796is included within the GATT Client. See [GATT client](../profiles/#sec:GATTClientProfiles) for more.
797
798On the server side, one ore more GATT profiles are converted ahead of time
799into the corresponding ATT attribute database and provided by the *att_server*
800implementation. The constant data are automatically served by the ATT server upon client
801request. To receive the dynamic data, such is characteristic value, the
802application needs to register read and/or write callback. In addition,
803notifications and indications can be sent. Please see Section on
804[GATT server](../profiles/#sec:GATTServerProfile) for more.
805
806## SMP - Security Manager Protocol {#sec:smpProtocols}
807
808The SMP protocol allows to setup authenticated and encrypted LE
809connection. After initialization and configuration, SMP handles security
810related functions on its own but emits events when feedback from the
811main app or the user is required. The two main tasks of the SMP protocol
812are: bonding and identity resolving.
813
814### LE Legacy Pairing and LE Secure Connections
815
816The original pairing algorithm introduced in Bluetooth Core V4.0 does not
817provide security in case of an attacker present during the initial pairing.
818To fix this, the Bluetooth Core V4.2 specification introduced the new
819*LE Secure Connections* method, while referring to the original method as *LE Legacy Pairing*.
820
821BTstack supports both pairing methods. To enable the more secure LE Secure Connections method,
822*ENABLE_LE_SECURE_CONNECTIONS* needs to be defined in *btstack_config.h*.
823
824LE Secure Connections are based on Elliptic Curve Diffie-Hellman (ECDH) algorithm for the key exchange.
825On start, a new public/private key pair is generated. During pairing, the
826Long Term Key (LTK) is generated based on the local keypair and the remote public key.
827To facilitate the creation of such a keypairs and the calculation of the LTK,
828the Bluetooth Core V4.2 specification introduced appropriate commands for the Bluetooth controller.
829
830As an alternative for controllers that don't provide these primitives, BTstack provides the relevant cryptographic functions in software via the BSD-2-Clause licensed [micro-ecc library](https://github.com/kmackay/micro-ecc/tree/static).
831When using using LE Secure Connections, the Peripheral must store LTK in non-volatile memory.
832
833To only allow LE Secure Connections, you can call *sm_set_secure_connections_only_mode(true)*.
834
835
836### Initialization
837
838To activate the security manager, call *sm_init()*.
839
840If you’re creating a product, you should also call *sm_set_ir()* and
841*sm_set_er()* with a fixed random 16 byte number to create the IR and
842ER key seeds. If possible use a unique random number per device instead
843of deriving it from the product serial number or something similar. The
844encryption key generated by the BLE peripheral will be ultimately
845derived from the ER key seed. See
846[Bluetooth Specification](https://www.bluetooth.org/Technical/Specifications/adopted.htm) -
847Bluetooth Core V4.0, Vol 3, Part G, 5.2.2 for more details on deriving
848the different keys. The IR key is used to identify a device if private,
849resolvable Bluetooth addresses are used.
850
851
852### Configuration
853
854To receive events from the Security Manager, a callback is necessary.
855How to register this packet handler depends on your application
856configuration.
857
858When *att_server* is used to provide a GATT/ATT service, *att_server*
859registers itself as the Security Manager packet handler. Security
860Manager events are then received by the application via the
861*att_server* packet handler.
862
863If *att_server* is not used, you can directly register your packet
864handler with the security manager by calling
865*sm_register_packet_handler*.
866
867The default SMP configuration in BTstack is to be as open as possible:
868
869-   accept all Short Term Key (STK) Generation methods,
870
871-   accept encryption key size from 7..16 bytes,
872
873-   expect no authentication requirements,
874
875-   don't require LE Secure Connections, and
876
877-   IO Capabilities set to *IO_CAPABILITY_NO_INPUT_NO_OUTPUT*.
878
879You can configure these items by calling following functions
880respectively:
881
882-   *sm_set_accepted_stk_generation_methods*
883
884-   *sm_set_encryption_key_size_range*
885
886-   *sm_set_authentication_requirements* : add SM_AUTHREQ_SECURE_CONNECTION flag to enable LE Secure Connections
887
888-   *sm_set_io_capabilities*
889
890
891### Identity Resolving
892
893Identity resolving is the process of matching a private, resolvable
894Bluetooth address to a previously paired device using its Identity
895Resolving (IR) key. After an LE connection gets established, BTstack
896automatically tries to resolve the address of this device. During this
897lookup, BTstack will emit the following events:
898
899-   *SM_EVENT_IDENTITY_RESOLVING_STARTED* to mark the start of a lookup,
900
901and later:
902
903-   *SM_EVENT_IDENTITY_RESOLVING_SUCCEEDED* on lookup success, or
904
905-   *SM_EVENT_IDENTITY_RESOLVING_FAILED* on lookup failure.
906
907
908### User interaction during Pairing
909
910BTstack will inform the app about pairing via theses events:
911
912  - *SM_EVENT_PAIRING_STARTED*: inform user that pairing has started
913  - *SM_EVENT_PAIRING_COMPLETE*: inform user that pairing is complete, see status
914
915Depending on the authentication requirements, IO capabilities,
916available OOB data, and the enabled STK generation methods,
917BTstack will request feedback from
918the app in the form of an event:
919
920  - *SM_EVENT_JUST_WORKS_REQUEST*: request a user to accept a Just Works pairing
921  - *SM_EVENT_PASSKEY_INPUT_NUMBER*: request user to input a passkey
922  - *SM_EVENT_PASSKEY_DISPLAY_NUMBER*: show a passkey to the user
923  - *SM_EVENT_PASSKEY_DISPLAY_CANCEL*: cancel show passkey to user
924  - *SM_EVENT_NUMERIC_COMPARISON_REQUEST*: show a passkey to the user and request confirmation
925
926To accept Just Works/Numeric Comparison, or provide a Passkey, *sm_just_works_confirm* or *sm_passkey_input* can be called respectively.
927Othwerise, *sm_bonding_decline* aborts the pairing.
928
929After the bonding process, *SM_EVENT_PAIRING_COMPLETE*, is emitted. Any active dialog can be closed on this.
930
931### Connection with Bonded Devices
932
933During pairing, two devices exchange bonding information, notably a Long-Term Key (LTK) and their respective Identity Resolving Key (IRK).
934On a subsequent connection, the Securit Manager will use this information to establish an encrypted connection.
935
936To inform about this, the following events are emitted:
937
938  - *SM_EVENT_REENCRYPTION_STARTED*: we have stored bonding information and either trigger encryption (as Central), or, sent a security request (as Peripheral).
939  - *SM_EVENT_REENCRYPTION_COMPLETE*: re-encryption is complete. If the remote device does not have a stored LTK, the status code will be *ERROR_CODE_PIN_OR_KEY_MISSING*.
940
941The *SM_EVENT_REENCRYPTION_COMPLETE* with  *ERROR_CODE_PIN_OR_KEY_MISSING* can be caused:
942
943  - if the remote device was reset or the bonding was removed, or,
944  - we're connected to an attacker that uses the Bluetooth address of a bonded device.
945
946In Peripheral role, pairing will start even in case of an re-encryption error. It might be helpful to inform the user about the lost bonding or reject it right away due to security considerations.
947
948
949### Keypress Notifications
950
951As part of Bluetooth Core V4.2 specification, a device with a keyboard but no display can send keypress notifications to provide better user feedback. In BTstack, the *sm_keypress_notification()* function is used for sending notifications. Notifications are received by BTstack via the *SM_EVENT_KEYPRESS_NOTIFICATION* event.
952
953### Cross-transport Key Derivation (CTKD) for LE Secure Connections
954
955In a dual-mode configuration, BTstack  generates an BR/EDR Link Key from the LE LTK via the Link Key Conversion functions *h6* ,
956(or *h7* if supported) when *ENABLE_CROSS_TRANSPORT_KEY_DERIVATION* is defined.
957The derived key then stored in local LE Device DB.
958
959The main use case for this is connections with smartphones. E.g. iOS provides APIs for LE scanning and connection, but none for BR/EDR. This allows an application to connect and pair with
960a device and also later setup a BR/EDR connection without the need for the smartphone user to use the system Settings menu.
961
962To derive an LE LTK from a BR/EDR link key, the Bluetooth controller needs to support Secure Connections via NIST P-256 elliptic curves. BTstack does not support LE Secure Connections via LE Transport currently.
963
964### Out-of-Band Data with LE Legacy Pairing
965
966LE Legacy Pairing can be made secure by providing a way for both devices
967to acquire a pre-shared secret 16 byte key by some fancy method.
968In most cases, this is not an option, especially since popular OS like iOS
969don’t provide a way to specify it. In some applications, where both
970sides of a Bluetooth link are developed together, this could provide a
971viable option.
972
973To provide OOB data, you can register an OOB data callback with
974*sm_register_oob_data_callback*.
975