xref: /btstack/doc/manual/docs-template/profiles.md (revision af7c3ae6cd1e2bcfd24e6d0654508ecf775c9e5d)
1#
2
3In the following, we explain how the various Bluetooth profiles are used
4in BTstack.
5
6## GAP - Generic Access Profile: Classic
7
8
9The GAP profile defines how devices find each other and establish a
10secure connection for other profiles. As mentioned before, the GAP
11functionality is split between and . Please check both.
12
13### Become discoverable
14
15A remote unconnected Bluetooth device must be set as “discoverable” in
16order to be seen by a device performing the inquiry scan. To become
17discoverable, an application can call *gap_discoverable_control* with
18input parameter 1. If you want to provide a helpful name for your
19device, the application can set its local name by calling
20*gap_set_local_name*. To save energy, you may set the device as
21undiscoverable again, once a connection is established. See Listing
22[below](#lst:Discoverable) for an example.
23
24~~~~ {#lst:Discoverable .c caption="{Setting discoverable mode.}"}
25    int main(void){
26        ...
27        // make discoverable
28        gap_discoverable_control(1);
29        btstack_run_loop_execute();
30        return 0;
31    }
32    void packet_handler (uint8_t packet_type, uint8_t *packet, uint16_t size){
33         ...
34         switch(state){
35              case W4_CHANNEL_COMPLETE:
36                  // if connection is successful, make device undiscoverable
37                  gap_discoverable_control(0);
38              ...
39         }
40     }
41~~~~
42
43### Discover remote devices {#sec:GAPdiscoverRemoteDevices}
44
45To scan for remote devices, the *hci_inquiry* command is used. Found
46remote devices are reported as a part of:
47
48- HCI_EVENT_INQUIRY_RESULT,
49
50- HCI_EVENT-_INQUIRY_RESULT_WITH_RSSI, or
51
52- HCI_EVENT_EXTENDED_INQUIRY_RESPONSE events.
53
54Each response contains at least the Bluetooth address, the class of device, the page scan
55repetition mode, and the clock offset of found device. The latter events
56add information about the received signal strength or provide the
57Extended Inquiry Result (EIR). A code snippet is shown in Listing
58[below](#lst:DiscoverDevices).
59
60~~~~ {#lst:DiscoverDevices .c caption="{Discover remote devices.}"}
61    void print_inquiry_results(uint8_t *packet){
62        int event = packet[0];
63        int numResponses = hci_event_inquiry_result_get_num_responses(packet);
64        uint16_t classOfDevice, clockOffset;
65        uint8_t  rssi, pageScanRepetitionMode;
66        for (i=0; i<numResponses; i++){
67            bt_flip_addr(addr, &packet[3+i*6]);
68            pageScanRepetitionMode = packet [3 + numResponses*6 + i];
69            if (event == HCI_EVENT_INQUIRY_RESULT){
70                classOfDevice = little_endian_read_24(packet, 3 + numResponses*(6+1+1+1) + i*3);
71                clockOffset =   little_endian_read_16(packet, 3 + numResponses*(6+1+1+1+3) + i*2) & 0x7fff;
72                rssi  = 0;
73            } else {
74                classOfDevice = little_endian_read_24(packet, 3 + numResponses*(6+1+1)     + i*3);
75                clockOffset =   little_endian_read_16(packet, 3 + numResponses*(6+1+1+3)   + i*2) & 0x7fff;
76                rssi  = packet [3 + numResponses*(6+1+1+3+2) + i*1];
77            }
78            printf("Device found: %s with COD: 0x%06x, pageScan %u, clock offset 0x%04x, rssi 0x%02x\n", bd_addr_to_str(addr), classOfDevice, pageScanRepetitionMode, clockOffset, rssi);
79        }
80    }
81
82    void packet_handler (uint8_t packet_type, uint8_t *packet, uint16_t size){
83        ...
84        switch (event) {
85             case HCI_STATE_WORKING:
86                hci_send_cmd(&hci_write_inquiry_mode, 0x01); // with RSSI
87                break;
88            case HCI_EVENT_COMMAND_COMPLETE:
89                if (COMMAND_COMPLETE_EVENT(packet, hci_write_inquiry_mode) ) {
90                    start_scan();
91                }
92            case HCI_EVENT_COMMAND_STATUS:
93                if (COMMAND_STATUS_EVENT(packet, hci_write_inquiry_mode) ) {
94                    printf("Ignoring error (0x%x) from hci_write_inquiry_mode.\n", packet[2]);
95                    hci_send_cmd(&hci_inquiry, HCI_INQUIRY_LAP, INQUIRY_INTERVAL, 0);
96                }
97                break;
98            case HCI_EVENT_INQUIRY_RESULT:
99            case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI:
100                print_inquiry_results(packet);
101                break;
102           ...
103        }
104    }
105~~~~
106
107By default, neither RSSI values nor EIR are reported. If the Bluetooth
108device implements Bluetooth Specification 2.1 or higher, the
109*hci_write_inquiry_mode* command enables reporting of this advanced
110features (0 for standard results, 1 for RSSI, 2 for RSSI and EIR).
111
112A complete GAP inquiry example is provided [here](examples/examples/#sec:gapinquiryExample).
113
114### Pairing of Devices
115
116By default, Bluetooth communication is not authenticated, and any device
117can talk to any other device. A Bluetooth device (for example, cellular
118phone) may choose to require authentication to provide a particular
119service (for example, a Dial-Up service). The process of establishing
120authentication is called pairing. Bluetooth provides two mechanism for
121this.
122
123On Bluetooth devices that conform to the Bluetooth v2.0 or older
124specification, a PIN code (up to 16 bytes ASCII) has to be entered on
125both sides. This isn’t optimal for embedded systems that do not have
126full I/O capabilities. To support pairing with older devices using a
127PIN, see Listing [below](#lst:PinCodeRequest).
128
129~~~~ {#lst:PinCodeRequest .c caption="{PIN code request.}"}
130    void packet_handler (uint8_t packet_type, uint8_t *packet, uint16_t size){
131        ...
132        switch (event) {
133            case HCI_EVENT_PIN_CODE_REQUEST:
134                // inform about pin code request
135                printf("Pin code request - using '0000'\n\r");
136                hci_event_pin_code_request_get_bd_addr(packet, bd_addr);
137
138                // baseband address, pin length, PIN: c-string
139                hci_send_cmd(&hci_pin_code_request_reply, &bd_addr, 4, "0000");
140                break;
141           ...
142        }
143    }
144~~~~
145
146The Bluetooth v2.1 specification introduces Secure Simple Pairing (SSP),
147which is a better approach as it both improves security and is better
148adapted to embedded systems. With SSP, the devices first exchange their
149IO Capabilities and then settle on one of several ways to verify that
150the pairing is legitimate. If the Bluetooth device supports SSP, BTstack
151enables it by default and even automatically accepts SSP pairing
152requests. Depending on the product in which BTstack is used, this may
153not be desired and should be replaced with code to interact with the
154user.
155
156Regardless of the authentication mechanism (PIN/SSP), on success, both
157devices will generate a link key. The link key can be stored either in
158the Bluetooth module itself or in a persistent storage, see
159[here](porting/#sec:persistentStoragePorting). The next time the device connects and
160requests an authenticated connection, both devices can use the
161previously generated link key. Please note that the pairing must be
162repeated if the link key is lost by one device.
163
164### Dedicated Bonding
165
166Aside from the regular bonding, Bluetooth also provides the concept of
167“dedicated bonding”, where a connection is established for the sole
168purpose of bonding the device. After the bonding process is over, the
169connection will be automatically terminated. BTstack supports dedicated
170bonding via the *gap_dedicated_bonding* function.
171
172## SPP - Serial Port Profile
173
174The SPP profile defines how to set up virtual serial ports and connect
175two Bluetooth enabled devices. Please keep in mind that a serial port does not
176preserve packet boundaries if you try to send data as packets and read about
177[RFCOMM packet boundaries]({protocols/#sec:noRfcommPacketBoundaries}).
178
179### Accessing an SPP Server on a remote device
180
181To access a remote SPP server, you first need to query the remote device
182for its SPP services. Section [on querying remote SDP service](#sec:querySDPProtocols)
183shows how to query for all RFCOMM channels. For SPP, you can do the same
184but use the SPP UUID 0x1101 for the query. After you have identified the
185correct RFCOMM channel, you can create an RFCOMM connection as shown
186[here](protocols/#sec:rfcommClientProtocols).
187
188### Providing an SPP Server
189
190To provide an SPP Server, you need to provide an RFCOMM service with a
191specific RFCOMM channel number as explained in section on
192[RFCOMM service](protocols/#sec:rfcommServiceProtocols). Then, you need to create
193an SDP record for it and publish it with the SDP server by calling
194*sdp_register_service*. BTstack provides the
195*spp_create_sdp_record* function in that requires an empty buffer of
196approximately 200 bytes, the service channel number, and a service name.
197Have a look at the [SPP Counter example](examples/examples/#sec:sppcounterExample).
198
199
200## PAN - Personal Area Networking Profile {#sec:panProfiles}
201
202
203The PAN profile uses BNEP to provide on-demand networking capabilities
204between Bluetooth devices. The PAN profile defines the following roles:
205
206-   PAN User (PANU)
207
208-   Network Access Point (NAP)
209
210-   Group Ad-hoc Network (GN)
211
212PANU is a Bluetooth device that communicates as a client with GN, or
213NAP, or with another PANU Bluetooth device, through a point-to-point
214connection. Either the PANU or the other Bluetooth device may terminate
215the connection at anytime.
216
217NAP is a Bluetooth device that provides the service of routing network
218packets between PANU by using BNEP and the IP routing mechanism. A NAP
219can also act as a bridge between Bluetooth networks and other network
220technologies by using the Ethernet packets.
221
222The GN role enables two or more PANUs to interact with each other
223through a wireless network without using additional networking hardware.
224The devices are connected in a piconet where the GN acts as a master and
225communicates either point-to-point or a point-to-multipoint with a
226maximum of seven PANU slaves by using BNEP.
227
228Currently, BTstack supports only PANU.
229
230### Accessing a remote PANU service
231
232To access a remote PANU service, you first need perform an SDP query to
233get the L2CAP PSM for the requested PANU UUID. With these two pieces of
234information, you can connect BNEP to the remote PANU service with the
235*bnep_connect* function. The Section on [PANU Demo example](examples/examples/#sec:panudemoExample)
236shows how this is accomplished.
237
238### Providing a PANU service
239
240To provide a PANU service, you need to provide a BNEP service with the
241service UUID, e.g. the PANU UUID, and a maximal ethernet frame size,
242as explained in Section [on BNEP service](protocols/#sec:bnepServiceProtocols). Then, you need to
243create an SDP record for it and publish it with the SDP server by
244calling *sdp_register_service*. BTstack provides the
245*pan_create_panu_sdp_record* function in *src/pan.c* that requires an
246empty buffer of approximately 200 bytes, a description, and a security
247description.
248
249## HSP - Headset Profile
250
251The HSP profile defines how a Bluetooth-enabled headset should communicate
252with another Bluetooth enabled device. It relies on SCO for audio encoded
253in 64 kbit/s CVSD and a subset of AT commands from GSM 07.07 for
254minimal controls including the ability to ring, answer a call, hang up and adjust the volume.
255
256The HSP defines two roles:
257
258 - Audio Gateway (AG) - a device that acts as the gateway of the audio, typically a mobile phone or PC.
259
260 - Headset (HS) - a device that acts as the AG's remote audio input and output control.
261
262There are following restrictions:
263- The CVSD is used for audio transmission.
264
265- Between headset and audio gateway, only one audio connection at a time is supported.
266
267- The profile offers only basic interoperability – for example, handling of multiple calls at the audio gateway is not included.
268
269- The only assumption on the headset’s user interface is the possibility to detect a user initiated action (e.g. pressing a button).
270
271%TODO: audio paths
272
273
274## HFP - Hands-Free Profile  {#sec:hfp}
275
276The HFP profile defines how a Bluetooth-enabled device, e.g. a car kit or a headset, can be used to place and receive calls via a audio gateway device, typically a mobile phone.
277It relies on SCO for audio encoded in 64 kbit/s CVSD and a bigger subset of AT commands from GSM 07.07 then HSP for
278controls including the ability to ring, to place and receive calls, join a conference call, to answer, hold or reject a call, and adjust the volume.
279
280The HFP defines two roles:
281
282- Audio Gateway (AG) – a device that acts as the gateway of the audio,, typically a mobile phone.
283
284- Hands-Free Unit (HF) – a device that acts as the AG's remote audio input and output control.
285
286### Supported Features {#sec:hfpSupportedFeatures}
287
288The supported features define the HFP capabilities of the device. The enumeration unfortunately differs between HF and AG sides.
289
290The AG supported features are set by combining the flags that start with HFP_AGSF_xx and calling hfp_ag_init_supported_features, followed by creating SDP record for the service using the same feature set.
291
292Similarly, the HF supported features are a combination of HFP_HFSF_xx flags and are configured by calling hfp_hf_init_supported_features, as well as creating an SDP record.
293
294| Define for AG Supported Feature         |  Description  |
295| --------------------------------------- |  ----------------------------  |
296| HFP_AGSF_THREE_WAY_CALLING              |  Three-way calling             |
297| HFP_AGSF_EC_NR_FUNCTION                 |  Echo Canceling and/or Noise Reduction function |
298| HFP_AGSF_VOICE_RECOGNITION_FUNCTION     |  Voice recognition function |
299| HFP_AGSF_IN_BAND_RING_TONE              |  In-band ring tone capability |
300| HFP_AGSF_ATTACH_A_NUMBER_TO_A_VOICE_TAG |  Attach a number to a voice tag |
301| HFP_AGSF_ABILITY_TO_REJECT_A_CALL       |  Ability to reject a call |
302| HFP_AGSF_ENHANCED_CALL_STATUS           |  Enhanced call status |
303| HFP_AGSF_ENHANCED_CALL_CONTROL          |  Enhanced call control |
304| HFP_AGSF_EXTENDED_ERROR_RESULT_CODES    |  Extended Error Result Codes |
305| HFP_AGSF_CODEC_NEGOTIATION              |  Codec negotiation |
306| HFP_AGSF_HF_INDICATORS                  |  HF Indicators |
307| HFP_AGSF_ESCO_S4                        |  eSCO S4 (and T2) Settings Supported |
308| HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS |  Enhanced voice recognition status |
309| HFP_AGSF_VOICE_RECOGNITION_TEXT         |  Voice recognition text |
310
311
312| Define for HF Supported Feature         |  Description  |
313| --------------------------------------- |  ----------------------------  |
314| HFP_HFSF_THREE_WAY_CALLING              |  Three-way calling  |
315| HFP_HFSF_EC_NR_FUNCTION                 |  Echo Canceling and/or Noise Reduction function |
316| HFP_HFSF_CLI_PRESENTATION_CAPABILITY    |  CLI presentation capability |
317| HFP_HFSF_VOICE_RECOGNITION_FUNCTION     |  Voice recognition function |
318| HFP_HFSF_REMOTE_VOLUME_CONTROL          |  Remote volume control |
319| HFP_HFSF_ATTACH_A_NUMBER_TO_A_VOICE_TAG |  Attach a number to a voice tag |
320| HFP_HFSF_ENHANCED_CALL_STATUS           |  Enhanced call status |
321| HFP_HFSF_ENHANCED_CALL_CONTROL          |  Enhanced call control |
322| HFP_HFSF_CODEC_NEGOTIATION              |  Codec negotiation |
323| HFP_HFSF_HF_INDICATORS                  |  HF Indicators |
324| HFP_HFSF_ESCO_S4                        |  eSCO S4 (and T2) Settings Supported |
325| HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS |  Enhanced voice recognition status |
326| HFP_HFSF_VOICE_RECOGNITION_TEXT         |  Voice recognition text |
327
328
329### Audio Voice Recognition Activation {#sec:hfpAVRActivation}
330
331Audio voice recognition (AVR) requires that HF and AG have the following  features enabled:
332
333- HF: HFP_HFSF_VOICE_RECOGNITION_FUNCTION and
334
335- AG: HFP_AGSF_VOICE_RECOGNITION_FUNCTION.
336
337It can be activated or deactivated on both sides by calling:
338
339    // AG
340    uint8_t hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle);
341    uint8_t hfp_ag_deactivate_voice_recognition(hci_con_handle_t acl_handle);
342
343    // HF
344    uint8_t hfp_hf_activate_voice_recognition(hci_con_handle_t acl_handle);
345    uint8_t hfp_hf_deactivate_voice_recognition(hci_con_handle_t acl_handle);
346
347On activation change, the HFP_SUBEVENT_VOICE_RECOGNITION_(DE)ACTIVATED event will be emitted with status field set to ERROR_CODE_SUCCESS on success.
348
349Voice recognition will stay active until either the deactivation command is called, or until the current Service Level Connection between the AG and the HF is dropped for any reason.
350
351| Use cases                                              |  Expected behavior  |
352|--------------------------------------------------------|---------------------|
353| No previous audio connection, AVR activated then deactivated | Audio connection will be opened by AG upon AVR activation, and upon AVR deactivation closed|
354| AVR activated and deactivated during existing audio connection | Audio remains active upon AVR deactivation |
355| Call to close audio connection during active AVR session       | The audio connection shut down will be refused |
356| AVR activated, but audio connection failed to be established   | AVR will stay activated |
357
358Beyond the audio routing and voice recognition activation capabilities, the rest of the voice recognition functionality is implementation dependent - the stack only provides the signaling for this.
359
360### Enhanced Audio Voice Recognition {#sec:hfpeAVRActivation}
361
362Similarly to AVR, Enhanced Audio voice recognition (eAVR) requires that HF and AG have the following features enabled:
363
364- HF: HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS and
365
366- AG: HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS.
367
368In addition, to allow textual representation of audio that is parsed by eAVR (note that parsing is not part of Bluetooth specification), both devices must enable:
369
370- HF: HFP_HFSF_VOICE_RECOGNITION_TEXT and
371
372- AG: HFP_AGSF_VOICE_RECOGNITION_TEXT.
373
374eAVR implements the same use cases as AVR (see previous section) and it can be activated or deactivated using the same API as for AVR, see above.
375
376When eAVR and audio channel are established there are several additional commands that can be sent:
377
378| HFP Role | eVRA API | Description |
379-----------|----------|-------------|
380|HF | hfp_hf_enhanced_voice_recognition_report_ready_for_audio| Ready to accept audio input. |
381|AG | hfp_ag_enhanced_voice_recognition_report_ready_for_audio | Voice recognition engine is ready to accept audio input. |
382|AG | hfp_ag_enhanced_voice_recognition_report_sending_audio | The voice recognition engine will play a sound, e.g. starting sound. |
383|AG | hfp_ag_enhanced_voice_recognition_report_processing_input | Voice recognition engine is processing the audio input. |
384|AG | hfp_ag_enhanced_voice_recognition_send_message | Report textual representation from the voice recognition engine. |
385
386
387## HID - Human-Interface Device Profile
388
389The HID profile allows an HID Host to connect to one or more HID Devices and communicate with them.
390Examples of Bluetooth HID devices are keyboards, mice, joysticks, gamepads, remote controls, and also voltmeters and temperature sensors.
391Typical HID hosts would be a personal computer, tablets, gaming console, industrial machine, or data-recording device.
392
393Please refer to:
394
395- [HID Host API](appendix/apis/#sec:hidHostAPIAppendix) and [hid_host_demo](examples/examples/#sec:hidhostdemoExample) for the HID Host role
396
397- [HID Device API](appendix/apis/#sec:hidDeviceAPIAppendix), [hid_keyboard_demo](examples/examples/#sec:hidkeyboarddemoExample) and [hid_mouse_demo](examples/examples/#sec:hidmousedemoExample)  for the HID Device role.
398
399
400## GAP LE - Generic Access Profile for Low Energy
401
402
403As with GAP for Classic, the GAP LE profile defines how to discover and
404how to connect to a Bluetooth Low Energy device. There are several GAP
405roles that a Bluetooth device can take, but the most important ones are
406the Central and the Peripheral role. Peripheral devices are those that
407provide information or can be controlled. Central devices are those that
408consume information or control the peripherals. Before the connection
409can be established, devices are first going through an advertising
410process.
411
412### Private addresses.
413
414To better protect privacy, an LE device can choose to use a private i.e.
415random Bluetooth address. This address changes at a user-specified rate.
416To allow for later reconnection, the central and peripheral devices will
417exchange their Identity Resolving Keys (IRKs) during bonding. The IRK is
418used to verify if a new address belongs to a previously bonded device.
419
420To toggle privacy mode using private addresses, call the
421*gap_random_address_set_mode* function. The update period can be set
422with *gap_random_address_set_update_period*.
423
424After a connection is established, the Security Manager will try to
425resolve the peer Bluetooth address as explained in Section on
426[SMP](protocols/#sec:smpProtocols).
427
428### Advertising and Discovery
429
430An LE device is discoverable and connectable, only if it periodically
431sends out Advertisements. An advertisement contains up to 31 bytes of
432data. To configure and enable advertisement broadcast, the following GAP
433functions can be used:
434
435-   *gap_advertisements_set_data*
436
437-   *gap_advertisements_set_params*
438
439-   *gap_advertisements_enable*
440
441In addition to the Advertisement data, a device in the peripheral role
442can also provide Scan Response data, which has to be explicitly queried
443by the central device. It can be set with *gap_scan_response_set_data*.
444
445Please have a look at the [SPP and LE
446Counter example](examples/examples/#sec:sppandlecounterExample).
447
448The scan parameters can be set with
449*gap_set_scan_parameters*. The scan can be started/stopped
450with *gap_start_scan*/*gap_stop_scan*.
451
452Finally, if a suitable device is found, a connection can be initiated by
453calling *gap_connect*. In contrast to Bluetooth classic, there
454is no timeout for an LE connection establishment. To cancel such an
455attempt, *gap_connect_cancel* has be be called.
456
457By default, a Bluetooth device stops sending Advertisements when it gets
458into the Connected state. However, it does not start broadcasting
459advertisements on disconnect again. To re-enable it, please send the
460*hci_le_set_advertise_enable* again .
461
462## GATT Client {#sec:GATTClientProfiles}
463
464The GATT profile uses ATT Attributes to represent a hierarchical
465structure of GATT Services and GATT Characteristics. Each Service has
466one or more Characteristics. Each Characteristic has meta data attached
467like its type or its properties. This hierarchy of Characteristics and
468Services are queried and modified via ATT operations.
469
470GATT defines both a server and a client role. A device can implement one
471or both GATT roles.
472
473The GATT Client is used to discover services, characteristics
474and their descriptors on a peer device. It allows to subscribe for
475notifications or indications that the characteristic on the GATT server
476has changed its value.
477
478To perform GATT queries, it provides a rich interface. Before calling
479queries, the GATT client must be initialized with *gatt_client_init*
480once.
481
482To allow for modular profile implementations, GATT client can be used
483independently by multiple entities.
484
485After an LE connection was created using the GAP LE API, you can query
486for the connection MTU with *gatt_client_get_mtu*.
487
488Multiple GATT queries to the same GATT Server cannot be interleaved.
489Therefore, you can either use a state machine or similar to perform the
490queries in sequence, or you can check if you can perform a GATT query
491on a particular connection right now using
492*gatt_client_is_ready*, and retry later if it is not ready.
493As a result to a GATT query, zero to many
494*GATT_EVENT_X*s are returned before a *GATT_EVENT_QUERY_COMPLETE* event
495completes the query.
496
497For more details on the available GATT queries, please consult
498[GATT Client API](#sec:gattClientAPIAppendix).
499
500### Authentication
501
502By default, the GATT Server is responsible for security and the GATT Client does not enforce any kind of authentication.
503If the GATT Client accesses Characteristic that require encrytion or authentication, the remote GATT Server will return an error,
504which is returned in the *att status* of the *GATT_EVENT_QUERY_COMPLETE*.
505
506You can define *ENABLE_GATT_CLIENT_PAIRING* to instruct the GATT Client to trigger pairing in this case and to repeat the request.
507
508This model allows for an attacker to spoof another device, but don't require authentication for the Characteristics.
509As a first improvement, you can define *ENABLE_LE_PROACTIVE_AUTHENTICATION* in *btstack_config.h*. When defined, the GATT Client will
510request the Security Manager to re-encrypt the connection if there is stored bonding information available.
511If this fails, the  *GATT_EVENT_QUERY_COMPLETE* will return with the att status *ATT_ERROR_BONDING_INFORMATION_MISSING*.
512
513With *ENABLE_LE_PROACTIVE_AUTHENTICATION* defined and in Central role, you need to delete the local bonding information if the remote
514lost its bonding information, e.g. because of a device reset. See *example/sm_pairing_central.c*.
515
516Even with the Proactive Authentication, your device may still connect to an attacker that provides the same advertising data as
517your actual device. If the device that you want to connect requires pairing, you can instruct the GATT Client to automatically
518request an encrypted connection before sending any GATT Client request by calling *gatt_client_set_required_security_level()*.
519If the device provides sufficient IO capabilities, a MITM attack can then be prevented. We call this 'Mandatory Authentication'.
520
521The following diagrams provide a detailed overview about the GATT Client security mechanisms in different configurations:
522
523-  [Reactive Authentication as Central](picts/gatt_client_security_reactive_authentication_central.svg)
524-  [Reactive Authentication as Peripheral](picts/gatt_client_security_reactive_authentication_peripheral.svg)
525-  [Proactive Authentication as Central](picts/gatt_client_security_proactive_authentication_central.svg)
526-  [Proactive Authentication as Peripheral](picts/gatt_client_security_proactive_authentication_peripheral.svg)
527-  [Mandatory Authentication as Central](picts/gatt_client_security_mandatory_authentication_central.svg)
528-  [Mandatory Authentication as Peripheral](picts/gatt_client_security_mandatory_authentication_peripheral.svg)
529
530## GATT Server {#sec:GATTServerProfiles}
531
532The GATT server stores data and accepts GATT client requests, commands
533and confirmations. The GATT server sends responses to requests and when
534configured, sends indication and notifications asynchronously to the
535GATT client.
536
537To save on both code space and memory, BTstack does not provide a GATT
538Server implementation. Instead, a textual description of the GATT
539profile is directly converted into a compact internal ATT Attribute
540database by a GATT profile compiler. The ATT protocol server -
541implemented by and - answers incoming ATT requests based on information
542provided in the compiled database and provides read- and write-callbacks
543for dynamic attributes.
544
545GATT profiles are defined by a simple textual comma separated value
546(.csv) representation. While the description is easy to read and edit,
547it is compact and can be placed in ROM.
548
549The current format is shown in Listing [below](#lst:GATTServerProfile).
550
551~~~~ {#lst:GATTServerProfile .c caption="{GATT profile.}"}
552    // import service_name
553    #import <service_name.gatt>
554
555    PRIMARY_SERVICE, {SERVICE_UUID}
556    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
557    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
558    ...
559    PRIMARY_SERVICE, {SERVICE_UUID}
560    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
561    ...
562~~~~
563
564UUIDs are either 16 bit (1800) or 128 bit
565(00001234-0000-1000-8000-00805F9B34FB).
566
567Value can either be a string (“this is a string”), or, a sequence of hex
568bytes (e.g. 01 02 03).
569
570Properties can be a list of properties combined using '|'
571
572Reads/writes to a Characteristic that is defined with the DYNAMIC flag,
573are forwarded to the application via callback. Otherwise, the
574Characteristics cannot be written and it will return the specified
575constant value.
576
577Adding NOTIFY and/or INDICATE automatically creates an additional Client
578Configuration Characteristic.
579
580Property                | Meaning
581------------------------|-----------------------------------------------
582READ                    | Characteristic can be read
583WRITE                   | Characteristic can be written using Write Request
584WRITE_WITHOUT_RESPONSE  | Characteristic can be written using Write Command
585NOTIFY                  | Characteristic allows notifications by server
586INDICATE                | Characteristic allows indication by server
587DYNAMIC                 | Read or writes to Characteristic are handled by application
588
589To require encryption or authentication before a Characteristic can be
590accessed, you can add one or more of the following properties:
591
592Property                | Meaning
593------------------------|-----------------------------------------------
594AUTHENTICATION_REQUIRED | Read and Write operations require Authentication
595READ_ENCRYPTED          | Read operations require Encryption
596READ_AUTHENTICATED      | Read operations require Authentication
597WRITE_ENCRYPTED         | Write operations require Encryption
598WRITE_AUTHENTICATED     | Write operations require Authentication
599ENCRYPTION_KEY_SIZE_X   | Require encryption size >= X, with W in [7..16]
600
601For example, Volume State Characteristic (Voice Control Service) requires:
602- Mandatory Properties: Read, Notify
603- Security Permittions: Encryption Required
604
605In addition, its read is handled by application. We can model this Characteristic as follows:
606
607~~~~
608    CHARACTERISTIC, ORG_BLUETOOTH_CHARACTERISTIC_VOLUME_STATE, DYNAMIC | READ | NOTIFY | ENCRYPTION_KEY_SIZE_16
609~~~~
610
611To use already implemented GATT Services, you can import it
612using the *#import <service_name.gatt>* command. See [list of provided services](gatt_services.md).
613
614BTstack only provides an ATT Server, while the GATT Server logic is
615mainly provided by the GATT compiler. While GATT identifies
616Characteristics by UUIDs, ATT uses Handles (16 bit values). To allow to
617identify a Characteristic without hard-coding the attribute ID, the GATT
618compiler creates a list of defines in the generated \*.h file.
619
620Similar to other protocols, it might be not possible to send any time.
621To send a Notification, you can call *att_server_request_can_send_now*
622to receive a ATT_EVENT_CAN_SEND_NOW event.
623
624If your application cannot handle an ATT Read Request in the *att_read_callback*
625in some situations, you can enable support for this by adding ENABLE_ATT_DELAYED_RESPONSE
626to *btstack_config.h*. Now, you can store the requested attribute handle and return
627*ATT_READ_RESPONSE_PENDING* instead of the length of the provided data when you don't have the data ready.
628For ATT operations that read more than one attribute, your *att_read_callback*
629might get called multiple times as well. To let you know that all necessary
630attribute handles have been 'requested' by the *att_server*, you'll get a final
631*att_read_callback* with the attribute handle of *ATT_READ_RESPONSE_PENDING*.
632When you've got the data for all requested attributes ready, you can call
633*att_server_response_ready*, which will trigger processing of the current request.
634Please keep in mind that there is only one active ATT operation and that it has a 30 second
635timeout after which the ATT server is considered defunct by the GATT Client.
636
637### Implementing Standard GATT Services {#sec:GATTStandardServices}
638
639Implementation of a standard GATT Service consists of the following 4 steps:
640
641  1. Identify full Service Name
642  2. Use Service Name to fetch XML definition at Bluetooth SIG site and convert into generic .gatt file
643  3. Edit .gatt file to set constant values and exclude unwanted Characteristics
644  4. Implement Service server, e.g., battery_service_server.c
645
646Step 1:
647
648To facilitate the creation of .gatt files for standard profiles defined by the Bluetooth SIG,
649the *tool/convert_gatt_service.py* script can be used. When run without a parameter, it queries the
650Bluetooth SIG website and lists the available Services by their Specification Name, e.g.,
651*org.bluetooth.service.battery_service*.
652
653    $ tool/convert_gatt_service.py
654    Fetching list of services from https://www.bluetooth.com/specifications/gatt/services
655
656    Specification Type                                     | Specification Name            | UUID
657    -------------------------------------------------------+-------------------------------+-----------
658    org.bluetooth.service.alert_notification               | Alert Notification Service    | 0x1811
659    org.bluetooth.service.automation_io                    | Automation IO                 | 0x1815
660    org.bluetooth.service.battery_service                  | Battery Service               | 0x180F
661    ...
662    org.bluetooth.service.weight_scale                     | Weight Scale                  | 0x181D
663
664    To convert a service into a .gatt file template, please call the script again with the requested Specification Type and the output file name
665    Usage: tool/convert_gatt_service.py SPECIFICATION_TYPE [service_name.gatt]
666
667Step 2:
668
669To convert service into .gatt file, call *tool/convert_gatt_service.py with the requested Specification Type and the output file name.
670
671    $ tool/convert_gatt_service.py org.bluetooth.service.battery_service battery_service.gatt
672    Fetching org.bluetooth.service.battery_service from
673    https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.battery_service.xml
674
675    Service Battery Service
676    - Characteristic Battery Level - properties ['Read', 'Notify']
677    -- Descriptor Characteristic Presentation Format       - TODO: Please set values
678    -- Descriptor Client Characteristic Configuration
679
680    Service successfully converted into battery_service.gatt
681    Please check for TODOs in the .gatt file
682
683
684Step 3:
685
686In most cases, you will need to customize the .gatt file. Please pay attention to the tool output and have a look
687at the generated .gatt file.
688
689E.g. in the generated .gatt file for the Battery Service
690
691    // Specification Type org.bluetooth.service.battery_service
692    // https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.battery_service.xml
693
694    // Battery Service 180F
695    PRIMARY_SERVICE, ORG_BLUETOOTH_SERVICE_BATTERY_SERVICE
696    CHARACTERISTIC, ORG_BLUETOOTH_CHARACTERISTIC_BATTERY_LEVEL, DYNAMIC | READ | NOTIFY,
697    // TODO: Characteristic Presentation Format: please set values
698    #TODO CHARACTERISTIC_FORMAT, READ, _format_, _exponent_, _unit_, _name_space_, _description_
699    CLIENT_CHARACTERISTIC_CONFIGURATION, READ | WRITE,
700
701you could delete the line regarding the CHARACTERISTIC_FORMAT, since it's not required if there is a single instance of the service.
702Please compare the .gatt file against the [Adopted Specifications](https://www.bluetooth.com/specifications/adopted-specifications).
703
704Step 4:
705
706As described [above](#sec:GATTServerProfiles) all read/write requests are handled by the application.
707To implement the new services as a reusable module, it's necessary to get access to all read/write requests related to this service.
708
709For this, the ATT DB allows to register read/write callbacks for a specific handle range with *att_server_register_can_send_now_callback()*.
710
711Since the handle range depends on the application's .gatt file, the handle range for Primary and Secondary Services can be queried with *gatt_server_get_get_handle_range_for_service_with_uuid16*.
712
713Similarly, you will need to know the attribute handle for particular Characteristics to handle Characteristic read/writes requests. You can get the attribute value handle for a Characteristics *gatt_server_get_value_handle_for_characteristic_with_uuid16()*.
714
715In addition to the attribute value handle, the handle for the Client Characteristic Configuration is needed to support Indications/Notifications. You can get this attribute handle with *gatt_server_get_client_configuration_handle_for_characteristic_with_uuid16()*
716
717Finally, in order to send Notifications and Indications independently from the main application, *att_server_register_can_send_now_callback* can be used to request a callback when it's possible to send a Notification or Indication.
718
719To see how this works together, please check out the Battery Service Server in *src/ble/battery_service_server.c*.
720
721### GATT Database Hash
722
723When a GATT Client connects to a GATT Server, it cannot know if the GATT Database has changed
724and has to discover the provided GATT Services and Characteristics after each connect.
725
726To speed this up, the Bluetooth
727specification defines a GATT Service Changed Characteristic, with the idea that a GATT Server would notify
728a bonded GATT Client if its database changed. However, this is quite fragile and it is not clear how it can be implemented
729in a robust way.
730
731The Bluetooth Core Spec 5.1 introduced the GATT Database Hash Characteristic, which allows for a simple
732robust mechanism to cache a remote GATT Database. The GATT Database Hash is a 16-byte value that is calculated
733over the list of Services and Characteristics. If there is any change to the database, the hash will change as well.
734
735To support this on the GATT Server, you only need to add a GATT Service with the GATT Database Characteristic to your .gatt file.
736The hash value is then calculated by the GATT compiler.
737
738
739    PRIMARY_SERVICE, GATT_SERVICE
740    CHARACTERISTIC, GATT_DATABASE_HASH, READ,
741
742Note: make sure to install the PyCryptodome python package as the hash is calculated using AES-CMAC,
743e.g. with:
744
745    pip install pycryptodomex
746