-
Notifications
You must be signed in to change notification settings - Fork 609
/
Peripheral.java
1104 lines (907 loc) · 41.2 KB
/
Peripheral.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
// (c) 2104 Don Coleman
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.megster.cordova.ble.central;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.*;
import android.os.Handler;
import android.util.Base64;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;
import androidx.annotation.RequiresPermission;
/**
* Peripheral wraps the BluetoothDevice and provides methods to convert to JSON.
*/
public class Peripheral extends BluetoothGattCallback {
// 0x2902 org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
//public final static UUID CLIENT_CHARACTERISTIC_CONFIGURATION_UUID = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB");
public final static UUID CLIENT_CHARACTERISTIC_CONFIGURATION_UUID = UUIDHelper.uuidFromString("2902");
private static final String TAG = "Peripheral";
private final static Map<Integer, String> bondStates = new Hashtable<Integer, String>() {{
put(BluetoothDevice.BOND_NONE, "none");
put(BluetoothDevice.BOND_BONDING, "bonding");
put(BluetoothDevice.BOND_BONDED, "bonded");
}};
private static final int FAKE_PERIPHERAL_RSSI = 0x7FFFFFFF;
private final BluetoothDevice device;
private byte[] advertisingData;
private Boolean isConnectable = null;
private int advertisingRSSI;
private boolean autoconnect = false;
private boolean connected = false;
private boolean connecting = false;
private final ConcurrentLinkedQueue<BLECommand> commandQueue = new ConcurrentLinkedQueue<BLECommand>();
private final Map<Integer, L2CAPContext> l2capContexts = new HashMap<Integer, L2CAPContext>();
private final AtomicBoolean bleProcessing = new AtomicBoolean();
BluetoothGatt gatt;
private CallbackContext connectCallback;
private CallbackContext refreshCallback;
private CallbackContext readCallback;
private CallbackContext writeCallback;
private CallbackContext requestMtuCallback;
private CallbackContext bondStateCallback;
private Activity currentActivity;
private final Map<String, SequentialCallbackContext> notificationCallbacks = new HashMap<String, SequentialCallbackContext>();
public Peripheral(BluetoothDevice device) {
LOG.d(TAG, "Creating un-scanned peripheral entry for address: %s", device.getAddress());
this.device = device;
this.advertisingRSSI = FAKE_PERIPHERAL_RSSI;
this.advertisingData = null;
}
public Peripheral(BluetoothDevice device, int advertisingRSSI, byte[] scanRecord, Boolean isConnectable) {
this.device = device;
this.advertisingRSSI = advertisingRSSI;
this.advertisingData = scanRecord;
this.isConnectable = isConnectable;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void gattConnect() {
closeGatt();
connected = false;
connecting = true;
queueCleanup("Aborted by new connect call");
callbackCleanup("Aborted by new connect call");
BluetoothDevice device = getDevice();
gatt = device.connectGatt(currentActivity, autoconnect, this, BluetoothDevice.TRANSPORT_LE);
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void connect(CallbackContext callbackContext, Activity activity, boolean auto) {
currentActivity = activity;
autoconnect = auto;
connectCallback = callbackContext;
gattConnect();
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
// the app requested the central disconnect from the peripheral
// disconnect the gatt, do not call connectCallback.error
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void disconnect() {
connected = false;
connecting = false;
autoconnect = false;
closeGatt();
queueCleanup("Central disconnected");
callbackCleanup("Central disconnected");
}
// the peripheral disconnected
// always call connectCallback.error to notify the app
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void peripheralDisconnected(String message) {
connected = false;
connecting = false;
// don't remove the gatt for autoconnect
if (!autoconnect) {
closeGatt();
}
sendDisconnectMessage(message);
queueCleanup(message);
callbackCleanup(message);
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void closeGatt() {
BluetoothGatt localGatt;
synchronized (this) {
localGatt = this.gatt;
this.gatt = null;
}
if (localGatt != null) {
localGatt.disconnect();
localGatt.close();
}
}
// notify the phone that the peripheral disconnected
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void sendDisconnectMessage(String messageContent) {
if (connectCallback != null) {
JSONObject message = this.asJSONObject(messageContent);
if (autoconnect) {
PluginResult result = new PluginResult(PluginResult.Status.ERROR, message);
result.setKeepCallback(true);
connectCallback.sendPluginResult(result);
} else {
connectCallback.error(message);
connectCallback = null;
}
}
}
@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
LOG.d(TAG, "mtu=%d, status=%d", mtu, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
requestMtuCallback.success(mtu);
} else {
requestMtuCallback.error("MTU request failed");
}
requestMtuCallback = null;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void requestMtu(CallbackContext callback, int mtuValue) {
LOG.d(TAG, "requestMtu mtu=%d", mtuValue);
if (gatt == null) {
callback.error("No GATT");
return;
}
if (gatt.requestMtu(mtuValue)) {
requestMtuCallback = callback;
} else {
callback.error("Could not initiate MTU request");
}
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void requestConnectionPriority(int priority) {
if (gatt != null) {
LOG.d(TAG, "requestConnectionPriority priority=" + priority);
gatt.requestConnectionPriority(priority);
}
}
/**
* Uses reflection to refresh the device cache. This *might* be helpful if a peripheral changes
* services or characteristics and does not correctly implement Service Changed 0x2a05
* on Generic Attribute Service 0x1801.
* <p>
* Since this uses an undocumented API it's not guaranteed to work.
*
*/
public void refreshDeviceCache(CallbackContext callback, final long timeoutMillis) {
LOG.d(TAG, "refreshDeviceCache");
boolean success = false;
if (gatt != null) {
try {
final Method refresh = gatt.getClass().getMethod("refresh");
if (refresh != null) {
success = (Boolean)refresh.invoke(gatt);
if (success) {
this.refreshCallback = callback;
Handler handler = new Handler();
LOG.d(TAG, "Waiting " + timeoutMillis + " milliseconds before discovering services");
handler.postDelayed(new Runnable() {
@SuppressLint("MissingPermission")
@Override
public void run() {
if (gatt != null) {
try {
gatt.discoverServices();
} catch(Exception e) {
LOG.e(TAG, "refreshDeviceCache Failed after delay", e);
}
}
}
}, timeoutMillis);
}
} else {
LOG.w(TAG, "Refresh method not found on gatt");
}
} catch(Exception e) {
LOG.e(TAG, "refreshDeviceCache Failed", e);
}
}
if (!success) {
callback.error("Service refresh failed");
}
}
public boolean isUnscanned() {
return advertisingData == null;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public JSONObject asJSONObject() {
JSONObject json = new JSONObject();
try {
json.put("name", device.getName());
json.put("id", device.getAddress()); // mac address
if (advertisingData != null) {
json.put("advertising", byteArrayToJSON(advertisingData));
}
// TODO real RSSI if we have it, else
if (advertisingRSSI != FAKE_PERIPHERAL_RSSI) {
json.put("rssi", advertisingRSSI);
}
if (this.isConnectable != null) {
json.put("connectable", this.isConnectable.booleanValue());
}
} catch (JSONException e) { // this shouldn't happen
e.printStackTrace();
}
return json;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public JSONObject asJSONObject(String errorMessage) {
JSONObject json = new JSONObject();
try {
json.put("name", device.getName());
json.put("id", device.getAddress()); // mac address
json.put("errorMessage", errorMessage);
} catch (JSONException e) { // this shouldn't happen
e.printStackTrace();
}
return json;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public JSONObject asJSONObject(BluetoothGatt gatt) {
JSONObject json = asJSONObject();
try {
JSONArray servicesArray = new JSONArray();
JSONArray characteristicsArray = new JSONArray();
json.put("services", servicesArray);
json.put("characteristics", characteristicsArray);
if (connected && gatt != null) {
for (BluetoothGattService service : gatt.getServices()) {
servicesArray.put(UUIDHelper.uuidToString(service.getUuid()));
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
JSONObject characteristicsJSON = new JSONObject();
characteristicsArray.put(characteristicsJSON);
characteristicsJSON.put("service", UUIDHelper.uuidToString(service.getUuid()));
characteristicsJSON.put("characteristic", UUIDHelper.uuidToString(characteristic.getUuid()));
//characteristicsJSON.put("instanceId", characteristic.getInstanceId());
characteristicsJSON.put("properties", Helper.decodeProperties(characteristic));
// characteristicsJSON.put("propertiesValue", characteristic.getProperties());
if (characteristic.getPermissions() > 0) {
characteristicsJSON.put("permissions", Helper.decodePermissions(characteristic));
// characteristicsJSON.put("permissionsValue", characteristic.getPermissions());
}
JSONArray descriptorsArray = new JSONArray();
for (BluetoothGattDescriptor descriptor: characteristic.getDescriptors()) {
JSONObject descriptorJSON = new JSONObject();
descriptorJSON.put("uuid", UUIDHelper.uuidToString(descriptor.getUuid()));
descriptorJSON.put("value", descriptor.getValue()); // always blank
if (descriptor.getPermissions() > 0) {
descriptorJSON.put("permissions", Helper.decodePermissions(descriptor));
// descriptorJSON.put("permissionsValue", descriptor.getPermissions());
}
descriptorsArray.put(descriptorJSON);
}
if (descriptorsArray.length() > 0) {
characteristicsJSON.put("descriptors", descriptorsArray);
}
}
}
}
} catch (JSONException e) { // TODO better error handling
e.printStackTrace();
}
return json;
}
static JSONObject byteArrayToJSON(byte[] bytes) throws JSONException {
JSONObject object = new JSONObject();
object.put("CDVType", "ArrayBuffer");
object.put("data", Base64.encodeToString(bytes, Base64.NO_WRAP));
return object;
}
public boolean isConnected() {
return connected;
}
public boolean isConnecting() {
return connecting;
}
public BluetoothDevice getDevice() {
return device;
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
// refreshCallback is a kludge for refreshing services, if it exists, it temporarily
// overrides the connect callback. Unfortunately this edge case make the code confusing.
if (status == BluetoothGatt.GATT_SUCCESS) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.asJSONObject(gatt));
if (refreshCallback != null) {
refreshCallback.sendPluginResult(result);
refreshCallback = null;
} else if (connectCallback != null) {
result.setKeepCallback(true);
connectCallback.sendPluginResult(result);
}
} else {
LOG.e(TAG, "Service discovery failed. status = %d", status);
if (refreshCallback != null) {
refreshCallback.error(this.asJSONObject("Service discovery failed"));
refreshCallback = null;
} else {
peripheralDisconnected("Service discovery failed");
}
}
}
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
this.gatt = gatt;
if (newState == BluetoothGatt.STATE_CONNECTED) {
LOG.d(TAG, "onConnectionStateChange CONNECTED");
connected = true;
connecting = false;
gatt.discoverServices();
} else { // Disconnected
LOG.d(TAG, "onConnectionStateChange DISCONNECTED");
connected = false;
peripheralDisconnected("Peripheral Disconnected");
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
LOG.d(TAG, "onCharacteristicChanged %s", characteristic);
SequentialCallbackContext callback = notificationCallbacks.get(generateHashKey(characteristic));
if (callback != null) {
callback.sendSequentialResult(characteristic.getValue());
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
LOG.d(TAG, "onCharacteristicRead %s", characteristic);
synchronized(this) {
if (readCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
readCallback.success(characteristic.getValue());
} else {
readCallback.error("Error reading " + characteristic.getUuid() + " status=" + status);
}
readCallback = null;
}
}
commandCompleted();
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
LOG.d(TAG, "onCharacteristicWrite %s", characteristic);
synchronized(this) {
if (writeCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
writeCallback.success();
} else {
writeCallback.error(status);
}
writeCallback = null;
}
}
commandCompleted();
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
LOG.d(TAG, "onDescriptorWrite %s", descriptor);
if (descriptor.getUuid().equals(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID)) {
BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
String key = generateHashKey(characteristic);
SequentialCallbackContext callback = notificationCallbacks.get(key);
if (callback != null) {
boolean success = callback.completeSubscription(status);
if (!success) {
notificationCallbacks.remove(key);
}
}
}
commandCompleted();
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
synchronized(this) {
if (readCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
updateRssi(rssi);
readCallback.success(rssi);
} else {
readCallback.error("Error reading RSSI status=" + status);
}
readCallback = null;
}
}
commandCompleted();
}
// Update rssi and scanRecord.
public void update(int rssi, byte[] scanRecord, boolean isConnectable) {
this.advertisingRSSI = rssi;
this.advertisingData = scanRecord;
this.isConnectable = isConnectable;
}
public void update(int rssi, byte[] scanRecord) {
this.advertisingRSSI = rssi;
this.advertisingData = scanRecord;
}
public void updateRssi(int rssi) {
advertisingRSSI = rssi;
}
// This seems way too complicated
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void registerNotifyCallback(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
commandCompleted();
return;
}
boolean success = false;
BluetoothGattService service = gatt.getService(serviceUUID);
if (service == null) {
callbackContext.error("Service " + serviceUUID + " not found.");
commandCompleted();
return;
}
BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
if (characteristic == null) {
callbackContext.error("Characteristic " + characteristicUUID + " not found.");
commandCompleted();
return;
}
String key = generateHashKey(serviceUUID, characteristic);
notificationCallbacks.put(key, new SequentialCallbackContext(callbackContext));
if (!gatt.setCharacteristicNotification(characteristic, true)) {
callbackContext.error("Failed to register notification for " + characteristicUUID);
notificationCallbacks.remove(key);
commandCompleted();
return;
}
// Why doesn't setCharacteristicNotification write the descriptor?
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID);
if (descriptor == null) {
callbackContext.error("Set notification failed for " + characteristicUUID);
notificationCallbacks.remove(key);
commandCompleted();
return;
}
// prefer notify over indicate
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
} else {
LOG.w(TAG, "Characteristic %s does not have NOTIFY or INDICATE property set", characteristicUUID);
}
if (!gatt.writeDescriptor(descriptor)) {
callbackContext.error("Failed to set client characteristic notification for " + characteristicUUID);
notificationCallbacks.remove(key);
commandCompleted();
}
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void removeNotifyCallback(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
commandCompleted();
return;
}
BluetoothGattService service = gatt.getService(serviceUUID);
if (service == null) {
callbackContext.error("Service " + serviceUUID + " not found.");
commandCompleted();
return;
}
BluetoothGattCharacteristic characteristic = findNotifyCharacteristic(service, characteristicUUID);
if (characteristic == null) {
callbackContext.error("Characteristic " + characteristicUUID + " not found.");
commandCompleted();
return;
}
String key = generateHashKey(serviceUUID, characteristic);
notificationCallbacks.remove(key);
if (gatt.setCharacteristicNotification(characteristic, false)) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIGURATION_UUID);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
callbackContext.success();
} else {
// TODO we can probably ignore and return success anyway since we removed the notification callback
callbackContext.error("Failed to stop notification for " + characteristicUUID);
}
commandCompleted();
}
// Some devices reuse UUIDs across characteristics, so we can't use service.getCharacteristic(characteristicUUID)
// instead check the UUID and properties for each characteristic in the service until we find the best match
// This function prefers Notify over Indicate
private BluetoothGattCharacteristic findNotifyCharacteristic(BluetoothGattService service, UUID characteristicUUID) {
BluetoothGattCharacteristic characteristic = null;
// Check for Notify first
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
if (characteristic != null) return characteristic;
// If there wasn't Notify Characteristic, check for Indicate
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
// As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have the correct properties
if (characteristic == null) {
characteristic = service.getCharacteristic(characteristicUUID);
}
return characteristic;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void readCharacteristic(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
commandCompleted();
return;
}
BluetoothGattService service = gatt.getService(serviceUUID);
if (service == null) {
callbackContext.error("Service " + serviceUUID + " not found.");
commandCompleted();
return;
}
BluetoothGattCharacteristic characteristic = findReadableCharacteristic(service, characteristicUUID);
if (characteristic == null) {
callbackContext.error("Characteristic " + characteristicUUID + " not found.");
commandCompleted();
return;
}
boolean success = false;
synchronized(this) {
readCallback = callbackContext;
if (gatt.readCharacteristic(characteristic)) {
success = true;
} else {
readCallback = null;
callbackContext.error("Read failed");
}
}
if (!success) {
commandCompleted();
}
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void readRSSI(CallbackContext callbackContext) {
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
commandCompleted();
return;
}
boolean success = false;
synchronized(this) {
readCallback = callbackContext;
if (gatt.readRemoteRssi()) {
success = true;
} else {
readCallback = null;
callbackContext.error("Read RSSI failed");
}
}
if (!success) {
commandCompleted();
}
}
// Some peripherals re-use UUIDs for multiple characteristics so we need to check the properties
// and UUID of all characteristics instead of using service.getCharacteristic(characteristicUUID)
private BluetoothGattCharacteristic findReadableCharacteristic(BluetoothGattService service, UUID characteristicUUID) {
BluetoothGattCharacteristic characteristic = null;
int read = BluetoothGattCharacteristic.PROPERTY_READ;
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & read) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
// As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have the correct properties
if (characteristic == null) {
characteristic = service.getCharacteristic(characteristicUUID);
}
return characteristic;
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
private void writeCharacteristic(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID, byte[] data, int writeType) {
if (gatt == null) {
callbackContext.error("BluetoothGatt is null");
commandCompleted();
return;
}
BluetoothGattService service = gatt.getService(serviceUUID);
if (service == null) {
callbackContext.error("Service " + serviceUUID + " not found.");
commandCompleted();
return;
}
BluetoothGattCharacteristic characteristic = findWritableCharacteristic(service, characteristicUUID, writeType);
if (characteristic == null) {
callbackContext.error("Characteristic " + characteristicUUID + " not found.");
commandCompleted();
return;
}
boolean success = false;
characteristic.setValue(data);
characteristic.setWriteType(writeType);
synchronized(this) {
writeCallback = callbackContext;
if (gatt.writeCharacteristic(characteristic)) {
success = true;
} else {
writeCallback = null;
callbackContext.error("Write failed");
}
}
if (!success) {
commandCompleted();
}
}
// Some peripherals re-use UUIDs for multiple characteristics so we need to check the properties
// and UUID of all characteristics instead of using service.getCharacteristic(characteristicUUID)
private BluetoothGattCharacteristic findWritableCharacteristic(BluetoothGattService service, UUID characteristicUUID, int writeType) {
BluetoothGattCharacteristic characteristic = null;
// get write property
int writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE;
if (writeType == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) {
writeProperty = BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE;
}
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for (BluetoothGattCharacteristic c : characteristics) {
if ((c.getProperties() & writeProperty) != 0 && characteristicUUID.equals(c.getUuid())) {
characteristic = c;
break;
}
}
// As a last resort, try and find ANY characteristic with this UUID, even if it doesn't have the correct properties
if (characteristic == null) {
characteristic = service.getCharacteristic(characteristicUUID);
}
return characteristic;
}
public void queueRead(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
BLECommand command = new BLECommand(callbackContext, serviceUUID, characteristicUUID, BLECommand.READ);
queueCommand(command);
}
public void queueWrite(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID, byte[] data, int writeType) {
BLECommand command = new BLECommand(callbackContext, serviceUUID, characteristicUUID, data, writeType);
queueCommand(command);
}
public void queueRegisterNotifyCallback(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
BLECommand command = new BLECommand(callbackContext, serviceUUID, characteristicUUID, BLECommand.REGISTER_NOTIFY);
queueCommand(command);
}
public void queueRemoveNotifyCallback(CallbackContext callbackContext, UUID serviceUUID, UUID characteristicUUID) {
BLECommand command = new BLECommand(callbackContext, serviceUUID, characteristicUUID, BLECommand.REMOVE_NOTIFY);
queueCommand(command);
}
public void queueReadRSSI(CallbackContext callbackContext) {
BLECommand command = new BLECommand(callbackContext, null, null, BLECommand.READ_RSSI);
queueCommand(command);
}
public void queueCleanup(String message) {
bleProcessing.set(true); // Stop anything else trying to process
for (BLECommand command = commandQueue.poll(); command != null; command = commandQueue.poll()) {
command.getCallbackContext().error(message);
}
bleProcessing.set(false); // Now re-allow processing
Collection<L2CAPContext> contexts;
synchronized (l2capContexts) {
contexts = new ArrayList<>(l2capContexts.values());
}
for(L2CAPContext context : contexts) {
context.disconnectL2Cap();
}
}
public void writeL2CapChannel(CallbackContext callbackContext, int psm, byte[] data) {
LOG.d(TAG,"L2CAP Write %s", psm);
getOrAddL2CAPContext(psm).writeL2CapChannel(callbackContext, data);
}
@SuppressLint("MissingPermission")
private void callbackCleanup(String message) {
synchronized(this) {
if (readCallback != null) {
readCallback.error(this.asJSONObject(message));
readCallback = null;
commandCompleted();
}
if (writeCallback != null) {
writeCallback.error(this.asJSONObject(message));
writeCallback = null;
commandCompleted();
}
if (refreshCallback != null) {
refreshCallback.error(this.asJSONObject(message));
refreshCallback = null;
}
if (requestMtuCallback != null) {
requestMtuCallback.error(message);
requestMtuCallback = null;
}
}
}
// add a new command to the queue
private void queueCommand(BLECommand command) {
LOG.d(TAG,"Queuing Command %s", command);
commandQueue.add(command);
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(true);
command.getCallbackContext().sendPluginResult(result);
processCommands();
}
// command finished, queue the next command
@SuppressLint("MissingPermission")
private void commandCompleted() {
LOG.d(TAG,"Processing Complete");
bleProcessing.set(false);
processCommands();
}
// process the queue
@SuppressLint("MissingPermission")
private void processCommands() {
final boolean canProcess = bleProcessing.compareAndSet(false, true);
if (!canProcess) { return; }
LOG.d(TAG,"Processing Commands");
BLECommand command = commandQueue.poll();
if (command != null) {
if (command.getType() == BLECommand.READ) {
LOG.d(TAG,"Read %s", command.getCharacteristicUUID());
readCharacteristic(command.getCallbackContext(), command.getServiceUUID(), command.getCharacteristicUUID());
} else if (command.getType() == BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT) {
LOG.d(TAG,"Write %s", command.getCharacteristicUUID());
writeCharacteristic(command.getCallbackContext(), command.getServiceUUID(), command.getCharacteristicUUID(), command.getData(), command.getType());
} else if (command.getType() == BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE) {
LOG.d(TAG,"Write No Response %s", command.getCharacteristicUUID());
writeCharacteristic(command.getCallbackContext(), command.getServiceUUID(), command.getCharacteristicUUID(), command.getData(), command.getType());
} else if (command.getType() == BLECommand.REGISTER_NOTIFY) {
LOG.d(TAG,"Register Notify %s", command.getCharacteristicUUID());
registerNotifyCallback(command.getCallbackContext(), command.getServiceUUID(), command.getCharacteristicUUID());
} else if (command.getType() == BLECommand.REMOVE_NOTIFY) {
LOG.d(TAG,"Remove Notify %s", command.getCharacteristicUUID());
removeNotifyCallback(command.getCallbackContext(), command.getServiceUUID(), command.getCharacteristicUUID());
} else if (command.getType() == BLECommand.READ_RSSI) {
LOG.d(TAG,"Read RSSI");
readRSSI(command.getCallbackContext());
} else {
// this shouldn't happen
bleProcessing.set(false);
throw new RuntimeException("Unexpected BLE Command type " + command.getType());
}
} else {
bleProcessing.set(false);
LOG.d(TAG, "Command Queue is empty.");
}
}
private String generateHashKey(BluetoothGattCharacteristic characteristic) {
return generateHashKey(characteristic.getService().getUuid(), characteristic);
}
private String generateHashKey(UUID serviceUUID, BluetoothGattCharacteristic characteristic) {
return serviceUUID + "|" + characteristic.getUuid() + "|" + characteristic.getInstanceId();
}
@RequiresPermission("android.permission.BLUETOOTH_CONNECT")
public void connectL2cap(CallbackContext callbackContext, int psm, boolean secureChannel) {
getOrAddL2CAPContext(psm).connectL2cap(callbackContext, secureChannel);
}
public void disconnectL2Cap(CallbackContext callbackContext, int psm) {
L2CAPContext context;
synchronized (l2capContexts) {
context = l2capContexts.get(psm);
};
if (context != null) {
context.disconnectL2Cap();