-
Notifications
You must be signed in to change notification settings - Fork 609
/
BLECentralPlugin.java
1534 lines (1256 loc) · 61.5 KB
/
BLECentralPlugin.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) 2014-2016 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.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanSettings;
import android.location.LocationManager;
import android.os.ParcelUuid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.os.Build;
import android.provider.Settings;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaArgs;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PermissionHelper;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import java.util.*;
import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_DUAL;
import static android.bluetooth.BluetoothDevice.DEVICE_TYPE_LE;
import static android.bluetooth.BluetoothDevice.ACTION_BOND_STATE_CHANGED;
import static android.bluetooth.BluetoothDevice.EXTRA_BOND_STATE;
public class BLECentralPlugin extends CordovaPlugin {
// permissions
private static final String ACCESS_BACKGROUND_LOCATION = "android.permission.ACCESS_BACKGROUND_LOCATION"; // API 29
private static final String BLUETOOTH_CONNECT = "android.permission.BLUETOOTH_CONNECT" ; // API 31
private static final String BLUETOOTH_SCAN = "android.permission.BLUETOOTH_SCAN" ; // API 31
// actions
private static final String STOP_SCAN = "stopScan";
private static final String START_SCAN_WITH_OPTIONS = "startScanWithOptions";
private static final String BONDED_DEVICES = "bondedDevices";
private static final String LIST = "list";
private static final String CONNECT = "connect";
private static final String AUTOCONNECT = "autoConnect";
private static final String DISCONNECT = "disconnect";
private static final String QUEUE_CLEANUP = "queueCleanup";
private static final String SET_PIN = "setPin";
private static final String BOND = "bond";
private static final String UNBOND = "unbond";
private static final String READ_BOND_STATE = "readBondState";
private static final String REQUEST_MTU = "requestMtu";
private static final String REQUEST_CONNECTION_PRIORITY = "requestConnectionPriority";
private final String CONNECTION_PRIORITY_HIGH = "high";
private final String CONNECTION_PRIORITY_LOW = "low";
private final String CONNECTION_PRIORITY_BALANCED = "balanced";
private static final String REFRESH_DEVICE_CACHE = "refreshDeviceCache";
private static final String READ = "read";
private static final String WRITE = "write";
private static final String WRITE_WITHOUT_RESPONSE = "writeWithoutResponse";
private static final String READ_RSSI = "readRSSI";
private static final String START_NOTIFICATION = "startNotification"; // register for characteristic notification
private static final String STOP_NOTIFICATION = "stopNotification"; // remove characteristic notification
private static final String IS_ENABLED = "isEnabled";
private static final String IS_LOCATION_ENABLED = "isLocationEnabled";
private static final String IS_CONNECTED = "isConnected";
private static final String SETTINGS = "showBluetoothSettings";
private static final String ENABLE = "enable";
private static final String START_STATE_NOTIFICATIONS = "startStateNotifications";
private static final String STOP_STATE_NOTIFICATIONS = "stopStateNotifications";
private static final String OPEN_L2CAP = "openL2Cap";
private static final String CLOSE_L2CAP = "closeL2Cap";
private static final String RECEIVE_L2CAP = "receiveDataL2Cap";
private static final String WRITE_L2CAP = "writeL2Cap";
private static final String START_LOCATION_STATE_NOTIFICATIONS = "startLocationStateNotifications";
private static final String STOP_LOCATION_STATE_NOTIFICATIONS = "stopLocationStateNotifications";
// callbacks
CallbackContext discoverCallback;
private CallbackContext enableBluetoothCallback;
private static final String TAG = "BLEPlugin";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
BluetoothAdapter bluetoothAdapter;
// key is the MAC Address
Map<String, Peripheral> peripherals = new LinkedHashMap<String, Peripheral>();
// scan options
boolean reportDuplicates = false;
boolean forceScanFilter = false;
private static final int REQUEST_BLUETOOTH_SCAN = 2;
private static final int REQUEST_BLUETOOTH_CONNECT = 3;
private static final int REQUEST_BLUETOOTH_CONNECT_AUTO = 4;
private static final int REQUEST_GET_BONDED_DEVICES = 5;
private static final int REQUEST_LIST_KNOWN_DEVICES = 6;
private static final int REQUEST_BOND = 7;
private static final int REQUEST_UNBOND = 8;
private static final int REQUEST_READ_BOND_STATE = 9;
private static int COMPILE_SDK_VERSION = -1;
private CallbackContext permissionCallback;
private String deviceMacAddress;
private boolean usePairingDialog;
private UUID[] serviceUUIDs;
private int scanSeconds;
private ScanSettings scanSettings;
private final Handler stopScanHandler = new Handler(Looper.getMainLooper());
private final Runnable stopScanRunnable = this::stopScan;
// Bluetooth state notification
CallbackContext stateCallback;
BroadcastReceiver stateReceiver;
private BroadcastReceiver bondStateReceiver;
Map<Integer, String> bluetoothStates = new Hashtable<Integer, String>() {{
put(BluetoothAdapter.STATE_OFF, "off");
put(BluetoothAdapter.STATE_TURNING_OFF, "turningOff");
put(BluetoothAdapter.STATE_ON, "on");
put(BluetoothAdapter.STATE_TURNING_ON, "turningOn");
}};
CallbackContext locationStateCallback;
BroadcastReceiver locationStateReceiver;
@Override
protected void pluginInitialize() {
if (COMPILE_SDK_VERSION == -1) {
Context context = cordova.getContext();
COMPILE_SDK_VERSION = context.getApplicationContext().getApplicationInfo().targetSdkVersion;
}
}
@SuppressLint("MissingPermission")
@Override
public void onDestroy() {
removeStateListener();
removeLocationStateListener();
removeBondStateListener();
for(Peripheral peripheral : peripherals.values()) {
peripheral.disconnect();
}
}
@SuppressLint("MissingPermission")
@Override
public void onReset() {
removeStateListener();
removeLocationStateListener();
removeBondStateListener();
for(Peripheral peripheral : peripherals.values()) {
peripheral.disconnect();
}
}
@Override
public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {
LOG.d(TAG, "action = %s", action);
if (bluetoothAdapter == null) {
Activity activity = cordova.getActivity();
@SuppressLint("ObsoleteSdkInt") boolean hardwareSupportsBLE = activity.getApplicationContext()
.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE) &&
Build.VERSION.SDK_INT >= 18;
if (!hardwareSupportsBLE) {
LOG.w(TAG, "This hardware does not support Bluetooth Low Energy.");
callbackContext.error("This hardware does not support Bluetooth Low Energy.");
return false;
}
BluetoothManager bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
}
boolean validAction = true;
if (action.equals(STOP_SCAN)) {
stopScan();
callbackContext.success();
} else if (action.equals(LIST)) {
listKnownDevices(callbackContext);
} else if (action.equals(CONNECT)) {
String macAddress = args.getString(0);
connect(callbackContext, macAddress);
} else if (action.equals(AUTOCONNECT)) {
String macAddress = args.getString(0);
autoConnect(callbackContext, macAddress);
} else if (action.equals(DISCONNECT)) {
String macAddress = args.getString(0);
disconnect(callbackContext, macAddress);
} else if (action.equals(QUEUE_CLEANUP)) {
String macAddress = args.getString(0);
queueCleanup(callbackContext, macAddress);
} else if (action.equals(SET_PIN)) {
String pin = args.getString(0);
setPin(callbackContext, pin);
} else if (action.equals(BOND)) {
String macAddress = args.getString(0);
JSONObject options = args.getJSONObject(1);
boolean usePairingDialog = options != null && options.optBoolean("usePairingDialog", true);
bond(callbackContext, macAddress, usePairingDialog);
} else if (action.equals(UNBOND)) {
String macAddress = args.getString(0);
unbond(callbackContext, macAddress);
} else if (action.equals(READ_BOND_STATE)) {
String macAddress = args.getString(0);
readBondState(callbackContext, macAddress);
} else if (action.equals(REQUEST_MTU)) {
String macAddress = args.getString(0);
int mtuValue = args.getInt(1);
requestMtu(callbackContext, macAddress, mtuValue);
} else if (action.equals(REQUEST_CONNECTION_PRIORITY)) {
String macAddress = args.getString(0);
String priority = args.getString(1);
requestConnectionPriority(callbackContext, macAddress, priority);
} else if (action.equals(REFRESH_DEVICE_CACHE)) {
String macAddress = args.getString(0);
long timeoutMillis = args.getLong(1);
refreshDeviceCache(callbackContext, macAddress, timeoutMillis);
} else if (action.equals(READ)) {
String macAddress = args.getString(0);
UUID serviceUUID = uuidFromString(args.getString(1));
UUID characteristicUUID = uuidFromString(args.getString(2));
read(callbackContext, macAddress, serviceUUID, characteristicUUID);
} else if (action.equals(READ_RSSI)) {
String macAddress = args.getString(0);
readRSSI(callbackContext, macAddress);
} else if (action.equals(WRITE)) {
String macAddress = args.getString(0);
UUID serviceUUID = uuidFromString(args.getString(1));
UUID characteristicUUID = uuidFromString(args.getString(2));
byte[] data = args.getArrayBuffer(3);
int type = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT;
write(callbackContext, macAddress, serviceUUID, characteristicUUID, data, type);
} else if (action.equals(WRITE_WITHOUT_RESPONSE)) {
String macAddress = args.getString(0);
UUID serviceUUID = uuidFromString(args.getString(1));
UUID characteristicUUID = uuidFromString(args.getString(2));
byte[] data = args.getArrayBuffer(3);
int type = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE;
write(callbackContext, macAddress, serviceUUID, characteristicUUID, data, type);
} else if (action.equals(START_NOTIFICATION)) {
String macAddress = args.getString(0);
UUID serviceUUID = uuidFromString(args.getString(1));
UUID characteristicUUID = uuidFromString(args.getString(2));
registerNotifyCallback(callbackContext, macAddress, serviceUUID, characteristicUUID);
} else if (action.equals(STOP_NOTIFICATION)) {
String macAddress = args.getString(0);
UUID serviceUUID = uuidFromString(args.getString(1));
UUID characteristicUUID = uuidFromString(args.getString(2));
removeNotifyCallback(callbackContext, macAddress, serviceUUID, characteristicUUID);
} else if (action.equals(IS_ENABLED)) {
if (bluetoothAdapter.isEnabled()) {
callbackContext.success();
} else {
callbackContext.error("Bluetooth is disabled.");
}
} else if (action.equals(IS_LOCATION_ENABLED)) {
if (locationServicesEnabled()) {
callbackContext.success();
} else {
callbackContext.error("Location services disabled.");
}
} else if (action.equals(IS_CONNECTED)) {
String macAddress = args.getString(0);
if (peripherals.containsKey(macAddress) && peripherals.get(macAddress).isConnected()) {
callbackContext.success();
} else {
callbackContext.error("Not connected");
}
} else if (action.equals(SETTINGS)) {
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
cordova.getActivity().startActivity(intent);
callbackContext.success();
} else if (action.equals(ENABLE)) {
enableBluetooth(callbackContext);
} else if (action.equals(START_STATE_NOTIFICATIONS)) {
if (this.stateCallback != null) {
callbackContext.error("State callback already registered.");
} else {
this.stateCallback = callbackContext;
addStateListener();
sendBluetoothStateChange(bluetoothAdapter.getState());
}
} else if (action.equals(STOP_STATE_NOTIFICATIONS)) {
if (this.stateCallback != null) {
// Clear callback in JavaScript without actually calling it
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(false);
this.stateCallback.sendPluginResult(result);
this.stateCallback = null;
}
removeStateListener();
callbackContext.success();
} else if (action.equals(START_LOCATION_STATE_NOTIFICATIONS)) {
if (this.locationStateCallback != null) {
callbackContext.error("Location state callback already registered.");
} else {
this.locationStateCallback = callbackContext;
addLocationStateListener();
sendLocationStateChange();
}
} else if (action.equals(STOP_LOCATION_STATE_NOTIFICATIONS)) {
if (this.locationStateCallback != null) {
// Clear callback in JavaScript without actually calling it
PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT);
result.setKeepCallback(false);
this.locationStateCallback.sendPluginResult(result);
this.locationStateCallback = null;
}
removeLocationStateListener();
callbackContext.success();
} else if (action.equals(START_SCAN_WITH_OPTIONS)) {
UUID[] serviceUUIDs = parseServiceUUIDList(args.getJSONArray(0));
JSONObject options = args.getJSONObject(1);
resetScanOptions();
this.reportDuplicates = options.optBoolean("reportDuplicates", false);
this.forceScanFilter = options.optBoolean("forceScanFilter", false);
ScanSettings.Builder scanSettings = new ScanSettings.Builder();
switch (options.optString("scanMode", "")) {
case "":
break;
case "lowPower":
scanSettings.setScanMode( ScanSettings.SCAN_MODE_LOW_POWER );
break;
case "balanced":
scanSettings.setScanMode( ScanSettings.SCAN_MODE_BALANCED );
break;
case "lowLatency":
scanSettings.setScanMode( ScanSettings.SCAN_MODE_LOW_LATENCY );
break;
case "opportunistic":
scanSettings.setScanMode( ScanSettings.SCAN_MODE_OPPORTUNISTIC );
break;
default:
callbackContext.error("scanMode must be one of: lowPower | balanced | lowLatency | opportunistic");
validAction = false;
break;
}
if (Build.VERSION.SDK_INT >= 23) {
switch (options.optString("callbackType", "")) {
case "":
break;
case "all":
scanSettings.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
break;
case "first":
scanSettings.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH);
break;
case "lost":
scanSettings.setCallbackType(ScanSettings.CALLBACK_TYPE_MATCH_LOST);
break;
default:
callbackContext.error("callbackType must be one of: all | first | lost");
validAction = false;
break;
}
}
if (Build.VERSION.SDK_INT >= 23) {
switch (options.optString("matchMode", "")) {
case "":
break;
case "aggressive":
scanSettings.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
break;
case "sticky":
scanSettings.setMatchMode(ScanSettings.MATCH_MODE_STICKY);
break;
default:
callbackContext.error("matchMode must be one of: aggressive | sticky");
validAction = false;
break;
}
}
if (Build.VERSION.SDK_INT >= 23) {
switch (options.optString("numOfMatches", "")) {
case "":
break;
case "one":
scanSettings.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT);
break;
case "few":
scanSettings.setNumOfMatches(ScanSettings.MATCH_NUM_FEW_ADVERTISEMENT);
break;
case "max":
scanSettings.setNumOfMatches(ScanSettings.MATCH_NUM_MAX_ADVERTISEMENT);
break;
default:
callbackContext.error("numOfMatches must be one of: one | few | max");
validAction = false;
break;
}
}
if (Build.VERSION.SDK_INT >= 26 /*O*/) {
switch (options.optString("phy", "")) {
case "":
break;
case "1m":
scanSettings.setPhy(BluetoothDevice.PHY_LE_1M);
break;
case "coded":
scanSettings.setPhy(BluetoothDevice.PHY_LE_CODED);
break;
case "all":
scanSettings.setPhy(ScanSettings.PHY_LE_ALL_SUPPORTED);
break;
default:
callbackContext.error("phy must be one of: 1m | coded | all");
validAction = false;
break;
}
}
if (validAction) {
String LEGACY = "legacy";
if (Build.VERSION.SDK_INT >= 26 /*O*/ && !options.isNull(LEGACY))
scanSettings.setLegacy( options.getBoolean(LEGACY) );
long reportDelay = options.optLong("reportDelay", -1 );
if (reportDelay >= 0L)
scanSettings.setReportDelay( reportDelay );
int scanDuration = options.optInt("duration", -1);
findLowEnergyDevices(callbackContext, serviceUUIDs, scanDuration, scanSettings.build() );
}
} else if (action.equals(BONDED_DEVICES)) {
getBondedDevices(callbackContext);
} else if (action.equals(OPEN_L2CAP)) {
String macAddress = args.getString(0);
int psm = args.getInt(1);
JSONObject options = args.optJSONObject(2);
boolean secureChannel = options != null && options.optBoolean("secureChannel", false);
connectL2cap(callbackContext, macAddress, psm, secureChannel);
} else if (action.equals(CLOSE_L2CAP)) {
String macAddress = args.getString(0);
int psm = args.getInt(1);
disconnectL2cap(callbackContext, macAddress, psm);
} else if (action.equals(WRITE_L2CAP)) {
String macAddress = args.getString(0);
int psm = args.getInt(1);
byte[] data = args.getArrayBuffer(2);
writeL2cap(callbackContext, macAddress, psm, data);
} else if (action.equals(RECEIVE_L2CAP)) {
String macAddress = args.getString(0);
int psm = args.getInt(1);
registerL2CapReceiver(callbackContext, macAddress, psm);
} else {
validAction = false;
}
return validAction;
}
private void enableBluetooth(CallbackContext callbackContext) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) {
// https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#ACTION_REQUEST_ENABLE
// Android 12+ requires BLUETOOTH_CONNECT in order to trigger an enable request
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
PermissionHelper.requestPermission(this, REQUEST_ENABLE_BLUETOOTH, BLUETOOTH_CONNECT);
return;
}
}
enableBluetoothCallback = callbackContext;
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
cordova.startActivityForResult(this, intent, REQUEST_ENABLE_BLUETOOTH);
}
@SuppressLint("MissingPermission")
private void getBondedDevices(CallbackContext callbackContext) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
PermissionHelper.requestPermission(this, REQUEST_GET_BONDED_DEVICES, BLUETOOTH_CONNECT);
return;
}
}
JSONArray bonded = new JSONArray();
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
device.getBondState();
int type = device.getType();
// just low energy devices (filters out classic and unknown devices)
if (type == DEVICE_TYPE_LE || type == DEVICE_TYPE_DUAL) {
Peripheral p = new Peripheral(device);
bonded.put(p.asJSONObject());
}
}
callbackContext.success(bonded);
}
private UUID[] parseServiceUUIDList(JSONArray jsonArray) throws JSONException {
List<UUID> serviceUUIDs = new ArrayList<UUID>();
for(int i = 0; i < jsonArray.length(); i++){
String uuidString = jsonArray.getString(i);
serviceUUIDs.add(uuidFromString(uuidString));
}
return serviceUUIDs.toArray(new UUID[jsonArray.length()]);
}
@SuppressLint("MissingPermission")
private void onBluetoothStateChange(Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
sendBluetoothStateChange(state);
if (state == BluetoothAdapter.STATE_OFF) {
// #894 When Bluetooth is physically turned off the whole process might die, so the normal
// onConnectionStateChange callbacks won't be invoked
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
for(Peripheral peripheral : peripherals.values()) {
if (!peripheral.isConnected()) continue;
int connectedState = bluetoothManager.getConnectionState(peripheral.getDevice(), BluetoothProfile.GATT);
if (connectedState == BluetoothProfile.STATE_DISCONNECTED) {
peripheral.peripheralDisconnected("Bluetooth Disabled");
}
}
}
}
}
private void sendBluetoothStateChange(int state) {
if (this.stateCallback != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, this.bluetoothStates.get(state));
result.setKeepCallback(true);
this.stateCallback.sendPluginResult(result);
}
}
private void addStateListener() {
if (this.stateReceiver == null) {
this.stateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
onBluetoothStateChange(intent);
}
};
}
try {
IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
webView.getContext().registerReceiver(this.stateReceiver, intentFilter);
} catch (Exception e) {
LOG.e(TAG, "Error registering state receiver: " + e.getMessage(), e);
}
}
private void removeStateListener() {
if (this.stateReceiver != null) {
try {
webView.getContext().unregisterReceiver(this.stateReceiver);
} catch (Exception e) {
LOG.e(TAG, "Error unregistering state receiver: " + e.getMessage(), e);
}
}
this.stateCallback = null;
this.stateReceiver = null;
}
private void onLocationStateChange(Intent intent) {
final String action = intent.getAction();
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(action)) {
sendLocationStateChange();
}
}
private void sendLocationStateChange() {
if (this.locationStateCallback != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, locationServicesEnabled());
result.setKeepCallback(true);
this.locationStateCallback.sendPluginResult(result);
}
}
private void addLocationStateListener() {
if (this.locationStateReceiver == null) {
this.locationStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
onLocationStateChange(intent);
}
};
}
try {
IntentFilter intentFilter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
intentFilter.addAction(Intent.ACTION_PROVIDER_CHANGED);
registerNonSystemReceiverCompat(this.locationStateReceiver, intentFilter);
} catch (Exception e) {
LOG.e(TAG, "Error registering location state receiver: " + e.getMessage(), e);
}
}
private void removeLocationStateListener() {
if (this.locationStateReceiver != null) {
try {
webView.getContext().unregisterReceiver(this.locationStateReceiver);
} catch (Exception e) {
LOG.e(TAG, "Error unregistering location state receiver: " + e.getMessage(), e);
}
}
this.locationStateCallback = null;
this.locationStateReceiver = null;
}
@SuppressLint("MissingPermission")
private void connect(CallbackContext callbackContext, String macAddress) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
deviceMacAddress = macAddress;
PermissionHelper.requestPermission(this, REQUEST_BLUETOOTH_CONNECT, BLUETOOTH_CONNECT);
return;
}
}
if (bluetoothAdapter.getState() != BluetoothAdapter.STATE_ON) {
LOG.w(TAG, "Tried to connect while Bluetooth is disabled.");
callbackContext.error("Bluetooth is disabled.");
return;
}
if (!peripherals.containsKey(macAddress) && BluetoothAdapter.checkBluetoothAddress(macAddress)) {
BluetoothDevice device = BLECentralPlugin.this.bluetoothAdapter.getRemoteDevice(macAddress);
Peripheral peripheral = new Peripheral(device);
peripherals.put(macAddress, peripheral);
}
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
// #894: BLE adapter state listener required so disconnect can be fired on BLE disabled
addStateListener();
peripheral.connect(callbackContext, cordova.getActivity(), false);
} else {
callbackContext.error("Peripheral " + macAddress + " not found.");
}
}
@SuppressLint("MissingPermission")
private void autoConnect(CallbackContext callbackContext, String macAddress) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
deviceMacAddress = macAddress;
PermissionHelper.requestPermission(this, REQUEST_BLUETOOTH_CONNECT_AUTO, BLUETOOTH_CONNECT);
return;
}
}
if (bluetoothAdapter.getState() != BluetoothAdapter.STATE_ON) {
LOG.w(TAG, "Tried to connect while Bluetooth is disabled.");
callbackContext.error("Bluetooth is disabled.");
return;
}
Peripheral peripheral = peripherals.get(macAddress);
// allow auto-connect to connect to devices without scanning
if (peripheral == null) {
if (BluetoothAdapter.checkBluetoothAddress(macAddress)) {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddress);
peripheral = new Peripheral(device);
peripherals.put(device.getAddress(), peripheral);
} else {
callbackContext.error(macAddress + " is not a valid MAC address.");
return;
}
}
// #894: BLE adapter state listener required so disconnect can be fired on BLE disabled
addStateListener();
peripheral.connect(callbackContext, cordova.getActivity(), true);
}
@SuppressLint("MissingPermission")
private void disconnect(CallbackContext callbackContext, String macAddress) {
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.disconnect();
callbackContext.success();
} else {
String message = "Peripheral " + macAddress + " not found.";
LOG.w(TAG, message);
callbackContext.error(message);
}
}
private void queueCleanup(CallbackContext callbackContext, String macAddress) {
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.queueCleanup("Aborted due to queue cleanup");
}
callbackContext.success();
}
BroadcastReceiver broadCastReceiver;
private void setPin(CallbackContext callbackContext, final String pin) {
try {
if (broadCastReceiver != null) {
webView.getContext().unregisterReceiver(broadCastReceiver);
}
broadCastReceiver = new BroadcastReceiver() {
@SuppressLint("MissingPermission")
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
if (type == BluetoothDevice.PAIRING_VARIANT_PIN) {
bluetoothDevice.setPin(pin.getBytes());
abortBroadcast();
}
}
}
};
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
webView.getContext().registerReceiver(broadCastReceiver, intentFilter);
callbackContext.success("OK");
} catch (Exception e) {
callbackContext.error("Error: " + e.getMessage());
return;
}
}
@SuppressLint("MissingPermission")
private void bond(CallbackContext callbackContext, String macAddress, boolean usePairingDialog) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
List<String> missingPermissions = new ArrayList<String>();
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
missingPermissions.add(BLUETOOTH_CONNECT);
}
if (usePairingDialog && !PermissionHelper.hasPermission(this, BLUETOOTH_SCAN)) {
missingPermissions.add(BLUETOOTH_SCAN);
}
if (!missingPermissions.isEmpty()) {
permissionCallback = callbackContext;
deviceMacAddress = macAddress;
this.usePairingDialog = usePairingDialog;
PermissionHelper.requestPermissions(this, REQUEST_BOND, missingPermissions.toArray(new String[0]));
return;
}
}
if (!peripherals.containsKey(macAddress) && BluetoothAdapter.checkBluetoothAddress(macAddress)) {
BluetoothDevice device = BLECentralPlugin.this.bluetoothAdapter.getRemoteDevice(macAddress);
Peripheral peripheral = new Peripheral(device);
peripherals.put(macAddress, peripheral);
}
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
addBondStateListener();
peripheral.bond(callbackContext, bluetoothAdapter, usePairingDialog);
} else {
callbackContext.error("Peripheral " + macAddress + " not found.");
}
}
@SuppressLint("MissingPermission")
private void unbond(CallbackContext callbackContext, String macAddress) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
deviceMacAddress = macAddress;
PermissionHelper.requestPermission(this, REQUEST_UNBOND, BLUETOOTH_CONNECT);
return;
}
}
if (!peripherals.containsKey(macAddress) && BluetoothAdapter.checkBluetoothAddress(macAddress)) {
BluetoothDevice device = BLECentralPlugin.this.bluetoothAdapter.getRemoteDevice(macAddress);
Peripheral peripheral = new Peripheral(device);
peripherals.put(macAddress, peripheral);
}
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.unbond(callbackContext);
} else {
callbackContext.success();
}
}
@SuppressLint("MissingPermission")
private void readBondState(CallbackContext callbackContext, String macAddress) {
if (COMPILE_SDK_VERSION >= 31 && Build.VERSION.SDK_INT >= 31) { // (API 31) Build.VERSION_CODE.S
if (!PermissionHelper.hasPermission(this, BLUETOOTH_CONNECT)) {
permissionCallback = callbackContext;
deviceMacAddress = macAddress;
PermissionHelper.requestPermission(this, REQUEST_READ_BOND_STATE, BLUETOOTH_CONNECT);
return;
}
}
if (!peripherals.containsKey(macAddress) && BluetoothAdapter.checkBluetoothAddress(macAddress)) {
BluetoothDevice device = BLECentralPlugin.this.bluetoothAdapter.getRemoteDevice(macAddress);
Peripheral peripheral = new Peripheral(device);
peripherals.put(macAddress, peripheral);
}
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.readBondState(callbackContext);
} else {
callbackContext.error("Peripheral " + macAddress + " not found.");
}
}
@SuppressLint("MissingPermission")
private void requestMtu(CallbackContext callbackContext, String macAddress, int mtuValue) {
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.requestMtu(callbackContext, mtuValue);
} else {
String message = "Peripheral " + macAddress + " not found.";
LOG.w(TAG, message);
callbackContext.error(message);
}
}
@SuppressLint("MissingPermission")
private void requestConnectionPriority(CallbackContext callbackContext, String macAddress, String priority) {
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral == null) {
callbackContext.error("Peripheral " + macAddress + " not found.");
return;
}
if (!peripheral.isConnected()) {
callbackContext.error("Peripheral " + macAddress + " is not connected.");
return;
}
int androidPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;
if (priority.equals(CONNECTION_PRIORITY_LOW)) {
androidPriority = BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER;
} else if (priority.equals(CONNECTION_PRIORITY_BALANCED)) {
androidPriority = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;
} else if (priority.equals(CONNECTION_PRIORITY_HIGH)) {
androidPriority = BluetoothGatt.CONNECTION_PRIORITY_HIGH;
}
peripheral.requestConnectionPriority(androidPriority);
callbackContext.success();
}
private void refreshDeviceCache(CallbackContext callbackContext, String macAddress, long timeoutMillis) {
Peripheral peripheral = peripherals.get(macAddress);
if (peripheral != null) {
peripheral.refreshDeviceCache(callbackContext, timeoutMillis);
} else {
String message = "Peripheral " + macAddress + " not found.";
LOG.w(TAG, message);
callbackContext.error(message);
}
}
private void read(CallbackContext callbackContext, String macAddress, UUID serviceUUID, UUID characteristicUUID) {