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