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