-
Notifications
You must be signed in to change notification settings - Fork 407
/
BleServerManager.java
821 lines (765 loc) · 35.3 KB
/
BleServerManager.java
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
package no.nordicsemi.android.ble;
import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.StringRes;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.UUID;
import no.nordicsemi.android.ble.annotation.CharacteristicPermissions;
import no.nordicsemi.android.ble.annotation.CharacteristicProperties;
import no.nordicsemi.android.ble.annotation.DescriptorPermissions;
import no.nordicsemi.android.ble.annotation.LogPriority;
import no.nordicsemi.android.ble.data.Data;
import no.nordicsemi.android.ble.observer.ServerObserver;
import no.nordicsemi.android.ble.utils.ILogger;
/**
* The manager for local GATT server. To be used with one or more instances of {@link BleManager}.
* <p>
* Note, that BLE Library supports only Client-only or Client-and-Server mode. It does not support
* Server-only mode. All interactions with the remote device, both as client and server, are
* performed using the BLE Manager instance, one for each connected device.
* For that last use case, the Client can be limited and client operations can be unused.
*
* @since 2.2
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class BleServerManager implements ILogger {
private final static UUID CHARACTERISTIC_EXTENDED_PROPERTIES_DESCRIPTOR_UUID = UUID.fromString("00002900-0000-1000-8000-00805f9b34fb");
private final static UUID CLIENT_USER_DESCRIPTION_DESCRIPTOR_UUID = UUID.fromString("00002901-0000-1000-8000-00805f9b34fb");
private final static UUID CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
/** Bluetooth GATT server instance, or null if not opened. */
private BluetoothGattServer server;
private final List<BleManager> managers = new ArrayList<>();
private final Context context;
private ServerObserver serverObserver;
/**
* List of server services returned by {@link #initializeServer()}.
* This list is empties when the services are being added one by one to the server.
* To get the server services, use {@link BluetoothGattServer#getServices()} instead.
*/
private Queue<BluetoothGattService> serverServices;
private List<BluetoothGattCharacteristic> sharedCharacteristics;
private List<BluetoothGattDescriptor> sharedDescriptors;
public BleServerManager(@NonNull final Context context) {
this.context = context;
}
/**
* Opens the GATT server and starts initializing services. This method only starts initializing
* services. The {@link ServerObserver#onServerReady()} will be called when all
* services are done.
*
* @return true, if the server has been started successfully. If GATT server could not
* be started, for example the Bluetooth is disabled, false is returned.
* @see #close()
*/
@SuppressLint("MissingPermission")
public final boolean open() {
if (server != null)
return true;
serverServices = new LinkedList<>(initializeServer());
final BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
if (bm != null) {
server = bm.openGattServer(context, gattServerCallback);
}
if (server != null) {
log(Log.INFO, "[Server] Server started successfully");
try {
final BluetoothGattService service = serverServices.remove();
server.addService(service);
} catch (final NoSuchElementException e) {
if (serverObserver != null)
serverObserver.onServerReady();
} catch (final Exception e) {
close();
return false;
}
return true;
}
log(Log.WARN, "GATT server initialization failed");
serverServices = null;
return false;
}
/**
* Closes the GATT server.
*/
@SuppressLint("MissingPermission")
public final void close() {
if (server != null) {
server.close();
server = null;
}
serverServices = null;
for (BleManager manager: managers) {
// closeServer() must be called before close(). Otherwise close() would remove
// the manager from managers list while iterating this loop.
manager.closeServer();
manager.close();
}
managers.clear();
}
/**
* Sets the server observer.
*
* @param observer the observer.
*/
public final void setServerObserver(@Nullable final ServerObserver observer) {
this.serverObserver = observer;
}
/**
* Returns the {@link BluetoothGattServer} instance.
*/
@Nullable
final BluetoothGattServer getServer() {
return server;
}
/**
* Adds the BLE Manager to be handled.
* @param manager the Ble Manager.
*/
final void addManager(@NonNull final BleManager manager) {
if (!managers.contains(manager)) {
managers.add(manager);
}
}
/**
* Removes the manager. Callbacks will no longer be passed to it.
* @param manager the manager to be removed.
*/
final void removeManager(@NonNull final BleManager manager) {
managers.remove(manager);
}
/**
* After calling this method, the server will not disconnect after few seconds.
* @param device The device to connect.
* @param autoConnect Should the device automatically reconnect after it was disconnected.
* @noinspection SameParameterValue
*/
final void useConnection(@NonNull final BluetoothDevice device, final boolean autoConnect) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
server.connect(device, autoConnect);
}
}
/**
* Cancels server connection.
* <p>
* As we're not calling {@link BluetoothGattServer#connect(BluetoothDevice, boolean)}, cancelling
* the connection should not be required. On the other hand, perhaps we should call connect(..).
* @param device The device to cancel connection to.
*/
final void cancelConnection(@NonNull final BluetoothDevice device) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S ||
context.checkCallingOrSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
server.cancelConnection(device);
}
}
final boolean isShared(@NonNull final BluetoothGattCharacteristic characteristic) {
return sharedCharacteristics != null && sharedCharacteristics.contains(characteristic);
}
final boolean isShared(@NonNull final BluetoothGattDescriptor descriptor) {
return sharedDescriptors != null && sharedDescriptors.contains(descriptor);
}
@Nullable
private BleManagerHandler getRequestHandler(@NonNull final BluetoothDevice device) {
for (final BleManager manager : managers) {
if (device.equals(manager.getBluetoothDevice())) {
return manager.requestHandler;
}
}
return null;
}
@Override
@LogPriority
public int getMinLogPriority() {
// By default, the library will log entries on INFO and higher priorities.
// Consider changing to false in production to increase speed and decrease memory allocations.
// Note: Before version 2.4.0 all logs were logged by default, so this changes previous behavior.
// To restore it, return Log.VERBOSE here.
return Log.INFO;
}
@Override
public void log(@LogPriority final int priority, @NonNull final String message) {
// Override to log events. Simple log can use Logcat:
//
// Log.println(priority, TAG, message);
//
// You may also use Timber:
//
// Timber.log(priority, message);
//
// or nRF Logger:
//
// Logger.log(logSession, LogContract.Log.Level.fromPriority(priority), message);
//
// Starting from nRF Logger 2.1.3, you may use log-timber and plant nRFLoggerTree.
// https://github.com/NordicSemiconductor/nRF-Logger-API
}
@Override
public void log(@LogPriority final int priority, @StringRes final int messageRes,
@Nullable final Object... params) {
final String message = context.getString(messageRes, params);
log(priority, message);
}
/**
* This method is called once, just after instantiating the {@link BleServerManager}.
* It should return a list of server GATT services that will be available for the remote device
* to use. You may use {@link #service(UUID, BluetoothGattCharacteristic...)} to easily
* instantiate a service.
* <p>
* Server services will be added to the local GATT configuration on the Android device.
* The library does not know what services are already set up by other apps or
* {@link BleServerManager} instances, so a UUID collision is possible.
* The remote device will discover all services set up by all apps.
* <p>
* In order to enable server callbacks (see {@link android.bluetooth.BluetoothGattServerCallback}),
* but without defining own services, return an empty list.
*
* @since 2.2
* @return The list of server GATT services, or null if no services should be created. An
* empty array to start the GATT server without any services.
*/
@NonNull
protected abstract List<BluetoothGattService> initializeServer();
/**
* A helper method for creating a primary service with given UUID and list of characteristics.
* This method can be called from {@link #initializeServer()}.
*
* @param uuid The service UUID.
* @param characteristics The optional list of characteristics.
* @return The new service.
*/
@NonNull
protected final BluetoothGattService service(@NonNull final UUID uuid, final BluetoothGattCharacteristic... characteristics) {
final BluetoothGattService service = new BluetoothGattService(uuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
for (BluetoothGattCharacteristic characteristic : characteristics) {
service.addCharacteristic(characteristic);
}
return service;
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, an initial value and a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic will NOT be shared between clients. Each client will write
* and read its own copy. To create a shared characteristic, use
* {@link #sharedCharacteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattCharacteristic characteristic(@NonNull final UUID uuid,
@CharacteristicProperties int properties,
@CharacteristicPermissions final int permissions,
@Nullable final byte[] initialValue,
final BluetoothGattDescriptor... descriptors) {
// Look for Client Characteristic Configuration descriptor,
// Characteristic User Description descriptor and Characteristic Extended Properties descriptor.
boolean writableAuxiliaries = false;
boolean cccdFound = false;
boolean cepdFound = false;
BluetoothGattDescriptor cepd = null;
for (final BluetoothGattDescriptor descriptor : descriptors) {
if (CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
cccdFound = true;
} else if (CLIENT_USER_DESCRIPTION_DESCRIPTOR_UUID.equals(descriptor.getUuid())
&& 0 != (descriptor.getPermissions() & (
BluetoothGattDescriptor.PERMISSION_WRITE
| BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED
| BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED_MITM))) {
writableAuxiliaries = true;
} else if (CHARACTERISTIC_EXTENDED_PROPERTIES_DESCRIPTOR_UUID.equals(descriptor.getUuid())) {
cepd = descriptor;
cepdFound = true;
}
}
if (writableAuxiliaries) {
if (cepd == null) {
cepd = new BluetoothGattDescriptor(CHARACTERISTIC_EXTENDED_PROPERTIES_DESCRIPTOR_UUID,
BluetoothGattDescriptor.PERMISSION_READ);
cepd.setValue(new byte[]{0x02, 0x00});
} else {
if (cepd.getValue() != null && cepd.getValue().length == 2) {
cepd.getValue()[0] |= 0x02;
} else {
cepd.setValue(new byte[]{0x02, 0x00});
}
}
}
final boolean cccdRequired = (properties & (BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_INDICATE)) != 0;
final boolean reliableWrite = cepd != null && cepd.getValue() != null
&& cepd.getValue().length == 2 && (cepd.getValue()[0] & 0x01) != 0;
if (writableAuxiliaries || reliableWrite) {
properties |= BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS;
}
if ((properties & BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS) != 0 && cepd == null) {
cepd = new BluetoothGattDescriptor(CHARACTERISTIC_EXTENDED_PROPERTIES_DESCRIPTOR_UUID, BluetoothGattDescriptor.PERMISSION_READ);
cepd.setValue(new byte[] { 0, 0 });
}
final BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(uuid, properties, permissions);
if (cccdRequired && !cccdFound) {
characteristic.addDescriptor(cccd());
}
for (BluetoothGattDescriptor descriptor: descriptors) {
characteristic.addDescriptor(descriptor);
}
if (cepd != null && !cepdFound) {
characteristic.addDescriptor(cepd);
}
characteristic.setValue(initialValue);
return characteristic;
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, an initial value and a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic will NOT be shared between clients. Each client will write
* and read its own copy. To create a shared characteristic, use
* {@link #sharedCharacteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattCharacteristic characteristic(@NonNull final UUID uuid,
@CharacteristicProperties final int properties,
@CharacteristicPermissions final int permissions,
@Nullable final Data initialValue,
final BluetoothGattDescriptor... descriptors) {
return characteristic(uuid, properties, permissions, initialValue != null ? initialValue.getValue() : null, descriptors);
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic will NOT be shared between clients. Each client will write
* and read its own copy. To create a shared characteristic, use
* {@link #sharedCharacteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattCharacteristic characteristic(@NonNull final UUID uuid,
@CharacteristicProperties final int properties,
@CharacteristicPermissions final int permissions,
final BluetoothGattDescriptor... descriptors) {
return characteristic(uuid, properties, permissions, (byte[]) null, descriptors);
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, an initial value and a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic is shared between clients. A value written by one of the
* connected clients will be available for all other clients. To create a sandboxed characteristic,
* use {@link #characteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattCharacteristic sharedCharacteristic(@NonNull final UUID uuid,
@CharacteristicProperties final int properties,
@CharacteristicPermissions final int permissions,
@Nullable final byte[] initialValue,
final BluetoothGattDescriptor... descriptors) {
final BluetoothGattCharacteristic characteristic = characteristic(uuid, properties, permissions, initialValue, descriptors);
if (sharedCharacteristics == null)
sharedCharacteristics = new ArrayList<>();
sharedCharacteristics.add(characteristic);
return characteristic;
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, an initial value and a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic is shared between clients. A value written by one of the
* connected clients will be available for all other clients. To create a sandboxed characteristic,
* use {@link #characteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattCharacteristic sharedCharacteristic(@NonNull final UUID uuid,
@CharacteristicProperties final int properties,
@CharacteristicPermissions final int permissions,
@Nullable final Data initialValue,
final BluetoothGattDescriptor... descriptors) {
return sharedCharacteristic(uuid, properties, permissions, initialValue != null ? initialValue.getValue() : null, descriptors);
}
/**
* A helper method that creates a characteristic with given UUID, properties and permissions.
* Optionally, a list of descriptors may be set.
* <p>
* The Client Characteristic Configuration Descriptor (CCCD) will be added automatically if
* {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY} or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}
* was set, if not added explicitly in the descriptors list.
* <p>
* If {@link #reliableWrite()} was added as one of the descriptors or the Characteristic User
* Description descriptor was created with any of write permissions
* (see {@link #description(String, boolean)}) the
* {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS} property will be added automatically.
* <p>
* The value of the characteristic is shared between clients. A value written by one of the
* connected clients will be available for all other clients. To create a sandboxed characteristic,
* use {@link #characteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param properties The bit mask of characteristic properties. See {@link BluetoothGattCharacteristic}
* for details.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param descriptors The optional list of descriptors.
* @return The characteristic.
* @noinspection SameParameterValue
*/
@NonNull
protected final BluetoothGattCharacteristic sharedCharacteristic(@NonNull final UUID uuid,
@CharacteristicProperties final int properties,
@CharacteristicPermissions final int permissions,
final BluetoothGattDescriptor... descriptors) {
return sharedCharacteristic(uuid, properties, permissions, (byte[]) null, descriptors);
}
/**
* A helper method that creates a descriptor with given UUID and permissions.
* Optionally, an initial value may be set.
* <p>
* The value of the descriptor will NOT be shared between clients. Each client will write
* and read its own copy. To create a shared descriptor, use
* {@link #sharedDescriptor(UUID, int, byte[])} instead.
*
* @param uuid The characteristic UUID.
* @param permissions The bit mask or descriptor permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the descriptor.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattDescriptor descriptor(@NonNull final UUID uuid,
@DescriptorPermissions final int permissions,
@Nullable final byte[] initialValue) {
final BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(uuid, permissions);
descriptor.setValue(initialValue);
return descriptor;
}
/**
* A helper method that creates a descriptor with given UUID and permissions.
* Optionally, an initial value may be set.
* <p>
* The value of the descriptor will NOT be shared between clients. Each client will write
* and read its own copy. To create a shared descriptor, use
* {@link #sharedDescriptor(UUID, int, byte[])} instead.
*
* @param uuid The characteristic UUID.
* @param permissions The bit mask or descriptor permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the descriptor.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattDescriptor descriptor(@NonNull final UUID uuid,
@DescriptorPermissions final int permissions,
@Nullable final Data initialValue) {
return descriptor(uuid, permissions, initialValue != null ? initialValue.getValue() : null);
}
/**
* A helper method that creates a descriptor with given UUID and permissions.
* Optionally, an initial value may be set.
* <p>
* The value of the characteristic is shared between clients. A value written by one of the
* connected clients will be available for all other clients. To create a sandboxed characteristic,
* use {@link #characteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattDescriptor sharedDescriptor(@NonNull final UUID uuid,
@DescriptorPermissions final int permissions,
@Nullable final byte[] initialValue) {
final BluetoothGattDescriptor descriptor = descriptor(uuid, permissions, initialValue);
if (sharedDescriptors == null)
sharedDescriptors = new ArrayList<>();
sharedDescriptors.add(descriptor);
return descriptor;
}
/**
* A helper method that creates a descriptor with given UUID and permissions.
* Optionally, an initial value may be set.
* <p>
* The value of the characteristic is shared between clients. A value written by one of the
* connected clients will be available for all other clients. To create a sandboxed characteristic,
* use {@link #characteristic(UUID, int, int, byte[], BluetoothGattDescriptor...)} instead.
*
* @param uuid The characteristic UUID.
* @param permissions The bit mask or characteristic permissions. See {@link BluetoothGattCharacteristic}
* for details.
* @param initialValue The optional initial value of the characteristic.
* @return The characteristic.
*/
@NonNull
protected final BluetoothGattDescriptor sharedDescriptor(@NonNull final UUID uuid,
@DescriptorPermissions final int permissions,
@Nullable final Data initialValue) {
return sharedDescriptor(uuid, permissions, initialValue != null ? initialValue.getValue() : null);
}
/**
* This helper method returns a new instance of Client Characteristic Configuration Descriptor
* (CCCD) that can be added to a server characteristic in {@link #initializeServer()}.
*
* @return The CCC descriptor used to enable and disable notifications or indications.
*/
@NonNull
protected final BluetoothGattDescriptor cccd() {
return descriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID,
BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE,
new byte[] { 0, 0 });
}
/**
* This helper method returns a new instance of Client Characteristic Configuration Descriptor
* (CCCD) that can be added to a server characteristic in {@link #initializeServer()}.
*
* @return The CCC descriptor used to enable and disable notifications or indications.
*/
@NonNull
protected final BluetoothGattDescriptor sharedCccd() {
return sharedDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID,
BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE,
new byte[] { 0, 0 });
}
/**
* This helper method returns a new instance of Characteristic Extended Properties descriptor
* that can be added to a server characteristic.
* This descriptor should be added it {@link BluetoothGattCharacteristic#PROPERTY_EXTENDED_PROPS}
* property is set.
* @return The CEP descriptor with Reliable Write bit set.
*/
@NonNull
protected final BluetoothGattDescriptor reliableWrite() {
return sharedDescriptor(CHARACTERISTIC_EXTENDED_PROPERTIES_DESCRIPTOR_UUID,
BluetoothGattDescriptor.PERMISSION_READ,
new byte[] { 1, 0 });
}
/**
* This helper method returns a new instance of Client User Description Descriptor
* that can be added to a server characteristic in {@link #initializeServer()}.
*
* @param description the UTF-8 string that is a user textual description of the characteristic.
* @param writableAuxiliaries if true, the descriptor will be writable and the Writable Auxiliaries
* bit in Characteristic Extended Properties descriptor will be set.
* See Vol. 3, Part F, Section 3.3.3.2 in Bluetooth Core specification 5.1.
* @return The User Description descriptor.
*/
@NonNull
protected final BluetoothGattDescriptor description(@Nullable final String description, final boolean writableAuxiliaries) {
final BluetoothGattDescriptor cud = descriptor(CLIENT_USER_DESCRIPTION_DESCRIPTOR_UUID,
BluetoothGattDescriptor.PERMISSION_READ | (writableAuxiliaries ? BluetoothGattDescriptor.PERMISSION_WRITE : 0),
description != null ? description.getBytes() : null);
if (!writableAuxiliaries) {
if (sharedDescriptors == null)
sharedDescriptors = new ArrayList<>();
sharedDescriptors.add(cud);
}
return cud;
}
private final BluetoothGattServerCallback gattServerCallback = new BluetoothGattServerCallback() {
@SuppressLint("MissingPermission")
@Override
public void onServiceAdded(final int status, @NonNull final BluetoothGattService service) {
if (status == BluetoothGatt.GATT_SUCCESS) {
try {
final BluetoothGattService nextService = serverServices.remove();
server.addService(nextService);
} catch (final Exception e) {
log(Log.INFO, "[Server] All services added successfully");
if (serverObserver != null)
serverObserver.onServerReady();
serverServices = null;
}
} else {
log(Log.ERROR, "[Server] Adding service failed with error " + status);
}
}
@Override
public void onConnectionStateChange(@NonNull final BluetoothDevice device, final int status, final int newState) {
if (newState == BluetoothGatt.STATE_CONNECTED) {
log(Log.INFO, "[Server] " + device.getAddress() + " is now connected");
if (serverObserver != null)
serverObserver.onDeviceConnectedToServer(device);
} else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
if (status == BluetoothGatt.GATT_SUCCESS) {
log(Log.INFO, "[Server] " + device.getAddress() + " is disconnected");
} else {
log(Log.WARN, "[Server] " + device.getAddress() + " has disconnected connected with status: " + status);
}
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null && handler.bluetoothGatt == null) {
// There is no client connection to the device.
// We have to notify disconnection manually.
handler.notifyDeviceDisconnected(device, status);
}
if (serverObserver != null)
serverObserver.onDeviceDisconnectedFromServer(device);
}
}
@Override
public void onCharacteristicReadRequest(@NonNull final BluetoothDevice device,
final int requestId, final int offset,
@NonNull final BluetoothGattCharacteristic characteristic) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onCharacteristicReadRequest(server, device, requestId, offset, characteristic);
}
}
@Override
public void onCharacteristicWriteRequest(@NonNull final BluetoothDevice device, final int requestId,
@NonNull final BluetoothGattCharacteristic characteristic,
final boolean preparedWrite, final boolean responseNeeded,
final int offset, @NonNull final byte[] value) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onCharacteristicWriteRequest(server, device, requestId, characteristic,
preparedWrite, responseNeeded, offset, value);
}
}
@Override
public void onDescriptorReadRequest(@NonNull final BluetoothDevice device, final int requestId, final int offset,
@NonNull final BluetoothGattDescriptor descriptor) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onDescriptorReadRequest(server, device, requestId, offset, descriptor);
}
}
@Override
public void onDescriptorWriteRequest(@NonNull final BluetoothDevice device, final int requestId,
@NonNull final BluetoothGattDescriptor descriptor,
final boolean preparedWrite, final boolean responseNeeded,
final int offset, @NonNull final byte[] value) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onDescriptorWriteRequest(server, device, requestId, descriptor,
preparedWrite, responseNeeded, offset, value);
}
}
@Override
public void onExecuteWrite(@NonNull final BluetoothDevice device, final int requestId,
final boolean execute) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onExecuteWrite(server, device, requestId, execute);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onNotificationSent(@NonNull final BluetoothDevice device, final int status) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onNotificationSent(server, device, status);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
@Override
public void onMtuChanged(@NonNull final BluetoothDevice device, final int mtu) {
final BleManagerHandler handler = getRequestHandler(device);
if (handler != null) {
handler.onMtuChanged(server, device, mtu);
}
}
};
}