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
|
/*
* 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 GATT_HANDLER_HPP_
#define GATT_HANDLER_HPP_
#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>
#include <mutex>
#include <atomic>
#include <thread>
#include "UUID.hpp"
#include "BTTypes.hpp"
#include "L2CAPComm.hpp"
#include "ATTPDUTypes.hpp"
#include "GATTTypes.hpp"
#include "LFRingbuffer.hpp"
/**
* - - - - - - - - - - - - - - -
*
* Module GATTHandler:
*
* - 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
* - BT Core Spec v5.2: Vol 3, Part G GATT: 3.4 Summary of GATT Profile Attribute Types
*/
namespace direct_bt {
class DBTDevice; // forward
/**
* A thread safe GATT handler associated to one device via one L2CAP connection.
* <p>
* Implementation utilizes a lock free ringbuffer receiving data within its separate thread.
* </p>
*/
class GATTHandler {
public:
enum class Defaults : int {
/* BT Core Spec v5.2: Vol 3, Part F 3.2.8: Maximum length of an attribute value. */
MAX_ATT_MTU = 512,
/* BT Core Spec v5.2: Vol 3, Part G GATT: 5.2.1 ATT_MTU */
MIN_ATT_MTU = 23,
/** 3s poll timeout for l2cap reader thread */
L2CAP_READER_THREAD_POLL_TIMEOUT = 3000,
/** 500ms timeout for l2cap command replies */
L2CAP_COMMAND_REPLY_TIMEOUT = 500,
/** Medium ringbuffer capacity... */
ATTPDU_RING_CAPACITY = 128
};
static inline int number(const Defaults d) { return static_cast<int>(d); }
private:
/* GATTHandle's Device back-reference */
std::weak_ptr<DBTDevice> wbr_device;
const std::string deviceString;
std::recursive_mutex mtx_write;
std::recursive_mutex mtx_command;
POctets rbuffer;
L2CAPComm l2cap;
const int replyTimeoutMS;
std::atomic<bool> isConnected; // reflects state
std::atomic<bool> hasIOError; // reflects state
LFRingbuffer<std::shared_ptr<const AttPDUMsg>, nullptr> attPDURing;
std::atomic<pthread_t> l2capReaderThreadId;
std::atomic<bool> l2capReaderRunning;
std::atomic<bool> l2capReaderShallStop;
std::mutex mtx_l2capReaderInit;
std::condition_variable cv_l2capReaderInit;
/** send immediate confirmation of indication events from device, defaults to true. */
bool sendIndicationConfirmation = true;
std::vector<std::shared_ptr<GATTCharacteristicListener>> eventListenerList;
std::recursive_mutex mtx_eventListenerList;
uint16_t serverMTU;
uint16_t usedMTU;
std::vector<GATTServiceRef> services;
std::shared_ptr<DBTDevice> getDevice() const { return wbr_device.lock(); }
bool validateConnected();
void l2capReaderThreadImpl();
void send(const AttPDUMsg & msg);
std::shared_ptr<const AttPDUMsg> sendWithReply(const AttPDUMsg & msg);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.4.2 MTU Exchange
* <p>
* Returns the server-mtu if successful, otherwise 0.
* </p>
*/
uint16_t exchangeMTU(const uint16_t clientMaxMTU=number(Defaults::MAX_ATT_MTU));
public:
GATTHandler(const std::shared_ptr<DBTDevice> & device, const int replyTimeoutMS = number(Defaults::L2CAP_COMMAND_REPLY_TIMEOUT));
~GATTHandler();
bool getIsConnected() const { return isConnected; }
bool getHasIOError() const { return hasIOError; }
std::string getStateString() const { return L2CAPComm::getStateString(isConnected, hasIOError); }
/**
* After successful l2cap connection, the MTU will be exchanged.
* See getServerMTU() and getUsedMTU(), the latter is in use.
*/
bool connect();
/**
* Disconnect this GATTHandler and optionally the associated device
* @param disconnectDevice if true, associated device will also be disconnected, otherwise not.
* @param ioErrorCause if true, reason for disconnection is an IO error
* @return true if successful, otherwise false
*/
bool disconnect(const bool disconnectDevice, const bool ioErrorCause);
bool isOpen() const { return isConnected && l2cap.isOpen(); }
uint16_t getServerMTU() const { return serverMTU; }
uint16_t getUsedMTU() const { return usedMTU; }
/**
* Find and return the GATTCharacterisicsDecl within internal primary services
* via given characteristic value handle.
* <p>
* Returns nullptr if not found.
* </p>
*/
GATTCharacteristicRef findCharacterisicsByValueHandle(const uint16_t charValueHandle);
/**
* Find and return the GATTCharacterisicsDecl within given list of primary services
* via given characteristic value handle.
* <p>
* Returns nullptr if not found.
* </p>
*/
GATTCharacteristicRef findCharacterisicsByValueHandle(const uint16_t charValueHandle, std::vector<GATTServiceRef> &services);
/**
* Find and return the GATTCharacterisicsDecl within given primary service
* via given characteristic value handle.
* <p>
* Returns nullptr if not found.
* </p>
*/
GATTCharacteristicRef findCharacterisicsByValueHandle(const uint16_t charValueHandle, GATTServiceRef service);
/**
* Discover all primary services _and_ all its characteristics declarations
* including their client config.
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.4.1 Discover All Primary Services
* </p>
* Method returns reference to GATTHandler internal data.
*/
std::vector<GATTServiceRef> & discoverCompletePrimaryServices();
/**
* Returns a reference of the internal kept GATTService list.
* <p>
* The internal list will be populated via {@link #discoverCompletePrimaryServices()}.
* </p>
*/
std::vector<GATTServiceRef> & getServices() { return services; }
/**
* Discover all primary services _only_.
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.4.1 Discover All Primary Services
* </p>
*/
bool discoverPrimaryServices(std::vector<GATTServiceRef> & result);
/**
* Discover all characteristics of a service and declaration attributes _only_.
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.6.1 Discover All Characteristics of a Service
* </p>
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1 Characterisic Declaration Attribute Value
* </p>
*/
bool discoverCharacteristics(GATTServiceRef & service);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.7.1 Discover All Characteristic Descriptors
*/
bool discoverDescriptors(GATTServiceRef & service);
/**
* Generic read GATT value and long value
* <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>
*/
bool readValue(const uint16_t handle, POctets & res, int expectedLength=-1);
/**
* 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>
*/
bool readCharacteristicValue(const GATTCharacteristic & c, POctets & res, int expectedLength=-1);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.12.1 Read Characteristic Descriptor
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.12.2 Read Long Characteristic Descriptor
* </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>
*/
bool readDescriptorValue(GATTDescriptor & cd, int expectedLength=-1);
/**
* Generic write GATT value and long value
*/
bool writeValue(const uint16_t handle, const TROOctets & value, const bool expResponse);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.12.3 Write Characteristic Descriptors
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3 Characteristic Descriptor
* </p>
* <p>
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
* </p>
*/
bool writeDescriptorValue(const GATTDescriptor & cd);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.3 Write Characteristic Value
*/
bool writeCharacteristicValue(const GATTCharacteristic & c, const TROOctets & value);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.1 Write Characteristic Value Without Response
*/
bool writeCharacteristicValueNoResp(const GATTCharacteristic & c, const TROOctets & value);
/**
* BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
* <p>
* Throws an IllegalArgumentException if the given GATTDescriptor is not a ClientCharacteristicConfiguration.
* </p>
*/
bool configIndicationNotification(GATTDescriptor & cd, const bool enableNotification, const bool enableIndication);
/**
* Add the given listener to the list if not already present.
* <p>
* Returns true if the given listener is not element of the list and has been newly added,
* otherwise false.
* </p>
*/
bool addCharacteristicListener(std::shared_ptr<GATTCharacteristicListener> l);
/**
* Remove the given listener from the list.
* <p>
* Returns true if the given listener is an element of the list and has been removed,
* otherwise false.
* </p>
*/
bool removeCharacteristicListener(std::shared_ptr<GATTCharacteristicListener> l);
/**
* Remove the given listener from the list.
* <p>
* Returns true if the given listener is an element of the list and has been removed,
* otherwise false.
* </p>
*/
bool removeCharacteristicListener(const GATTCharacteristicListener * l);
/**
* Remove all event listener from the list.
* <p>
* Returns the number of removed event listener.
* </p>
*/
int removeAllCharacteristicListener();
/**
* Enable or disable sending an immediate confirmation for received indication events from the device.
* <p>
* Default value is true.
* </p>
* <p>
* This setting is per GATTHandler and hence per DBTDevice.
* </p>
*/
void setSendIndicationConfirmation(const bool v);
/**
* Returns whether sending an immediate confirmation for received indication events from the device is enabled.
* <p>
* Default value is true.
* </p>
* <p>
* This setting is per GATTHandler and hence per DBTDevice.
* </p>
*/
bool getSendIndicationConfirmation();
/*****************************************************/
/** Higher level semantic functionality **/
/*****************************************************/
std::shared_ptr<GenericAccess> getGenericAccess(std::vector<GATTServiceRef> & primServices);
std::shared_ptr<GenericAccess> getGenericAccess(std::vector<GATTCharacteristicRef> & genericAccessCharDeclList);
std::shared_ptr<DeviceInformation> getDeviceInformation(std::vector<GATTServiceRef> & primServices);
std::shared_ptr<DeviceInformation> getDeviceInformation(std::vector<GATTCharacteristicRef> & deviceInfoCharDeclList);
/**
* Issues a ping to the device, validating whether it is still reachable.
* <p>
* This method could be periodically utilized to shorten the underlying OS disconnect period
* after turning the device off, which lies within 7-13s.
* </p>
* <p>
* In case the device is no more reachable, disconnect will be initiated due to the occurring IO error.
* </p>
* @return {@code true} if successful, otherwise false in case no GATT services exists etc.
*/
bool ping();
};
} // namespace direct_bt
#endif /* GATT_HANDLER_HPP_ */
|