1 /** @file
2 * @brief Generic Attribute Profile handling.
3 */
4
5 /*
6 * Copyright (c) 2015-2016 Intel Corporation
7 *
8 * SPDX-License-Identifier: Apache-2.0
9 */
10 #ifndef ZEPHYR_INCLUDE_BLUETOOTH_GATT_H_
11 #define ZEPHYR_INCLUDE_BLUETOOTH_GATT_H_
12
13 /**
14 * @brief Generic Attribute Profile (GATT)
15 * @details The GATT layer manages the service database by providing APIs for
16 * service registration and attribute declaration. For more
17 * information, see @ref bt_gatt_client and @ref bt_gatt_server.
18 * @defgroup bt_gatt Generic Attribute Profile (GATT)
19 * @ingroup bluetooth
20 * @{
21 */
22
23 #include <stdint.h>
24 #include <stddef.h>
25 #include <string.h>
26
27 #include <sys/types.h>
28
29 #include <zephyr/autoconf.h>
30 #include <zephyr/bluetooth/addr.h>
31 #include <zephyr/bluetooth/conn.h>
32 #include <zephyr/bluetooth/uuid.h>
33 #include <zephyr/bluetooth/att.h>
34 #include <zephyr/sys/atomic.h>
35 #include <zephyr/sys/iterable_sections.h>
36 #include <zephyr/sys/slist.h>
37 #include <zephyr/sys/util.h>
38 #include <zephyr/sys/util_macro.h>
39 #include <zephyr/toolchain.h>
40
41 #ifdef __cplusplus
42 extern "C" {
43 #endif
44
45 /** GATT attribute permission bit field values */
46 enum bt_gatt_perm {
47 /** No operations supported, e.g. for notify-only */
48 BT_GATT_PERM_NONE = 0,
49
50 /** Attribute read permission. */
51 BT_GATT_PERM_READ = BIT(0),
52
53 /** Attribute write permission. */
54 BT_GATT_PERM_WRITE = BIT(1),
55
56 /** @brief Attribute read permission with encryption.
57 *
58 * If set, requires encryption for read access.
59 */
60 BT_GATT_PERM_READ_ENCRYPT = BIT(2),
61
62 /** @brief Attribute write permission with encryption.
63 *
64 * If set, requires encryption for write access.
65 */
66 BT_GATT_PERM_WRITE_ENCRYPT = BIT(3),
67
68 /** @brief Attribute read permission with authentication.
69 *
70 * If set, requires encryption using authenticated link-key for read
71 * access.
72 */
73 BT_GATT_PERM_READ_AUTHEN = BIT(4),
74
75 /** @brief Attribute write permission with authentication.
76 *
77 * If set, requires encryption using authenticated link-key for write
78 * access.
79 */
80 BT_GATT_PERM_WRITE_AUTHEN = BIT(5),
81
82 /** @brief Attribute prepare write permission.
83 *
84 * If set, allows prepare writes with use of ``BT_GATT_WRITE_FLAG_PREPARE``
85 * passed to write callback.
86 */
87 BT_GATT_PERM_PREPARE_WRITE = BIT(6),
88
89 /** @brief Attribute read permission with LE Secure Connection encryption.
90 *
91 * If set, requires that LE Secure Connections is used for read access.
92 */
93 BT_GATT_PERM_READ_LESC = BIT(7),
94
95 /** @brief Attribute write permission with LE Secure Connection encryption.
96 *
97 * If set, requires that LE Secure Connections is used for write access.
98 */
99 BT_GATT_PERM_WRITE_LESC = BIT(8),
100 };
101
102 /**
103 * @brief Construct error return value for attribute read and write callbacks.
104 *
105 * @param _att_err ATT error code
106 *
107 * @return Appropriate error code for the attribute callbacks.
108 */
109 #define BT_GATT_ERR(_att_err) (-(_att_err))
110
111 /** GATT attribute write flags */
112 enum bt_gatt_attr_write_flag {
113 /** @brief Attribute prepare write flag
114 *
115 * If set, write callback should only check if the device is
116 * authorized but no data shall be written.
117 */
118 BT_GATT_WRITE_FLAG_PREPARE = BIT(0),
119
120 /** @brief Attribute write command flag
121 *
122 * If set, indicates that write operation is a command (Write without
123 * response) which doesn't generate any response.
124 */
125 BT_GATT_WRITE_FLAG_CMD = BIT(1),
126
127 /** @brief Attribute write execute flag
128 *
129 * If set, indicates that write operation is a execute, which indicates
130 * the end of a long write, and will come after 1 or more
131 * @ref BT_GATT_WRITE_FLAG_PREPARE.
132 */
133 BT_GATT_WRITE_FLAG_EXECUTE = BIT(2),
134 };
135
136 /* Forward declaration of GATT Attribute structure */
137 struct bt_gatt_attr;
138
139 /** @typedef bt_gatt_attr_read_func_t
140 * @brief Attribute read callback
141 *
142 * This is the type of the bt_gatt_attr.read() method.
143 *
144 * This function may safely assume the Attribute Permissions
145 * are satisfied for this read. Callers are responsible for
146 * this.
147 *
148 * Callers may set @p conn to emulate a GATT client read, or
149 * leave it NULL for local reads.
150 *
151 * @note GATT server relies on this method to handle read
152 * operations from remote GATT clients. But this method is not
153 * reserved for the GATT server. E.g. You can lookup attributes
154 * in the local ATT database and invoke this method.
155 *
156 * @note The GATT server propagates the return value from this
157 * method back to the remote client.
158 *
159 * @param conn The connection that is requesting to read.
160 * NULL if local.
161 * @param attr The attribute that's being read
162 * @param buf Buffer to place the read result in
163 * @param len Length of data to read
164 * @param offset Offset to start reading from
165 *
166 * @return Number of bytes read, or in case of an error
167 * ``BT_GATT_ERR()`` with a specific ``BT_ATT_ERR_*`` error code.
168 */
169 typedef ssize_t (*bt_gatt_attr_read_func_t)(struct bt_conn *conn,
170 const struct bt_gatt_attr *attr,
171 void *buf, uint16_t len,
172 uint16_t offset);
173
174 /** @typedef bt_gatt_attr_write_func_t
175 * @brief Attribute Value write implementation
176 *
177 * This is the type of the bt_gatt_attr.write() method.
178 *
179 * This function may safely assume the Attribute Permissions
180 * are satisfied for this write. Callers are responsible for
181 * this.
182 *
183 * Callers may set @p conn to emulate a GATT client write, or
184 * leave it NULL for local writes.
185 *
186 * If @p flags contains @ref BT_GATT_WRITE_FLAG_PREPARE, then
187 * the method shall not perform a write, but instead only check
188 * if the write is authorized and return an error code if not.
189 *
190 * Attribute Value write implementations can and often do have
191 * side effects besides potentially storing the value. E.g.
192 * togging an LED.
193 *
194 * @note GATT server relies on this method to handle write
195 * operations from remote GATT clients. But this method is not
196 * reserved for the GATT server. E.g. You can lookup attributes
197 * in the local ATT database and invoke this method.
198 *
199 * @note The GATT server propagates the return value from this
200 * method back to the remote client.
201 *
202 * @param conn The connection that is requesting to write
203 * @param attr The attribute that's being written
204 * @param buf Buffer with the data to write
205 * @param len Number of bytes in the buffer
206 * @param offset Offset to start writing from
207 * @param flags Flags of type @ref bt_gatt_attr_write_flag
208 *
209 * @return Number of bytes written, or in case of an error
210 * ``BT_GATT_ERR()`` with a specific ``BT_ATT_ERR_*`` error code.
211 */
212 typedef ssize_t (*bt_gatt_attr_write_func_t)(struct bt_conn *conn,
213 const struct bt_gatt_attr *attr,
214 const void *buf, uint16_t len,
215 uint16_t offset, uint8_t flags);
216
217 /** @brief GATT Attribute
218 *
219 * This type primarily represents an ATT Attribute that may be
220 * an entry in the local ATT database. The objects of this type
221 * must be part of an array that forms a GATT service.
222 *
223 * While the formed GATT service is registered with the local
224 * GATT server, pointers to this type can typically be given to
225 * GATT server APIs, like bt_gatt_notify().
226 */
227 struct bt_gatt_attr {
228 /** @brief Attribute Type
229 *
230 * The Attribute Type is a UUID which determines the interface that can
231 * be expected from the read() and write() methods and
232 * the possible permission configurations.
233 *
234 * E.g. Attribute of type @ref BT_UUID_GATT_CPF will act as a
235 * GATT Characteristic Presentation Format descriptor as
236 * specified in Core Specification 3.G.3.3.3.5.
237 *
238 * You can define a new Attribute Type for your application specific
239 * use by generating a new UUID for it.
240 */
241 const struct bt_uuid *uuid;
242
243 /** @brief Attribute Value read method
244 *
245 * Readable Attributes must implement this method.
246 *
247 * Must be NULL if the attribute is not readable.
248 *
249 * The behavior of this method is determined by the Attribute
250 * Type.
251 *
252 * See @ref bt_gatt_attr_read_func_t.
253 */
254 bt_gatt_attr_read_func_t read;
255
256 /** @brief Attribute Value write method
257 *
258 * Writeable Attributes must implement this method.
259 *
260 * Must be NULL if the attribute is not writable.
261 *
262 * The behavior of this method is determined by the Attribute
263 * Type.
264 *
265 * See @ref bt_gatt_attr_write_func_t.
266 */
267 bt_gatt_attr_write_func_t write;
268
269 /** @brief Private data for read() and write() implementation
270 *
271 * The meaning of this field varies and is not specified here.
272 *
273 * @note Attributes may have the same Attribute Type but have
274 * different implementations, with incompatible user data.
275 * Attribute Type alone must not be used to infer the type of
276 * the user data.
277 *
278 * @sa bt_gatt_discover_func_t about this field.
279 */
280 void *user_data;
281
282 /** @brief Attribute Handle
283 *
284 * The Attribute Handle is an index corresponding to a specific
285 * Attribute in the ATT database.
286 *
287 * @note Use bt_gatt_attr_get_handle() for attributes in the
288 * local ATT database.
289 */
290 uint16_t handle;
291
292 /** @brief Attribute Permissions
293 *
294 * Bit field of @ref bt_gatt_perm.
295 *
296 * The permissions are security requirements that must be
297 * satisfied before calling read() or write().
298 */
299 uint16_t perm: 15;
300
301 /** @cond INTERNAL_HIDDEN
302 * Indicates if the attribute handle was assigned automatically.
303 *
304 * This flag is set to 1 if the attribute handle was assigned by the stack,
305 * and 0 if it was manually set by the application.
306 *
307 * @note Applications must not modify this field.
308 */
309 bool _auto_assigned_handle: 1;
310 /** @endcond */
311 };
312
313 /** @brief Static GATT Service structure
314 *
315 * Allows the user the declare static GATT Services with the aim of reducing the
316 * used RAM. The @ref BT_GATT_SERVICE_DEFINE macro can be used to statically
317 * define and register a service.
318 */
319 struct bt_gatt_service_static {
320 /** Service Attributes */
321 const struct bt_gatt_attr *attrs;
322 /** Service Attribute count */
323 size_t attr_count;
324 };
325
326 /** @brief GATT Service structure
327 *
328 * This structure is used to define GATT services which can be registered and
329 * unregistered at runtime. See @ref bt_gatt_service_register for when services
330 * should be registered.
331 */
332 struct bt_gatt_service {
333 /** Service Attributes */
334 struct bt_gatt_attr *attrs;
335 /** Service Attribute count */
336 size_t attr_count;
337 /** @cond INTERNAL_HIDDEN
338 * Field used for list handling.
339 */
340 sys_snode_t node;
341 /** @endcond */
342 };
343
344 /** @brief Service Attribute Value.
345 *
346 * This is the data described by the Attribute Type and indexed by the
347 * Attribute Handle in the database.
348 */
349 struct bt_gatt_service_val {
350 /** Service UUID. */
351 const struct bt_uuid *uuid;
352 /** Handle of the last Attribute within the Service. */
353 uint16_t end_handle;
354 };
355
356 /** @brief Include Attribute Value.
357 *
358 * This structure represents an included service attribute in the GATT
359 * server. An included service is a service that is referenced within another
360 * service, allowing for the reuse of common service definitions.
361 */
362 struct bt_gatt_include {
363 /** Service UUID. */
364 const struct bt_uuid *uuid;
365 /** Handle of the first attribute within the included service. */
366 uint16_t start_handle;
367 /** Handle of the last attribute within the included service. */
368 uint16_t end_handle;
369 };
370
371 /** @brief GATT callback structure. */
372 struct bt_gatt_cb {
373 /** @brief The maximum ATT MTU on a connection has changed.
374 *
375 * This callback notifies the application that the maximum TX or RX
376 * ATT MTU has increased.
377 *
378 * @param conn Connection object.
379 * @param tx Updated TX ATT MTU.
380 * @param rx Updated RX ATT MTU.
381 */
382 void (*att_mtu_updated)(struct bt_conn *conn, uint16_t tx, uint16_t rx);
383
384 /** @cond INTERNAL_HIDDEN
385 * Field used for list handling.
386 */
387 sys_snode_t node;
388 /** @endcond */
389 };
390
391 /** @brief GATT authorization callback structure. */
392 struct bt_gatt_authorization_cb {
393 /** @brief Authorize the GATT read operation.
394 *
395 * This callback allows the application to authorize the GATT
396 * read operation for the attribute that is being read.
397 *
398 * @param conn Connection object.
399 * @param attr The attribute that is being read.
400 *
401 * @retval true Authorize the operation and allow it to execute.
402 * @retval false Reject the operation and prevent it from executing.
403 */
404 bool (*read_authorize)(struct bt_conn *conn,
405 const struct bt_gatt_attr *attr);
406
407 /** @brief Authorize the GATT write operation.
408 *
409 * This callback allows the application to authorize the GATT
410 * write operation for the attribute that is being written.
411 *
412 * @param conn Connection object.
413 * @param attr The attribute that is being written.
414 *
415 * @retval true Authorize the operation and allow it to execute.
416 * @retval false Reject the operation and prevent it from executing.
417 */
418 bool (*write_authorize)(struct bt_conn *conn,
419 const struct bt_gatt_attr *attr);
420 };
421
422 /** Characteristic Properties Bit field values */
423
424 /**
425 * @brief Characteristic broadcast property.
426 *
427 * If set, permits broadcasts of the Characteristic Value using Server
428 * Characteristic Configuration Descriptor.
429 */
430 #define BT_GATT_CHRC_BROADCAST 0x01
431 /**
432 * @brief Characteristic read property.
433 *
434 * If set, permits reads of the Characteristic Value.
435 */
436 #define BT_GATT_CHRC_READ 0x02
437 /**
438 * @brief Characteristic write without response property.
439 *
440 * If set, permits write of the Characteristic Value without response.
441 */
442 #define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04
443 /**
444 * @brief Characteristic write with response property.
445 *
446 * If set, permits write of the Characteristic Value with response.
447 */
448 #define BT_GATT_CHRC_WRITE 0x08
449 /**
450 * @brief Characteristic notify property.
451 *
452 * If set, permits notifications of a Characteristic Value without
453 * acknowledgment.
454 */
455 #define BT_GATT_CHRC_NOTIFY 0x10
456 /**
457 * @brief Characteristic indicate property.
458 *
459 * If set, permits indications of a Characteristic Value with acknowledgment.
460 */
461 #define BT_GATT_CHRC_INDICATE 0x20
462 /**
463 * @brief Characteristic Authenticated Signed Writes property.
464 *
465 * @deprecated This API is deprecated.
466 *
467 * If set, permits signed writes to the Characteristic Value.
468 */
469 #define BT_GATT_CHRC_AUTH 0x40 __DEPRECATED_MACRO
470 /**
471 * @brief Characteristic Extended Properties property.
472 *
473 * If set, additional characteristic properties are defined in the
474 * Characteristic Extended Properties Descriptor.
475 */
476 #define BT_GATT_CHRC_EXT_PROP 0x80
477
478 /** @brief Attribute Value of a Characteristic Declaration.
479 *
480 * This is the data associated with the characteristic, and can be read from or
481 * written to by a GATT client depending on the characteristic properties.
482 */
483 struct bt_gatt_chrc {
484 /** Characteristic UUID. */
485 const struct bt_uuid *uuid;
486 /** Characteristic Value handle. */
487 uint16_t value_handle;
488 /** Characteristic properties, a bitmap of ``BT_GATT_CHRC_*`` macros. */
489 uint8_t properties;
490 };
491
492 /** Characteristic Extended Properties Bit field values */
493 #define BT_GATT_CEP_RELIABLE_WRITE 0x0001
494 #define BT_GATT_CEP_WRITABLE_AUX 0x0002
495
496 /** @brief Characteristic Extended Properties Attribute Value.
497 *
498 * Used in the discovery of standard characteristic descriptor values. Shall
499 * exist if the @ref BT_GATT_CHRC_EXT_PROP bit is set in the characteristic
500 * properties. Can be used with the @ref BT_GATT_CEP macro to declare the CEP
501 * descriptor.
502 */
503 struct bt_gatt_cep {
504 /** Characteristic Extended properties, a bitmap of ``BT_GATT_CEP_*`` macros. */
505 uint16_t properties;
506 };
507
508 /** Client Characteristic Configuration Values */
509
510 /**
511 * @brief Client Characteristic Configuration Notification.
512 *
513 * If set, changes to Characteristic Value shall be notified.
514 */
515 #define BT_GATT_CCC_NOTIFY 0x0001
516 /**
517 * @brief Client Characteristic Configuration Indication.
518 *
519 * If set, changes to Characteristic Value shall be indicated.
520 */
521 #define BT_GATT_CCC_INDICATE 0x0002
522
523 /** @brief Client Characteristic Configuration Attribute Value
524 *
525 * Used in the discovery of standard characteristic descriptor values.
526 */
527 struct bt_gatt_ccc {
528 /** Client Characteristic Configuration flags, a bitmap of ``BT_GATT_CCC_*`` macros. */
529 uint16_t flags;
530 };
531
532 /** Server Characteristic Configuration Values */
533
534 /**
535 * @brief Server Characteristic Configuration Broadcast
536 *
537 * If set, the characteristic value shall be broadcast in the advertising data
538 * when the server is advertising.
539 */
540 #define BT_GATT_SCC_BROADCAST 0x0001
541
542 /** @brief Server Characteristic Configuration Attribute Value
543 *
544 * Used in the discovery of standard characteristic descriptor values.
545 */
546 struct bt_gatt_scc {
547 /** Server Characteristic Configuration flags, a bitmap of ``BT_GATT_SCC_*`` macros. */
548 uint16_t flags;
549 };
550
551 /** @brief GATT Characteristic Presentation Format Attribute Value.
552 *
553 * Used in the discovery of standard characteristic descriptor values. Can be
554 * used with the @ref BT_GATT_CPF macro to declare the CPF descriptor.
555 */
556 struct bt_gatt_cpf {
557 /** @brief Format of the value of the characteristic.
558 *
559 * The format types can be found in section 2.4.1 of the Bluetooth SIG
560 * Assigned Numbers document.
561 */
562 uint8_t format;
563 /** @brief Exponent field for value formatting.
564 *
565 * Only used on integer format types.
566 * actual value = Characteristic Value x 10^Exponent
567 */
568 int8_t exponent;
569 /** @brief UUID of the unit of the characteristic.
570 *
571 * The units can be found in section 3.5 of the Bluetooth SIG Assigned
572 * Numbers document.
573 */
574 uint16_t unit;
575 /** @brief Name space of the description.
576 *
577 * Used to identify the organization that is responsible for defining
578 * the enumerations for the description field. See section 2.4.2 of the
579 * Bluetooth SIG Assigned Numbers document.
580 */
581 uint8_t name_space;
582 /** @brief Description of the characteristic as defined in a higher layer profile.
583 *
584 * An enumerated value defined by the organization identified by the
585 * name_space field. See section 2.4.2.1 of the Bluetooth SIG Assigned
586 * Numbers document.
587 */
588 uint16_t description;
589 };
590
591 /**
592 * @defgroup bt_gatt_server GATT Server APIs
593 * @ingroup bt_gatt
594 * @{
595 */
596
597 /** Converts a GATT error to string.
598 *
599 * The GATT errors are created with @ref BT_GATT_ERR.
600 *
601 * The error codes are described in the Bluetooth Core specification,
602 * Vol 3, Part F, Section 3.4.1.1.
603 *
604 * The ATT and GATT documentation found in Vol 4, Part F and
605 * Part G describe when the different error codes are used.
606 *
607 * See also the defined BT_ATT_ERR_* macros.
608 *
609 * @return The string representation of the GATT error code.
610 * If @kconfig{CONFIG_BT_ATT_ERR_TO_STR} is not enabled,
611 * this just returns the empty string.
612 */
bt_gatt_err_to_str(int gatt_err)613 static inline const char *bt_gatt_err_to_str(int gatt_err)
614 {
615 return bt_att_err_to_str((gatt_err) < 0 ? -(gatt_err) : (gatt_err));
616 }
617
618 /** @brief Register GATT callbacks.
619 *
620 * Register callbacks to monitor the state of GATT. The callback struct
621 * must remain valid for the remainder of the program.
622 *
623 * @param cb Callback struct.
624 */
625 void bt_gatt_cb_register(struct bt_gatt_cb *cb);
626
627 /** @brief Unregister GATT callbacks.
628 *
629 * Unregister callbacks for monitoring the state of GATT. The callback
630 * struct should be one that was previously registered.
631 *
632 * @param cb Callback struct.
633 *
634 * @return 0 in case of success or negative value in case of error.
635 */
636 int bt_gatt_cb_unregister(struct bt_gatt_cb *cb);
637
638 /** @brief Register GATT authorization callbacks.
639 *
640 * Register callbacks to perform application-specific authorization of GATT
641 * operations on all registered GATT attributes. The callback structure must
642 * remain valid throughout the entire duration of the Bluetooth subsys
643 * activity.
644 *
645 * The @kconfig{CONFIG_BT_GATT_AUTHORIZATION_CUSTOM} Kconfig must be enabled
646 * to make this API functional.
647 *
648 * This API allows the user to register only one callback structure
649 * concurrently. Passing NULL unregisters the previous set of callbacks
650 * and makes it possible to register a new one.
651 *
652 * @param cb Callback struct.
653 *
654 * @return Zero on success or negative error code otherwise.
655 */
656 int bt_gatt_authorization_cb_register(const struct bt_gatt_authorization_cb *cb);
657
658 /** @brief Register GATT service.
659 *
660 * To register a GATT service, applications can make use of macros such as
661 * ``BT_GATT_PRIMARY_SERVICE``, ``BT_GATT_CHARACTERISTIC``,
662 * ``BT_GATT_DESCRIPTOR``, etc.
663 *
664 * When using @kconfig{CONFIG_BT_SETTINGS} then all services that should have
665 * bond configuration loaded, i.e. CCC values, must be registered before
666 * calling @ref settings_load.
667 *
668 * When using @kconfig{CONFIG_BT_GATT_CACHING} and @kconfig{CONFIG_BT_SETTINGS}
669 * then all services that should be included in the GATT Database Hash
670 * calculation should be added before calling @ref settings_load.
671 * All services registered after settings_load will trigger a new database hash
672 * calculation and a new hash stored.
673 *
674 * There are two situations where this function can be called: either before
675 * `bt_init()` has been called, or after `settings_load()` has been called.
676 * Registering a service in the middle is not supported and will return an
677 * error.
678 *
679 * @param svc Service containing the available attributes
680 *
681 * @return 0 in case of success or negative value in case of error.
682 * @return -EAGAIN if ``bt_init()`` has been called but ``settings_load()`` hasn't yet.
683 */
684 int bt_gatt_service_register(struct bt_gatt_service *svc);
685
686 /** @brief Unregister GATT service.
687 *
688 * @param svc Service to be unregistered.
689 *
690 * @return 0 in case of success or negative value in case of error.
691 */
692 int bt_gatt_service_unregister(struct bt_gatt_service *svc);
693
694 /** @brief Check if GATT service is registered.
695 *
696 * @param svc Service to be checked.
697 *
698 * @return true if registered or false if not register.
699 */
700 bool bt_gatt_service_is_registered(const struct bt_gatt_service *svc);
701
702 /** @brief to be used as return values for @ref bt_gatt_attr_func_t and @ref bt_gatt_read_func_t
703 * type callbacks.
704 */
705 enum bt_gatt_iter {
706 BT_GATT_ITER_STOP = 0,
707 BT_GATT_ITER_CONTINUE,
708 };
709
710 /** @typedef bt_gatt_attr_func_t
711 * @brief Attribute iterator callback.
712 *
713 * @param attr Attribute found.
714 * @param handle Attribute handle found.
715 * @param user_data Data given.
716 *
717 * @return ``BT_GATT_ITER_CONTINUE`` if should continue to the next attribute.
718 * @return ``BT_GATT_ITER_STOP`` to stop.
719 */
720 typedef uint8_t (*bt_gatt_attr_func_t)(const struct bt_gatt_attr *attr,
721 uint16_t handle,
722 void *user_data);
723
724 /** @brief Attribute iterator by type.
725 *
726 * Iterate attributes in the given range matching given UUID and/or data.
727 *
728 * @param start_handle Start attribute handle.
729 * @param end_handle End attribute handle. Often set to start_handle + attr_count or
730 * BT_ATT_LAST_ATTRIBUTE_HANDLE.
731 * @param uuid UUID to match, passing NULL skips UUID matching.
732 * @param attr_data Attribute data to match, passing NULL skips data matching.
733 * @param num_matches Number matches, passing 0 makes it unlimited.
734 * @param func Callback function.
735 * @param user_data Data to pass to the callback.
736 */
737 void bt_gatt_foreach_attr_type(uint16_t start_handle, uint16_t end_handle,
738 const struct bt_uuid *uuid,
739 const void *attr_data, uint16_t num_matches,
740 bt_gatt_attr_func_t func,
741 void *user_data);
742
743 /** @brief Attribute iterator.
744 *
745 * Iterate attributes in the given range.
746 *
747 * @param start_handle Starting attribute handle.
748 * @param end_handle Ending attribute handle.
749 * @param func Callback function.
750 * @param user_data Data to pass to the callback.
751 */
bt_gatt_foreach_attr(uint16_t start_handle,uint16_t end_handle,bt_gatt_attr_func_t func,void * user_data)752 static inline void bt_gatt_foreach_attr(uint16_t start_handle, uint16_t end_handle,
753 bt_gatt_attr_func_t func,
754 void *user_data)
755 {
756 bt_gatt_foreach_attr_type(start_handle, end_handle, NULL, NULL, 0, func,
757 user_data);
758 }
759
760 /** @brief Iterate to the next attribute
761 *
762 * Iterate to the next attribute following a given attribute.
763 *
764 * @param attr Current Attribute.
765 *
766 * @return The next attribute or NULL if it cannot be found.
767 */
768 struct bt_gatt_attr *bt_gatt_attr_next(const struct bt_gatt_attr *attr);
769
770 /** @brief Find Attribute by UUID.
771 *
772 * Find the attribute with the matching UUID.
773 * To limit the search to a service set the attr to the service attributes and
774 * the ``attr_count`` to the service attribute count .
775 *
776 * @param attr Pointer to an attribute that serves as the starting point
777 * for the search of a match for the UUID.
778 * Passing NULL will search the entire range.
779 * @param attr_count The number of attributes from the starting point to
780 * search for a match for the UUID.
781 * Set to 0 to search until the end.
782 * @param uuid UUID to match.
783 */
784 struct bt_gatt_attr *bt_gatt_find_by_uuid(const struct bt_gatt_attr *attr,
785 uint16_t attr_count,
786 const struct bt_uuid *uuid);
787
788 /** @brief Get Attribute handle.
789 *
790 * @param attr An attribute object currently registered in the
791 * local ATT server.
792 *
793 * @return Handle of the corresponding attribute or zero if the attribute
794 * could not be found.
795 */
796 uint16_t bt_gatt_attr_get_handle(const struct bt_gatt_attr *attr);
797
798 /** @brief Get the handle of the characteristic value descriptor.
799 *
800 * @param attr A Characteristic Attribute.
801 *
802 * @note The ``user_data`` of the attribute must be of type @ref bt_gatt_chrc and the ``uuid`` shall
803 * be BT_UUID_GATT_CHRC.
804 *
805 * @return the handle of the corresponding Characteristic Value. The value will
806 * be zero (the invalid handle) if @p attr was not a characteristic
807 * attribute.
808 */
809 uint16_t bt_gatt_attr_value_handle(const struct bt_gatt_attr *attr);
810
811 /** @brief Generic Read Attribute value helper.
812 *
813 * Read attribute value from local database storing the result into buffer.
814 *
815 * @param conn Connection object.
816 * @param attr Attribute to read.
817 * @param buf Buffer to store the value.
818 * @param buf_len Buffer length.
819 * @param offset Start offset.
820 * @param value Attribute value.
821 * @param value_len Length of the attribute value.
822 *
823 * @return number of bytes read in case of success or negative values in
824 * case of error.
825 */
826 ssize_t bt_gatt_attr_read(struct bt_conn *conn, const struct bt_gatt_attr *attr,
827 void *buf, uint16_t buf_len, uint16_t offset,
828 const void *value, uint16_t value_len);
829
830 /** @brief Read Service Attribute helper.
831 *
832 * Read service attribute value from local database storing the result into
833 * buffer after encoding it.
834 * @note Only use this with attributes which ``user_data`` is a ``bt_uuid``.
835 *
836 * @param conn Connection object.
837 * @param attr Attribute to read.
838 * @param buf Buffer to store the value read.
839 * @param len Buffer length.
840 * @param offset Start offset.
841 *
842 * @return number of bytes read in case of success or negative values in
843 * case of error.
844 */
845 ssize_t bt_gatt_attr_read_service(struct bt_conn *conn,
846 const struct bt_gatt_attr *attr,
847 void *buf, uint16_t len, uint16_t offset);
848
849 /**
850 * @brief Statically define and register a service.
851 *
852 * Helper macro to statically define and register a service.
853 *
854 * @param _name Service name.
855 */
856 #define BT_GATT_SERVICE_DEFINE(_name, ...) \
857 const struct bt_gatt_attr attr_##_name[] = { __VA_ARGS__ }; \
858 const STRUCT_SECTION_ITERABLE(bt_gatt_service_static, _name) = \
859 BT_GATT_SERVICE(attr_##_name)
860
861 #define _BT_GATT_ATTRS_ARRAY_DEFINE(n, _instances, _attrs_def) \
862 static struct bt_gatt_attr attrs_##n[] = _attrs_def(_instances[n])
863
864 #define _BT_GATT_SERVICE_ARRAY_ITEM(_n, _) BT_GATT_SERVICE(attrs_##_n)
865
866 /**
867 * @brief Statically define service structure array.
868 *
869 * Helper macro to statically define service structure array. Each element
870 * of the array is linked to the service attribute array which is also
871 * defined in this scope using ``_attrs_def`` macro.
872 *
873 * @param _name Name of service structure array.
874 * @param _instances Array of instances to pass as user context to the
875 * attribute callbacks.
876 * @param _instance_num Number of elements in instance array.
877 * @param _attrs_def Macro provided by the user that defines attribute
878 * array for the service. This macro should accept single
879 * parameter which is the instance context.
880 */
881 #define BT_GATT_SERVICE_INSTANCE_DEFINE( \
882 _name, _instances, _instance_num, _attrs_def) \
883 BUILD_ASSERT(ARRAY_SIZE(_instances) == _instance_num, \
884 "The number of array elements does not match its size"); \
885 LISTIFY(_instance_num, _BT_GATT_ATTRS_ARRAY_DEFINE, (;), \
886 _instances, _attrs_def); \
887 static struct bt_gatt_service _name[] = { \
888 LISTIFY(_instance_num, _BT_GATT_SERVICE_ARRAY_ITEM, (,)) \
889 }
890
891 /**
892 * @brief Service Structure Declaration Macro.
893 *
894 * Helper macro to declare a service structure.
895 *
896 * @param _attrs Service attributes.
897 */
898 #define BT_GATT_SERVICE(_attrs) \
899 { \
900 .attrs = _attrs, \
901 .attr_count = ARRAY_SIZE(_attrs), \
902 }
903
904 /**
905 * @brief Primary Service Declaration Macro.
906 *
907 * Helper macro to declare a primary service attribute.
908 *
909 * @param _service Service attribute value.
910 */
911 #define BT_GATT_PRIMARY_SERVICE(_service) \
912 BT_GATT_ATTRIBUTE(BT_UUID_GATT_PRIMARY, BT_GATT_PERM_READ, \
913 bt_gatt_attr_read_service, NULL, (void *)_service)
914
915 /**
916 * @brief Secondary Service Declaration Macro.
917 *
918 * Helper macro to declare a secondary service attribute.
919 *
920 * @note A secondary service is only intended to be included from a primary
921 * service or another secondary service or other higher layer specification.
922 *
923 * @param _service Service attribute value.
924 */
925 #define BT_GATT_SECONDARY_SERVICE(_service) \
926 BT_GATT_ATTRIBUTE(BT_UUID_GATT_SECONDARY, BT_GATT_PERM_READ, \
927 bt_gatt_attr_read_service, NULL, (void *)_service)
928
929 /** @brief Read Include Attribute helper.
930 *
931 * Read include service attribute value from local database storing the result
932 * into buffer after encoding it.
933 * @note Only use this with attributes which user_data is a ``bt_gatt_include``.
934 * The function returns EINVAL if @p attr or @p attr->user_data is NULL.
935 *
936 * @param conn Connection object.
937 * @param attr Attribute to read.
938 * @param buf Buffer to store the value read.
939 * @param len Buffer length.
940 * @param offset Start offset.
941 *
942 * @return number of bytes read in case of success or negative values in
943 * case of error.
944 */
945 ssize_t bt_gatt_attr_read_included(struct bt_conn *conn,
946 const struct bt_gatt_attr *attr,
947 void *buf, uint16_t len, uint16_t offset);
948
949 /**
950 * @brief Include Service Declaration Macro.
951 *
952 * Helper macro to declare database internal include service attribute.
953 *
954 * @param _service_incl the first service attribute of service to include
955 */
956 #define BT_GATT_INCLUDE_SERVICE(_service_incl) \
957 BT_GATT_ATTRIBUTE(BT_UUID_GATT_INCLUDE, BT_GATT_PERM_READ, \
958 bt_gatt_attr_read_included, NULL, _service_incl)
959
960 /** @brief Read Characteristic Attribute helper.
961 *
962 * Read characteristic attribute value from local database storing the result
963 * into buffer after encoding it.
964 * @note Only use this with attributes which ``user_data`` is a ``bt_gatt_chrc``.
965 *
966 * @param conn Connection object.
967 * @param attr Attribute to read.
968 * @param buf Buffer to store the value read.
969 * @param len Buffer length.
970 * @param offset Start offset.
971 *
972 * @return number of bytes read in case of success or negative values in
973 * case of error.
974 */
975 ssize_t bt_gatt_attr_read_chrc(struct bt_conn *conn,
976 const struct bt_gatt_attr *attr, void *buf,
977 uint16_t len, uint16_t offset);
978
979 /** @brief Gatt Characteristic Initialization Macro.
980 *
981 * Helper macro used within the @ref BT_GATT_CHARACTERISTIC macro in the GATT attribute declaration
982 * to set the attribute user data.
983 *
984 * @param _uuid Characteristic attribute uuid.
985 * @param _handle Characcteristic attribute handle at init.
986 * @param _props Characteristic attribute properties,
987 * a bitmap of ``BT_GATT_CHRC_*`` macros.
988 */
989 #define BT_GATT_CHRC_INIT(_uuid, _handle, _props) \
990 { \
991 .uuid = _uuid, \
992 .value_handle = _handle, \
993 .properties = _props, \
994 }
995
996 /**
997 * @brief Characteristic and Value Declaration Macro.
998 *
999 * Helper macro to declare a characteristic attribute along with its
1000 * attribute value.
1001 *
1002 * @param _uuid Characteristic attribute uuid.
1003 * @param _props Characteristic attribute properties,
1004 * a bitmap of ``BT_GATT_CHRC_*`` macros.
1005 * @param _perm Characteristic Attribute access permissions,
1006 * a bitmap of @ref bt_gatt_perm values.
1007 * @param _read Characteristic Attribute read callback
1008 * (@ref bt_gatt_attr_read_func_t).
1009 * @param _write Characteristic Attribute write callback
1010 * (@ref bt_gatt_attr_write_func_t).
1011 * @param _user_data Characteristic Attribute user data.
1012 */
1013 #define BT_GATT_CHARACTERISTIC(_uuid, _props, _perm, _read, _write, _user_data) \
1014 BT_GATT_ATTRIBUTE(BT_UUID_GATT_CHRC, BT_GATT_PERM_READ, \
1015 bt_gatt_attr_read_chrc, NULL, \
1016 ((struct bt_gatt_chrc[]) { \
1017 BT_GATT_CHRC_INIT(_uuid, 0U, _props), \
1018 })), \
1019 BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _user_data)
1020
1021 /**
1022 * @brief BT_GATT_CCC_MAX is defined depending on whether
1023 * @kconfig{CONFIG_BT_SETTINGS_CCC_LAZY_LOADING} or @kconfig{CONFIG_BT_CONN} is set.
1024 *
1025 * @kconfig{CONFIG_BT_SETTINGS_CCC_LAZY_LOADING} will set BT_GATT_CCC_MAX to
1026 * @kconfig{CONFIG_BT_MAX_CONN}
1027 * @kconfig{CONFIG_BT_CONN} will set BT_GATT_CCC_MAX to @kconfig{CONFIG_BT_MAX_PAIRED} +
1028 * @kconfig{CONFIG_BT_MAX_CONN}
1029 * If neither are set, BT_GATT_CCC_MAX is 0.
1030 *
1031 */
1032 #if defined(CONFIG_BT_SETTINGS_CCC_LAZY_LOADING)
1033 #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_CONN)
1034 #elif defined(CONFIG_BT_CONN)
1035 #define BT_GATT_CCC_MAX (CONFIG_BT_MAX_PAIRED + CONFIG_BT_MAX_CONN)
1036 #else
1037 #define BT_GATT_CCC_MAX 0
1038 #endif
1039
1040 /** @brief GATT CCC configuration entry.
1041 *
1042 * bt_gatt_ccc_cfg is used within @ref bt_gatt_attr_read_ccc and @ref bt_gatt_attr_write_ccc to
1043 * read and write the ccc configurations respectively.
1044 *
1045 */
1046 struct bt_gatt_ccc_cfg {
1047 /** Local identity, BT_ID_DEFAULT in most cases. */
1048 uint8_t id;
1049 /** Remote peer address. */
1050 bt_addr_le_t peer;
1051 /** @brief Configuration value
1052 * Value used to enable or disable notifications or indications for a specific
1053 * characteristic.
1054 */
1055 uint16_t value;
1056 };
1057
1058 /** Macro to keep old name for deprecation period. */
1059 #define _bt_gatt_ccc bt_gatt_ccc_managed_user_data __DEPRECATED_MACRO
1060
1061 /** @brief Internal representation of CCC value.
1062 *
1063 * @note Only use this as an argument for @ref BT_GATT_CCC_MANAGED
1064 */
1065 struct bt_gatt_ccc_managed_user_data {
1066 /** Configuration for each connection */
1067 struct bt_gatt_ccc_cfg cfg[BT_GATT_CCC_MAX];
1068
1069 /** Highest value of all connected peer's subscriptions */
1070 uint16_t value;
1071
1072 /** @brief CCC attribute changed callback
1073 *
1074 * @param attr The attribute that's changed value
1075 * @param value New value
1076 */
1077 void (*cfg_changed)(const struct bt_gatt_attr *attr, uint16_t value);
1078
1079 /** @brief CCC attribute write validation callback
1080 *
1081 * @param conn The connection that is requesting to write
1082 * @param attr The attribute that's being written
1083 * @param value CCC value to write
1084 *
1085 * @return Number of bytes to write, or in case of an error
1086 * BT_GATT_ERR() with a specific error code.
1087 */
1088 ssize_t (*cfg_write)(struct bt_conn *conn,
1089 const struct bt_gatt_attr *attr, uint16_t value);
1090
1091 /** @brief CCC attribute match handler
1092 *
1093 * Indicate if it is OK to send a notification or indication
1094 * to the subscriber.
1095 *
1096 * @param conn The connection that is being checked
1097 * @param attr The attribute that's being checked
1098 *
1099 * @return true if application has approved notification/indication,
1100 * false if application does not approve.
1101 */
1102 bool (*cfg_match)(struct bt_conn *conn,
1103 const struct bt_gatt_attr *attr);
1104 };
1105
1106 /** @brief Read Client Characteristic Configuration Attribute helper.
1107 *
1108 * Read CCC attribute value from local database storing the result into buffer
1109 * after encoding it.
1110 *
1111 * @param conn Connection object.
1112 * @param attr Attribute to read.
1113 * @param buf Buffer to store the value read.
1114 * @param len Buffer length.
1115 * @param offset Start offset.
1116 *
1117 * @return number of bytes read in case of success or negative values in
1118 * case of error.
1119 */
1120 /** @cond INTERNAL_HIDDEN
1121 * @note Only use this with attributes which user_data is a bt_gatt_ccc_managed_user_data.
1122 * @ref bt_gatt_ccc_managed_user_data being the internal representation of CCC value.
1123 */
1124 /** @endcond */
1125 ssize_t bt_gatt_attr_read_ccc(struct bt_conn *conn,
1126 const struct bt_gatt_attr *attr, void *buf,
1127 uint16_t len, uint16_t offset);
1128
1129 /** @brief Write Client Characteristic Configuration Attribute helper.
1130 *
1131 * Write value in the buffer into CCC attribute.
1132 *
1133 * @param conn Connection object.
1134 * @param attr Attribute to read.
1135 * @param buf Buffer to store the value read.
1136 * @param len Buffer length.
1137 * @param offset Start offset.
1138 * @param flags Write flags, see @ref bt_gatt_attr_write_flag.
1139 *
1140 * @return number of bytes written in case of success or negative values in
1141 * case of error.
1142 */
1143 /** @cond INTERNAL_HIDDEN
1144 * @note Only use this with attributes which user_data is a bt_gatt_ccc_managed_user_data.
1145 * @ref bt_gatt_ccc_managed_user_data being the internal representation of CCC value.
1146 */
1147 /** @endcond */
1148 ssize_t bt_gatt_attr_write_ccc(struct bt_conn *conn,
1149 const struct bt_gatt_attr *attr, const void *buf,
1150 uint16_t len, uint16_t offset, uint8_t flags);
1151
1152 /** Macro to keep old name for deprecation period. */
1153 #define BT_GATT_CCC_INITIALIZER BT_GATT_CCC_MANAGED_USER_DATA_INIT __DEPRECATED_MACRO
1154
1155 /**
1156 * @brief Initialize Client Characteristic Configuration Declaration Macro.
1157 *
1158 * Helper macro to initialize a Managed CCC attribute value.
1159 *
1160 * @param _changed Configuration changed callback.
1161 * @param _write Configuration write callback.
1162 * @param _match Configuration match callback.
1163 */
1164 #define BT_GATT_CCC_MANAGED_USER_DATA_INIT(_changed, _write, _match) \
1165 { \
1166 .cfg = {}, \
1167 .cfg_changed = _changed, \
1168 .cfg_write = _write, \
1169 .cfg_match = _match, \
1170 }
1171
1172 /**
1173 * @brief Managed Client Characteristic Configuration Declaration Macro.
1174 *
1175 * Helper macro to declare a Managed CCC attribute.
1176 *
1177 * @param _ccc A new @ref bt_gatt_ccc_managed_user_data object with the same lifetime
1178 * as the results of the call to BT_GATT_CCC_MANAGED.
1179 * See the documentation of @ref bt_gatt_ccc_managed_user_data on how
1180 * to initialize it.
1181 * @param _perm CCC access permissions,
1182 * a bitmap of @ref bt_gatt_perm values.
1183 */
1184 #define BT_GATT_CCC_MANAGED(_ccc, _perm) \
1185 BT_GATT_ATTRIBUTE(BT_UUID_GATT_CCC, _perm, \
1186 bt_gatt_attr_read_ccc, bt_gatt_attr_write_ccc, \
1187 _ccc)
1188
1189 /**
1190 * @brief Client Characteristic Configuration Declaration Macro.
1191 *
1192 * Helper macro to declare a CCC attribute.
1193 *
1194 * @param _changed Configuration changed callback.
1195 * @param _perm CCC access permissions,
1196 * a bitmap of @ref bt_gatt_perm values.
1197 */
1198 #define BT_GATT_CCC(_changed, _perm) \
1199 BT_GATT_CCC_MANAGED(((struct bt_gatt_ccc_managed_user_data[]){ \
1200 BT_GATT_CCC_MANAGED_USER_DATA_INIT(_changed, NULL, NULL)}), \
1201 _perm)
1202
1203 /**
1204 * @brief Client Characteristic Configuration Declaration Macro with write callback.
1205 *
1206 * Helper macro to declare a CCC attribute with a write callback.
1207 *
1208 * @param _changed Configuration changed callback.
1209 * @param _write Configuration write callback.
1210 * @param _perm CCC access permissions,
1211 * a bitmap of @ref bt_gatt_perm values.
1212 */
1213 #define BT_GATT_CCC_WITH_WRITE_CB(_changed, _write, _perm) \
1214 BT_GATT_CCC_MANAGED(((struct bt_gatt_ccc_managed_user_data[]){ \
1215 BT_GATT_CCC_MANAGED_USER_DATA_INIT(_changed, _write, NULL)}), \
1216 _perm)
1217
1218 /** @brief Read Characteristic Extended Properties Attribute helper
1219 *
1220 * Read CEP attribute value from local database storing the result into buffer
1221 * after encoding it.
1222 *
1223 * @note Only use this with attributes which user_data is a bt_gatt_cep.
1224 *
1225 * @param conn Connection object
1226 * @param attr Attribute to read
1227 * @param buf Buffer to store the value read
1228 * @param len Buffer length
1229 * @param offset Start offset
1230 *
1231 * @return number of bytes read in case of success or negative values in
1232 * case of error.
1233 */
1234 ssize_t bt_gatt_attr_read_cep(struct bt_conn *conn,
1235 const struct bt_gatt_attr *attr, void *buf,
1236 uint16_t len, uint16_t offset);
1237
1238 /**
1239 * @brief Characteristic Extended Properties Declaration Macro.
1240 *
1241 * Helper macro to declare a CEP attribute.
1242 *
1243 * @param _value Pointer to a struct bt_gatt_cep.
1244 */
1245 #define BT_GATT_CEP(_value) \
1246 BT_GATT_DESCRIPTOR(BT_UUID_GATT_CEP, BT_GATT_PERM_READ, \
1247 bt_gatt_attr_read_cep, NULL, (void *)_value)
1248
1249 /** @brief Read Characteristic User Description Descriptor Attribute helper
1250 *
1251 * Read CUD attribute value from local database storing the result into buffer
1252 * after encoding it.
1253 *
1254 * @note Only use this with attributes which user_data is a NULL-terminated C
1255 * string.
1256 *
1257 * @param conn Connection object
1258 * @param attr Attribute to read
1259 * @param buf Buffer to store the value read
1260 * @param len Buffer length
1261 * @param offset Start offset
1262 *
1263 * @return number of bytes read in case of success or negative values in
1264 * case of error.
1265 */
1266 ssize_t bt_gatt_attr_read_cud(struct bt_conn *conn,
1267 const struct bt_gatt_attr *attr, void *buf,
1268 uint16_t len, uint16_t offset);
1269
1270 /**
1271 * @brief Characteristic User Format Descriptor Declaration Macro.
1272 *
1273 * Helper macro to declare a CUD attribute.
1274 *
1275 * @param _value User description NULL-terminated C string.
1276 * @param _perm Descriptor attribute access permissions,
1277 * a bitmap of @ref bt_gatt_perm values.
1278 */
1279 #define BT_GATT_CUD(_value, _perm) \
1280 BT_GATT_DESCRIPTOR(BT_UUID_GATT_CUD, _perm, bt_gatt_attr_read_cud, \
1281 NULL, (void *)_value)
1282
1283 /** @brief Read Characteristic Presentation format Descriptor Attribute helper
1284 *
1285 * Read CPF attribute value from local database storing the result into buffer
1286 * after encoding it.
1287 *
1288 * @note Only use this with attributes which user_data is a @ref bt_gatt_cpf.
1289 *
1290 * @param conn Connection object
1291 * @param attr Attribute to read
1292 * @param buf Buffer to store the value read
1293 * @param len Buffer length
1294 * @param offset Start offset
1295 *
1296 * @return number of bytes read in case of success or negative values in
1297 * case of error.
1298 */
1299 ssize_t bt_gatt_attr_read_cpf(struct bt_conn *conn,
1300 const struct bt_gatt_attr *attr, void *buf,
1301 uint16_t len, uint16_t offset);
1302
1303 /**
1304 * @brief Characteristic Presentation Format Descriptor Declaration Macro.
1305 *
1306 * Helper macro to declare a CPF attribute.
1307 *
1308 * @param _value Pointer to a struct bt_gatt_cpf.
1309 */
1310 #define BT_GATT_CPF(_value) \
1311 BT_GATT_DESCRIPTOR(BT_UUID_GATT_CPF, BT_GATT_PERM_READ, \
1312 bt_gatt_attr_read_cpf, NULL, (void *)_value)
1313
1314 /**
1315 * @brief Descriptor Declaration Macro.
1316 *
1317 * Helper macro to declare a descriptor attribute.
1318 *
1319 * @param _uuid Descriptor attribute uuid.
1320 * @param _perm Descriptor attribute access permissions,
1321 * a bitmap of @ref bt_gatt_perm values.
1322 * @param _read Descriptor attribute read callback
1323 * (@ref bt_gatt_attr_read_func_t).
1324 * @param _write Descriptor attribute write callback
1325 * (@ref bt_gatt_attr_write_func_t).
1326 * @param _user_data Descriptor attribute user data.
1327 */
1328 #define BT_GATT_DESCRIPTOR(_uuid, _perm, _read, _write, _user_data) \
1329 BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _user_data)
1330
1331 /**
1332 * @brief Attribute Declaration Macro.
1333 *
1334 * Helper macro to declare an attribute.
1335 *
1336 * @param _uuid Attribute uuid.
1337 * @param _perm Attribute access permissions,
1338 * a bitmap of @ref bt_gatt_perm values.
1339 * @param _read Attribute read callback (@ref bt_gatt_attr_read_func_t).
1340 * @param _write Attribute write callback (@ref bt_gatt_attr_write_func_t).
1341 * @param _user_data Attribute user data.
1342 */
1343 #define BT_GATT_ATTRIBUTE(_uuid, _perm, _read, _write, _user_data) \
1344 { \
1345 .uuid = _uuid, \
1346 .read = _read, \
1347 .write = _write, \
1348 .user_data = _user_data, \
1349 .handle = 0, \
1350 .perm = _perm, \
1351 }
1352
1353 /** @brief Notification complete result callback.
1354 *
1355 * @param conn Connection object.
1356 * @param user_data Data passed in by the user.
1357 */
1358 typedef void (*bt_gatt_complete_func_t) (struct bt_conn *conn, void *user_data);
1359
1360 /** @brief GATT notification parameters
1361 *
1362 * See also @ref bt_gatt_notify_cb and @ref bt_gatt_notify_multiple, using this parameter.
1363 */
1364 struct bt_gatt_notify_params {
1365 /** @brief Notification Attribute UUID type
1366 *
1367 * Optional, use to search for an attribute with matching UUID when
1368 * the attribute object pointer is not known.
1369 */
1370 const struct bt_uuid *uuid;
1371 /** @brief Notification Attribute object
1372 *
1373 * Optional if uuid is provided, in this case it will be used as start
1374 * range to search for the attribute with the given UUID.
1375 */
1376 const struct bt_gatt_attr *attr;
1377 /** Notification Value data */
1378 const void *data;
1379 /** Notification Value length */
1380 uint16_t len;
1381 /** Notification Value callback */
1382 bt_gatt_complete_func_t func;
1383 /** Notification Value callback user data */
1384 void *user_data;
1385 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
1386 /** Att channel options. */
1387 enum bt_att_chan_opt chan_opt;
1388 #endif /* CONFIG_BT_EATT */
1389 };
1390
1391 /** @brief Notify attribute value change.
1392 *
1393 * This function works in the same way as @ref bt_gatt_notify.
1394 * With the addition that after sending the notification the
1395 * callback function will be called.
1396 *
1397 * The callback is run from System Workqueue context.
1398 * When called from the System Workqueue context this API will not wait for
1399 * resources for the callback but instead return an error.
1400 *
1401 * Alternatively it is possible to notify by UUID by setting it on the
1402 * parameters, when using this method the attribute if provided is used as the
1403 * start range when looking up for possible matches.
1404 *
1405 * @param conn Connection object.
1406 * @param params Notification parameters.
1407 *
1408 * @return 0 in case of success or negative value in case of error.
1409 */
1410 int bt_gatt_notify_cb(struct bt_conn *conn,
1411 struct bt_gatt_notify_params *params);
1412
1413 /** @brief Send multiple notifications in a single PDU.
1414 *
1415 * The GATT Server will send a single ATT_MULTIPLE_HANDLE_VALUE_NTF PDU
1416 * containing all the notifications passed to this API.
1417 *
1418 * All `params` must have the same `func` and `user_data` (due to
1419 * implementation limitation). But `func(user_data)` will be invoked for each
1420 * parameter.
1421 *
1422 * As this API may block to wait for Bluetooth Host resources, it is not
1423 * recommended to call it from a cooperative thread or a Bluetooth callback.
1424 *
1425 * The peer's GATT Client must write to this device's Client Supported Features
1426 * attribute and set the bit for Multiple Handle Value Notifications before
1427 * this API can be used.
1428 *
1429 * Only use this API to force the use of the ATT_MULTIPLE_HANDLE_VALUE_NTF PDU.
1430 * For standard applications, `bt_gatt_notify_cb` is preferred, as it will use
1431 * this PDU if supported and automatically fallback to ATT_HANDLE_VALUE_NTF
1432 * when not supported by the peer.
1433 *
1434 * This API has an additional limitation: it only accepts valid attribute
1435 * references and not UUIDs like `bt_gatt_notify` and `bt_gatt_notify_cb`.
1436 *
1437 * @param conn
1438 * Target client.
1439 * Notifying all connected clients by passing `NULL` is not yet supported,
1440 * please use `bt_gatt_notify` instead.
1441 * @param num_params
1442 * Element count of `params` array. Has to be greater than 1.
1443 * @param params
1444 * Array of notification parameters. It is okay to free this after calling
1445 * this function.
1446 *
1447 * @retval 0
1448 * Success. The PDU is queued for sending.
1449 * @retval -EINVAL
1450 * - One of the attribute handles is invalid.
1451 * - Only one parameter was passed. This API expects 2 or more.
1452 * - Not all `func` were equal or not all `user_data` were equal.
1453 * - One of the characteristics is not notifiable.
1454 * - An UUID was passed in one of the parameters.
1455 * @retval -ERANGE
1456 * - The notifications cannot all fit in a single ATT_MULTIPLE_HANDLE_VALUE_NTF.
1457 * - They exceed the MTU of all open ATT bearers.
1458 * @retval -EPERM
1459 * The connection has a lower security level than required by one of the
1460 * attributes.
1461 * @retval -EOPNOTSUPP
1462 * The peer hasn't yet communicated that it supports this PDU type.
1463 */
1464 int bt_gatt_notify_multiple(struct bt_conn *conn,
1465 uint16_t num_params,
1466 struct bt_gatt_notify_params params[]);
1467
1468 /** @brief Notify attribute value change.
1469 *
1470 * Send notification of attribute value change, if connection is NULL notify
1471 * all peer that have notification enabled via CCC otherwise do a direct
1472 * notification only the given connection.
1473 *
1474 * The attribute object on the parameters can be the so called Characteristic
1475 * Declaration, which is usually declared with BT_GATT_CHARACTERISTIC followed
1476 * by BT_GATT_CCC, or the Characteristic Value Declaration which is
1477 * automatically created after the Characteristic Declaration when using
1478 * BT_GATT_CHARACTERISTIC.
1479 *
1480 * @param conn Connection object.
1481 * @param attr Characteristic or Characteristic Value attribute.
1482 * @param data Pointer to Attribute data.
1483 * @param len Attribute value length.
1484 *
1485 * @return 0 in case of success or negative value in case of error.
1486 */
bt_gatt_notify(struct bt_conn * conn,const struct bt_gatt_attr * attr,const void * data,uint16_t len)1487 static inline int bt_gatt_notify(struct bt_conn *conn,
1488 const struct bt_gatt_attr *attr,
1489 const void *data, uint16_t len)
1490 {
1491 struct bt_gatt_notify_params params;
1492
1493 memset(¶ms, 0, sizeof(params));
1494
1495 params.attr = attr;
1496 params.data = data;
1497 params.len = len;
1498 #if defined(CONFIG_BT_EATT)
1499 params.chan_opt = BT_ATT_CHAN_OPT_NONE;
1500 #endif /* CONFIG_BT_EATT */
1501
1502 return bt_gatt_notify_cb(conn, ¶ms);
1503 }
1504
1505 /** @brief Notify attribute value change by UUID.
1506 *
1507 * Send notification of attribute value change, if connection is NULL notify
1508 * all peer that have notification enabled via CCC otherwise do a direct
1509 * notification only on the given connection.
1510 *
1511 * The attribute object is the starting point for the search of the UUID.
1512 *
1513 * @param conn Connection object.
1514 * @param uuid The UUID. If the server contains multiple services with the same
1515 * UUID, then the first occurrence, starting from the attr given,
1516 * is used.
1517 * @param attr Pointer to an attribute that serves as the starting point for
1518 * the search of a match for the UUID.
1519 * @param data Pointer to Attribute data.
1520 * @param len Attribute value length.
1521 *
1522 * @return 0 in case of success or negative value in case of error.
1523 */
bt_gatt_notify_uuid(struct bt_conn * conn,const struct bt_uuid * uuid,const struct bt_gatt_attr * attr,const void * data,uint16_t len)1524 static inline int bt_gatt_notify_uuid(struct bt_conn *conn,
1525 const struct bt_uuid *uuid,
1526 const struct bt_gatt_attr *attr,
1527 const void *data, uint16_t len)
1528 {
1529 struct bt_gatt_notify_params params;
1530
1531 memset(¶ms, 0, sizeof(params));
1532
1533 params.uuid = uuid;
1534 params.attr = attr;
1535 params.data = data;
1536 params.len = len;
1537 #if defined(CONFIG_BT_EATT)
1538 params.chan_opt = BT_ATT_CHAN_OPT_NONE;
1539 #endif /* CONFIG_BT_EATT */
1540
1541 return bt_gatt_notify_cb(conn, ¶ms);
1542 }
1543
1544 /* Forward declaration of the bt_gatt_indicate_params structure */
1545 struct bt_gatt_indicate_params;
1546
1547 /** @typedef bt_gatt_indicate_func_t
1548 * @brief Indication complete result callback.
1549 *
1550 * @param conn Connection object.
1551 * @param params Indication params object.
1552 * @param err ATT error code
1553 */
1554 typedef void (*bt_gatt_indicate_func_t)(struct bt_conn *conn,
1555 struct bt_gatt_indicate_params *params,
1556 uint8_t err);
1557
1558 /** @typedef bt_gatt_indicate_params_destroy_t
1559 * @brief Callback to destroy or clean up the GATT Indicate Value parameters.
1560 *
1561 * This callback function is invoked to clean up any resources associated with the
1562 * `bt_gatt_indicate_params` structure once the GATT indication operation is completed.
1563 *
1564 * @param params Pointer to the GATT Indicate parameters structure to be cleaned up.
1565 */
1566 typedef void (*bt_gatt_indicate_params_destroy_t)(
1567 struct bt_gatt_indicate_params *params);
1568
1569 /** @brief GATT Indicate Value parameters
1570 *
1571 * See also @ref bt_gatt_indicate, using this parameter.
1572 *
1573 */
1574 struct bt_gatt_indicate_params {
1575 /** @brief Indicate Attribute UUID type
1576 *
1577 * Optional, use to search for an attribute with matching UUID when
1578 * the attribute object pointer is not known.
1579 */
1580 const struct bt_uuid *uuid;
1581 /** @brief Indicate Attribute object
1582 *
1583 * Optional if uuid is provided, in this case it will be used as start
1584 * range to search for the attribute with the given UUID.
1585 */
1586 const struct bt_gatt_attr *attr;
1587 /** Indicate Value callback */
1588 bt_gatt_indicate_func_t func;
1589 /** Indicate operation complete callback */
1590 bt_gatt_indicate_params_destroy_t destroy;
1591 /** Indicate Value data*/
1592 const void *data;
1593 /** Indicate Value length*/
1594 uint16_t len;
1595 /** Private reference counter */
1596 uint8_t _ref;
1597 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
1598 /** Att channel options. */
1599 enum bt_att_chan_opt chan_opt;
1600 #endif /* CONFIG_BT_EATT */
1601 };
1602
1603 /** @brief Indicate attribute value change.
1604 *
1605 * Send an indication of attribute value change. if connection is NULL
1606 * indicate all peer that have notification enabled via CCC otherwise do a
1607 * direct indication only the given connection.
1608 *
1609 * The attribute object on the parameters can be the so called Characteristic
1610 * Declaration, which is usually declared with BT_GATT_CHARACTERISTIC followed
1611 * by BT_GATT_CCC, or the Characteristic Value Declaration which is
1612 * automatically created after the Characteristic Declaration when using
1613 * BT_GATT_CHARACTERISTIC.
1614 *
1615 * Alternatively it is possible to indicate by UUID by setting it on the
1616 * parameters, when using this method the attribute if provided is used as the
1617 * start range when looking up for possible matches.
1618 *
1619 * @note This procedure is asynchronous therefore the parameters need to
1620 * remains valid while it is active. The procedure is active until
1621 * the destroy callback is run.
1622 *
1623 * @param conn Connection object.
1624 * @param params Indicate parameters.
1625 *
1626 * @return 0 in case of success or negative value in case of error.
1627 */
1628 int bt_gatt_indicate(struct bt_conn *conn,
1629 struct bt_gatt_indicate_params *params);
1630
1631 /** @brief Check if connection have subscribed to attribute
1632 *
1633 * Check if the connection has subscribed to an attribute value change.
1634 *
1635 * The attribute object can be the so called Characteristic Declaration,
1636 * which is usually declared with BT_GATT_CHARACTERISTIC followed
1637 * by BT_GATT_CCC, or the Characteristic Value Declaration which is
1638 * automatically created after the Characteristic Declaration when using
1639 * BT_GATT_CHARACTERISTIC, or the Client Characteristic Configuration
1640 * Descriptor (CCCD) which is created by BT_GATT_CCC.
1641 *
1642 * @param conn Connection object.
1643 * @param attr Attribute object.
1644 * @param ccc_type The subscription type, @ref BT_GATT_CCC_NOTIFY and/or
1645 * @ref BT_GATT_CCC_INDICATE.
1646 *
1647 * @return true if the attribute object has been subscribed.
1648 */
1649 bool bt_gatt_is_subscribed(struct bt_conn *conn,
1650 const struct bt_gatt_attr *attr, uint16_t ccc_type);
1651
1652 /** @brief Get ATT MTU for a connection
1653 *
1654 * Get negotiated ATT connection MTU, note that this does not equal the largest
1655 * amount of attribute data that can be transferred within a single packet.
1656 *
1657 * @param conn Connection object.
1658 *
1659 * @return MTU in bytes
1660 */
1661 uint16_t bt_gatt_get_mtu(struct bt_conn *conn);
1662
1663 /** @brief Get Unenhanced ATT (UATT) MTU for a connection
1664 *
1665 * Get UATT connection MTU.
1666 *
1667 * The ATT_MTU defines the largest size of an ATT PDU, encompassing the ATT
1668 * opcode, additional fields, and any attribute value payload. Consequently,
1669 * the maximum size of a value payload is less and varies based on the type
1670 * of ATT PDU. For example, in an ATT_HANDLE_VALUE_NTF PDU, the Attribute Value
1671 * field can contain up to ATT_MTU - 3 octets (size of opcode and handle).
1672 *
1673 * @param conn Connection object.
1674 *
1675 * @return 0 if @p conn does not have an UATT ATT_MTU (e.g: disconnected).
1676 * @return Current UATT ATT_MTU.
1677 */
1678 uint16_t bt_gatt_get_uatt_mtu(struct bt_conn *conn);
1679
1680 /** @} */
1681
1682 /**
1683 * @defgroup bt_gatt_client GATT Client APIs
1684 * @ingroup bt_gatt
1685 * @{
1686 */
1687
1688 /** @brief GATT Exchange MTU parameters
1689 *
1690 * Used with @ref bt_gatt_exchange_mtu function to initiate an MTU exchange. The
1691 * response is handled in the callback @p func, which is called upon
1692 * completion from the 'config BT_RECV_CONTEXT' context.
1693 *
1694 * @p params must remain valid until the callback executes.
1695 */
1696 struct bt_gatt_exchange_params {
1697 /** Callback for MTU exchange response */
1698 void (*func)(struct bt_conn *conn, uint8_t err,
1699 struct bt_gatt_exchange_params *params);
1700 };
1701
1702 /** @brief Exchange MTU
1703 *
1704 * Once per connection, this client procedure can be used to set the MTU to
1705 * the maximum possible size the buffers can hold.
1706 *
1707 * As the response comes in callback @p params->func, for example
1708 * @ref bt_gatt_get_mtu can be invoked in the mtu_exchange-callback to read
1709 * out the new negotiated ATT connection MTU. The callback is run from the
1710 * context specified by 'config BT_RECV_CONTEXT' and @p params must remain
1711 * valid until start of callback.
1712 *
1713 * @param conn Connection object.
1714 * @param params Exchange MTU parameters.
1715 *
1716 * @retval 0 Successfully queued request. Will call @p params->func on
1717 * resolution.
1718 *
1719 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
1720 * Allow a pending request to resolve before retrying, or call this function
1721 * from a separate thread to get blocking behavior. Queue size is controlled
1722 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
1723 *
1724 * @retval -EALREADY The MTU exchange procedure has been already performed.
1725 */
1726 int bt_gatt_exchange_mtu(struct bt_conn *conn,
1727 struct bt_gatt_exchange_params *params);
1728
1729 struct bt_gatt_discover_params;
1730
1731 /** @typedef bt_gatt_discover_func_t
1732 * @brief Discover attribute callback function.
1733 *
1734 * @param conn Connection object.
1735 * @param attr Attribute found, or NULL if not found.
1736 * @param params Discovery parameters given.
1737 *
1738 * If discovery procedure has completed this callback will be called with
1739 * attr set to NULL. This will not happen if procedure was stopped by returning
1740 * BT_GATT_ITER_STOP.
1741 *
1742 * The attribute object as well as its UUID and value objects are temporary and
1743 * must be copied to in order to cache its information.
1744 *
1745 * @note @ref bt_gatt_attr is given as an argument to @ref bt_gatt_discover function, but
1746 * it's not a proper object of this type. @ref bt_gatt_attr.perm, and methods
1747 * bt_gatt_attr.read() and bt_gatt_attr.write() are not available, and it's
1748 * unsound to pass the pointer to GATT server APIs.
1749 * Only the following fields of the attribute contains valid information:
1750 * - uuid UUID representing the type of attribute.
1751 * - handle Handle in the remote database.
1752 * - user_data The value of the attribute, if the discovery type maps to an
1753 * ATT operation that provides this information. NULL otherwise.
1754 * See below.
1755 *
1756 * The effective type of @c attr->user_data is determined by @c params. Note
1757 * that the fields @c params->type and @c params->uuid are left unchanged by
1758 * the discovery procedure.
1759 *
1760 * @c params->type | @c params->uuid | Type of @c attr->user_data
1761 * -------------------------------------|-------------------------|---------------------------
1762 * @ref BT_GATT_DISCOVER_PRIMARY | any | @ref bt_gatt_service_val
1763 * @ref BT_GATT_DISCOVER_SECONDARY | any | @ref bt_gatt_service_val
1764 * @ref BT_GATT_DISCOVER_INCLUDE | any | @ref bt_gatt_include
1765 * @ref BT_GATT_DISCOVER_CHARACTERISTIC | any | @ref bt_gatt_chrc
1766 * @ref BT_GATT_DISCOVER_STD_CHAR_DESC | @ref BT_UUID_GATT_CEP | @ref bt_gatt_cep
1767 * @ref BT_GATT_DISCOVER_STD_CHAR_DESC | @ref BT_UUID_GATT_CCC | @ref bt_gatt_ccc
1768 * @ref BT_GATT_DISCOVER_STD_CHAR_DESC | @ref BT_UUID_GATT_SCC | @ref bt_gatt_scc
1769 * @ref BT_GATT_DISCOVER_STD_CHAR_DESC | @ref BT_UUID_GATT_CPF | @ref bt_gatt_cpf
1770 * @ref BT_GATT_DISCOVER_DESCRIPTOR | any | NULL
1771 * @ref BT_GATT_DISCOVER_ATTRIBUTE | any | NULL
1772 *
1773 * Also consider if using read-by-type instead of discovery is more convenient.
1774 * See @ref bt_gatt_read with @ref bt_gatt_read_params.handle_count set to
1775 * @c 0.
1776 *
1777 * @return BT_GATT_ITER_CONTINUE to continue discovery procedure.
1778 * @return BT_GATT_ITER_STOP to stop discovery procedure.
1779 */
1780 typedef uint8_t (*bt_gatt_discover_func_t)(struct bt_conn *conn,
1781 const struct bt_gatt_attr *attr,
1782 struct bt_gatt_discover_params *params);
1783
1784 /** GATT Discover types */
1785 enum bt_gatt_discover_type {
1786 /** Discover Primary Services. */
1787 BT_GATT_DISCOVER_PRIMARY,
1788 /** Discover Secondary Services. */
1789 BT_GATT_DISCOVER_SECONDARY,
1790 /** Discover Included Services. */
1791 BT_GATT_DISCOVER_INCLUDE,
1792 /** @brief Discover Characteristic Values.
1793 *
1794 * Discover Characteristic Value and its properties.
1795 */
1796 BT_GATT_DISCOVER_CHARACTERISTIC,
1797 /** @brief Discover Descriptors.
1798 *
1799 * Discover Attributes which are not services or characteristics.
1800 *
1801 * @note The use of this type of discover is not recommended for
1802 * discovering in ranges across multiple services/characteristics
1803 * as it may incur in extra round trips.
1804 */
1805 BT_GATT_DISCOVER_DESCRIPTOR,
1806 /** @brief Discover Attributes.
1807 *
1808 * Discover Attributes of any type.
1809 *
1810 * @note The use of this type of discover is not recommended for
1811 * discovering in ranges across multiple services/characteristics
1812 * as it may incur in more round trips.
1813 */
1814 BT_GATT_DISCOVER_ATTRIBUTE,
1815 /** @brief Discover standard characteristic descriptor values.
1816 *
1817 * Discover standard characteristic descriptor values and their
1818 * properties.
1819 * Supported descriptors:
1820 * - Characteristic Extended Properties
1821 * - Client Characteristic Configuration
1822 * - Server Characteristic Configuration
1823 * - Characteristic Presentation Format
1824 */
1825 BT_GATT_DISCOVER_STD_CHAR_DESC,
1826 };
1827
1828 /** Handle value to denote that the CCC will be automatically discovered */
1829 #define BT_GATT_AUTO_DISCOVER_CCC_HANDLE 0x0000U
1830
1831 /** @brief GATT Discover Attributes parameters */
1832 struct bt_gatt_discover_params {
1833 /** Discover UUID type */
1834 const struct bt_uuid *uuid;
1835 /** Discover attribute callback */
1836 bt_gatt_discover_func_t func;
1837 union {
1838 /** See @ref bt_gatt_include for more on included services. */
1839 struct {
1840 /** Include service attribute declaration handle */
1841 uint16_t attr_handle;
1842 /** Starting attribute handle for included service */
1843 uint16_t start_handle;
1844 /** Ending attribute handle for included service */
1845 uint16_t end_handle;
1846 } _included;
1847 /** Starting attribute handle to begin discovery */
1848 uint16_t start_handle;
1849 };
1850 /** @brief Ending attribute handle to stop discovery at
1851 *
1852 * @note When discovery begins this can be set to
1853 * @ref BT_ATT_LAST_ATTRIBUTE_HANDLE to discover all attributes
1854 * in the service.
1855 */
1856 uint16_t end_handle;
1857 /** Discover type */
1858 uint8_t type;
1859 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC) || defined(__DOXYGEN__)
1860 /** Only for stack-internal use, used for automatic discovery. */
1861 struct bt_gatt_subscribe_params *sub_params;
1862 #endif /* defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC) || defined(__DOXYGEN__) */
1863 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
1864 /** Att channel options. */
1865 enum bt_att_chan_opt chan_opt;
1866 #endif /* CONFIG_BT_EATT */
1867 };
1868
1869 /** @brief GATT Discover function
1870 *
1871 * This procedure is used by a client to discover attributes on a server.
1872 *
1873 * Primary Service Discovery: Procedure allows to discover primary services
1874 * either by Discover All Primary Services or
1875 * Discover Primary Services by Service UUID.
1876 * Include Service Discovery: Procedure allows to discover all Include Services
1877 * within specified range.
1878 * Characteristic Discovery: Procedure allows to discover all characteristics
1879 * within specified handle range as well as
1880 * discover characteristics with specified UUID.
1881 * Descriptors Discovery: Procedure allows to discover all characteristic
1882 * descriptors within specified range.
1883 *
1884 * For each attribute found the callback is called which can then decide
1885 * whether to continue discovering or stop.
1886 *
1887 * The Response comes in callback @p params->func. The callback is run from
1888 * the BT RX thread. @p params must remain valid until start of callback where
1889 * iter `attr` is `NULL` or callback will return `BT_GATT_ITER_STOP`.
1890 *
1891 * @param conn Connection object.
1892 * @param params Discover parameters.
1893 *
1894 * @retval 0 Successfully queued request. Will call @p params->func on
1895 * resolution.
1896 *
1897 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
1898 * Allow a pending request to resolve before retrying, or call this function
1899 * from a separate thread to get blocking behavior. Queue size is controlled
1900 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
1901 */
1902 int bt_gatt_discover(struct bt_conn *conn,
1903 struct bt_gatt_discover_params *params);
1904
1905 struct bt_gatt_read_params;
1906
1907 /** @typedef bt_gatt_read_func_t
1908 * @brief Read callback function
1909 *
1910 * When reading using by_uuid, `params->start_handle` is the attribute handle
1911 * for this `data` item.
1912 *
1913 * If the received data length is invalid, the callback will called with the
1914 * error @ref BT_ATT_ERR_INVALID_PDU.
1915 *
1916 * @param conn Connection object.
1917 * @param err ATT error code.
1918 * @param params Read parameters used.
1919 * @param data Attribute value data. NULL means read has completed.
1920 * @param length Attribute value length.
1921 *
1922 * @return BT_GATT_ITER_CONTINUE if should continue to the next attribute.
1923 * @return BT_GATT_ITER_STOP to stop.
1924 */
1925 typedef uint8_t (*bt_gatt_read_func_t)(struct bt_conn *conn, uint8_t err,
1926 struct bt_gatt_read_params *params,
1927 const void *data, uint16_t length);
1928
1929 /** @brief GATT Read parameters */
1930 struct bt_gatt_read_params {
1931 /** Read attribute callback. */
1932 bt_gatt_read_func_t func;
1933 /** If equals to 1 single.handle and single.offset are used.
1934 * If greater than 1 multiple.handles are used.
1935 * If equals to 0 by_uuid is used for Read Using Characteristic UUID.
1936 */
1937 size_t handle_count;
1938 union {
1939 struct {
1940 /** Attribute handle. */
1941 uint16_t handle;
1942 /** Attribute data offset. */
1943 uint16_t offset;
1944 } single;
1945 struct {
1946 /** Attribute handles to read with Read Multiple
1947 * Characteristic Values.
1948 */
1949 uint16_t *handles;
1950 /** If true use Read Multiple Variable Length
1951 * Characteristic Values procedure.
1952 * The values of the set of attributes may be of
1953 * variable or unknown length.
1954 * If false use Read Multiple Characteristic Values
1955 * procedure.
1956 * The values of the set of attributes must be of a
1957 * known fixed length, with the exception of the last
1958 * value that can have a variable length.
1959 */
1960 bool variable;
1961 } multiple;
1962 struct {
1963 /** @brief Requested start attribute handle number.
1964 *
1965 * @details The starting handle is set to the starting point of the range
1966 * over which this read should be performed. For example, this could be
1967 * set to @ref BT_ATT_FIRST_ATTRIBUTE_HANDLE to set the starting point of
1968 * the range at the beginning of the GATT database, or to the starting
1969 * handle of a service after discovery.
1970 *
1971 * This value is automatically incremented by the stack after
1972 * processing each matching handle-value pair returned by the server.
1973 */
1974 uint16_t start_handle;
1975 /** @brief Requested end attribute handle number.
1976 *
1977 * @details The end handle is set to the ending point of the range over
1978 * which this read should be performed. For example, this could be set to
1979 * @ref BT_ATT_LAST_ATTRIBUTE_HANDLE to set the ending point of the range
1980 * at the end of the GATT database, or to the end handle for service after
1981 * discovery, where the end_handle is available in the
1982 * @ref bt_gatt_service_val.
1983 */
1984 uint16_t end_handle;
1985 /** 2 or 16 octet UUID. */
1986 const struct bt_uuid *uuid;
1987 } by_uuid;
1988 };
1989 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
1990 /** Att channel options. */
1991 enum bt_att_chan_opt chan_opt;
1992 #endif /* CONFIG_BT_EATT */
1993 /** Internal */
1994 uint16_t _att_mtu;
1995 };
1996
1997 /** @brief Read Attribute Value by handle
1998 *
1999 * This procedure reads the attribute value and returns it to the callback.
2000 *
2001 * When reading attributes by UUID the callback can be called multiple times
2002 * depending on how many instances of a given UUID exists with the start_handle
2003 * being updated for each instance.
2004 *
2005 * To perform a GATT Long Read procedure, start with a Characteristic Value
2006 * Read (by setting @c offset @c 0 and @c handle_count @c 1) and then return
2007 * @ref BT_GATT_ITER_CONTINUE from the callback. This is equivalent to calling
2008 * @ref bt_gatt_read again, but with the correct offset to continue the read.
2009 * This may be repeated until the procedure is complete, which is signaled by
2010 * the callback being called with @p data set to @c NULL.
2011 *
2012 * Note that returning @ref BT_GATT_ITER_CONTINUE is really starting a new ATT
2013 * operation, so this can fail to allocate resources. However, all API errors
2014 * are reported as if the server returned @ref BT_ATT_ERR_UNLIKELY. There is no
2015 * way to distinguish between this condition and a @ref BT_ATT_ERR_UNLIKELY
2016 * response from the server itself.
2017 *
2018 * Note that the effect of returning @ref BT_GATT_ITER_CONTINUE from the
2019 * callback varies depending on the type of read operation.
2020 *
2021 * The Response comes in callback @p params->func. The callback is run from
2022 * the context specified by 'config BT_RECV_CONTEXT'.
2023 * @p params must remain valid until start of callback.
2024 * If the received data length is invalid, the callback @p params->func will
2025 * called with the error @ref BT_ATT_ERR_INVALID_PDU.
2026 *
2027 * @param conn Connection object.
2028 * @param params Read parameters.
2029 *
2030 * @retval 0 Successfully queued request. Will call @p params->func on
2031 * resolution.
2032 *
2033 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2034 * Allow a pending request to resolve before retrying, or call this function
2035 * from a separate thread to get blocking behavior. Queue size is controlled
2036 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2037 */
2038 int bt_gatt_read(struct bt_conn *conn, struct bt_gatt_read_params *params);
2039
2040 struct bt_gatt_write_params;
2041
2042 /** @typedef bt_gatt_write_func_t
2043 * @brief Write callback function
2044 *
2045 * @param conn Connection object.
2046 * @param err ATT error code.
2047 * @param params Write parameters used.
2048 */
2049 typedef void (*bt_gatt_write_func_t)(struct bt_conn *conn, uint8_t err,
2050 struct bt_gatt_write_params *params);
2051
2052 /** @brief GATT Write parameters */
2053 struct bt_gatt_write_params {
2054 /** Response callback */
2055 bt_gatt_write_func_t func;
2056 /** Attribute handle */
2057 uint16_t handle;
2058 /** Attribute data offset */
2059 uint16_t offset;
2060 /** Data to be written */
2061 const void *data;
2062 /** Length of the data */
2063 uint16_t length;
2064 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
2065 /** Att channel options. */
2066 enum bt_att_chan_opt chan_opt;
2067 #endif /* CONFIG_BT_EATT */
2068 };
2069
2070 /** @brief Write Attribute Value by handle
2071 *
2072 * The Response comes in callback @p params->func. The callback is run from
2073 * the context specified by 'config BT_RECV_CONTEXT'.
2074 * @p params must remain valid until start of callback.
2075 *
2076 * @param conn Connection object.
2077 * @param params Write parameters.
2078 *
2079 * @retval 0 Successfully queued request. Will call @p params->func on
2080 * resolution.
2081 *
2082 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2083 * Allow a pending request to resolve before retrying, or call this function
2084 * from a separate thread to get blocking behavior. Queue size is controlled
2085 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2086 */
2087 int bt_gatt_write(struct bt_conn *conn, struct bt_gatt_write_params *params);
2088
2089 /** @brief Write Attribute Value by handle without response with callback.
2090 *
2091 * This function works in the same way as @ref bt_gatt_write_without_response.
2092 * With the addition that after sending the write the callback function will be
2093 * called.
2094 *
2095 * The callback is run from System Workqueue context.
2096 * When called from the System Workqueue context this API will not wait for
2097 * resources for the callback but instead return an error.
2098 *
2099 * @param conn Connection object.
2100 * @param handle Attribute handle.
2101 * @param data Data to be written.
2102 * @param length Data length.
2103 * @param sign Whether to sign data.
2104 * @param func Transmission complete callback.
2105 * @param user_data User data to be passed back to callback.
2106 *
2107 * @retval 0 Successfully queued request.
2108 *
2109 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2110 * Allow a pending request to resolve before retrying, or call this function
2111 * from a separate thread to get blocking behavior. Queue size is controlled
2112 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2113 */
2114 int bt_gatt_write_without_response_cb(struct bt_conn *conn, uint16_t handle,
2115 const void *data, uint16_t length,
2116 bool sign, bt_gatt_complete_func_t func,
2117 void *user_data);
2118
2119 /** @brief Write Attribute Value by handle without response
2120 *
2121 * This procedure write the attribute value without requiring an
2122 * acknowledgment that the write was successfully performed
2123 *
2124 * @param conn Connection object.
2125 * @param handle Attribute handle.
2126 * @param data Data to be written.
2127 * @param length Data length.
2128 * @param sign Whether to sign data.
2129 *
2130 * @retval 0 Successfully queued request.
2131 *
2132 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2133 * Allow a pending request to resolve before retrying, or call this function
2134 * from a separate thread to get blocking behavior. Queue size is controlled
2135 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2136 */
bt_gatt_write_without_response(struct bt_conn * conn,uint16_t handle,const void * data,uint16_t length,bool sign)2137 static inline int bt_gatt_write_without_response(struct bt_conn *conn,
2138 uint16_t handle, const void *data,
2139 uint16_t length, bool sign)
2140 {
2141 return bt_gatt_write_without_response_cb(conn, handle, data, length,
2142 sign, NULL, NULL);
2143 }
2144
2145 struct bt_gatt_subscribe_params;
2146
2147 /** @typedef bt_gatt_notify_func_t
2148 * @brief Notification callback function
2149 *
2150 * In the case of an empty notification, the @p data pointer will be non-NULL
2151 * while the @p length will be 0, which is due to the special case where
2152 * a @p data NULL pointer means unsubscribed.
2153 *
2154 * @param conn Connection object. May be NULL, indicating that the peer is
2155 * being unpaired
2156 * @param params Subscription parameters.
2157 * @param data Attribute value data. If NULL then subscription was removed.
2158 * @param length Attribute value length.
2159 *
2160 * @return BT_GATT_ITER_CONTINUE to continue receiving value notifications.
2161 * BT_GATT_ITER_STOP to unsubscribe from value notifications.
2162 */
2163 typedef uint8_t (*bt_gatt_notify_func_t)(struct bt_conn *conn,
2164 struct bt_gatt_subscribe_params *params,
2165 const void *data, uint16_t length);
2166
2167 /** @typedef bt_gatt_subscribe_func_t
2168 * @brief Subscription callback function
2169 *
2170 * @param conn Connection object.
2171 * @param err ATT error code.
2172 * @param params Subscription parameters used.
2173 */
2174 typedef void (*bt_gatt_subscribe_func_t)(struct bt_conn *conn, uint8_t err,
2175 struct bt_gatt_subscribe_params *params);
2176
2177 /** Subscription flags */
2178 enum bt_gatt_sub_flag {
2179 /** @brief Persistence flag
2180 *
2181 * If set, indicates that the subscription is not saved
2182 * on the GATT server side. Therefore, upon disconnection,
2183 * the subscription will be automatically removed
2184 * from the client's subscriptions list and
2185 * when the client reconnects, it will have to
2186 * issue a new subscription.
2187 */
2188 BT_GATT_SUBSCRIBE_FLAG_VOLATILE,
2189
2190 /** @brief No resubscribe flag
2191 *
2192 * By default when BT_GATT_SUBSCRIBE_FLAG_VOLATILE is unset, the
2193 * subscription will be automatically renewed when the client
2194 * reconnects, as a workaround for GATT servers that do not persist
2195 * subscriptions.
2196 *
2197 * This flag will disable the automatic resubscription. It is useful
2198 * if the application layer knows that the GATT server remembers
2199 * subscriptions from previous connections and wants to avoid renewing
2200 * the subscriptions.
2201 */
2202 BT_GATT_SUBSCRIBE_FLAG_NO_RESUB,
2203
2204 /** @brief Write pending flag
2205 *
2206 * If set, indicates write operation is pending waiting remote end to
2207 * respond.
2208 *
2209 * @note Internal use only.
2210 */
2211 BT_GATT_SUBSCRIBE_FLAG_WRITE_PENDING,
2212
2213 /** @brief Sent flag
2214 *
2215 * If set, indicates that a subscription request (CCC write) has
2216 * already been sent in the active connection.
2217 *
2218 * Used to avoid sending subscription requests multiple times when the
2219 * @kconfig{CONFIG_BT_GATT_AUTO_RESUBSCRIBE} quirk is enabled.
2220 *
2221 * @note Internal use only.
2222 */
2223 BT_GATT_SUBSCRIBE_FLAG_SENT,
2224
2225 BT_GATT_SUBSCRIBE_NUM_FLAGS
2226 };
2227
2228 /** @brief GATT Subscribe parameters */
2229 struct bt_gatt_subscribe_params {
2230 /** Notification value callback */
2231 bt_gatt_notify_func_t notify;
2232 /** Subscribe CCC write request response callback
2233 * If given, called with the subscription parameters given when subscribing
2234 */
2235 bt_gatt_subscribe_func_t subscribe;
2236
2237 /** Subscribe value handle */
2238 uint16_t value_handle;
2239 /** Subscribe CCC handle */
2240 uint16_t ccc_handle;
2241 #if defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC) || defined(__DOXYGEN__)
2242 /** Subscribe End handle (for automatic discovery) */
2243 uint16_t end_handle;
2244 /** Discover parameters used when ccc_handle = @ref BT_GATT_AUTO_DISCOVER_CCC_HANDLE */
2245 struct bt_gatt_discover_params *disc_params;
2246 #endif /* defined(CONFIG_BT_GATT_AUTO_DISCOVER_CCC) || defined(__DOXYGEN__) */
2247 /** Subscribe value */
2248 uint16_t value;
2249 #if defined(CONFIG_BT_SMP)
2250 /** Minimum required security for received notification. Notifications
2251 * and indications received over a connection with a lower security
2252 * level are silently discarded.
2253 */
2254 bt_security_t min_security;
2255 #endif
2256 /** Subscription flags, see @ref bt_gatt_sub_flag */
2257 ATOMIC_DEFINE(flags, BT_GATT_SUBSCRIBE_NUM_FLAGS);
2258
2259 /** @cond INTERNAL_HIDDEN
2260 * Field used for list handling.
2261 */
2262 sys_snode_t node;
2263 /** @endcond */
2264 #if defined(CONFIG_BT_EATT) || defined(__DOXYGEN__)
2265 /** Att channel options. */
2266 enum bt_att_chan_opt chan_opt;
2267 #endif /* CONFIG_BT_EATT */
2268 };
2269
2270 /** @brief Subscribe Attribute Value Notification
2271 *
2272 * This procedure subscribe to value notification using the Client
2273 * Characteristic Configuration handle.
2274 * If notification received subscribe value callback is called to return
2275 * notified value. One may then decide whether to unsubscribe directly from
2276 * this callback. Notification callback with NULL data will not be called if
2277 * subscription was removed by this method.
2278 *
2279 * The Response comes in callback @p params->subscribe. The callback is run from
2280 * the context specified by 'config BT_RECV_CONTEXT'.
2281 * The Notification callback @p params->notify is also called from the BT RX
2282 * thread.
2283 *
2284 * @note Notifications are asynchronous therefore the @p params must remain
2285 * valid while subscribed and cannot be reused for additional subscriptions
2286 * whilst active.
2287 *
2288 * @param conn Connection object.
2289 * @param params Subscribe parameters.
2290 *
2291 * @retval 0 Successfully queued request. Will call @p params->write on
2292 * resolution.
2293 *
2294 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2295 * Allow a pending request to resolve before retrying, or call this function
2296 * from a separate thread to get blocking behavior. Queue size is controlled
2297 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2298 *
2299 * @retval -EALREADY if there already exist a subscription using the @p params.
2300 *
2301 * @retval -EBUSY if @p params.ccc_handle is 0 and @kconfig{CONFIG_BT_GATT_AUTO_DISCOVER_CCC} is
2302 * enabled and discovery for the @p params is already in progress.
2303 */
2304 int bt_gatt_subscribe(struct bt_conn *conn,
2305 struct bt_gatt_subscribe_params *params);
2306
2307 /** @brief Resubscribe Attribute Value Notification subscription
2308 *
2309 * Resubscribe to Attribute Value Notification when already subscribed from a
2310 * previous connection. The GATT server will remember subscription from
2311 * previous connections when bonded, so resubscribing can be done without
2312 * performing a new subscribe procedure after a power cycle.
2313 *
2314 * @note Notifications are asynchronous therefore the parameters need to
2315 * remain valid while subscribed.
2316 *
2317 * @param id Local identity (in most cases BT_ID_DEFAULT).
2318 * @param peer Remote address.
2319 * @param params Subscribe parameters.
2320 *
2321 * @return 0 in case of success or negative value in case of error.
2322 */
2323 int bt_gatt_resubscribe(uint8_t id, const bt_addr_le_t *peer,
2324 struct bt_gatt_subscribe_params *params);
2325
2326 /** @brief Unsubscribe Attribute Value Notification
2327 *
2328 * This procedure unsubscribe to value notification using the Client
2329 * Characteristic Configuration handle. Notification callback with NULL data
2330 * will be called if subscription was removed by this call, until then the
2331 * parameters cannot be reused.
2332 *
2333 * The Response comes in callback @p params->func. The callback is run from
2334 * the BT RX thread.
2335 *
2336 * @param conn Connection object.
2337 * @param params Subscribe parameters. The parameters shall be a @ref bt_gatt_subscribe_params from
2338 * a previous call to bt_gatt_subscribe().
2339 *
2340 * @retval 0 Successfully queued request. Will call @p params->write on
2341 * resolution.
2342 *
2343 * @retval -ENOMEM ATT request queue is full and blocking would cause deadlock.
2344 * Allow a pending request to resolve before retrying, or call this function
2345 * from a separate thread to get blocking behavior. Queue size is controlled
2346 * by @kconfig{CONFIG_BT_ATT_TX_COUNT}.
2347 */
2348 int bt_gatt_unsubscribe(struct bt_conn *conn,
2349 struct bt_gatt_subscribe_params *params);
2350
2351 /** @brief Try to cancel the first pending request identified by @p params.
2352 *
2353 * This function does not release @p params for reuse. The usual callbacks
2354 * for the request still apply. A successful cancel simulates a
2355 * #BT_ATT_ERR_UNLIKELY response from the server.
2356 *
2357 * This function can cancel the following request functions:
2358 * - #bt_gatt_exchange_mtu
2359 * - #bt_gatt_discover
2360 * - #bt_gatt_read
2361 * - #bt_gatt_write
2362 * - #bt_gatt_subscribe
2363 * - #bt_gatt_unsubscribe
2364 *
2365 * @param conn The connection the request was issued on.
2366 * @param params The address `params` used in the request function call.
2367 */
2368 void bt_gatt_cancel(struct bt_conn *conn, void *params);
2369
2370 /** @} */
2371
2372 #ifdef __cplusplus
2373 }
2374 #endif
2375
2376 /**
2377 * @}
2378 */
2379
2380 #endif /* ZEPHYR_INCLUDE_BLUETOOTH_GATT_H_ */
2381