@capgo/capacitor-bluetooth-low-energy 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1149 @@
1
+ package ee.forgr.plugin.bluetooth_low_energy;
2
+
3
+ import android.Manifest;
4
+ import android.bluetooth.BluetoothAdapter;
5
+ import android.bluetooth.BluetoothDevice;
6
+ import android.bluetooth.BluetoothGatt;
7
+ import android.bluetooth.BluetoothGattCallback;
8
+ import android.bluetooth.BluetoothGattCharacteristic;
9
+ import android.bluetooth.BluetoothGattDescriptor;
10
+ import android.bluetooth.BluetoothGattService;
11
+ import android.bluetooth.BluetoothManager;
12
+ import android.bluetooth.BluetoothProfile;
13
+ import android.bluetooth.le.AdvertiseCallback;
14
+ import android.bluetooth.le.AdvertiseData;
15
+ import android.bluetooth.le.AdvertiseSettings;
16
+ import android.bluetooth.le.BluetoothLeAdvertiser;
17
+ import android.bluetooth.le.BluetoothLeScanner;
18
+ import android.bluetooth.le.ScanCallback;
19
+ import android.bluetooth.le.ScanFilter;
20
+ import android.bluetooth.le.ScanResult;
21
+ import android.bluetooth.le.ScanSettings;
22
+ import android.content.Context;
23
+ import android.content.Intent;
24
+ import android.content.pm.PackageManager;
25
+ import android.location.LocationManager;
26
+ import android.os.Build;
27
+ import android.os.Handler;
28
+ import android.os.Looper;
29
+ import android.os.ParcelUuid;
30
+ import android.provider.Settings;
31
+ import androidx.annotation.RequiresPermission;
32
+ import androidx.core.app.ActivityCompat;
33
+ import com.getcapacitor.JSArray;
34
+ import com.getcapacitor.JSObject;
35
+ import com.getcapacitor.Plugin;
36
+ import com.getcapacitor.PluginCall;
37
+ import com.getcapacitor.PluginMethod;
38
+ import com.getcapacitor.annotation.CapacitorPlugin;
39
+ import com.getcapacitor.annotation.Permission;
40
+ import com.getcapacitor.annotation.PermissionCallback;
41
+ import java.util.ArrayList;
42
+ import java.util.HashMap;
43
+ import java.util.List;
44
+ import java.util.Map;
45
+ import java.util.UUID;
46
+
47
+ @CapacitorPlugin(
48
+ name = "BluetoothLowEnergy",
49
+ permissions = {
50
+ @Permission(
51
+ alias = "bluetooth",
52
+ strings = {
53
+ Manifest.permission.BLUETOOTH,
54
+ Manifest.permission.BLUETOOTH_ADMIN,
55
+ Manifest.permission.BLUETOOTH_SCAN,
56
+ Manifest.permission.BLUETOOTH_CONNECT,
57
+ Manifest.permission.BLUETOOTH_ADVERTISE
58
+ }
59
+ ),
60
+ @Permission(
61
+ alias = "location",
62
+ strings = {
63
+ Manifest.permission.ACCESS_FINE_LOCATION,
64
+ Manifest.permission.ACCESS_COARSE_LOCATION
65
+ }
66
+ )
67
+ }
68
+ )
69
+ public class BluetoothLowEnergyPlugin extends Plugin {
70
+
71
+ private final String pluginVersion = "1.0.0";
72
+ private BluetoothManager bluetoothManager;
73
+ private BluetoothAdapter bluetoothAdapter;
74
+ private BluetoothLeScanner bluetoothLeScanner;
75
+ private BluetoothLeAdvertiser bluetoothLeAdvertiser;
76
+
77
+ private final Map<String, BluetoothDevice> discoveredDevices = new HashMap<>();
78
+ private final Map<String, BluetoothGatt> connectedGatts = new HashMap<>();
79
+ private final Map<String, List<BluetoothGattService>> deviceServices = new HashMap<>();
80
+
81
+ private ScanCallback scanCallback;
82
+ private AdvertiseCallback advertiseCallback;
83
+ private Handler scanHandler;
84
+ private boolean isScanning = false;
85
+ private String mode = "central";
86
+
87
+ private PluginCall pendingConnectCall;
88
+ private PluginCall pendingDiscoverCall;
89
+ private PluginCall pendingReadCall;
90
+ private PluginCall pendingWriteCall;
91
+ private PluginCall pendingNotifyCall;
92
+ private PluginCall pendingReadDescriptorCall;
93
+ private PluginCall pendingWriteDescriptorCall;
94
+ private PluginCall pendingRssiCall;
95
+ private PluginCall pendingMtuCall;
96
+
97
+ private static final UUID CLIENT_CHARACTERISTIC_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
98
+
99
+ @Override
100
+ public void load() {
101
+ bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
102
+ if (bluetoothManager != null) {
103
+ bluetoothAdapter = bluetoothManager.getAdapter();
104
+ }
105
+ scanHandler = new Handler(Looper.getMainLooper());
106
+ }
107
+
108
+ @PluginMethod
109
+ public void initialize(PluginCall call) {
110
+ mode = call.getString("mode", "central");
111
+
112
+ if (bluetoothAdapter == null) {
113
+ call.reject("Bluetooth is not available on this device");
114
+ return;
115
+ }
116
+
117
+ if (mode.equals("central")) {
118
+ bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
119
+ } else {
120
+ bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
121
+ }
122
+
123
+ call.resolve();
124
+ }
125
+
126
+ @PluginMethod
127
+ public void isAvailable(PluginCall call) {
128
+ JSObject ret = new JSObject();
129
+ ret.put("available", bluetoothAdapter != null);
130
+ call.resolve(ret);
131
+ }
132
+
133
+ @PluginMethod
134
+ public void isEnabled(PluginCall call) {
135
+ JSObject ret = new JSObject();
136
+ ret.put("enabled", bluetoothAdapter != null && bluetoothAdapter.isEnabled());
137
+ call.resolve(ret);
138
+ }
139
+
140
+ @PluginMethod
141
+ public void isLocationEnabled(PluginCall call) {
142
+ LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
143
+ boolean enabled = false;
144
+ if (locationManager != null) {
145
+ enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
146
+ locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
147
+ }
148
+ JSObject ret = new JSObject();
149
+ ret.put("enabled", enabled);
150
+ call.resolve(ret);
151
+ }
152
+
153
+ @PluginMethod
154
+ public void openAppSettings(PluginCall call) {
155
+ Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
156
+ intent.setData(android.net.Uri.parse("package:" + getContext().getPackageName()));
157
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
158
+ getContext().startActivity(intent);
159
+ call.resolve();
160
+ }
161
+
162
+ @PluginMethod
163
+ public void openBluetoothSettings(PluginCall call) {
164
+ Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
165
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
166
+ getContext().startActivity(intent);
167
+ call.resolve();
168
+ }
169
+
170
+ @PluginMethod
171
+ public void openLocationSettings(PluginCall call) {
172
+ Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
173
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
174
+ getContext().startActivity(intent);
175
+ call.resolve();
176
+ }
177
+
178
+ @PluginMethod
179
+ public void checkPermissions(PluginCall call) {
180
+ JSObject ret = new JSObject();
181
+ ret.put("bluetooth", getBluetoothPermissionState());
182
+ ret.put("location", getLocationPermissionState());
183
+ call.resolve(ret);
184
+ }
185
+
186
+ @PluginMethod
187
+ public void requestPermissions(PluginCall call) {
188
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
189
+ requestPermissionForAlias("bluetooth", call, "permissionCallback");
190
+ } else {
191
+ requestPermissionForAlias("location", call, "permissionCallback");
192
+ }
193
+ }
194
+
195
+ @PermissionCallback
196
+ private void permissionCallback(PluginCall call) {
197
+ JSObject ret = new JSObject();
198
+ ret.put("bluetooth", getBluetoothPermissionState());
199
+ ret.put("location", getLocationPermissionState());
200
+ call.resolve(ret);
201
+ }
202
+
203
+ private String getBluetoothPermissionState() {
204
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
205
+ if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED &&
206
+ ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
207
+ return "granted";
208
+ }
209
+ return "prompt";
210
+ }
211
+ return "granted";
212
+ }
213
+
214
+ private String getLocationPermissionState() {
215
+ if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
216
+ return "granted";
217
+ }
218
+ return "prompt";
219
+ }
220
+
221
+ @PluginMethod
222
+ public void startScan(PluginCall call) {
223
+ if (bluetoothLeScanner == null) {
224
+ call.reject("Bluetooth scanner not available");
225
+ return;
226
+ }
227
+
228
+ if (!hasBlePermissions()) {
229
+ call.reject("Required permissions not granted");
230
+ return;
231
+ }
232
+
233
+ JSArray servicesArray = call.getArray("services");
234
+ double timeout = call.getDouble("timeout", 0.0);
235
+ boolean allowDuplicates = call.getBoolean("allowDuplicates", false);
236
+
237
+ List<ScanFilter> filters = new ArrayList<>();
238
+ if (servicesArray != null) {
239
+ try {
240
+ for (int i = 0; i < servicesArray.length(); i++) {
241
+ String serviceUuid = servicesArray.getString(i);
242
+ ScanFilter filter = new ScanFilter.Builder()
243
+ .setServiceUuid(ParcelUuid.fromString(normalizeUuid(serviceUuid)))
244
+ .build();
245
+ filters.add(filter);
246
+ }
247
+ } catch (Exception e) {
248
+ // Ignore filter errors
249
+ }
250
+ }
251
+
252
+ ScanSettings.Builder settingsBuilder = new ScanSettings.Builder()
253
+ .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
254
+
255
+ if (!allowDuplicates && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
256
+ settingsBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH);
257
+ }
258
+
259
+ scanCallback = new ScanCallback() {
260
+ @Override
261
+ public void onScanResult(int callbackType, ScanResult result) {
262
+ handleScanResult(result);
263
+ }
264
+
265
+ @Override
266
+ public void onBatchScanResults(List<ScanResult> results) {
267
+ for (ScanResult result : results) {
268
+ handleScanResult(result);
269
+ }
270
+ }
271
+
272
+ @Override
273
+ public void onScanFailed(int errorCode) {
274
+ // Scan failed
275
+ }
276
+ };
277
+
278
+ try {
279
+ if (filters.isEmpty()) {
280
+ bluetoothLeScanner.startScan(scanCallback);
281
+ } else {
282
+ bluetoothLeScanner.startScan(filters, settingsBuilder.build(), scanCallback);
283
+ }
284
+ isScanning = true;
285
+
286
+ if (timeout > 0) {
287
+ scanHandler.postDelayed(() -> {
288
+ stopScanInternal();
289
+ }, (long) timeout);
290
+ }
291
+
292
+ call.resolve();
293
+ } catch (SecurityException e) {
294
+ call.reject("Permission denied: " + e.getMessage());
295
+ }
296
+ }
297
+
298
+ private void handleScanResult(ScanResult result) {
299
+ BluetoothDevice device = result.getDevice();
300
+ String deviceId = device.getAddress();
301
+ discoveredDevices.put(deviceId, device);
302
+
303
+ JSObject deviceObj = new JSObject();
304
+ deviceObj.put("deviceId", deviceId);
305
+ try {
306
+ deviceObj.put("name", device.getName());
307
+ } catch (SecurityException e) {
308
+ deviceObj.put("name", null);
309
+ }
310
+ deviceObj.put("rssi", result.getRssi());
311
+
312
+ if (result.getScanRecord() != null) {
313
+ byte[] manufacturerData = result.getScanRecord().getManufacturerSpecificData(0);
314
+ if (manufacturerData != null) {
315
+ deviceObj.put("manufacturerData", bytesToHex(manufacturerData));
316
+ }
317
+
318
+ List<ParcelUuid> serviceUuids = result.getScanRecord().getServiceUuids();
319
+ if (serviceUuids != null) {
320
+ JSArray uuids = new JSArray();
321
+ for (ParcelUuid uuid : serviceUuids) {
322
+ uuids.put(uuid.getUuid().toString());
323
+ }
324
+ deviceObj.put("serviceUuids", uuids);
325
+ }
326
+ }
327
+
328
+ JSObject event = new JSObject();
329
+ event.put("device", deviceObj);
330
+ notifyListeners("deviceScanned", event);
331
+ }
332
+
333
+ @PluginMethod
334
+ public void stopScan(PluginCall call) {
335
+ stopScanInternal();
336
+ call.resolve();
337
+ }
338
+
339
+ private void stopScanInternal() {
340
+ if (bluetoothLeScanner != null && scanCallback != null && isScanning) {
341
+ try {
342
+ bluetoothLeScanner.stopScan(scanCallback);
343
+ } catch (SecurityException e) {
344
+ // Ignore
345
+ }
346
+ isScanning = false;
347
+ }
348
+ }
349
+
350
+ @PluginMethod
351
+ public void connect(PluginCall call) {
352
+ String deviceId = call.getString("deviceId");
353
+ if (deviceId == null) {
354
+ call.reject("deviceId is required");
355
+ return;
356
+ }
357
+
358
+ BluetoothDevice device = discoveredDevices.get(deviceId);
359
+ if (device == null) {
360
+ // Try to get device by address
361
+ if (bluetoothAdapter != null) {
362
+ try {
363
+ device = bluetoothAdapter.getRemoteDevice(deviceId);
364
+ } catch (Exception e) {
365
+ call.reject("Device not found");
366
+ return;
367
+ }
368
+ } else {
369
+ call.reject("Device not found");
370
+ return;
371
+ }
372
+ }
373
+
374
+ boolean autoConnect = call.getBoolean("autoConnect", false);
375
+ pendingConnectCall = call;
376
+
377
+ try {
378
+ BluetoothGatt gatt = device.connectGatt(getContext(), autoConnect, gattCallback);
379
+ connectedGatts.put(deviceId, gatt);
380
+ } catch (SecurityException e) {
381
+ call.reject("Permission denied: " + e.getMessage());
382
+ }
383
+ }
384
+
385
+ @PluginMethod
386
+ public void disconnect(PluginCall call) {
387
+ String deviceId = call.getString("deviceId");
388
+ if (deviceId == null) {
389
+ call.reject("deviceId is required");
390
+ return;
391
+ }
392
+
393
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
394
+ if (gatt != null) {
395
+ try {
396
+ gatt.disconnect();
397
+ gatt.close();
398
+ } catch (SecurityException e) {
399
+ // Ignore
400
+ }
401
+ connectedGatts.remove(deviceId);
402
+ deviceServices.remove(deviceId);
403
+ }
404
+
405
+ JSObject event = new JSObject();
406
+ event.put("deviceId", deviceId);
407
+ notifyListeners("deviceDisconnected", event);
408
+
409
+ call.resolve();
410
+ }
411
+
412
+ @PluginMethod
413
+ public void createBond(PluginCall call) {
414
+ String deviceId = call.getString("deviceId");
415
+ if (deviceId == null) {
416
+ call.reject("deviceId is required");
417
+ return;
418
+ }
419
+
420
+ BluetoothDevice device = discoveredDevices.get(deviceId);
421
+ if (device == null) {
422
+ call.reject("Device not found");
423
+ return;
424
+ }
425
+
426
+ try {
427
+ device.createBond();
428
+ call.resolve();
429
+ } catch (SecurityException e) {
430
+ call.reject("Permission denied: " + e.getMessage());
431
+ }
432
+ }
433
+
434
+ @PluginMethod
435
+ public void isBonded(PluginCall call) {
436
+ String deviceId = call.getString("deviceId");
437
+ if (deviceId == null) {
438
+ call.reject("deviceId is required");
439
+ return;
440
+ }
441
+
442
+ BluetoothDevice device = discoveredDevices.get(deviceId);
443
+ if (device == null) {
444
+ JSObject ret = new JSObject();
445
+ ret.put("bonded", false);
446
+ call.resolve(ret);
447
+ return;
448
+ }
449
+
450
+ try {
451
+ boolean bonded = device.getBondState() == BluetoothDevice.BOND_BONDED;
452
+ JSObject ret = new JSObject();
453
+ ret.put("bonded", bonded);
454
+ call.resolve(ret);
455
+ } catch (SecurityException e) {
456
+ call.reject("Permission denied: " + e.getMessage());
457
+ }
458
+ }
459
+
460
+ @PluginMethod
461
+ public void discoverServices(PluginCall call) {
462
+ String deviceId = call.getString("deviceId");
463
+ if (deviceId == null) {
464
+ call.reject("deviceId is required");
465
+ return;
466
+ }
467
+
468
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
469
+ if (gatt == null) {
470
+ call.reject("Device not connected");
471
+ return;
472
+ }
473
+
474
+ pendingDiscoverCall = call;
475
+ try {
476
+ gatt.discoverServices();
477
+ } catch (SecurityException e) {
478
+ call.reject("Permission denied: " + e.getMessage());
479
+ }
480
+ }
481
+
482
+ @PluginMethod
483
+ public void getServices(PluginCall call) {
484
+ String deviceId = call.getString("deviceId");
485
+ if (deviceId == null) {
486
+ call.reject("deviceId is required");
487
+ return;
488
+ }
489
+
490
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
491
+ if (gatt == null) {
492
+ call.reject("Device not connected");
493
+ return;
494
+ }
495
+
496
+ List<BluetoothGattService> services = gatt.getServices();
497
+ JSArray servicesArray = new JSArray();
498
+
499
+ for (BluetoothGattService service : services) {
500
+ JSObject serviceObj = new JSObject();
501
+ serviceObj.put("uuid", service.getUuid().toString());
502
+
503
+ JSArray characteristicsArray = new JSArray();
504
+ for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
505
+ JSObject charObj = new JSObject();
506
+ charObj.put("uuid", characteristic.getUuid().toString());
507
+
508
+ JSObject properties = new JSObject();
509
+ int props = characteristic.getProperties();
510
+ properties.put("broadcast", (props & BluetoothGattCharacteristic.PROPERTY_BROADCAST) != 0);
511
+ properties.put("read", (props & BluetoothGattCharacteristic.PROPERTY_READ) != 0);
512
+ properties.put("writeWithoutResponse", (props & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0);
513
+ properties.put("write", (props & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0);
514
+ properties.put("notify", (props & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0);
515
+ properties.put("indicate", (props & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0);
516
+ properties.put("authenticatedSignedWrites", (props & BluetoothGattCharacteristic.PROPERTY_SIGNED_WRITE) != 0);
517
+ properties.put("extendedProperties", (props & BluetoothGattCharacteristic.PROPERTY_EXTENDED_PROPS) != 0);
518
+ charObj.put("properties", properties);
519
+
520
+ JSArray descriptorsArray = new JSArray();
521
+ for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
522
+ JSObject descObj = new JSObject();
523
+ descObj.put("uuid", descriptor.getUuid().toString());
524
+ descriptorsArray.put(descObj);
525
+ }
526
+ charObj.put("descriptors", descriptorsArray);
527
+
528
+ characteristicsArray.put(charObj);
529
+ }
530
+ serviceObj.put("characteristics", characteristicsArray);
531
+
532
+ servicesArray.put(serviceObj);
533
+ }
534
+
535
+ JSObject ret = new JSObject();
536
+ ret.put("services", servicesArray);
537
+ call.resolve(ret);
538
+ }
539
+
540
+ @PluginMethod
541
+ public void getConnectedDevices(PluginCall call) {
542
+ JSArray devicesArray = new JSArray();
543
+ for (Map.Entry<String, BluetoothGatt> entry : connectedGatts.entrySet()) {
544
+ JSObject deviceObj = new JSObject();
545
+ deviceObj.put("deviceId", entry.getKey());
546
+ try {
547
+ BluetoothDevice device = entry.getValue().getDevice();
548
+ deviceObj.put("name", device.getName());
549
+ } catch (SecurityException e) {
550
+ deviceObj.put("name", null);
551
+ }
552
+ devicesArray.put(deviceObj);
553
+ }
554
+
555
+ JSObject ret = new JSObject();
556
+ ret.put("devices", devicesArray);
557
+ call.resolve(ret);
558
+ }
559
+
560
+ @PluginMethod
561
+ public void readCharacteristic(PluginCall call) {
562
+ String deviceId = call.getString("deviceId");
563
+ String serviceUuid = call.getString("service");
564
+ String characteristicUuid = call.getString("characteristic");
565
+
566
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null) {
567
+ call.reject("deviceId, service, and characteristic are required");
568
+ return;
569
+ }
570
+
571
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
572
+ if (gatt == null) {
573
+ call.reject("Device not connected");
574
+ return;
575
+ }
576
+
577
+ BluetoothGattCharacteristic characteristic = findCharacteristic(gatt, serviceUuid, characteristicUuid);
578
+ if (characteristic == null) {
579
+ call.reject("Characteristic not found");
580
+ return;
581
+ }
582
+
583
+ pendingReadCall = call;
584
+ try {
585
+ gatt.readCharacteristic(characteristic);
586
+ } catch (SecurityException e) {
587
+ call.reject("Permission denied: " + e.getMessage());
588
+ }
589
+ }
590
+
591
+ @PluginMethod
592
+ public void writeCharacteristic(PluginCall call) {
593
+ String deviceId = call.getString("deviceId");
594
+ String serviceUuid = call.getString("service");
595
+ String characteristicUuid = call.getString("characteristic");
596
+ JSArray valueArray = call.getArray("value");
597
+ String writeType = call.getString("type", "withResponse");
598
+
599
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null || valueArray == null) {
600
+ call.reject("deviceId, service, characteristic, and value are required");
601
+ return;
602
+ }
603
+
604
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
605
+ if (gatt == null) {
606
+ call.reject("Device not connected");
607
+ return;
608
+ }
609
+
610
+ BluetoothGattCharacteristic characteristic = findCharacteristic(gatt, serviceUuid, characteristicUuid);
611
+ if (characteristic == null) {
612
+ call.reject("Characteristic not found");
613
+ return;
614
+ }
615
+
616
+ try {
617
+ byte[] value = jsArrayToBytes(valueArray);
618
+ characteristic.setValue(value);
619
+
620
+ if (writeType.equals("withoutResponse")) {
621
+ characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
622
+ } else {
623
+ characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
624
+ }
625
+
626
+ pendingWriteCall = call;
627
+ gatt.writeCharacteristic(characteristic);
628
+ } catch (Exception e) {
629
+ call.reject("Failed to write: " + e.getMessage());
630
+ }
631
+ }
632
+
633
+ @PluginMethod
634
+ public void startCharacteristicNotifications(PluginCall call) {
635
+ String deviceId = call.getString("deviceId");
636
+ String serviceUuid = call.getString("service");
637
+ String characteristicUuid = call.getString("characteristic");
638
+
639
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null) {
640
+ call.reject("deviceId, service, and characteristic are required");
641
+ return;
642
+ }
643
+
644
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
645
+ if (gatt == null) {
646
+ call.reject("Device not connected");
647
+ return;
648
+ }
649
+
650
+ BluetoothGattCharacteristic characteristic = findCharacteristic(gatt, serviceUuid, characteristicUuid);
651
+ if (characteristic == null) {
652
+ call.reject("Characteristic not found");
653
+ return;
654
+ }
655
+
656
+ try {
657
+ gatt.setCharacteristicNotification(characteristic, true);
658
+
659
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
660
+ if (descriptor != null) {
661
+ int properties = characteristic.getProperties();
662
+ if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
663
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
664
+ } else {
665
+ descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
666
+ }
667
+ pendingNotifyCall = call;
668
+ gatt.writeDescriptor(descriptor);
669
+ } else {
670
+ call.resolve();
671
+ }
672
+ } catch (SecurityException e) {
673
+ call.reject("Permission denied: " + e.getMessage());
674
+ }
675
+ }
676
+
677
+ @PluginMethod
678
+ public void stopCharacteristicNotifications(PluginCall call) {
679
+ String deviceId = call.getString("deviceId");
680
+ String serviceUuid = call.getString("service");
681
+ String characteristicUuid = call.getString("characteristic");
682
+
683
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null) {
684
+ call.reject("deviceId, service, and characteristic are required");
685
+ return;
686
+ }
687
+
688
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
689
+ if (gatt == null) {
690
+ call.reject("Device not connected");
691
+ return;
692
+ }
693
+
694
+ BluetoothGattCharacteristic characteristic = findCharacteristic(gatt, serviceUuid, characteristicUuid);
695
+ if (characteristic == null) {
696
+ call.reject("Characteristic not found");
697
+ return;
698
+ }
699
+
700
+ try {
701
+ gatt.setCharacteristicNotification(characteristic, false);
702
+
703
+ BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
704
+ if (descriptor != null) {
705
+ descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
706
+ pendingNotifyCall = call;
707
+ gatt.writeDescriptor(descriptor);
708
+ } else {
709
+ call.resolve();
710
+ }
711
+ } catch (SecurityException e) {
712
+ call.reject("Permission denied: " + e.getMessage());
713
+ }
714
+ }
715
+
716
+ @PluginMethod
717
+ public void readDescriptor(PluginCall call) {
718
+ String deviceId = call.getString("deviceId");
719
+ String serviceUuid = call.getString("service");
720
+ String characteristicUuid = call.getString("characteristic");
721
+ String descriptorUuid = call.getString("descriptor");
722
+
723
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null || descriptorUuid == null) {
724
+ call.reject("deviceId, service, characteristic, and descriptor are required");
725
+ return;
726
+ }
727
+
728
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
729
+ if (gatt == null) {
730
+ call.reject("Device not connected");
731
+ return;
732
+ }
733
+
734
+ BluetoothGattDescriptor descriptor = findDescriptor(gatt, serviceUuid, characteristicUuid, descriptorUuid);
735
+ if (descriptor == null) {
736
+ call.reject("Descriptor not found");
737
+ return;
738
+ }
739
+
740
+ pendingReadDescriptorCall = call;
741
+ try {
742
+ gatt.readDescriptor(descriptor);
743
+ } catch (SecurityException e) {
744
+ call.reject("Permission denied: " + e.getMessage());
745
+ }
746
+ }
747
+
748
+ @PluginMethod
749
+ public void writeDescriptor(PluginCall call) {
750
+ String deviceId = call.getString("deviceId");
751
+ String serviceUuid = call.getString("service");
752
+ String characteristicUuid = call.getString("characteristic");
753
+ String descriptorUuid = call.getString("descriptor");
754
+ JSArray valueArray = call.getArray("value");
755
+
756
+ if (deviceId == null || serviceUuid == null || characteristicUuid == null || descriptorUuid == null || valueArray == null) {
757
+ call.reject("deviceId, service, characteristic, descriptor, and value are required");
758
+ return;
759
+ }
760
+
761
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
762
+ if (gatt == null) {
763
+ call.reject("Device not connected");
764
+ return;
765
+ }
766
+
767
+ BluetoothGattDescriptor descriptor = findDescriptor(gatt, serviceUuid, characteristicUuid, descriptorUuid);
768
+ if (descriptor == null) {
769
+ call.reject("Descriptor not found");
770
+ return;
771
+ }
772
+
773
+ try {
774
+ byte[] value = jsArrayToBytes(valueArray);
775
+ descriptor.setValue(value);
776
+ pendingWriteDescriptorCall = call;
777
+ gatt.writeDescriptor(descriptor);
778
+ } catch (Exception e) {
779
+ call.reject("Failed to write: " + e.getMessage());
780
+ }
781
+ }
782
+
783
+ @PluginMethod
784
+ public void readRssi(PluginCall call) {
785
+ String deviceId = call.getString("deviceId");
786
+ if (deviceId == null) {
787
+ call.reject("deviceId is required");
788
+ return;
789
+ }
790
+
791
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
792
+ if (gatt == null) {
793
+ call.reject("Device not connected");
794
+ return;
795
+ }
796
+
797
+ pendingRssiCall = call;
798
+ try {
799
+ gatt.readRemoteRssi();
800
+ } catch (SecurityException e) {
801
+ call.reject("Permission denied: " + e.getMessage());
802
+ }
803
+ }
804
+
805
+ @PluginMethod
806
+ public void requestMtu(PluginCall call) {
807
+ String deviceId = call.getString("deviceId");
808
+ Integer mtu = call.getInt("mtu");
809
+
810
+ if (deviceId == null || mtu == null) {
811
+ call.reject("deviceId and mtu are required");
812
+ return;
813
+ }
814
+
815
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
816
+ if (gatt == null) {
817
+ call.reject("Device not connected");
818
+ return;
819
+ }
820
+
821
+ pendingMtuCall = call;
822
+ try {
823
+ gatt.requestMtu(mtu);
824
+ } catch (SecurityException e) {
825
+ call.reject("Permission denied: " + e.getMessage());
826
+ }
827
+ }
828
+
829
+ @PluginMethod
830
+ public void requestConnectionPriority(PluginCall call) {
831
+ String deviceId = call.getString("deviceId");
832
+ String priority = call.getString("priority", "balanced");
833
+
834
+ if (deviceId == null) {
835
+ call.reject("deviceId is required");
836
+ return;
837
+ }
838
+
839
+ BluetoothGatt gatt = connectedGatts.get(deviceId);
840
+ if (gatt == null) {
841
+ call.reject("Device not connected");
842
+ return;
843
+ }
844
+
845
+ int priorityValue;
846
+ switch (priority) {
847
+ case "high":
848
+ priorityValue = BluetoothGatt.CONNECTION_PRIORITY_HIGH;
849
+ break;
850
+ case "low":
851
+ priorityValue = BluetoothGatt.CONNECTION_PRIORITY_LOW_POWER;
852
+ break;
853
+ default:
854
+ priorityValue = BluetoothGatt.CONNECTION_PRIORITY_BALANCED;
855
+ break;
856
+ }
857
+
858
+ try {
859
+ gatt.requestConnectionPriority(priorityValue);
860
+ call.resolve();
861
+ } catch (SecurityException e) {
862
+ call.reject("Permission denied: " + e.getMessage());
863
+ }
864
+ }
865
+
866
+ @PluginMethod
867
+ public void startAdvertising(PluginCall call) {
868
+ if (bluetoothLeAdvertiser == null) {
869
+ call.reject("Bluetooth advertiser not available");
870
+ return;
871
+ }
872
+
873
+ String name = call.getString("name");
874
+ JSArray servicesArray = call.getArray("services");
875
+
876
+ AdvertiseSettings settings = new AdvertiseSettings.Builder()
877
+ .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
878
+ .setConnectable(true)
879
+ .setTimeout(0)
880
+ .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM)
881
+ .build();
882
+
883
+ AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder()
884
+ .setIncludeDeviceName(name != null);
885
+
886
+ if (servicesArray != null) {
887
+ try {
888
+ for (int i = 0; i < servicesArray.length(); i++) {
889
+ String serviceUuid = servicesArray.getString(i);
890
+ dataBuilder.addServiceUuid(ParcelUuid.fromString(normalizeUuid(serviceUuid)));
891
+ }
892
+ } catch (Exception e) {
893
+ // Ignore
894
+ }
895
+ }
896
+
897
+ advertiseCallback = new AdvertiseCallback() {
898
+ @Override
899
+ public void onStartSuccess(AdvertiseSettings settingsInEffect) {
900
+ // Advertising started
901
+ }
902
+
903
+ @Override
904
+ public void onStartFailure(int errorCode) {
905
+ // Advertising failed
906
+ }
907
+ };
908
+
909
+ try {
910
+ bluetoothLeAdvertiser.startAdvertising(settings, dataBuilder.build(), advertiseCallback);
911
+ call.resolve();
912
+ } catch (SecurityException e) {
913
+ call.reject("Permission denied: " + e.getMessage());
914
+ }
915
+ }
916
+
917
+ @PluginMethod
918
+ public void stopAdvertising(PluginCall call) {
919
+ if (bluetoothLeAdvertiser != null && advertiseCallback != null) {
920
+ try {
921
+ bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
922
+ } catch (SecurityException e) {
923
+ // Ignore
924
+ }
925
+ }
926
+ call.resolve();
927
+ }
928
+
929
+ @PluginMethod
930
+ public void startForegroundService(PluginCall call) {
931
+ // Foreground service implementation would go here
932
+ // This requires additional setup with a ForegroundService class
933
+ call.resolve();
934
+ }
935
+
936
+ @PluginMethod
937
+ public void stopForegroundService(PluginCall call) {
938
+ call.resolve();
939
+ }
940
+
941
+ @PluginMethod
942
+ public void getPluginVersion(PluginCall call) {
943
+ JSObject ret = new JSObject();
944
+ ret.put("version", pluginVersion);
945
+ call.resolve(ret);
946
+ }
947
+
948
+ // MARK: - GATT Callback
949
+
950
+ private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
951
+ @Override
952
+ public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
953
+ String deviceId = gatt.getDevice().getAddress();
954
+
955
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
956
+ if (pendingConnectCall != null) {
957
+ pendingConnectCall.resolve();
958
+ pendingConnectCall = null;
959
+ }
960
+
961
+ JSObject event = new JSObject();
962
+ event.put("deviceId", deviceId);
963
+ notifyListeners("deviceConnected", event);
964
+ } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
965
+ connectedGatts.remove(deviceId);
966
+ deviceServices.remove(deviceId);
967
+
968
+ JSObject event = new JSObject();
969
+ event.put("deviceId", deviceId);
970
+ notifyListeners("deviceDisconnected", event);
971
+ }
972
+ }
973
+
974
+ @Override
975
+ public void onServicesDiscovered(BluetoothGatt gatt, int status) {
976
+ if (pendingDiscoverCall != null) {
977
+ if (status == BluetoothGatt.GATT_SUCCESS) {
978
+ pendingDiscoverCall.resolve();
979
+ } else {
980
+ pendingDiscoverCall.reject("Service discovery failed");
981
+ }
982
+ pendingDiscoverCall = null;
983
+ }
984
+ }
985
+
986
+ @Override
987
+ public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
988
+ if (pendingReadCall != null) {
989
+ if (status == BluetoothGatt.GATT_SUCCESS) {
990
+ JSObject ret = new JSObject();
991
+ ret.put("value", bytesToJsArray(characteristic.getValue()));
992
+ pendingReadCall.resolve(ret);
993
+ } else {
994
+ pendingReadCall.reject("Read failed");
995
+ }
996
+ pendingReadCall = null;
997
+ }
998
+ }
999
+
1000
+ @Override
1001
+ public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
1002
+ if (pendingWriteCall != null) {
1003
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1004
+ pendingWriteCall.resolve();
1005
+ } else {
1006
+ pendingWriteCall.reject("Write failed");
1007
+ }
1008
+ pendingWriteCall = null;
1009
+ }
1010
+ }
1011
+
1012
+ @Override
1013
+ public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
1014
+ String deviceId = gatt.getDevice().getAddress();
1015
+ String serviceUuid = characteristic.getService().getUuid().toString();
1016
+ String characteristicUuid = characteristic.getUuid().toString();
1017
+
1018
+ JSObject event = new JSObject();
1019
+ event.put("deviceId", deviceId);
1020
+ event.put("service", serviceUuid);
1021
+ event.put("characteristic", characteristicUuid);
1022
+ event.put("value", bytesToJsArray(characteristic.getValue()));
1023
+ notifyListeners("characteristicChanged", event);
1024
+ }
1025
+
1026
+ @Override
1027
+ public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
1028
+ if (pendingReadDescriptorCall != null) {
1029
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1030
+ JSObject ret = new JSObject();
1031
+ ret.put("value", bytesToJsArray(descriptor.getValue()));
1032
+ pendingReadDescriptorCall.resolve(ret);
1033
+ } else {
1034
+ pendingReadDescriptorCall.reject("Read failed");
1035
+ }
1036
+ pendingReadDescriptorCall = null;
1037
+ }
1038
+ }
1039
+
1040
+ @Override
1041
+ public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
1042
+ if (pendingNotifyCall != null) {
1043
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1044
+ pendingNotifyCall.resolve();
1045
+ } else {
1046
+ pendingNotifyCall.reject("Failed to enable notifications");
1047
+ }
1048
+ pendingNotifyCall = null;
1049
+ } else if (pendingWriteDescriptorCall != null) {
1050
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1051
+ pendingWriteDescriptorCall.resolve();
1052
+ } else {
1053
+ pendingWriteDescriptorCall.reject("Write failed");
1054
+ }
1055
+ pendingWriteDescriptorCall = null;
1056
+ }
1057
+ }
1058
+
1059
+ @Override
1060
+ public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
1061
+ if (pendingRssiCall != null) {
1062
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1063
+ JSObject ret = new JSObject();
1064
+ ret.put("rssi", rssi);
1065
+ pendingRssiCall.resolve(ret);
1066
+ } else {
1067
+ pendingRssiCall.reject("Failed to read RSSI");
1068
+ }
1069
+ pendingRssiCall = null;
1070
+ }
1071
+ }
1072
+
1073
+ @Override
1074
+ public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
1075
+ if (pendingMtuCall != null) {
1076
+ if (status == BluetoothGatt.GATT_SUCCESS) {
1077
+ JSObject ret = new JSObject();
1078
+ ret.put("mtu", mtu);
1079
+ pendingMtuCall.resolve(ret);
1080
+ } else {
1081
+ pendingMtuCall.reject("Failed to change MTU");
1082
+ }
1083
+ pendingMtuCall = null;
1084
+ }
1085
+ }
1086
+ };
1087
+
1088
+ // MARK: - Helper Methods
1089
+
1090
+ private boolean hasBlePermissions() {
1091
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1092
+ return ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED &&
1093
+ ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED;
1094
+ } else {
1095
+ return ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
1096
+ }
1097
+ }
1098
+
1099
+ private BluetoothGattCharacteristic findCharacteristic(BluetoothGatt gatt, String serviceUuid, String characteristicUuid) {
1100
+ BluetoothGattService service = gatt.getService(UUID.fromString(normalizeUuid(serviceUuid)));
1101
+ if (service == null) {
1102
+ return null;
1103
+ }
1104
+ return service.getCharacteristic(UUID.fromString(normalizeUuid(characteristicUuid)));
1105
+ }
1106
+
1107
+ private BluetoothGattDescriptor findDescriptor(BluetoothGatt gatt, String serviceUuid, String characteristicUuid, String descriptorUuid) {
1108
+ BluetoothGattCharacteristic characteristic = findCharacteristic(gatt, serviceUuid, characteristicUuid);
1109
+ if (characteristic == null) {
1110
+ return null;
1111
+ }
1112
+ return characteristic.getDescriptor(UUID.fromString(normalizeUuid(descriptorUuid)));
1113
+ }
1114
+
1115
+ private String normalizeUuid(String uuid) {
1116
+ if (uuid.length() == 4) {
1117
+ return "0000" + uuid.toLowerCase() + "-0000-1000-8000-00805f9b34fb";
1118
+ } else if (uuid.length() == 8) {
1119
+ return uuid.toLowerCase() + "-0000-1000-8000-00805f9b34fb";
1120
+ }
1121
+ return uuid.toLowerCase();
1122
+ }
1123
+
1124
+ private String bytesToHex(byte[] bytes) {
1125
+ StringBuilder sb = new StringBuilder();
1126
+ for (byte b : bytes) {
1127
+ sb.append(String.format("%02x", b));
1128
+ }
1129
+ return sb.toString();
1130
+ }
1131
+
1132
+ private byte[] jsArrayToBytes(JSArray array) throws Exception {
1133
+ byte[] bytes = new byte[array.length()];
1134
+ for (int i = 0; i < array.length(); i++) {
1135
+ bytes[i] = (byte) array.getInt(i);
1136
+ }
1137
+ return bytes;
1138
+ }
1139
+
1140
+ private JSArray bytesToJsArray(byte[] bytes) {
1141
+ JSArray array = new JSArray();
1142
+ if (bytes != null) {
1143
+ for (byte b : bytes) {
1144
+ array.put(b & 0xFF);
1145
+ }
1146
+ }
1147
+ return array;
1148
+ }
1149
+ }