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