/
BleManagerHandler.java
3472 lines (3220 loc) · 129 KB
/
BleManagerHandler.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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package no.nordicsemi.android.ble;
import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.util.Pair;
import java.lang.reflect.Method;
import java.security.InvalidParameterException;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingDeque;
import androidx.annotation.IntRange;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;
import no.nordicsemi.android.ble.annotation.ConnectionPriority;
import no.nordicsemi.android.ble.annotation.ConnectionState;
import no.nordicsemi.android.ble.annotation.LogPriority;
import no.nordicsemi.android.ble.annotation.PhyMask;
import no.nordicsemi.android.ble.annotation.PhyOption;
import no.nordicsemi.android.ble.annotation.PhyValue;
import no.nordicsemi.android.ble.callback.ConnectionPriorityCallback;
import no.nordicsemi.android.ble.callback.DataReceivedCallback;
import no.nordicsemi.android.ble.callback.FailCallback;
import no.nordicsemi.android.ble.callback.MtuCallback;
import no.nordicsemi.android.ble.callback.SuccessCallback;
import no.nordicsemi.android.ble.data.Data;
import no.nordicsemi.android.ble.error.GattError;
import no.nordicsemi.android.ble.observer.BondingObserver;
import no.nordicsemi.android.ble.observer.ConnectionObserver;
import no.nordicsemi.android.ble.utils.ParserUtils;
@SuppressWarnings({"WeakerAccess", "unused", "deprecation", "DeprecatedIsStillUsed"})
abstract class BleManagerHandler extends RequestHandler {
private final static String TAG = "BleManager";
private final static String ERROR_CONNECTION_STATE_CHANGE = "Error on connection state change";
private final static String ERROR_DISCOVERY_SERVICE = "Error on discovering services";
private final static String ERROR_AUTH_ERROR_WHILE_BONDED = "Phone has lost bonding information";
private final static String ERROR_READ_CHARACTERISTIC = "Error on reading characteristic";
private final static String ERROR_WRITE_CHARACTERISTIC = "Error on writing characteristic";
private final static String ERROR_READ_DESCRIPTOR = "Error on reading descriptor";
private final static String ERROR_WRITE_DESCRIPTOR = "Error on writing descriptor";
private final static String ERROR_MTU_REQUEST = "Error on mtu request";
private final static String ERROR_CONNECTION_PRIORITY_REQUEST = "Error on connection priority request";
private final static String ERROR_READ_RSSI = "Error on RSSI read";
private final static String ERROR_READ_PHY = "Error on PHY read";
private final static String ERROR_PHY_UPDATE = "Error on PHY update";
private final static String ERROR_RELIABLE_WRITE = "Error on Execute Reliable Write";
private final static String ERROR_NOTIFY = "Error on sending notification/indication";
private final Object LOCK = new Object();
private BluetoothDevice bluetoothDevice;
private BluetoothGatt bluetoothGatt;
private BleManager manager;
private BleServerManager serverManager;
private Handler handler;
private final Deque<Request> taskQueue = new LinkedBlockingDeque<>();
private Deque<Request> initQueue;
/**
* A time after which receiving 133 error is considered a timeout, instead of a
* different reason.
* A {@link BluetoothDevice#connectGatt(Context, boolean, BluetoothGattCallback)} call will
* fail after 30 seconds if the device won't be found until then. Other errors happen much
* earlier. 20 sec should be OK here.
*/
private final static long CONNECTION_TIMEOUT_THRESHOLD = 20000; // ms
/**
* Flag set when services were discovered.
*/
private boolean servicesDiscovered;
/**
* Flag set to true when the {@link #isRequiredServiceSupported(BluetoothGatt)} returned false.
*/
private boolean deviceNotSupported;
/**
* Flag set when service discovery was requested.
*/
private boolean serviceDiscoveryRequested;
/**
* A timestamp when the last connection attempt was made. This is distinguish two situations
* when the 133 error happens during a connection attempt: a timeout (when ~30 sec passed since
* connection was requested), or an error (packet collision, packet missed, etc.)
*/
private long connectionTime;
/**
* A temporary counter to prevent requesting service discovery for old connection.
*/
private int connectionCount = 0;
/**
* Flag set to true when the device is connected.
*/
private boolean connected;
/**
* Flag set to true when the initialization queue is complete.
*/
private boolean ready;
/**
* A flag indicating that an operation is currently in progress.
*/
private boolean operationInProgress;
/**
* This flag is set to false only when the {@link ConnectRequest#shouldAutoConnect()} method
* returns true and the device got disconnected without calling {@link BleManager#disconnect()}
* method. If {@link ConnectRequest#shouldAutoConnect()} returns false (default) this is always
* set to true.
*/
private boolean userDisconnected;
/**
* Flag set to true when {@link ConnectRequest#shouldAutoConnect()} method returned true.
* The first connection attempt is done with <code>autoConnect</code> flag set to false
* (to make the first connection quick) but on connection lost the manager will call
* {@link BleManager#connect(BluetoothDevice)} again. This time this method will call
* {@link BluetoothGatt#connect()} which always uses <code>autoConnect</code> equal true.
*/
private boolean initialConnection;
/**
* The connection state. One of:
* {@link BluetoothGatt#STATE_CONNECTING STATE_CONNECTING},
* {@link BluetoothGatt#STATE_CONNECTED STATE_CONNECTED},
* {@link BluetoothGatt#STATE_DISCONNECTING STATE_DISCONNECTING},
* {@link BluetoothGatt#STATE_DISCONNECTED STATE_DISCONNECTED}
*/
@ConnectionState
private int connectionState = BluetoothGatt.STATE_DISCONNECTED;
/**
* This flag is required to resume operations after the connection priority request was made.
* It is used only on Android Oreo and newer, as only there there is onConnectionUpdated
* callback. However, as this callback is triggered every time the connection parameters
* change, even when such request wasn't made, this flag ensures the nextRequest() method
* won't be called during another operation.
*/
private boolean connectionPriorityOperationInProgress = false;
/**
* A flag indicating that Reliable Write is in progress.
*/
private boolean reliableWriteInProgress;
/**
* The current MTU (Maximum Transfer Unit). The maximum number of bytes that can be sent in
* a single packet is MTU-3.
*/
private int mtu = 23;
/**
* Last received battery value or -1 if value wasn't received.
*
* @deprecated Battery value should be kept in the profile manager instead. See BatteryManager
* class in Android nRF Toolbox app.
*/
@IntRange(from = -1, to = 100)
@Deprecated
private int batteryValue = -1;
/** Values of non-shared characteristics. Each connected device has its own copy of such. */
private Map<BluetoothGattCharacteristic, byte[]> characteristicValues;
/** Values of non-shared descriptors. Each connected device has its own copy of such. */
private Map<BluetoothGattDescriptor, byte[]> descriptorValues;
/**
* Temporary values of characteristic to support Reliable Write. The temp value will be
* set as valid when the write request is executed, or discarded when aborted.
*/
private Deque<Pair<Object /* BluetoothGattCharacteristic of BluetoothGattDescriptor> */, byte[]>> preparedValues;
private int prepareError;
/**
* The connect request. This is instantiated in {@link BleManager#connect(BluetoothDevice, int)}
* and nullified after the device is ready.
* <p>
* This request has a separate reference, as it is notified when the device becomes ready,
* after the initialization requests are done.
*/
private ConnectRequest connectRequest;
/**
* Currently performed request or null in idle state.
*/
private Request request;
/**
* Currently performer request set, or null if none.
*/
private RequestQueue requestQueue;
/**
* A map of {@link ValueChangedCallback}s for handling notifications, indications and
* write callbacks to server characteristic and descriptors.
*/
@NonNull
private final HashMap<Object, ValueChangedCallback> valueChangedCallbacks = new HashMap<>();
/**
* A special handler for Battery Level notifications.
*/
@Nullable
@Deprecated
private ValueChangedCallback batteryLevelNotificationCallback;
/**
* An instance of a request that waits for a notification or an indication.
* There may be only a single instance of such request at a time as this is a blocking request.
*/
@Nullable
private AwaitingRequest<?> awaitingRequest;
private final BroadcastReceiver bluetoothStateBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
final int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.STATE_OFF);
log(Log.DEBUG, () ->
"[Broadcast] Action received: " + BluetoothAdapter.ACTION_STATE_CHANGED +
", state changed to " + state2String(state)
);
switch (state) {
case BluetoothAdapter.STATE_TURNING_OFF:
case BluetoothAdapter.STATE_OFF:
if (previousState != BluetoothAdapter.STATE_TURNING_OFF
&& previousState != BluetoothAdapter.STATE_OFF) {
// No more calls are possible
operationInProgress = true;
taskQueue.clear();
initQueue = null;
final BluetoothDevice device = bluetoothDevice;
if (device != null) {
// Signal the current request, if any
if (request != null && request.type != Request.Type.DISCONNECT) {
request.notifyFail(device, FailCallback.REASON_BLUETOOTH_DISABLED);
request = null;
}
if (awaitingRequest != null) {
awaitingRequest.notifyFail(device, FailCallback.REASON_BLUETOOTH_DISABLED);
awaitingRequest = null;
}
if (connectRequest != null) {
connectRequest.notifyFail(device, FailCallback.REASON_BLUETOOTH_DISABLED);
connectRequest = null;
}
}
// The connection is killed by the system, no need to disconnect gently.
userDisconnected = true;
// Allow new requests when Bluetooth is enabled again. close() doesn't do it.
// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/25
// and: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/41
operationInProgress = false;
// This will call close()
if (device != null) {
notifyDeviceDisconnected(device, ConnectionObserver.REASON_TERMINATE_LOCAL_HOST);
}
} else {
// Calling close() will prevent the STATE_OFF event from being logged
// (this receiver will be unregistered). But it doesn't matter.
close();
}
break;
}
}
private String state2String(final int state) {
switch (state) {
case BluetoothAdapter.STATE_TURNING_ON:
return "TURNING ON";
case BluetoothAdapter.STATE_ON:
return "ON";
case BluetoothAdapter.STATE_TURNING_OFF:
return "TURNING OFF";
case BluetoothAdapter.STATE_OFF:
return "OFF";
default:
return "UNKNOWN (" + state + ")";
}
}
};
private final BroadcastReceiver mBondingBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
// Skip other devices.
if (bluetoothDevice == null || device == null
|| !device.getAddress().equals(bluetoothDevice.getAddress()))
return;
log(Log.DEBUG, () ->
"[Broadcast] Action received: " + BluetoothDevice.ACTION_BOND_STATE_CHANGED +
", bond state changed to: " + ParserUtils.bondStateToString(bondState) +
" (" + bondState + ")");
switch (bondState) {
case BluetoothDevice.BOND_NONE:
if (previousBondState == BluetoothDevice.BOND_BONDING) {
postCallback(c -> c.onBondingFailed(device));
postBondingStateChange(o -> o.onBondingFailed(device));
log(Log.WARN, () -> "Bonding failed");
if (request != null && request.type == Request.Type.CREATE_BOND) {
request.notifyFail(device, FailCallback.REASON_REQUEST_FAILED);
request = null;
}
// If the device started to pair just after the connection was
// established the services were not discovered. We may try to discover services
// despite the fail bonding process.
// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/335
if (!servicesDiscovered && !serviceDiscoveryRequested) {
post(() -> {
serviceDiscoveryRequested = true;
log(Log.VERBOSE, () -> "Discovering services...");
log(Log.DEBUG, () -> "gatt.discoverServices()");
bluetoothGatt.discoverServices();
});
return;
}
} else if (previousBondState == BluetoothDevice.BOND_BONDED) {
// Removing the bond will cause disconnection.
userDisconnected = true;
if (request != null && request.type == Request.Type.REMOVE_BOND) {
// The device has already disconnected by now.
log(Log.INFO, () -> "Bond information removed");
request.notifySuccess(device);
request = null;
}
// When the bond information has been removed (either with Remove Bond request
// or in Android Settings), the BluetoothGatt object should be closed, so
// the library won't reconnect to the device automatically.
// See: https://github.com/NordicSemiconductor/Android-BLE-Library/issues/157
if (!isConnected())
close();
// Due to https://github.com/NordicSemiconductor/Android-BLE-Library/issues/363,
// the call to close() here has been placed behind an if statement.
// Instead, the 'userDisconnected' flag is set to true (here and in
// 'internalRemoveBond()'.
// When the device gets disconnected, close() method will be called from
// 'notifyDeviceDisconnected(...)'.
}
break;
case BluetoothDevice.BOND_BONDING:
postCallback(c -> c.onBondingRequired(device));
postBondingStateChange(o -> o.onBondingRequired(device));
return;
case BluetoothDevice.BOND_BONDED:
log(Log.INFO, () -> "Device bonded");
postCallback(c -> c.onBonded(device));
postBondingStateChange(o -> o.onBonded(device));
if (request != null && request.type == Request.Type.CREATE_BOND) {
request.notifySuccess(device);
request = null;
break;
}
// If the device started to pair just after the connection was
// established the services were not discovered.
if (!servicesDiscovered && !serviceDiscoveryRequested) {
post(() -> {
serviceDiscoveryRequested = true;
log(Log.VERBOSE, () -> "Discovering services...");
log(Log.DEBUG, () -> "gatt.discoverServices()");
bluetoothGatt.discoverServices();
});
return;
}
// On older Android versions, after executing a command on secured attribute
// of a device that is not bonded, let's say a write characteristic operation,
// the system will start bonding. The BOND_BONDING and BOND_BONDED events will
// be received, but the command will not be repeated automatically.
//
// Test results:
// Devices that require repeating the last task:
// - Nexus 4 with Android 5.1.1
// - Samsung S6 with 5.0.1
// - Samsung S8 with Android 7.0
// - Nexus 9 with Android 7.1.1
// Devices that repeat the request automatically:
// - Pixel 2 with Android 8.1.0
// - Samsung S8 with Android 8.0.0
//
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
if (request != null) {
// Repeat the last command in that case.
enqueueFirst(request);
break;
}
}
// No need to repeat the request.
return;
}
nextRequest(true);
}
};
/**
* Initializes the object.
*
* @param manager The BLE manager.
*/
void init(@NonNull final BleManager manager, @NonNull final Handler handler) {
this.manager = manager;
this.handler = handler;
}
/**
* Binds the server with the BLE manager handler. Call with null to unbind the server.
*
* @param server the server to bind; null to unbind the server.
*/
void useServer(@Nullable final BleServerManager server) {
this.serverManager = server;
}
/**
* Closes and releases resources.
*/
void close() {
try {
final Context context = manager.getContext();
context.unregisterReceiver(bluetoothStateBroadcastReceiver);
context.unregisterReceiver(mBondingBroadcastReceiver);
} catch (final Exception e) {
// the receiver must have been not registered or unregistered before.
}
synchronized (LOCK) {
if (bluetoothGatt != null) {
if (manager.shouldClearCacheWhenDisconnected()) {
if (internalRefreshDeviceCache()) {
log(Log.INFO, () -> "Cache refreshed");
} else {
log(Log.WARN, () -> "Refreshing failed");
}
}
log(Log.DEBUG, () -> "gatt.close()");
try {
bluetoothGatt.close();
} catch (final Throwable t) {
// ignore
}
bluetoothGatt = null;
}
reliableWriteInProgress = false;
initialConnection = false;
valueChangedCallbacks.clear();
// close() is called in notifyDeviceDisconnected, which may enqueue new requests.
// Setting this flag to false would allow to enqueue a new request before the
// current one ends processing. The following line should not be uncommented.
// mGattCallback.operationInProgress = false;
taskQueue.clear();
initQueue = null;
bluetoothDevice = null;
connected = false;
}
}
public BluetoothDevice getBluetoothDevice() {
return bluetoothDevice;
}
/**
* Returns the value of the server characteristic. For characteristics that are not shared,
* the value may be different for each connected device.
*
* @param serverCharacteristic The characteristic to get value of.
* @return The value.
*/
@Nullable
public final byte[] getCharacteristicValue(@NonNull final BluetoothGattCharacteristic serverCharacteristic) {
if (characteristicValues != null && characteristicValues.containsKey(serverCharacteristic))
return characteristicValues.get(serverCharacteristic);
return serverCharacteristic.getValue();
}
/**
* Returns the value of the server descriptor. For descriptor that are not shared,
* the value may be different for each connected device.
*
* @param serverDescriptor The descriptor to get value of.
* @return The value.
*/
@Nullable
public final byte[] getDescriptorValue(@NonNull final BluetoothGattDescriptor serverDescriptor) {
if (descriptorValues != null && descriptorValues.containsKey(serverDescriptor))
return descriptorValues.get(serverDescriptor);
return serverDescriptor.getValue();
}
// Requests implementation
private boolean internalConnect(@NonNull final BluetoothDevice device,
@Nullable final ConnectRequest connectRequest) {
final boolean bluetoothEnabled = BluetoothAdapter.getDefaultAdapter().isEnabled();
if (connected || !bluetoothEnabled) {
final BluetoothDevice currentDevice = bluetoothDevice;
if (bluetoothEnabled && currentDevice != null && currentDevice.equals(device)) {
if (this.connectRequest != null) {
this.connectRequest.notifySuccess(device);
}
} else {
// We can't return false here, as the request would be notified with
// bluetoothDevice instance instead, and that may be null or a wrong device.
if (this.connectRequest != null) {
this.connectRequest.notifyFail(device,
bluetoothEnabled ?
FailCallback.REASON_REQUEST_FAILED :
FailCallback.REASON_BLUETOOTH_DISABLED);
} // else, the request was already failed by the Bluetooth state receiver
}
this.connectRequest = null;
nextRequest(true);
return true;
}
final Context context = manager.getContext();
synchronized (LOCK) {
if (bluetoothGatt != null) {
// There are 2 ways of reconnecting to the same device:
// 1. Reusing the same BluetoothGatt object and calling connect() - this will force
// the autoConnect flag to true
// 2. Closing it and reopening a new instance of BluetoothGatt object.
// The gatt.close() is an asynchronous method. It requires some time before it's
// finished and device.connectGatt(...) can't be called immediately or service
// discovery may never finish on some older devices (Nexus 4, Android 5.0.1).
// If shouldAutoConnect() method returned false we can't call gatt.connect() and
// have to close gatt and open it again.
if (!initialConnection) {
log(Log.DEBUG, () -> "gatt.close()");
try {
bluetoothGatt.close();
} catch (final Throwable t) {
// ignore
}
bluetoothGatt = null;
try {
log(Log.DEBUG, () -> "wait(200)");
Thread.sleep(200); // Is 200 ms enough?
} catch (final InterruptedException e) {
// Ignore
}
} else {
// Instead, the gatt.connect() method will be used to reconnect to the same device.
// This method forces autoConnect = true even if the gatt was created with this
// flag set to false.
initialConnection = false;
connectionTime = 0L; // no timeout possible when autoConnect used
connectionState = BluetoothGatt.STATE_CONNECTING;
log(Log.VERBOSE, () -> "Connecting...");
postCallback(c -> c.onDeviceConnecting(device));
postConnectionStateChange(o -> o.onDeviceConnecting(device));
log(Log.DEBUG, () -> "gatt.connect()");
bluetoothGatt.connect();
return true;
}
} else {
if (connectRequest != null) {
// Register bonding broadcast receiver
context.registerReceiver(bluetoothStateBroadcastReceiver,
new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
context.registerReceiver(mBondingBroadcastReceiver,
new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
}
}
// This should not happen in normal circumstances, but may, when Bluetooth was turned off
// when retrying to create a connection.
if (connectRequest == null)
return false;
final boolean shouldAutoConnect = connectRequest.shouldAutoConnect();
// We will receive Link Loss events only when the device is connected with autoConnect=true.
userDisconnected = !shouldAutoConnect;
// The first connection will always be done with autoConnect = false to make the connection quick.
// If the shouldAutoConnect() method returned true, the manager will automatically try to
// reconnect to this device on link loss.
if (shouldAutoConnect) {
initialConnection = true;
}
bluetoothDevice = device;
log(Log.VERBOSE, () -> connectRequest.isFirstAttempt() ? "Connecting..." : "Retrying...");
connectionState = BluetoothGatt.STATE_CONNECTING;
postCallback(c -> c.onDeviceConnecting(device));
postConnectionStateChange(o -> o.onDeviceConnecting(device));
connectionTime = SystemClock.elapsedRealtime();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
// connectRequest will never be null here.
final int preferredPhy = connectRequest.getPreferredPhy();
log(Log.DEBUG, () ->
"gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, "
+ ParserUtils.phyMaskToString(preferredPhy) + ")");
bluetoothGatt = device.connectGatt(context, false, gattCallback,
BluetoothDevice.TRANSPORT_LE, preferredPhy, handler);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
// connectRequest will never be null here.
final int preferredPhy = connectRequest.getPreferredPhy();
log(Log.DEBUG, () ->
"gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE, "
+ ParserUtils.phyMaskToString(preferredPhy) + ")");
// A variant of connectGatt with Handled can't be used here.
// Check https://github.com/NordicSemiconductor/Android-BLE-Library/issues/54
// This bug specifically occurs in SDK 26 and is fixed in SDK 27
bluetoothGatt = device.connectGatt(context, false, gattCallback,
BluetoothDevice.TRANSPORT_LE, preferredPhy/*, handler*/);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
log(Log.DEBUG, () -> "gatt = device.connectGatt(autoConnect = false, TRANSPORT_LE)");
bluetoothGatt = device.connectGatt(context, false, gattCallback,
BluetoothDevice.TRANSPORT_LE);
} else {
log(Log.DEBUG, () -> "gatt = device.connectGatt(autoConnect = false)");
bluetoothGatt = device.connectGatt(context, false, gattCallback);
}
return true;
}
private boolean internalDisconnect(final int reason) {
userDisconnected = true;
initialConnection = false;
ready = false;
final BluetoothGatt gatt = bluetoothGatt;
if (gatt != null) {
final boolean wasConnected = connected;
connectionState = BluetoothGatt.STATE_DISCONNECTING;
log(Log.VERBOSE, () -> wasConnected ? "Disconnecting..." : "Cancelling connection...");
final BluetoothDevice device = gatt.getDevice();
if (wasConnected) {
postCallback(c -> c.onDeviceDisconnecting(device));
postConnectionStateChange(o -> o.onDeviceDisconnecting(device));
}
log(Log.DEBUG, () -> "gatt.disconnect()");
gatt.disconnect();
if (wasConnected)
return true;
// If the device wasn't connected, there will be no callback after calling
// gatt.disconnect(), the connection attempt will be stopped.
connectionState = BluetoothGatt.STATE_DISCONNECTED;
log(Log.INFO, () -> "Disconnected");
close();
postCallback(c -> c.onDeviceDisconnected(device));
postConnectionStateChange(o -> o.onDeviceDisconnected(device, reason));
}
// request may be of type DISCONNECT or CONNECT (timeout).
// For the latter, it has already been notified with REASON_TIMEOUT.
final Request r = request;
if (r != null && r.type == Request.Type.DISCONNECT) {
if (bluetoothDevice != null || gatt != null)
r.notifySuccess(bluetoothDevice != null ? bluetoothDevice : gatt.getDevice());
else
r.notifyInvalidRequest();
}
nextRequest(true);
return true;
}
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
private boolean internalCreateBond(final boolean ensure) {
final BluetoothDevice device = bluetoothDevice;
if (device == null)
return false;
if (ensure)
log(Log.VERBOSE, () -> "Ensuring bonding...");
else
log(Log.VERBOSE, () -> "Starting bonding...");
// Warning: The check below only ensures that the bond information is present on the
// Android side, not on both. If the bond information has been remove from the
// peripheral side, the code below will notify bonding as success, but in fact the
// link will not be encrypted! Currently there is no way to ensure that the link
// is secure.
// Android, despite reporting bond state as BONDED, creates an unencrypted link
// and does not report this as a problem. Calling createBond() on a valid,
// encrypted link, to ensure that the link is encrypted, returns false (error).
// The same result is returned if only the Android side has bond information,
// making both cases indistinguishable.
//
// Solution: To make sure that sensitive data are sent only on encrypted link make sure
// the characteristic/descriptor is protected and reading/writing to it will
// initiate bonding request. To make sure link is encrypted, use ensureBond()
// method in BleManager, which will remove old and recreate bonding until this
// Android bug is fixed.
if (!ensure && device.getBondState() == BluetoothDevice.BOND_BONDED) {
log(Log.WARN, () -> "Bond information present on client, skipping bonding");
request.notifySuccess(device);
nextRequest(true);
return true;
}
final boolean result = createBond(device);
if (ensure && !result) {
// This will be added as a second.
// Copy all callbacks from the current request and clear them in the original.
final Request bond = Request.createBond().setRequestHandler(this);
// bond.beforeCallback was already fired.
bond.successCallback = request.successCallback;
bond.invalidRequestCallback = request.invalidRequestCallback;
bond.failCallback = request.failCallback;
bond.internalSuccessCallback = request.internalSuccessCallback;
bond.internalFailCallback = request.internalFailCallback;
request.successCallback = null;
request.invalidRequestCallback = null;
request.failCallback = null;
request.internalSuccessCallback = null;
request.internalFailCallback = null;
enqueueFirst(bond);
// This will be added as first.
enqueueFirst(Request.removeBond().setRequestHandler(this));
nextRequest(true);
return true;
}
return result;
}
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
private boolean createBond(@NonNull final BluetoothDevice device) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
log(Log.DEBUG, () -> "device.createBond()");
return device.createBond();
} else {
/*
* There is a createBond() method in BluetoothDevice class but for now it's hidden.
* We will call it using reflections. It has been revealed in KitKat (Api19).
*/
try {
final Method createBond = device.getClass().getMethod("createBond");
log(Log.DEBUG, () -> "device.createBond() (hidden)");
return createBond.invoke(device) == Boolean.TRUE;
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while creating bond", e);
return false;
}
}
}
@RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
private boolean internalRemoveBond() {
final BluetoothDevice device = bluetoothDevice;
if (device == null)
return false;
log(Log.VERBOSE, () -> "Removing bond information...");
if (device.getBondState() == BluetoothDevice.BOND_NONE) {
log(Log.WARN, () -> "Device is not bonded");
request.notifySuccess(device);
nextRequest(true);
return true;
}
/*
* There is a removeBond() method in BluetoothDevice class but for now it's hidden.
* We will call it using reflections.
*/
try {
//noinspection JavaReflectionMemberAccess
final Method removeBond = device.getClass().getMethod("removeBond");
log(Log.DEBUG, () -> "device.removeBond() (hidden)");
// Removing a call will initiate disconnection.
userDisconnected = true;
return removeBond.invoke(device) == Boolean.TRUE;
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while removing bond", e);
}
return false;
}
/**
* When the device is bonded and has the Generic Attribute service and the Service Changed
* characteristic this method enables indications on this characteristic.
* In case one of the requirements is not fulfilled this method returns <code>false</code>.
*
* @return <code>true</code> when the request has been sent, <code>false</code> when the device
* is not bonded, does not have the Generic Attribute service, the GA service does not have
* the Service Changed characteristic or this characteristic does not have the CCCD.
*/
private boolean ensureServiceChangedEnabled() {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || !connected)
return false;
// The Service Changed indications have sense only on bonded devices.
final BluetoothDevice device = gatt.getDevice();
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
return false;
final BluetoothGattService gaService = gatt.getService(BleManager.GENERIC_ATTRIBUTE_SERVICE);
if (gaService == null)
return false;
final BluetoothGattCharacteristic scCharacteristic =
gaService.getCharacteristic(BleManager.SERVICE_CHANGED_CHARACTERISTIC);
if (scCharacteristic == null)
return false;
log(Log.INFO, () -> "Service Changed characteristic found on a bonded device");
return internalEnableIndications(scCharacteristic);
}
private boolean internalEnableNotifications(@Nullable final BluetoothGattCharacteristic characteristic) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || characteristic == null || !connected)
return false;
final BluetoothGattDescriptor descriptor = getCccd(characteristic, BluetoothGattCharacteristic.PROPERTY_NOTIFY);
if (descriptor != null) {
log(Log.DEBUG, () -> "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
gatt.setCharacteristicNotification(characteristic, true);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
log(Log.VERBOSE, () -> "Enabling notifications for " + characteristic.getUuid());
log(Log.DEBUG, () ->
"gatt.writeDescriptor(" + BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
return internalWriteDescriptorWorkaround(descriptor);
}
return false;
}
private boolean internalDisableNotifications(@Nullable final BluetoothGattCharacteristic characteristic) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || characteristic == null || !connected)
return false;
final BluetoothGattDescriptor descriptor = getCccd(characteristic,
BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_INDICATE);
if (descriptor != null) {
log(Log.DEBUG, () -> "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", false)");
gatt.setCharacteristicNotification(characteristic, false);
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
log(Log.VERBOSE, () -> "Disabling notifications and indications for " + characteristic.getUuid());
log(Log.DEBUG, () ->
"gatt.writeDescriptor(" + BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x00-00)");
return internalWriteDescriptorWorkaround(descriptor);
}
return false;
}
private boolean internalEnableIndications(@Nullable final BluetoothGattCharacteristic characteristic) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || characteristic == null || !connected)
return false;
final BluetoothGattDescriptor descriptor = getCccd(characteristic, BluetoothGattCharacteristic.PROPERTY_INDICATE);
if (descriptor != null) {
log(Log.DEBUG, () -> "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
gatt.setCharacteristicNotification(characteristic, true);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
log(Log.VERBOSE, () -> "Enabling indications for " + characteristic.getUuid());
log(Log.DEBUG, () ->
"gatt.writeDescriptor(" + BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x02-00)");
return internalWriteDescriptorWorkaround(descriptor);
}
return false;
}
private boolean internalDisableIndications(@Nullable final BluetoothGattCharacteristic characteristic) {
// This writes exactly the same settings so do not duplicate code.
return internalDisableNotifications(characteristic);
}
private boolean internalSendNotification(@Nullable final BluetoothGattCharacteristic serverCharacteristic,
final boolean confirm) {
if (serverManager == null || serverManager.getServer() == null || serverCharacteristic == null)
return false;
final int requiredProperty = confirm ? BluetoothGattCharacteristic.PROPERTY_INDICATE : BluetoothGattCharacteristic.PROPERTY_NOTIFY;
if ((serverCharacteristic.getProperties() & requiredProperty) == 0)
return false;
final BluetoothGattDescriptor cccd = serverCharacteristic.getDescriptor(BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
if (cccd == null)
return false;
// If notifications/indications were enabled, send the notification/indication.
final byte[] value = descriptorValues != null && descriptorValues.containsKey(cccd) ? descriptorValues.get(cccd) : cccd.getValue();
if (value != null && value.length == 2 && value[0] != 0) {
log(Log.VERBOSE, () -> "[Server] Sending " + (confirm ? "indication" : "notification") + " to " + serverCharacteristic.getUuid());
log(Log.DEBUG, () -> "server.notifyCharacteristicChanged(device, " + serverCharacteristic.getUuid() + ", " + confirm + ")");
final boolean result = serverManager.getServer().notifyCharacteristicChanged(bluetoothDevice, serverCharacteristic, confirm);
if (result && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
post(() -> {
notifyNotificationSent(bluetoothDevice);
nextRequest(true);
});
}
return result;
}
// Otherwise, assume the data was sent. The remote side has not registered for them.
nextRequest(true);
return true;
}
/**
* Returns the Client Characteristic Config Descriptor if the characteristic has the
* required property. It may return null if the CCCD is not there.
*
* @param characteristic the characteristic to look the CCCD in.
* @param requiredProperty the required property: {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY}
* or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}.
* @return The CCC descriptor or null if characteristic is null, if it doesn't have the
* required property, or if the CCCD is missing.
*/
private static BluetoothGattDescriptor getCccd(@Nullable final BluetoothGattCharacteristic characteristic,
final int requiredProperty) {
if (characteristic == null)
return null;
// Check characteristic property
final int properties = characteristic.getProperties();
if ((properties & requiredProperty) == 0)
return null;
return characteristic.getDescriptor(BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
}
private boolean internalReadCharacteristic(@Nullable final BluetoothGattCharacteristic characteristic) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || characteristic == null || !connected)
return false;
// Check characteristic property.
final int properties = characteristic.getProperties();
if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) == 0)
return false;
log(Log.VERBOSE, () -> "Reading characteristic " + characteristic.getUuid());
log(Log.DEBUG, () -> "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
return gatt.readCharacteristic(characteristic);
}
private boolean internalWriteCharacteristic(@Nullable final BluetoothGattCharacteristic characteristic) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || characteristic == null || !connected)
return false;
// Check characteristic property.
final int properties = characteristic.getProperties();
if ((properties & (BluetoothGattCharacteristic.PROPERTY_WRITE |
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) == 0)
return false;
log(Log.VERBOSE, () ->
"Writing characteristic " + characteristic.getUuid() +
" (" + ParserUtils.writeTypeToString(characteristic.getWriteType()) + ")");
log(Log.DEBUG, () -> "gatt.writeCharacteristic(" + characteristic.getUuid() + ")");
return gatt.writeCharacteristic(characteristic);
}
private boolean internalReadDescriptor(@Nullable final BluetoothGattDescriptor descriptor) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || descriptor == null || !connected)
return false;
log(Log.VERBOSE, () -> "Reading descriptor " + descriptor.getUuid());
log(Log.DEBUG, () -> "gatt.readDescriptor(" + descriptor.getUuid() + ")");
return gatt.readDescriptor(descriptor);
}
private boolean internalWriteDescriptor(@Nullable final BluetoothGattDescriptor descriptor) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || descriptor == null || !connected)
return false;
log(Log.VERBOSE, () -> "Writing descriptor " + descriptor.getUuid());
log(Log.DEBUG, () -> "gatt.writeDescriptor(" + descriptor.getUuid() + ")");
return internalWriteDescriptorWorkaround(descriptor);
}
/**
* There was a bug in Android up to 6.0 where the descriptor was written using parent
* characteristic's write type, instead of always Write With Response, as the spec says.
* <p>
* See: <a href="https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0">
* https://android.googlesource.com/platform/frameworks/base/+/942aebc95924ab1e7ea1e92aaf4e7fc45f695a6c%5E%21/#F0</a>
*
* @param descriptor the descriptor to be written
* @return the result of {@link BluetoothGatt#writeDescriptor(BluetoothGattDescriptor)}
*/
private boolean internalWriteDescriptorWorkaround(@Nullable final BluetoothGattDescriptor descriptor) {
final BluetoothGatt gatt = bluetoothGatt;
if (gatt == null || descriptor == null || !connected)
return false;