aboutsummaryrefslogtreecommitdiffstats
path: root/api/direct_bt/GATTCharacteristic.hpp
blob: 67274a322235f862f0397861acd7590318e3446c (plain)
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
/*
 * 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_CHARACTERISTIC_HPP_
#define GATT_CHARACTERISTIC_HPP_

#include <cstring>
#include <string>
#include <memory>
#include <cstdint>
#include <vector>

#include <mutex>
#include <atomic>

#include "UUID.hpp"
#include "BTTypes.hpp"
#include "OctetTypes.hpp"
#include "ATTPDUTypes.hpp"

#include "GATTDescriptor.hpp"

#include "JavaUplink.hpp"

/**
 * - - - - - - - - - - - - - - -
 *
 * Module GATTCharacteristic:
 *
 * - 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 GATTCharacteristicListener; // forward

    class GATTService; // forward
    typedef std::shared_ptr<GATTService> GATTServiceRef;

    /**
     * <p>
     * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1 Characteristic Declaration Attribute Value
     * </p>
     * handle -> CDAV value
     * <p>
     * BT Core Spec v5.2: Vol 3, Part G GATT: 4.6.1 Discover All Characteristics of a Service
     *
     * Here the handle is a service's characteristics-declaration
     * and the value the Characteristics Property, Characteristics Value Handle _and_ Characteristics UUID.
     * </p>
     */
    class GATTCharacteristic : public JavaUplink {
        private:
            /** Characteristics's service weak back-reference */
            std::weak_ptr<GATTService> wbr_service;
            bool enabledNotifyState = false;
            bool enabledIndicateState = false;

        public:
            /** BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.1.1 Characteristic Properties */
            enum PropertyBitVal : uint8_t {
                Broadcast = 0x01,
                Read = 0x02,
                WriteNoAck = 0x04,
                WriteWithAck = 0x08,
                Notify = 0x10,
                Indicate = 0x20,
                AuthSignedWrite = 0x40,
                ExtProps = 0x80
            };
            /**
             * Returns string values as defined in <https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/gatt-api.txt>
             * <pre>
             * org.bluez.GattCharacteristic1 :: array{string} Flags [read-only]
             * </pre>
             */
            static std::string getPropertyString(const PropertyBitVal prop);

            static std::string getPropertiesString(const PropertyBitVal properties);
            static std::vector<std::unique_ptr<std::string>> getPropertiesStringList(const PropertyBitVal properties);

            /**
             * Characteristics's Service Handle - key to service's handle range, retrieved from Characteristics data.
             * <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 service_handle;

            /**
             * 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::shared_ptr<const uuid_t> value_type;

            /** List of Characteristic Descriptions as shared reference */
            std::vector<GATTDescriptorRef> descriptorList;

            /* Optional Client Characteristic Configuration index within descriptorList */
            int clientCharacteristicsConfigIndex = -1;

            GATTCharacteristic(const GATTServiceRef & service, const uint16_t service_handle, const uint16_t handle,
                                   const PropertyBitVal properties, const uint16_t value_handle, std::shared_ptr<const uuid_t> value_type)
            : wbr_service(service), service_handle(service_handle), handle(handle),
              properties(properties), value_handle(value_handle), value_type(value_type) {}

            std::string get_java_class() const override {
                return java_class();
            }
            static std::string java_class() {
                return std::string(JAVA_DBT_PACKAGE "DBTGattCharacteristic");
            }

            std::shared_ptr<GATTService> getService() const { return wbr_service.lock(); }

            std::shared_ptr<DBTDevice> getDevice() const;

            bool hasProperties(const PropertyBitVal v) const { return v == ( properties & v ); }

            std::string getPropertiesString() const {
                return getPropertiesString(properties);
            }
            std::string toString() const;

            void clearDescriptors() {
                descriptorList.clear();
                clientCharacteristicsConfigIndex = -1;
            }

            GATTDescriptorRef getClientCharacteristicConfig() {
                if( 0 > clientCharacteristicsConfigIndex ) {
                    return nullptr;
                }
                return descriptorList.at(clientCharacteristicsConfigIndex);
            }

            /**
             * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
             * <p>
             * Method enables notification and/or indication for this characteristic at BLE level.
             * </p>
             * <p>
             * Implementation masks this Characteristic properties PropertyBitVal::Notify and PropertyBitVal::Indicate
             * with the respective user request parameters, hence removes unsupported requests.
             * </p>
             * <p>
             * Notification and/or indication configuration is only performed per characteristic if changed.
             * </p>
             * <p>
             * It is recommended to utilize notification over indication, as its link-layer handshake
             * and higher potential bandwidth may deliver material higher performance.
             * </p>
             * @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 GATTDescriptor of type ClientCharacteristicConfiguration, or if the operation has failed.
             * Otherwise returns true.
             * @throws IllegalStateException if notification or indication is set to be enabled
             * and the {@link DBTDevice's}'s {@link GATTHandler} is null, i.e. not connected
             */
            bool configNotificationIndication(const bool enableNotification, const bool enableIndication, bool enabledState[2]);

            /**
             * BT Core Spec v5.2: Vol 3, Part G GATT: 3.3.3.3 Client Characteristic Configuration
             * <p>
             * Method will attempt to enable notification on the BLE level, if available,
             * otherwise indication if available.
             * </p>
             * <p>
             * Notification and/or indication configuration is only performed per characteristic if changed.
             * </p>
             * <p>
             * It is recommended to utilize notification over indication, as its link-layer handshake
             * and higher potential bandwidth may deliver material higher performance.
             * </p>
             * @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 GATTDescriptor of type ClientCharacteristicConfiguration, or if the operation has failed.
             * Otherwise returns true.
             * @throws IllegalStateException if notification or indication is set to be enabled
             * and the {@link DBTDevice's}'s {@link GATTHandler} is null, i.e. not connected
             */
            bool enableNotificationOrIndication(bool enabledState[2]);

            /**
             * Add the given GATTCharacteristicListener to the listener list if not already present.
             * <p>
             * Occurring notifications and indications, if enabled via configNotificationIndication(bool, bool, bool[])
             * or enableNotificationOrIndication(bool[]),
             * will call the respective GATTCharacteristicListener callback method.
             * </p>
             * <p>
             * Returns true if the given listener is not element of the list and has been newly added,
             * otherwise false.
             * </p>
             * <p>
             * Convenience delegation call to GATTHandler via DBTDevice
             * </p>
             * <p>
             * To restrict the listener to listen only to this GATTCharacteristic instance,
             * user has to implement GATTCharacteristicListener::match(GATTCharacteristicRef) accordingly.
             * <br>
             * For this purpose, use may derive from AssociatedGATTCharacteristicListener,
             * which provides these simple matching filter facilities.
             * </p>
             * @throws IllegalStateException if the {@link DBTDevice's}'s {@link GATTHandler} is null, i.e. not connected
             */
            bool addCharacteristicListener(std::shared_ptr<GATTCharacteristicListener> l);

            /**
             * Add the given GATTCharacteristicListener 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.
             * <p>
             * Implementation will attempt to enable notification only, if available,
             * otherwise indication if available. <br>
             * Implementation uses enableNotificationOrIndication(bool[]) to enable either.
             * </p>
             * <p>
             * Occurring notifications and indications will call the respective GATTCharacteristicListener
             * callback method.
             * </p>
             * <p>
             * 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.
             * </p>
             * <p>
             * To restrict the listener to listen only to this GATTCharacteristic instance,
             * user has to implement GATTCharacteristicListener::match(GATTCharacteristicRef) accordingly.
             * <br>
             * For this purpose, use may derive from AssociatedGATTCharacteristicListener,
             * which provides these simple matching filter facilities.
             * </p>
             * @param enabledState array of size 2, holding the resulting enabled state for notification and indication
             * using enableNotificationOrIndication(bool[])
             * @throws IllegalStateException if the {@link DBTDevice's}'s {@link GATTHandler} is null, i.e. not connected
             */
            bool addCharacteristicListener(std::shared_ptr<GATTCharacteristicListener> l, bool enabledState[2]);

            /**
             * Disables the notification and/or indication for this characteristic at BLE level
             * if {@code disableIndicationNotification == true}
             * and removes the given {@link GATTCharacteristicListener} from the listener list.
             * <p>
             * Returns true if the given listener is an element of the list and has been removed,
             * otherwise false.
             * </p>
             * <p>
             * Convenience delegation call to GATTHandler via DBTDevice
             * performing addCharacteristicListener(..)
             * and {@link #configNotificationIndication(bool, bool, bool[]) if {@code disableIndicationNotification == true}.
             * </p>
             * <p>
             * If the DBTDevice's GATTHandler is null, i.e. not connected, {@code false} is being returned.
             * </p>
             * @param l
             * @param disableIndicationNotification if true, disables the notification and/or indication for this characteristic
             * using {@link #configNotificationIndication(bool, bool, bool[])
             * @return
             */
            bool removeCharacteristicListener(std::shared_ptr<GATTCharacteristicListener> l, bool disableIndicationNotification);

            /**
             * Disables the notification and/or indication for this characteristic at BLE level
             * if {@code disableIndicationNotification == true}
             * and removes all {@link GATTCharacteristicListener} from the listener list.
             * <p>
             * Returns the number of removed event listener.
             * </p>
             * <p>
             * Convenience delegation call to GATTHandler via DBTDevice
             * performing addCharacteristicListener(..)
             * and configNotificationIndication(..) if {@code disableIndicationNotification == true}.
             * </p>
             * <p>
             * If the DBTDevice's GATTHandler is null, i.e. not connected, {@code zero} is being returned.
             * </p>
             * @param disableIndicationNotification if true, disables the notification and/or indication for this characteristic
             * using {@link #configNotificationIndication(bool, bool, bool[])
             * @return
             */
            int removeAllCharacteristicListener(bool disableIndicationNotification);

            /**
             * 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 GATTHandler via DBTDevice
             * <p>
             * </p>
             * If the DBTDevice's GATTHandler is null, i.e. not connected, an IllegalStateException is thrown.
             * </p>
             */
            bool readValue(POctets & res, int expectedLength=-1);

            /**
             * BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.3 Write Characteristic Value
             * <p>
             * Convenience delegation call to GATTHandler via DBTDevice
             * <p>
             * </p>
             * If the DBTDevice's GATTHandler is null, i.e. not connected, an IllegalStateException is thrown.
             * </p>
             */
            bool writeValue(const TROOctets & value);

            /**
             * BT Core Spec v5.2: Vol 3, Part G GATT: 4.9.1 Write Characteristic Value Without Response
             * <p>
             * Convenience delegation call to GATTHandler via DBTDevice
             * <p>
             * </p>
             * If the DBTDevice's GATTHandler is null, i.e. not connected, an IllegalStateException is thrown.
             * </p>
             */
            bool writeValueNoResp(const TROOctets & value);
    };
    typedef std::shared_ptr<GATTCharacteristic> GATTCharacteristicRef;

    inline bool operator==(const GATTCharacteristic& lhs, const GATTCharacteristic& rhs)
    { return lhs.handle == rhs.handle; /** unique attribute handles */ }

    inline bool operator!=(const GATTCharacteristic& lhs, const GATTCharacteristic& rhs)
    { return !(lhs == rhs); }

    /**
     * {@link GATTCharacteristic} event listener for notification and indication events.
     * <p>
     * A listener instance may be attached to a {@link BluetoothGattCharacteristic} via
     * {@link GATTCharacteristic::addCharacteristicListener(std::shared_ptr<GATTCharacteristicListener>)} to listen to events,
     * see method's API doc for {@link GATTCharacteristic} filtering.
     * </p>
     * <p>
     * User may utilize {@link AssociatedGATTCharacteristicListener} to listen to only one {@link GATTCharacteristic}.
     * </p>
     * <p>
     * A listener instance may be attached to a {@link GATTHandler} via
     * {@link GATTHandler::addCharacteristicListener(std::shared_ptr<GATTCharacteristicListener>)}
     * to listen to all events of the device or the matching filtered events.
     * </p>
     * <p>
     * The listener receiver maintains a unique set of listener instances without duplicates.
     * </p>
     */
    class GATTCharacteristicListener {
        public:
            /**
             * Custom filter for all event methods,
             * which will not be called if this method returns false.
             * <p>
             * User may override this method to test whether the methods shall be called
             * for the given GATTCharacteristic.
             * </p>
             * <p>
             * Defaults to true;
             * </p>
             */
            virtual bool match(const GATTCharacteristic & characteristic) {
                (void)characteristic;
                return true;
            }

            /**
             * Called from native BLE stack, initiated by a received notification associated
             * with the given {@link GATTCharacteristic}.
             * @param charDecl {@link GATTCharacteristic} related to this notification
             * @param charValue the notification value
             * @param timestamp the indication monotonic timestamp, see getCurrentMilliseconds()
             */
            virtual void notificationReceived(GATTCharacteristicRef charDecl,
                                              std::shared_ptr<TROOctets> charValue, const uint64_t timestamp) = 0;

            /**
             * Called from native BLE stack, initiated by a received indication associated
             * with the given {@link GATTCharacteristic}.
             * @param charDecl {@link GATTCharacteristic} related to this indication
             * @param charValue the indication value
             * @param timestamp the indication monotonic timestamp, see {@link BluetoothUtils#getCurrentMilliseconds()}
             * @param confirmationSent if true, the native stack has sent the confirmation, otherwise user is required to do so.
             */
            virtual void indicationReceived(GATTCharacteristicRef charDecl,
                                            std::shared_ptr<TROOctets> charValue, const uint64_t timestamp,
                                            const bool confirmationSent) = 0;

            virtual ~GATTCharacteristicListener() {}

            /**
             * Default comparison operator, merely testing for same memory reference.
             * <p>
             * Specializations may override.
             * </p>
             */
            virtual bool operator==(const GATTCharacteristicListener& rhs) const
            { return this == &rhs; }

            bool operator!=(const GATTCharacteristicListener& rhs) const
            { return !(*this == rhs); }
    };

    class AssociatedGATTCharacteristicListener : public GATTCharacteristicListener{
        private:
            const GATTCharacteristic * associatedCharacteristic;

        public:
            /**
             * Passing the associated GATTCharacteristic to filter out non matching events.
             */
            AssociatedGATTCharacteristicListener(const GATTCharacteristic * characteristicMatch)
            : associatedCharacteristic(characteristicMatch) { }

            bool match(const GATTCharacteristic & characteristic) override {
                if( nullptr == associatedCharacteristic ) {
                    return true;
                }
                return *associatedCharacteristic == characteristic;
            }
    };

} // namespace direct_bt

#endif /* GATT_CHARACTERISTIC_HPP_ */