1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
|
/*
* Author: Sven Gothel <sgothel@jausoft.com>
* Copyright (c) 2020 Gothel Software e.K.
* Copyright (c) 2020 ZAFENA AB
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BT_GATT_CHARACTERISTIC_HPP_
#define BT_GATT_CHARACTERISTIC_HPP_
#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <mutex>
#include <atomic>
#include <jau/java_uplink.hpp>
#include <jau/octets.hpp>
#include <jau/uuid.hpp>
#include "BTTypes0.hpp"
#include "ATTPDUTypes.hpp"
#include "BTTypes1.hpp"
#include "BTGattDesc.hpp"
/**
* - - - - - - - - - - - - - - -
*
* Module BTGattChar:
*
* - BT Core Spec v5.2: Vol 3, Part G Generic Attribute Protocol (GATT)
* - BT Core Spec v5.2: Vol 3, Part G GATT: 2.6 GATT Profile Hierarchy
*/
namespace direct_bt {
class BTGattHandler; // forward
typedef std::shared_ptr<BTGattHandler> BTGattHandlerRef;
class BTDevice; // forward
typedef std::shared_ptr<BTDevice> BTDeviceRef;
class BTGattService; // forward
typedef std::shared_ptr<BTGattService> BTGattServiceRef;
class BTGattCharListener; // forward
typedef std::shared_ptr<BTGattCharListener> BTGattCharListenerRef;
/**
* Representing a Gatt Characteristic object from the ::GATTRole::Client perspective.
*
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3 Characteristic Definition
*
* handle -> CDAV value
*
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.6.1 Discover All Characteristics of a Service
*
* The handle represents a service's characteristics-declaration
* and the value the Characteristics Property, Characteristics Value Handle _and_ Characteristics UUID.
*/
class BTGattChar : public BTObject {
private:
/** Characteristics's service weak back-reference */
std::weak_ptr<BTGattService> wbr_service;
bool enabledNotifyState = false;
bool enabledIndicateState = false;
std::string toShortString() const noexcept;
public:
/** BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties */
enum PropertyBitVal : uint8_t {
NONE = 0,
Broadcast = (1 << 0),
Read = (1 << 1),
WriteNoAck = (1 << 2),
WriteWithAck = (1 << 3),
Notify = (1 << 4),
Indicate = (1 << 5),
AuthSignedWrite = (1 << 6),
ExtProps = (1 << 7)
};
/**
* Characteristic Handle of this instance.
* <p>
* Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
* </p>
*/
const uint16_t handle;
/* Characteristics Property */
const PropertyBitVal properties;
/**
* Characteristics Value Handle.
* <p>
* Attribute handles are unique for each device (server) (BT Core Spec v5.2: Vol 3, Part F Protocol..: 3.2.2 Attribute Handle).
* </p>
*/
const uint16_t value_handle;
/* Characteristics Value Type UUID */
std::unique_ptr<const jau::uuid_t> value_type;
/** List of Characteristic Descriptions as shared reference */
jau::darray<BTGattDescRef> descriptorList;
/* Optional Client Characteristic Configuration index within descriptorList */
int clientCharConfigIndex = -1;
/* Optional Characteristic User Description index within descriptorList */
int userDescriptionIndex = -1;
BTGattChar(const BTGattServiceRef & service_, const uint16_t handle_,
const PropertyBitVal properties_, const uint16_t value_handle_, std::unique_ptr<const jau::uuid_t> && value_type_) noexcept
: wbr_service(service_), handle(handle_),
properties(properties_), value_handle(value_handle_), value_type(std::move(value_type_)) {}
std::string get_java_class() const noexcept override {
return java_class();
}
static std::string java_class() noexcept {
return std::string(JAVA_DBT_PACKAGE "DBTGattChar");
}
BTGattServiceRef getServiceUnchecked() const noexcept { return wbr_service.lock(); }
BTGattHandlerRef getGattHandlerUnchecked() const noexcept;
BTDeviceRef getDeviceUnchecked() const noexcept;
bool hasProperties(const PropertyBitVal v) const noexcept { return v == ( properties & v ); }
/**
* Find a BTGattDesc by its desc_uuid.
*
* @parameter desc_uuid the UUID of the desired BTGattDesc
* @return The matching descriptor or null if not found
*/
std::shared_ptr<BTGattDesc> findGattDesc(const jau::uuid_t& desc_uuid) noexcept;
std::string toString() const noexcept override;
void clearDescriptors() noexcept {
descriptorList.clear();
clientCharConfigIndex = -1;
userDescriptionIndex = -1;
}
/**
* Return the Client Characteristic Configuration BTGattDescRef if available or nullptr.
*
* The BTGattDesc::Type::CLIENT_CHARACTERISTIC_CONFIGURATION has been indexed while
* retrieving the GATT database from the server.
*/
BTGattDescRef getClientCharConfig() const noexcept {
if( 0 > clientCharConfigIndex ) {
return nullptr;
}
return descriptorList.at(static_cast<size_t>(clientCharConfigIndex)); // abort if out of bounds
}
/**
* Return the User Description BTGattDescRef if available or nullptr.
*
* The BTGattDesc::Type::CHARACTERISTIC_USER_DESCRIPTION has been indexed while
* retrieving the GATT database from the server.
*/
BTGattDescRef getUserDescription() const noexcept {
if( 0 > userDescriptionIndex ) {
return nullptr;
}
return descriptorList.at(static_cast<size_t>(userDescriptionIndex)); // abort if out of bounds
}
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
*
* Method enables notification and/or indication for this characteristic at BLE level.
*
* Implementation masks this Characteristic properties PropertyBitVal::Notify and PropertyBitVal::Indicate
* with the respective user request parameters, hence removes unsupported requests.
*
* Notification and/or indication configuration is only performed per characteristic if changed.
*
* It is recommended to utilize notification over indication, as its link-layer handshake
* and higher potential bandwidth may deliver material higher performance.
*
* @param enableNotification
* @param enableIndication
* @param enabledState array of size 2, holding the resulting enabled state for notification and indication.
* @return false if this characteristic has no PropertyBitVal::Notify or PropertyBitVal::Indication present,
* or there is no BTGattDesc of type ClientCharacteristicConfiguration, or if the operation has failed.
* Otherwise returns true.
*
* @see enableNotificationOrIndication()
* @see disableIndicationNotification()
*/
bool configNotificationIndication(const bool enableNotification, const bool enableIndication, bool enabledState[2]) noexcept;
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
*
* Method will attempt to enable notification on the BLE level, if available,
* otherwise indication if available.
*
* Notification and/or indication configuration is only performed per characteristic if changed.
*
* It is recommended to utilize notification over indication, as its link-layer handshake
* and higher potential bandwidth may deliver material higher performance.
*
* @param enabledState array of size 2, holding the resulting enabled state for notification and indication.
* @return false if this characteristic has no PropertyBitVal::Notify or PropertyBitVal::Indication present,
* or there is no BTGattDesc of type ClientCharacteristicConfiguration, or if the operation has failed.
* Otherwise returns true.
*
* @see configNotificationIndication()
* @see disableIndicationNotification()
*/
bool enableNotificationOrIndication(bool enabledState[2]) noexcept;
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
*
* Method will attempt to disable notification and indication on the BLE level.
*
* Notification and/or indication configuration is only performed per characteristic if changed.
*
* @return false if this characteristic has no PropertyBitVal::Notify or PropertyBitVal::Indication present,
* or there is no BTGattDesc of type ClientCharacteristicConfiguration, or if the operation has failed.
* Otherwise returns true.
*
* @see configNotificationIndication()
* @see enableNotificationOrIndication()
* @since 2.4.0
*/
bool disableIndicationNotification() noexcept;
/**
* Add the given BTGattCharListener to the listener list if not already present.
*
* Occurring notifications and indications for this characteristic,
* if enabled via configNotificationIndication(bool, bool, bool[]) or enableNotificationOrIndication(bool[]),
* will call the respective BTGattCharListener callback method.
*
* Returns true if the given listener is not element of the list and has been newly added,
* otherwise false.
*
* Convenience delegation call to BTGattHandler via BTDevice
*
* @see BTGattChar::disableIndicationNotification()
* @see BTGattChar::enableNotificationOrIndication()
* @see BTGattChar::configNotificationIndication()
* @see BTGattChar::addCharListener()
* @see BTGattChar::removeCharListener()
* @see BTGattChar::removeAllAssociatedCharListener()
*/
bool addCharListener(const BTGattCharListenerRef& l) noexcept;
/**
* Add the given BTGattCharListener to the listener list if not already present
* and if enabling the notification <i>or</i> indication for this characteristic at BLE level was successful.<br>
* Notification and/or indication configuration is only performed per characteristic if changed.
*
* Implementation will enable notification if available,
* otherwise indication will be enabled if available. <br>
* Implementation uses enableNotificationOrIndication(bool[]) to enable either.
*
* Occurring notifications and indications for this characteristic
* will call the respective BTGattCharListener callback method.
*
* Returns true if enabling the notification and/or indication was successful
* and if the given listener is not element of the list and has been newly added,
* otherwise false.
*
* @param enabledState array of size 2, holding the resulting enabled state for notification and indication
* using enableNotificationOrIndication(bool[])
*
* @see BTGattChar::disableIndicationNotification()
* @see BTGattChar::enableNotificationOrIndication()
* @see BTGattChar::configNotificationIndication()
* @see BTGattChar::addCharListener()
* @see BTGattChar::removeCharListener()
* @see BTGattChar::removeAllAssociatedCharListener()
*/
bool addCharListener(const BTGattCharListenerRef& l, bool enabledState[2]) noexcept;
/**
* Remove the given associated BTGattCharListener from the listener list if present.
*
* To disables the notification and/or indication for this characteristic at BLE level
* use disableIndicationNotification() when desired.
*
* @param l
* @return
*
* @see BTGattChar::disableIndicationNotification()
* @see BTGattChar::enableNotificationOrIndication()
* @see BTGattChar::configNotificationIndication()
* @see BTGattChar::addCharListener()
* @see BTGattChar::removeCharListener()
* @see BTGattChar::removeAllAssociatedCharListener()
* @since 2.4.0
*/
bool removeCharListener(const BTGattCharListenerRef& l) noexcept;
/**
* Removes all associated BTGattCharListener and and {@link BTGattCharListener} from the listener list.
*
* Also disables the notification and/or indication for this characteristic at BLE level
* if `disableIndicationNotification == true`.
*
* Returns the number of removed event listener.
*
* If the BTDevice's BTGattHandler is null, i.e. not connected, `zero` is being returned.
*
* @param shallDisableIndicationNotification if true, disables the notification and/or indication for this characteristic
* using {@link #disableIndicationNotification()
* @return
* @see BTGattChar::disableIndicationNotification()
* @see BTGattChar::configNotificationIndication()
* @see BTGattChar::addCharListener()
* @see BTGattChar::removeCharListener()
* @see BTGattChar::removeAllAssociatedCharListener()
*/
int removeAllAssociatedCharListener(bool shallDisableIndicationNotification) noexcept;
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.8.1 Read Characteristic Value
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.8.3 Read Long Characteristic Value
* </p>
* <p>
* If expectedLength = 0, then only one ATT_READ_REQ/RSP will be used.
* </p>
* <p>
* If expectedLength < 0, then long values using multiple ATT_READ_BLOB_REQ/RSP will be used until
* the response returns zero. This is the default parameter.
* </p>
* <p>
* If expectedLength > 0, then long values using multiple ATT_READ_BLOB_REQ/RSP will be used
* if required until the response returns zero.
* </p>
* <p>
* Convenience delegation call to BTGattHandler via BTDevice
* <p>
* </p>
* If the BTDevice's BTGattHandler is null, i.e. not connected, false is returned.
* </p>
*/
bool readValue(jau::POctets & res, int expectedLength=-1) noexcept;
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.3 Write Characteristic Value
* <p>
* Convenience delegation call to BTGattHandler via BTDevice
* <p>
* </p>
* If the BTDevice's BTGattHandler is null, i.e. not connected, false is returned.
* </p>
*/
bool writeValue(const jau::TROOctets & value) noexcept;
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.1 Write Characteristic Value Without Response
* <p>
* Convenience delegation call to BTGattHandler via BTDevice
* <p>
* </p>
* If the BTDevice's BTGattHandler is null, i.e. not connected, false is returned.
* </p>
*/
bool writeValueNoResp(const jau::TROOctets & value) noexcept;
};
typedef std::shared_ptr<BTGattChar> BTGattCharRef;
inline bool operator==(const BTGattChar& lhs, const BTGattChar& rhs) noexcept
{ return lhs.handle == rhs.handle; /** unique attribute handles */ }
inline bool operator!=(const BTGattChar& lhs, const BTGattChar& rhs) noexcept
{ return !(lhs == rhs); }
constexpr uint8_t number(const BTGattChar::PropertyBitVal rhs) noexcept {
return static_cast<uint8_t>(rhs);
}
constexpr BTGattChar::PropertyBitVal operator |(const BTGattChar::PropertyBitVal lhs, const BTGattChar::PropertyBitVal rhs) noexcept {
return static_cast<BTGattChar::PropertyBitVal> ( number(lhs) | number(rhs) );
}
constexpr BTGattChar::PropertyBitVal operator &(const BTGattChar::PropertyBitVal lhs, const BTGattChar::PropertyBitVal rhs) noexcept {
return static_cast<BTGattChar::PropertyBitVal> ( number(lhs) & number(rhs) );
}
constexpr bool operator ==(const BTGattChar::PropertyBitVal lhs, const BTGattChar::PropertyBitVal rhs) noexcept {
return number(lhs) == number(rhs);
}
constexpr bool operator !=(const BTGattChar::PropertyBitVal lhs, const BTGattChar::PropertyBitVal rhs) noexcept {
return !( lhs == rhs );
}
std::string to_string(const BTGattChar::PropertyBitVal mask) noexcept;
/**
* {@link BTGattChar} event listener for notification and indication events.
* <p>
* A listener instance may be attached to a BTGattChar instance via
* {@link BTGattChar::addCharListener(BTGattCharListenerRef)} to listen to its events.
* </p>
* <p>
* A listener instance may be attached to a BTGattHandler via
* {@link BTGattHandler::addCharListener(BTGattCharListenerRef)}
* to listen to all events of the device or the matching filtered events.
* </p>
* <p>
* The listener manager maintains a unique set of listener instances without duplicates.
* </p>
*/
class BTGattCharListener : public jau::JavaUplink {
public:
/**
* Returns a unique string denominating the type of this instance.
*
* Simple access and provision of a typename string representation
* at compile time like RTTI via jau::type_name_cue.
*/
virtual const char * type_name() const noexcept;
/**
* Called from native BLE stack, initiated by a received notification associated
* with the given {@link BTGattChar}.
* @param charDecl {@link BTGattChar} related to this notification
* @param charValue the notification value
* @param timestamp monotonic timestamp at reception, see jau::getCurrentMilliseconds()
*/
virtual void notificationReceived(BTGattCharRef charDecl,
const jau::TROOctets& charValue, const uint64_t timestamp) = 0;
/**
* Called from native BLE stack, initiated by a received indication associated
* with the given {@link BTGattChar}.
* @param charDecl {@link BTGattChar} related to this indication
* @param charValue the indication value
* @param timestamp monotonic timestamp at reception, see jau::getCurrentMilliseconds()
* @param confirmationSent if true, the native stack has sent the confirmation, otherwise user is required to do so.
*/
virtual void indicationReceived(BTGattCharRef charDecl,
const jau::TROOctets& charValue, const uint64_t timestamp,
const bool confirmationSent) = 0;
~BTGattCharListener() noexcept override {}
/** Return a simple description about this instance. */
std::string toString() const noexcept override {
return std::string(type_name())+"["+jau::to_string(this)+"]";
}
std::string get_java_class() const noexcept override {
return java_class();
}
static std::string java_class() noexcept {
return std::string(JAVA_MAIN_PACKAGE "BTGattCharListener");
}
/**
* Default comparison operator, merely testing for same memory reference.
* <p>
* Specializations may override.
* </p>
*/
virtual bool operator==(const BTGattCharListener& rhs) const noexcept
{ return this == &rhs; }
bool operator!=(const BTGattCharListener& rhs) const noexcept
{ return !(*this == rhs); }
};
typedef std::shared_ptr<BTGattCharListener> BTGattCharListenerRef;
} // namespace direct_bt
#endif /* BT_GATT_CHARACTERISTIC_HPP_ */
|