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