-
Notifications
You must be signed in to change notification settings - Fork 354
/
Copy pathBluetoothLePlugin.java
4841 lines (3716 loc) · 161 KB
/
BluetoothLePlugin.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 com.randdusing.bluetoothle;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.ParcelUuid;
import android.provider.Settings;
import android.util.Base64;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanSettings;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanCallback;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
@SuppressWarnings("unchecked")
public class BluetoothLePlugin extends CordovaPlugin {
//Initialization related variables
private final int REQUEST_BT_ENABLE = 59627; /*Random integer*/
private final int REQUEST_ACCESS_FINE_LOCATION = 59628;
private final int REQUEST_LOCATION_SOURCE_SETTINGS = 59629;
private final int REQUEST_BLUETOOTH_SCAN = 59630;
private final int REQUEST_BLUETOOTH_ADVERTISE = 59631;
private final int REQUEST_BLUETOOTH_CONNECT = 59632;
private BluetoothAdapter bluetoothAdapter;
private boolean isReceiverRegistered = false;
private boolean isBondReceiverRegistered = false;
//General callback variables
private CallbackContext initCallbackContext;
private CallbackContext scanCallbackContext;
private CallbackContext permissionsCallback;
private CallbackContext locationCallback;
private CallbackContext initPeripheralCallback;
private BluetoothGattServer gattServer;
private CallbackContext addServiceCallback;
private CallbackContext advertiseCallbackContext;
private boolean isAdvertising = false;
//Store connections and all their callbacks
private HashMap<Object, HashMap<Object, Object>> connections;
//Store bonds
private HashMap<String, CallbackContext> bonds = new HashMap<String, CallbackContext>();
//Discovery related variables
private final int STATE_UNDISCOVERED = 0;
private final int STATE_DISCOVERING = 1;
private final int STATE_DISCOVERED = 2;
//Quick Writes
private LinkedList<byte[]> queueQuick = new LinkedList<byte[]>();
//Object keys
private final String keyStatus = "status";
private final String keyError = "error";
private final String keyMessage = "message";
private final String keyRequest = "request";
private final String keyStatusReceiver = "statusReceiver";
private final String keyName = "name";
private final String keyAddress = "address";
private final String keyRssi = "rssi";
private final String keyScanMode = "scanMode";
private final String keyMatchMode = "matchMode";
private final String keyMatchNum = "matchNum";
private final String keyCallbackType = "callbackType";
private final String keyAdvertisement = "advertisement";
private final String keyUuid = "uuid";
private final String keyService = "service";
private final String keyServices = "services";
private final String keyCharacteristic = "characteristic";
private final String keyCharacteristics = "characteristics";
private final String keyProperties = "properties";
private final String keyPermissions = "permissions";
private final String keyDescriptor = "descriptor";
private final String keyDescriptors = "descriptors";
private final String keyValue = "value";
private final String keyType = "type";
private final String keyIsInitialized = "isInitialized";
private final String keyIsEnabled = "isEnabled";
private final String keyIsScanning = "isScanning";
private final String keyIsBonded = "isBonded";
private final String keyIsConnected = "isConnected";
private final String keyIsDiscovered = "isDiscovered";
private final String keyIsDiscoverable = "isDiscoverable";
private final String keyPeripheral = "peripheral";
private final String keyState = "state";
private final String keyDiscoveredState = "discoveredState";
private final String keyConnectionPriority = "connectionPriority";
private final String keyMtu = "mtu";
private final String keyPin = "pin";
private final String keyQueue = "queue";
//Write Types
private final String writeTypeNoResponse = "noResponse";
//Status Types
private final String statusEnabled = "enabled";
private final String statusDisabled = "disabled";
private final String statusScanStarted = "scanStarted";
private final String statusScanStopped = "scanStopped";
private final String statusScanResult = "scanResult";
private final String statusBonded = "bonded";
private final String statusBonding = "bonding";
private final String statusUnbonded = "unbonded";
private final String statusConnected = "connected";
private final String statusDisconnected = "disconnected";
private final String statusClosed = "closed";
private final String statusDiscovered = "discovered";
private final String statusRead = "read";
private final String statusSubscribed = "subscribed";
private final String statusSubscribedResult = "subscribedResult";
private final String statusUnsubscribed = "unsubscribed";
private final String statusWritten = "written";
private final String statusReadDescriptor = "readDescriptor";
private final String statusWrittenDescriptor = "writtenDescriptor";
private final String statusRssi = "rssi";
private final String statusConnectionPriorityRequested = "connectionPriorityRequested";
private final String statusMtu = "mtu";
//Properties
private final String propertyBroadcast = "broadcast";
private final String propertyRead = "read";
private final String propertyWriteWithoutResponse = "writeWithoutResponse";
private final String propertyWrite = "write";
private final String propertyNotify = "notify";
private final String propertyIndicate = "indicate";
private final String propertyAuthenticatedSignedWrites = "authenticatedSignedWrites";
private final String propertyExtendedProperties = "extendedProperties";
private final String propertyNotifyEncryptionRequired = "notifyEncryptionRequired";
private final String propertyIndicateEncryptionRequired = "indicateEncryptionRequired";
private final String propertyConnectionPriorityHigh = "high";
private final String propertyConnectionPriorityLow = "low";
private final String propertyConnectionPriorityBalanced = "balanced";
//Permissions
private final String permissionRead = "read";
private final String permissionReadEncrypted = "readEncrypted";
private final String permissionReadEncryptedMITM = "readEncryptedMITM";
private final String permissionWrite = "write";
private final String permissionWriteEncrypted = "writeEncrypted";
private final String permissionWriteEncryptedMITM = "writeEncryptedMITM";
private final String permissionWriteSigned = "writeSigned";
private final String permissionWriteSignedMITM = "writeSignedMITM";
//Error Types
private final String errorInitialize = "initialize";
private final String errorEnable = "enable";
private final String errorDisable = "disable";
private final String errorArguments = "arguments";
private final String errorStartScan = "startScan";
private final String errorStopScan = "stopScan";
private final String errorBond = "bond";
private final String errorUnbond = "unbond";
private final String errorConnect = "connect";
private final String errorReconnect = "reconnect";
private final String errorDiscover = "discover";
private final String errorServices = "services";
private final String errorCharacteristics = "characteristics";
private final String errorDescriptors = "descriptors";
private final String errorRead = "read";
private final String errorSubscription = "subscription";
private final String errorWrite = "write";
private final String errorReadDescriptor = "readDescriptor";
private final String errorWriteDescriptor = "writeDescriptor";
private final String errorRssi = "rssi";
private final String errorNeverConnected = "neverConnected";
private final String errorIsNotDisconnected = "isNotDisconnected";
private final String errorIsNotConnected = "isNotConnected";
private final String errorIsDisconnected = "isDisconnected";
private final String errorService = "service";
private final String errorCharacteristic = "characteristic";
private final String errorDescriptor = "descriptor";
private final String errorRequestConnectionPriority = "requestConnectPriority";
private final String errorMtu = "mtu";
private final String errorRetrievePeripheralsByAddress = "retrievePeripheralsByAddress";
//Error Messages
//Initialization
private final String logNotEnabled = "Bluetooth not enabled";
private final String logNotDisabled = "Bluetooth not disabled";
private final String logNotInit = "Bluetooth not initialized";
private final String logOperationUnsupported = "Operation unsupported";
//Scanning
private final String logAlreadyScanning = "Scanning already in progress";
private final String logScanStartFail = "Scan failed to start";
private final String logNotScanning = "Not scanning";
//Bonding
private final String logBonded = "Device already bonded";
private final String logBonding = "Device already bonding";
private final String logUnbonded = "Device already unbonded";
private final String logBondFail = "Device failed to bond on return";
private final String logUnbondFail = "Device failed to unbond on return";
//Connection
private final String logPreviouslyConnected = "Device previously connected, reconnect or close for new device";
private final String logConnectFail = "Connection failed";
private final String logNeverConnected = "Never connected to device";
private final String logIsNotConnected = "Device isn't connected";
private final String logIsNotDisconnected = "Device isn't disconnected";
private final String logIsDisconnected = "Device is disconnected";
private final String logNoAddress = "No device address";
private final String logNoDevice = "Device not found";
private final String logReconnectFail = "Reconnection to device failed";
//Discovery
private final String logAlreadyDiscovering = "Already discovering device";
private final String logDiscoveryFail = "Unable to discover device";
//Read/write
private final String logNoArgObj = "Argument object not found";
private final String logNoService = "Service not found";
private final String logNoCharacteristic = "Characteristic not found";
private final String logNoDescriptor = "Descriptor not found";
private final String logReadFail = "Unable to read";
private final String logReadFailReturn = "Unable to read on return";
private final String logSubscribeFail = "Unable to subscribe";
private final String logSubscribeAlready = "Already subscribed";
private final String logUnsubscribeFail = "Unable to unsubscribe";
private final String logUnsubscribeAlready = "Already unsubscribed";
private final String logWriteFail = "Unable to write";
private final String logWriteFailReturn = "Unable to write on return";
private final String logWriteValueNotFound = "Write value not found";
private final String logWriteValueNotSet = "Write value not set";
private final String logReadDescriptorFail = "Unable to read descriptor";
private final String logReadDescriptorFailReturn = "Unable to read descriptor on return";
private final String logWriteDescriptorNotAllowed = "Unable to write client configuration descriptor";
private final String logWriteDescriptorFail = "Unable to write descriptor";
private final String logWriteDescriptorValueNotFound = "Write descriptor value not found";
private final String logWriteDescriptorValueNotSet = "Write descriptor value not set";
private final String logWriteDescriptorFailReturn = "Descriptor not written on return";
private final String logRssiFail = "Unable to read RSSI";
private final String logRssiFailReturn = "Unable to read RSSI on return";
//Request Connection Priority
private final String logRequestConnectionPriorityNull = "Request connection priority not set";
private final String logRequestConnectionPriorityInvalid = "Request connection priority is invalid";
private final String logRequestConnectionPriorityFailed = "Request connection priority failed";
//MTU
private final String logMtuFail = "Unable to set MTU";
private final String logMtuFailReturn = "Unable to set MTU on return";
private final String logRequiresAPI21 = "Requires API level 21";
private final String operationConnect = "connect";
private final String operationDiscover = "discover";
private final String operationRssi = "rssi";
private final String operationRead = "read";
private final String operationSubscribe = "subscribe";
private final String operationUnsubscribe = "unsubscribe";
private final String operationWrite = "write";
private final String operationMtu = "mtu";
private final String baseUuidStart = "0000";
private final String baseUuidEnd = "-0000-1000-8000-00805F9B34FB";
//Client Configuration UUID for notifying/indicating
private final UUID clientConfigurationDescriptorUuid = UUID.fromString("00002902-0000-1000-8000-00805F9B34FB");
public BluetoothLePlugin() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
return;
}
createScanCallback();
createAdvertiseCallback();
}
//Actions
@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
//Execute the specified action
if ("initialize".equals(action)) {
initializeAction(args, callbackContext);
} else if ("enable".equals(action)) {
enableAction(callbackContext);
} else if ("getAdapterInfo".equals(action)) {
getAdapterInfoAction(callbackContext);
} else if ("disable".equals(action)) {
disableAction(callbackContext);
} else if ("startScan".equals(action)) {
startScanAction(args, callbackContext);
} else if ("stopScan".equals(action)) {
stopScanAction(callbackContext);
} else if ("retrieveConnected".equals(action)) {
retrieveConnectedAction(args, callbackContext);
} else if ("bond".equals(action)) {
bondAction(args, callbackContext);
} else if ("unbond".equals(action)) {
unbondAction(args, callbackContext);
} else if ("connect".equals(action)) {
connectAction(args, callbackContext);
} else if ("reconnect".equals(action)) {
reconnectAction(args, callbackContext);
} else if ("disconnect".equals(action)) {
disconnectAction(args, callbackContext);
} else if ("services".equals(action)) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, errorServices);
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
} else if ("characteristics".equals(action)) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, errorCharacteristics);
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
} else if ("descriptors".equals(action)) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, errorDescriptors);
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
} else if ("close".equals(action)) {
closeAction(args, callbackContext);
} else if ("discover".equals(action)) {
discoverAction(args, callbackContext);
} else if ("read".equals(action)) {
Operation operation = new Operation("read", args, callbackContext);
queueAdd(operation);
} else if ("subscribe".equals(action)) {
Operation operation = new Operation("subscribe", args, callbackContext);
queueAdd(operation);
} else if ("unsubscribe".equals(action)) {
Operation operation = new Operation("unsubscribe", args, callbackContext);
queueAdd(operation);
} else if ("write".equals(action)) {
Operation operation = new Operation("write", args, callbackContext);
queueAdd(operation);
} else if ("writeQ".equals(action)) {
writeQAction(args, callbackContext);
} else if ("readDescriptor".equals(action)) {
Operation operation = new Operation("readDescriptor", args, callbackContext);
queueAdd(operation);
} else if ("writeDescriptor".equals(action)) {
Operation operation = new Operation("writeDescriptor", args, callbackContext);
queueAdd(operation);
} else if ("rssi".equals(action)) {
rssiAction(args, callbackContext);
} else if ("isInitialized".equals(action)) {
isInitializedAction(callbackContext);
} else if ("isEnabled".equals(action)) {
isEnabledAction(callbackContext);
} else if ("isScanning".equals(action)) {
isScanningAction(callbackContext);
} else if ("wasConnected".equals(action)) {
wasConnectedAction(args, callbackContext);
} else if ("isConnected".equals(action)) {
isConnectedAction(args, callbackContext);
} else if ("isDiscovered".equals(action)) {
isDiscoveredAction(args, callbackContext);
} else if ("isBonded".equals(action)) {
isBondedAction(args, callbackContext);
} else if ("requestConnectionPriority".equals(action)) {
requestConnectionPriorityAction(args, callbackContext);
} else if ("mtu".equals(action)) {
mtuAction(args, callbackContext);
} else if ("hasPermission".equals(action)) {
hasPermissionAction(callbackContext);
} else if ("requestPermission".equals(action)) {
requestPermissionAction(callbackContext);
} else if ("hasPermissionBtScan".equals(action)) {
hasPermissionBtScanAction(callbackContext);
} else if ("requestPermissionBtScan".equals(action)) {
requestPermissionBtScanAction(callbackContext);
} else if ("hasPermissionBtConnect".equals(action)) {
hasPermissionBtConnectAction(callbackContext);
} else if ("requestPermissionBtConnect".equals(action)) {
requestPermissionBtConnectAction(callbackContext);
} else if ("hasPermissionBtAdvertise".equals(action)) {
hasPermissionBtAdvertiseAction(callbackContext);
} else if ("requestPermissionBtAdvertise".equals(action)) {
requestPermissionBtAdvertiseAction(callbackContext);
} else if ("isLocationEnabled".equals(action)) {
isLocationEnabledAction(callbackContext);
} else if ("requestLocation".equals(action)) {
requestLocationAction(callbackContext);
} else if ("initializePeripheral".equals(action)) {
initializePeripheralAction(args, callbackContext);
} else if ("addService".equals(action)) {
addServiceAction(args, callbackContext);
} else if ("removeService".equals(action)) {
removeServiceAction(args, callbackContext);
} else if ("removeAllServices".equals(action)) {
removeAllServicesAction(args, callbackContext);
} else if ("startAdvertising".equals(action)) {
startAdvertisingAction(args, callbackContext);
} else if ("stopAdvertising".equals(action)) {
stopAdvertisingAction(args, callbackContext);
} else if ("isAdvertising".equals(action)) {
isAdvertisingAction(callbackContext);
} else if ("respond".equals(action)) {
respondAction(args, callbackContext);
} else if ("notify".equals(action)) {
notifyAction(args, callbackContext);
} else if ("setPin".equals(action)) {
setPinAction(args, callbackContext);
} else if ("retrievePeripheralsByAddress".equals(action)) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, errorRetrievePeripheralsByAddress);
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
} else {
return false;
}
return true;
}
private void initializePeripheralAction(JSONArray args, CallbackContext callbackContext) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.LOLLIPOP) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "initializePeripheral");
addProperty(returnObj, "message", logOperationUnsupported);
callbackContext.error(returnObj);
return;
}
initPeripheralCallback = callbackContext;
initGattServer();
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyStatus, statusEnabled);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, returnObj);
pluginResult.setKeepCallback(true);
initPeripheralCallback.sendPluginResult(pluginResult);
//TODO standardize with main init function as well
}
private void addServiceAction(JSONArray args, CallbackContext callbackContext) {
JSONObject obj = getArgsObject(args);
if (isNotArgsObject(obj, callbackContext)) {
return;
}
addServiceCallback = callbackContext;
UUID uuid = getUUID(obj.optString("service", null));
BluetoothGattService service = new BluetoothGattService(uuid, BluetoothGattService.SERVICE_TYPE_PRIMARY);
JSONArray characteristicsIn = obj.optJSONArray("characteristics");
for (int i = 0; i < characteristicsIn.length(); i++) {
JSONObject characteristicIn = null;
try {
characteristicIn = characteristicsIn.getJSONObject(i);
} catch (JSONException ex) {
continue;
}
UUID characteristicUuid = getUUID(characteristicIn.optString("uuid", null));
boolean includeClientConfiguration = false;
JSONObject propertiesIn = characteristicIn.optJSONObject("properties");
int properties = 0;
if (propertiesIn != null) {
if (propertiesIn.optString("broadcast", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_BROADCAST;
}
if (propertiesIn.optString("extendedProps", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS;
}
if (propertiesIn.optString("indicate", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_INDICATE;
includeClientConfiguration = true;
}
if (propertiesIn.optString("notify", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_NOTIFY;
includeClientConfiguration = true;
}
if (propertiesIn.optString("read", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_READ;
}
if (propertiesIn.optString("signedWrite", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE;
}
if (propertiesIn.optString("write", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_WRITE;
}
if (propertiesIn.optString("writeNoResponse", null) != null) {
properties |= BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE;
}
if (propertiesIn.optString(propertyNotifyEncryptionRequired, null) != null) {
properties |= 0x100;
}
if (propertiesIn.optString(propertyIndicateEncryptionRequired, null) != null) {
properties |= 0x200;
}
}
JSONObject permissionsIn = characteristicIn.optJSONObject("permissions");
int permissions = 0;
if (permissionsIn != null) {
if (permissionsIn.optString("read", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_READ;
}
if (permissionsIn.optString("readEncrypted", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED;
}
if (permissionsIn.optString("readEncryptedMITM", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_READ_ENCRYPTED_MITM;
}
if (permissionsIn.optString("write", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_WRITE;
}
if (permissionsIn.optString("writeEncrypted", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED;
}
if (permissionsIn.optString("writeEncryptedMITM", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_WRITE_ENCRYPTED_MITM;
}
if (permissionsIn.optString("writeSigned", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED;
}
if (permissionsIn.optString("writeSignedMITM", null) != null) {
permissions |= BluetoothGattCharacteristic.PERMISSION_WRITE_SIGNED_MITM;
}
}
BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(characteristicUuid, properties, permissions);
if (includeClientConfiguration) {
BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(clientConfigurationDescriptorUuid, BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE);
characteristic.addDescriptor(descriptor);
}
JSONArray descriptorsIn = obj.optJSONArray("descriptors");
if (descriptorsIn != null) {
for (int j = 0; j < descriptorsIn.length(); j++) {
JSONObject descriptorIn = null;
try {
descriptorIn = descriptorsIn.getJSONObject(j);
} catch (JSONException ex) {
continue;
}
UUID descriptorUuid = getUUID(descriptorIn.optString("uuid", null));
permissionsIn = descriptorIn.optJSONObject("permissions");
permissions = 0;
if (permissionsIn != null) {
if (permissionsIn.optString("read", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_READ;
}
if (permissionsIn.optString("readEncrypted", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED;
}
if (permissionsIn.optString("readEncryptedMITM", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_READ_ENCRYPTED_MITM;
}
if (permissionsIn.optString("write", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_WRITE;
}
if (permissionsIn.optString("writeEncrypted", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED;
}
if (permissionsIn.optString("writeEncryptedMITM", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_WRITE_ENCRYPTED_MITM;
}
if (permissionsIn.optString("writeSigned", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED;
}
if (permissionsIn.optString("writeSignedMITM", null) != null) {
permissions |= BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED_MITM;
}
}
BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(descriptorUuid, permissions);
characteristic.addDescriptor(descriptor);
}
}
service.addCharacteristic(characteristic);
}
boolean result = gattServer.addService(service);
if (result) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "service", uuid.toString());
addProperty(returnObj, "status", "serviceAdded");
callbackContext.success(returnObj);
} else {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "service", uuid.toString());
addProperty(returnObj, "error", "service");
addProperty(returnObj, "message", "Failed to add service");
callbackContext.error(returnObj);
}
}
private void removeServiceAction(JSONArray args, CallbackContext callbackContext) {
JSONObject obj = getArgsObject(args);
if (isNotArgsObject(obj, callbackContext)) {
return;
}
UUID uuid = getUUID(obj.optString("service", null));
BluetoothGattService service = gattServer.getService(uuid);
if (service == null) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "service", uuid.toString());
addProperty(returnObj, "error", "service");
addProperty(returnObj, "message", "Service doesn't exist");
callbackContext.error(returnObj);
return;
}
boolean result = gattServer.removeService(service);
if (result) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "service", uuid.toString());
addProperty(returnObj, "status", "serviceRemoved");
callbackContext.success(returnObj);
} else {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "service", uuid.toString());
addProperty(returnObj, "error", "service");
addProperty(returnObj, "message", "Failed to remove service");
callbackContext.error(returnObj);
}
}
private void removeAllServicesAction(JSONArray args, CallbackContext callbackContext) {
gattServer.clearServices();
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "status", "allServicesRemoved");
callbackContext.success(returnObj);
}
private void startAdvertisingAction(JSONArray args, CallbackContext callbackContext) {
JSONObject obj = getArgsObject(args);
if (isNotArgsObject(obj, callbackContext)) {
return;
}
BluetoothLeAdvertiser advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
if (advertiser == null) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "startAdvertising");
addProperty(returnObj, "message", "Advertising isn't supported");
callbackContext.error(returnObj);
return;
}
AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
String modeS = obj.optString("mode", "balanced");
int mode = AdvertiseSettings.ADVERTISE_MODE_BALANCED;
if (modeS.equals("lowLatency")) {
mode = AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY;
} else if (modeS.equals("lowPower")) {
mode = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
}
settingsBuilder.setAdvertiseMode(mode);
boolean connectable = obj.optBoolean("connectable", true);
settingsBuilder.setConnectable(connectable);
int timeout = obj.optInt("timeout", 1000);
if (timeout < 0 || timeout > 180000) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "startAdvertising");
addProperty(returnObj, "message", "Invalid timeout (0 - 180000)");
callbackContext.error(returnObj);
return;
}
String adapterName = obj.optString("name");
bluetoothAdapter.setName(adapterName);
settingsBuilder.setTimeout(timeout);
String txPowerLevelS = obj.optString("txPowerLevel", "medium");
int txPowerLevel = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM;
if (txPowerLevelS.equals("high")) {
txPowerLevel = AdvertiseSettings.ADVERTISE_TX_POWER_HIGH;
} else if (txPowerLevelS.equals("low")) {
txPowerLevel = AdvertiseSettings.ADVERTISE_TX_POWER_LOW;
} else if (txPowerLevelS.equals("ultraLow")) {
txPowerLevel = AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW;
}
settingsBuilder.setTxPowerLevel(txPowerLevel);
AdvertiseSettings advertiseSettings = settingsBuilder.build();
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
int manufacturerId = obj.optInt("manufacturerId", 0);
byte[] manufacturerSpecificData = getPropertyBytes(obj, "manufacturerSpecificData");
if (manufacturerId >= 0 && manufacturerSpecificData != null) {
dataBuilder.addManufacturerData(manufacturerId, manufacturerSpecificData);
}
UUID uuid = getUUID(obj.optString("service", null));
if (uuid != null) {
byte[] serviceData = getPropertyBytes(obj, "serviceData");
if (serviceData != null) {
dataBuilder.addServiceData(new ParcelUuid(uuid), serviceData);
} else {
dataBuilder.addServiceUuid(new ParcelUuid(uuid));
}
}
dataBuilder.setIncludeDeviceName(obj.optBoolean("includeDeviceName", true));
dataBuilder.setIncludeTxPowerLevel(obj.optBoolean("includeTxPowerLevel", true));
AdvertiseData advertiseData = dataBuilder.build();
advertiseCallbackContext = callbackContext;
advertiser.startAdvertising(advertiseSettings, advertiseData, advertiseCallback);
}
private void stopAdvertisingAction(JSONArray args, CallbackContext callbackContext) {
BluetoothLeAdvertiser advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
if (advertiser == null) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "stopAdvertising");
addProperty(returnObj, "message", "Advertising isn't supported");
callbackContext.error(returnObj);
return;
}
advertiser.stopAdvertising(advertiseCallback);
if (isAdvertising) isAdvertising = false;
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "status", "advertisingStopped");
callbackContext.success(returnObj);
}
private void isAdvertisingAction(CallbackContext callbackContext) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "isAdvertising", isAdvertising);
callbackContext.success(returnObj);
}
private void respondAction(JSONArray args, CallbackContext callbackContext) {
JSONObject obj = getArgsObject(args);
if (isNotArgsObject(obj, callbackContext)) {
return;
}
String address = getAddress(obj);
if (isNotAddress(address, callbackContext)) {
return;
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
int requestId = obj.optInt("requestId", 0); //TODO validate?
int status = obj.optInt("status", 0);
int offset = obj.optInt("offset", 0);
byte[] value = getPropertyBytes(obj, "value");
boolean result = gattServer.sendResponse(device, requestId, 0, offset, value);
if (result) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "status", "responded");
addProperty(returnObj, "requestId", requestId);
callbackContext.success(returnObj);
} else {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "respond");
addProperty(returnObj, "message", "Failed to respond");
addProperty(returnObj, "requestId", requestId);
callbackContext.error(returnObj);
}
}
private void notifyAction(JSONArray args, CallbackContext callbackContext) {
JSONObject obj = getArgsObject(args);
if (isNotArgsObject(obj, callbackContext)) {
return;
}
String address = getAddress(obj);
if (isNotAddress(address, callbackContext)) {
return;
}
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
UUID serviceUuid = getUUID(obj.optString("service", null));
BluetoothGattService service = gattServer.getService(serviceUuid);
if (service == null) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "service");
addProperty(returnObj, "message", "Service not found");
callbackContext.error(returnObj);
}
UUID characteristicUuid = getUUID(obj.optString("characteristic", null));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
if (characteristic == null) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "characteristic");
addProperty(returnObj, "message", "Characteristic not found");
callbackContext.error(returnObj);
}
byte[] value = getPropertyBytes(obj, "value");
boolean setResult = characteristic.setValue(value);
if (!setResult) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "respond");
addProperty(returnObj, "message", "Failed to set value");
callbackContext.error(returnObj);
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(clientConfigurationDescriptorUuid);
byte[] descriptorValue = descriptor.getValue();
boolean isIndicate = false;
if (Arrays.equals(descriptorValue, BluetoothGattDescriptor.ENABLE_INDICATION_VALUE)) {
isIndicate = true;
}
//Wait for onNotificationSent event
boolean result = gattServer.notifyCharacteristicChanged(device, characteristic, isIndicate);
if (!result) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "error", "notify");
addProperty(returnObj, "message", "Failed to notify");
callbackContext.error(returnObj);
}
}
/**
* ACCESS_FINE_LOCATION
*/
public void hasPermissionAction(CallbackContext callbackContext) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "hasPermission", cordova.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
callbackContext.success(returnObj);
}
public void requestPermissionAction(CallbackContext callbackContext) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, "requestPermission");
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
return;
}
permissionsCallback = callbackContext;
cordova.requestPermission(this, REQUEST_ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
}
/**
* BLUETOOTH_SCAN
*/
public void hasPermissionBtScanAction(CallbackContext callbackContext) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "hasPermission", Build.VERSION.SDK_INT < Build.VERSION_CODES.S || cordova.hasPermission(Manifest.permission.BLUETOOTH_SCAN));
callbackContext.success(returnObj);
}
public void requestPermissionBtScanAction(CallbackContext callbackContext) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, "requestPermission");
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
return;
}
permissionsCallback = callbackContext;
cordova.requestPermission(this, REQUEST_BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_SCAN);
}
/**
* BLUETOOTH_CONNECT
*/
public void hasPermissionBtConnectAction(CallbackContext callbackContext) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "hasPermission", Build.VERSION.SDK_INT < Build.VERSION_CODES.S || cordova.hasPermission(Manifest.permission.BLUETOOTH_CONNECT));
callbackContext.success(returnObj);
}
public void requestPermissionBtConnectAction(CallbackContext callbackContext) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, "requestPermission");
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
return;
}
permissionsCallback = callbackContext;
cordova.requestPermission(this, REQUEST_BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_CONNECT);
}
/**
* BLUETOOTH_ADVERTISE
*/
public void hasPermissionBtAdvertiseAction(CallbackContext callbackContext) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, "hasPermission", Build.VERSION.SDK_INT < Build.VERSION_CODES.S || cordova.hasPermission(Manifest.permission.BLUETOOTH_ADVERTISE));
callbackContext.success(returnObj);
}
public void requestPermissionBtAdvertiseAction(CallbackContext callbackContext) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
JSONObject returnObj = new JSONObject();
addProperty(returnObj, keyError, "requestPermission");
addProperty(returnObj, keyMessage, logOperationUnsupported);
callbackContext.error(returnObj);
return;
}
permissionsCallback = callbackContext;
cordova.requestPermission(this, REQUEST_BLUETOOTH_ADVERTISE, Manifest.permission.BLUETOOTH_ADVERTISE);
}
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
if (permissionsCallback == null) {
return;
}