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