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