xref: /btstack/doc/manual/docs-template/profiles.md (revision 543e856b65fc370989df3ef004a15751f33dc229)
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
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
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
330
331Audio voice recognition (AVR) requires that HF and AG have the following  features enabled:
332- HF: HFP_HFSF_VOICE_RECOGNITION_FUNCTION and
333- AG: HFP_AGSF_VOICE_RECOGNITION_FUNCTION.
334
335It can be activated or deactivated on both sides by calling:
336
337    // AG
338    uint8_t hfp_ag_activate_voice_recognition(hci_con_handle_t acl_handle);
339    uint8_t hfp_ag_deactivate_voice_recognition(hci_con_handle_t acl_handle);
340
341    // HF
342    uint8_t hfp_hf_activate_voice_recognition(hci_con_handle_t acl_handle);
343    uint8_t hfp_hf_deactivate_voice_recognition(hci_con_handle_t acl_handle);
344
345On either activation change, the HFP_SUBEVENT_VOICE_RECOGNITION_STATUS event will be emitted with status field set to ERROR_CODE_SUCCESS on success. The state field of this event indicates the current voice recognition state : 0 - if deactivated, 1 - if activated.
346
347Voice 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.
348
349| Use cases                                              |  Expected behavior  |
350|--------------------------------------------------------|---------------------|
351| No previous audio connection, AVR activated then deactivated | Audio connection will be opened by AG upon AVR activation, and upon AVR deactivation closed|
352| AVR activated and deactivated during existing audio connection | Audio remains active upon AVR deactivation |
353| Call to close audio connection during active AVR session       | The audio connection shut down will be refused |
354| AVR activated, but audio connection failed to be established   | AVR will stay activated |
355
356Beyond 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.
357
358### Enhanced Audio Voice Recognition
359
360Similarly to AVR, Enhanced Audio voice recognition (eAVR) requires that HF and AG have the following features enabled:
361- HF: HFP_HFSF_ENHANCED_VOICE_RECOGNITION_STATUS and
362- AG: HFP_AGSF_ENHANCED_VOICE_RECOGNITION_STATUS.
363
364In 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:
365- HF: HFP_HFSF_VOICE_RECOGNITION_TEXT and
366- AG: HFP_AGSF_VOICE_RECOGNITION_TEXT.
367
368eAVR implements the same use cases as AVR (see previous section). It can be activated or deactivated on both sides by calling:
369
370    // AG
371    uint8_t hfp_ag_enhanced_voice_recognition_activate(hci_con_handle_t acl_handle);
372    uint8_t hfp_ag_enhanced_voice_recognition_deactivate(hci_con_handle_t acl_handle);
373
374    // HF
375    uint8_t hfp_hf_enhanced_voice_recognition_activate(hci_con_handle_t acl_handle);
376    uint8_t hfp_hf_enhanced_voice_recognition_deactivate(hci_con_handle_t acl_handle);
377
378When eAVR and audio channel are established there are several additional commands that can be sent:
379
380| HFP Role | eVRA API | Description |
381-----------|----------|-------------|
382|HF | hfp_hf_enhanced_voice_recognition_report_ready_for_audio| Ready to accept audio input. |
383|AG | hfp_ag_enhanced_voice_recognition_report_ready_for_audio | Voice recognition engine is ready to accept audio input. |
384|AG | hfp_ag_enhanced_voice_recognition_report_sending_audio | The voice recognition engine will play a sound, e.g. starting sound. |
385|AG | hfp_ag_enhanced_voice_recognition_report_processing_input | Voice recognition engine is processing the audio input. |
386|AG | hfp_ag_enhanced_voice_recognition_send_message | Report textual representation from the voice recognition engine. |
387
388
389## HID - Human-Interface Device Profile
390
391The HID profile allows an HID Host to connect to one or more HID Devices and communicate with them.
392Examples of Bluetooth HID devices are keyboards, mice, joysticks, gamepads, remote controls, and also voltmeters and temperature sensors.
393Typical HID hosts would be a personal computer, tablets, gaming console, industrial machine, or data-recording device.
394
395Please refer to:
396
397- [HID Host API](appendix/apis/#sec:hidHostAPIAppendix) and [hid_host_demo](examples/examples/#sec:hidhostdemoExample) for the HID Host role
398
399- [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.
400
401
402## GAP LE - Generic Access Profile for Low Energy
403
404
405As with GAP for Classic, the GAP LE profile defines how to discover and
406how to connect to a Bluetooth Low Energy device. There are several GAP
407roles that a Bluetooth device can take, but the most important ones are
408the Central and the Peripheral role. Peripheral devices are those that
409provide information or can be controlled. Central devices are those that
410consume information or control the peripherals. Before the connection
411can be established, devices are first going through an advertising
412process.
413
414### Private addresses.
415
416To better protect privacy, an LE device can choose to use a private i.e.
417random Bluetooth address. This address changes at a user-specified rate.
418To allow for later reconnection, the central and peripheral devices will
419exchange their Identity Resolving Keys (IRKs) during bonding. The IRK is
420used to verify if a new address belongs to a previously bonded device.
421
422To toggle privacy mode using private addresses, call the
423*gap_random_address_set_mode* function. The update period can be set
424with *gap_random_address_set_update_period*.
425
426After a connection is established, the Security Manager will try to
427resolve the peer Bluetooth address as explained in Section on
428[SMP](protocols/#sec:smpProtocols).
429
430### Advertising and Discovery
431
432An LE device is discoverable and connectable, only if it periodically
433sends out Advertisements. An advertisement contains up to 31 bytes of
434data. To configure and enable advertisement broadcast, the following GAP
435functions can be used:
436
437-   *gap_advertisements_set_data*
438
439-   *gap_advertisements_set_params*
440
441-   *gap_advertisements_enable*
442
443In addition to the Advertisement data, a device in the peripheral role
444can also provide Scan Response data, which has to be explicitly queried
445by the central device. It can be set with *gap_scan_response_set_data*.
446
447Please have a look at the [SPP and LE
448Counter example](examples/examples/#sec:sppandlecounterExample).
449
450The scan parameters can be set with
451*gap_set_scan_parameters*. The scan can be started/stopped
452with *gap_start_scan*/*gap_stop_scan*.
453
454Finally, if a suitable device is found, a connection can be initiated by
455calling *gap_connect*. In contrast to Bluetooth classic, there
456is no timeout for an LE connection establishment. To cancel such an
457attempt, *gap_connect_cancel* has be be called.
458
459By default, a Bluetooth device stops sending Advertisements when it gets
460into the Connected state. However, it does not start broadcasting
461advertisements on disconnect again. To re-enable it, please send the
462*hci_le_set_advertise_enable* again .
463
464## GATT Client {#sec:GATTClientProfiles}
465
466The GATT profile uses ATT Attributes to represent a hierarchical
467structure of GATT Services and GATT Characteristics. Each Service has
468one or more Characteristics. Each Characteristic has meta data attached
469like its type or its properties. This hierarchy of Characteristics and
470Services are queried and modified via ATT operations.
471
472GATT defines both a server and a client role. A device can implement one
473or both GATT roles.
474
475The GATT Client is used to discover services, characteristics
476and their descriptors on a peer device. It allows to subscribe for
477notifications or indications that the characteristic on the GATT server
478has changed its value.
479
480To perform GATT queries, it provides a rich interface. Before calling
481queries, the GATT client must be initialized with *gatt_client_init*
482once.
483
484To allow for modular profile implementations, GATT client can be used
485independently by multiple entities.
486
487After an LE connection was created using the GAP LE API, you can query
488for the connection MTU with *gatt_client_get_mtu*.
489
490Multiple GATT queries to the same GATT Server cannot be interleaved.
491Therefore, you can either use a state machine or similar to perform the
492queries in sequence, or you can check if you can perform a GATT query
493on a particular connection right now using
494*gatt_client_is_ready*, and retry later if it is not ready.
495As a result to a GATT query, zero to many
496*GATT_EVENT_X*s are returned before a *GATT_EVENT_QUERY_COMPLETE* event
497completes the query.
498
499For more details on the available GATT queries, please consult
500[GATT Client API](#sec:gattClientAPIAppendix).
501
502### Authentication
503
504By default, the GATT Server is responsible for security and the GATT Client does not enforce any kind of authentication.
505If the GATT Client accesses Characteristic that require encrytion or authentication, the remote GATT Server will return an error,
506which is returned in the *att status* of the *GATT_EVENT_QUERY_COMPLETE*.
507
508You can define *ENABLE_GATT_CLIENT_PAIRING* to instruct the GATT Client to trigger pairing in this case and to repeat the request.
509
510This model allows for an attacker to spoof another device, but don't require authentication for the Characteristics.
511As a first improvement, you can define *ENABLE_LE_PROACTIVE_AUTHENTICATION* in *btstack_config.h*. When defined, the GATT Client will
512request the Security Manager to re-encrypt the connection if there is stored bonding information available.
513If this fails, the  *GATT_EVENT_QUERY_COMPLETE* will return with the att status *ATT_ERROR_BONDING_INFORMATION_MISSING*.
514
515With *ENABLE_LE_PROACTIVE_AUTHENTICATION* defined and in Central role, you need to delete the local bonding information if the remote
516lost its bonding information, e.g. because of a device reset. See *example/sm_pairing_central.c*.
517
518Even with the Proactive Authentication, your device may still connect to an attacker that provides the same advertising data as
519your actual device. If the device that you want to connect requires pairing, you can instruct the GATT Client to automatically
520request an encrypted connection before sending any GATT Client request by calling *gatt_client_set_required_security_level()*.
521If the device provides sufficient IO capabilities, a MITM attack can then be prevented. We call this 'Mandatory Authentication'.
522
523The following diagrams provide a detailed overview about the GATT Client security mechanisms in different configurations:
524
525-  [Reactive Authentication as Central](picts/gatt_client_security_reactive_authentication_central.svg)
526-  [Reactive Authentication as Peripheral](picts/gatt_client_security_reactive_authentication_peripheral.svg)
527-  [Proactive Authentication as Central](picts/gatt_client_security_proactive_authentication_central.svg)
528-  [Proactive Authentication as Peripheral](picts/gatt_client_security_proactive_authentication_peripheral.svg)
529-  [Mandatory Authentication as Central](picts/gatt_client_security_mandatory_authentication_central.svg)
530-  [Mandatory Authentication as Peripheral](picts/gatt_client_security_mandatory_authentication_peripheral.svg)
531
532## GATT Server {#sec:GATTServerProfiles}
533
534The GATT server stores data and accepts GATT client requests, commands
535and confirmations. The GATT server sends responses to requests and when
536configured, sends indication and notifications asynchronously to the
537GATT client.
538
539To save on both code space and memory, BTstack does not provide a GATT
540Server implementation. Instead, a textual description of the GATT
541profile is directly converted into a compact internal ATT Attribute
542database by a GATT profile compiler. The ATT protocol server -
543implemented by and - answers incoming ATT requests based on information
544provided in the compiled database and provides read- and write-callbacks
545for dynamic attributes.
546
547GATT profiles are defined by a simple textual comma separated value
548(.csv) representation. While the description is easy to read and edit,
549it is compact and can be placed in ROM.
550
551The current format is shown in Listing [below](#lst:GATTServerProfile).
552
553~~~~ {#lst:GATTServerProfile .c caption="{GATT profile.}"}
554    // import service_name
555    #import <service_name.gatt>
556
557    PRIMARY_SERVICE, {SERVICE_UUID}
558    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
559    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
560    ...
561    PRIMARY_SERVICE, {SERVICE_UUID}
562    CHARACTERISTIC, {ATTRIBUTE_TYPE_UUID}, {PROPERTIES}, {VALUE}
563    ...
564~~~~
565
566UUIDs are either 16 bit (1800) or 128 bit
567(00001234-0000-1000-8000-00805F9B34FB).
568
569Value can either be a string (“this is a string”), or, a sequence of hex
570bytes (e.g. 01 02 03).
571
572Properties can be a list of properties combined using '|'
573
574Reads/writes to a Characteristic that is defined with the DYNAMIC flag,
575are forwarded to the application via callback. Otherwise, the
576Characteristics cannot be written and it will return the specified
577constant value.
578
579Adding NOTIFY and/or INDICATE automatically creates an addition Client
580Configuration Characteristic.
581
582Property                | Meaning
583------------------------|-----------------------------------------------
584READ                    | Characteristic can be read
585WRITE                   | Characteristic can be written using Write Request
586WRITE_WITHOUT_RESPONSE  | Characteristic can be written using Write Command
587NOTIFY                  | Characteristic allows notifications by server
588INDICATE                | Characteristic allows indication by server
589DYNAMIC                 | Read or writes to Characteristic are handled by application
590
591To require encryption or authentication before a Characteristic can be
592accessed, you can add one or more of the following properties:
593
594Property                | Meaning
595------------------------|-----------------------------------------------
596AUTHENTICATION_REQUIRED | Read and Write operations require Authentication
597READ_ENCRYPTED          | Read operations require Encryption
598READ_AUTHENTICATED      | Read operations require Authentication
599WRITE_ENCRYPTED         | Write operations require Encryption
600WRITE_AUTHENTICATED     | Write operations require Authentication
601ENCRYPTION_KEY_SIZE_X   | Require encryption size >= X, with W in [7..16]
602
603To use already implemented GATT Services, you can import it
604using the *#import <service_name.gatt>* command. See [list of provided services](gatt_services.md).
605
606BTstack only provides an ATT Server, while the GATT Server logic is
607mainly provided by the GATT compiler. While GATT identifies
608Characteristics by UUIDs, ATT uses Handles (16 bit values). To allow to
609identify a Characteristic without hard-coding the attribute ID, the GATT
610compiler creates a list of defines in the generated \*.h file.
611
612Similar to other protocols, it might be not possible to send any time.
613To send a Notification, you can call *att_server_request_can_send_now*
614to receive a ATT_EVENT_CAN_SEND_NOW event.
615
616If your application cannot handle an ATT Read Request in the *att_read_callback*
617in some situations, you can enable support for this by adding ENABLE_ATT_DELAYED_RESPONSE
618to *btstack_config.h*. Now, you can store the requested attribute handle and return
619*ATT_READ_RESPONSE_PENDING* instead of the length of the provided data when you don't have the data ready.
620For ATT operations that read more than one attribute, your *att_read_callback*
621might get called multiple times as well. To let you know that all necessary
622attribute handles have been 'requested' by the *att_server*, you'll get a final
623*att_read_callback* with the attribute handle of *ATT_READ_RESPONSE_PENDING*.
624When you've got the data for all requested attributes ready, you can call
625*att_server_response_ready*, which will trigger processing of the current request.
626Please keep in mind that there is only one active ATT operation and that it has a 30 second
627timeout after which the ATT server is considered defunct by the GATT Client.
628
629### Implementing Standard GATT Services {#sec:GATTStandardServices}
630
631Implementation of a standard GATT Service consists of the following 4 steps:
632
633  1. Identify full Service Name
634  2. Use Service Name to fetch XML definition at Bluetooth SIG site and convert into generic .gatt file
635  3. Edit .gatt file to set constant values and exclude unwanted Characteristics
636  4. Implement Service server, e.g., battery_service_server.c
637
638Step 1:
639
640To facilitate the creation of .gatt files for standard profiles defined by the Bluetooth SIG,
641the *tool/convert_gatt_service.py* script can be used. When run without a parameter, it queries the
642Bluetooth SIG website and lists the available Services by their Specification Name, e.g.,
643*org.bluetooth.service.battery_service*.
644
645    $ tool/convert_gatt_service.py
646    Fetching list of services from https://www.bluetooth.com/specifications/gatt/services
647
648    Specification Type                                     | Specification Name            | UUID
649    -------------------------------------------------------+-------------------------------+-----------
650    org.bluetooth.service.alert_notification               | Alert Notification Service    | 0x1811
651    org.bluetooth.service.automation_io                    | Automation IO                 | 0x1815
652    org.bluetooth.service.battery_service                  | Battery Service               | 0x180F
653    ...
654    org.bluetooth.service.weight_scale                     | Weight Scale                  | 0x181D
655
656    To convert a service into a .gatt file template, please call the script again with the requested Specification Type and the output file name
657    Usage: tool/convert_gatt_service.py SPECIFICATION_TYPE [service_name.gatt]
658
659Step 2:
660
661To convert service into .gatt file, call *tool/convert_gatt_service.py with the requested Specification Type and the output file name.
662
663    $ tool/convert_gatt_service.py org.bluetooth.service.battery_service battery_service.gatt
664    Fetching org.bluetooth.service.battery_service from
665    https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.battery_service.xml
666
667    Service Battery Service
668    - Characteristic Battery Level - properties ['Read', 'Notify']
669    -- Descriptor Characteristic Presentation Format       - TODO: Please set values
670    -- Descriptor Client Characteristic Configuration
671
672    Service successfully converted into battery_service.gatt
673    Please check for TODOs in the .gatt file
674
675
676Step 3:
677
678In most cases, you will need to customize the .gatt file. Please pay attention to the tool output and have a look
679at the generated .gatt file.
680
681E.g. in the generated .gatt file for the Battery Service
682
683    // Specification Type org.bluetooth.service.battery_service
684    // https://www.bluetooth.com/api/gatt/xmlfile?xmlFileName=org.bluetooth.service.battery_service.xml
685
686    // Battery Service 180F
687    PRIMARY_SERVICE, ORG_BLUETOOTH_SERVICE_BATTERY_SERVICE
688    CHARACTERISTIC, ORG_BLUETOOTH_CHARACTERISTIC_BATTERY_LEVEL, DYNAMIC | READ | NOTIFY,
689    // TODO: Characteristic Presentation Format: please set values
690    #TODO CHARACTERISTIC_FORMAT, READ, _format_, _exponent_, _unit_, _name_space_, _description_
691    CLIENT_CHARACTERISTIC_CONFIGURATION, READ | WRITE,
692
693you could delete the line regarding the CHARACTERISTIC_FORMAT, since it's not required if there is a single instance of the service.
694Please compare the .gatt file against the [Adopted Specifications](https://www.bluetooth.com/specifications/adopted-specifications).
695
696Step 4:
697
698As described [above](#sec:GATTServerProfiles) all read/write requests are handled by the application.
699To implement the new services as a reusable module, it's necessary to get access to all read/write requests related to this service.
700
701For this, the ATT DB allows to register read/write callbacks for a specific handle range with *att_server_register_can_send_now_callback()*.
702
703Since 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*.
704
705Similarly, 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()*.
706
707In 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()*
708
709Finally, 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.
710
711To see how this works together, please check out the Battery Service Server in *src/ble/battery_service_server.c*.
712
713### GATT Database Hash
714
715When a GATT Client connects to a GATT Server, it cannot know if the GATT Database has changed
716and has to discover the provided GATT Services and Characteristics after each connect.
717
718To speed this up, the Bluetooth
719specification defines a GATT Service Changed Characteristic, with the idea that a GATT Server would notify
720a bonded GATT Client if its database changed. However, this is quite fragile and it is not clear how it can be implemented
721in a robust way.
722
723The Bluetooth Core Spec 5.1 introduced the GATT Database Hash Characteristic, which allows for a simple
724robust mechanism to cache a remote GATT Database. The GATT Database Hash is a 16-byte value that is calculated
725over the list of Services and Characteristics. If there is any change to the database, the hash will change as well.
726
727To support this on the GATT Server, you only need to add a GATT Service with the GATT Database Characteristic to your .gatt file.
728The hash value is then calculated by the GATT compiler.
729
730
731    PRIMARY_SERVICE, GATT_SERVICE
732    CHARACTERISTIC, GATT_DATABASE_HASH, READ,
733
734Note: make sure to install the PyCryptodome python package as the hash is calculated using AES-CMAC,
735e.g. with:
736
737    pip install pycryptodomex
738