@capgo/capacitor-bluetooth-low-energy 8.2.10 → 8.2.12

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.
package/README.md CHANGED
@@ -188,6 +188,7 @@ Current native limitation: `requestDevice()` resolves the first matching scanned
188
188
  * [`addListener('characteristicChanged', ...)`](#addlistenercharacteristicchanged-)
189
189
  * [`addListener('centralConnected', ...)`](#addlistenercentralconnected-)
190
190
  * [`addListener('centralDisconnected', ...)`](#addlistenercentraldisconnected-)
191
+ * [`addListener('adapterStateChanged', ...)`](#addlisteneradapterstatechanged-)
191
192
  * [`addListener('gattCharacteristicReadRequest', ...)`](#addlistenergattcharacteristicreadrequest-)
192
193
  * [`addListener('gattCharacteristicWriteRequest', ...)`](#addlistenergattcharacteristicwriterequest-)
193
194
  * [`removeAllListeners()`](#removealllisteners)
@@ -923,6 +924,26 @@ Add a listener for central disconnected events (peripheral mode).
923
924
  --------------------
924
925
 
925
926
 
927
+ ### addListener('adapterStateChanged', ...)
928
+
929
+ ```typescript
930
+ addListener(eventName: 'adapterStateChanged', listenerFunc: (event: AdapterStateChangedEvent) => void) => Promise<PluginListenerHandle>
931
+ ```
932
+
933
+ Add a listener for Bluetooth adapter power state changes.
934
+
935
+ | Param | Type | Description |
936
+ | ------------------ | ------------------------------------------------------------------------------------------------- | ----------------------- |
937
+ | **`eventName`** | <code>'adapterStateChanged'</code> | - The event name |
938
+ | **`listenerFunc`** | <code>(event: <a href="#adapterstatechangedevent">AdapterStateChangedEvent</a>) =&gt; void</code> | - The listener function |
939
+
940
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
941
+
942
+ **Since:** 8.2.11
943
+
944
+ --------------------
945
+
946
+
926
947
  ### addListener('gattCharacteristicReadRequest', ...)
927
948
 
928
949
  ```typescript
@@ -1474,6 +1495,15 @@ Event emitted when a central disconnects from the local GATT server.
1474
1495
  | **`deviceId`** | <code>string</code> | The central device ID. | 8.2.0 |
1475
1496
 
1476
1497
 
1498
+ #### AdapterStateChangedEvent
1499
+
1500
+ Event emitted when the Bluetooth adapter is turned on or off.
1501
+
1502
+ | Prop | Type | Description | Since |
1503
+ | ------------- | -------------------- | -------------------------------------------------- | ------ |
1504
+ | **`enabled`** | <code>boolean</code> | Whether Bluetooth is enabled (adapter powered on). | 8.2.11 |
1505
+
1506
+
1477
1507
  #### GattCharacteristicReadRequestEvent
1478
1508
 
1479
1509
  Event emitted when a central reads a local GATT characteristic.
@@ -21,8 +21,10 @@ import android.bluetooth.le.ScanCallback;
21
21
  import android.bluetooth.le.ScanFilter;
22
22
  import android.bluetooth.le.ScanResult;
23
23
  import android.bluetooth.le.ScanSettings;
24
+ import android.content.BroadcastReceiver;
24
25
  import android.content.Context;
25
26
  import android.content.Intent;
27
+ import android.content.IntentFilter;
26
28
  import android.content.pm.PackageManager;
27
29
  import android.location.LocationManager;
28
30
  import android.os.Build;
@@ -77,7 +79,7 @@ import java.util.UUID;
77
79
  )
78
80
  public class BluetoothLowEnergyPlugin extends Plugin {
79
81
 
80
- private final String pluginVersion = "8.2.10";
82
+ private final String pluginVersion = "8.2.12";
81
83
  private BluetoothManager bluetoothManager;
82
84
  private BluetoothAdapter bluetoothAdapter;
83
85
  private BluetoothLeScanner bluetoothLeScanner;
@@ -113,6 +115,9 @@ public class BluetoothLowEnergyPlugin extends Plugin {
113
115
 
114
116
  private static final UUID CLIENT_CHARACTERISTIC_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
115
117
 
118
+ private BroadcastReceiver bluetoothStateReceiver;
119
+ private final Object peripheralStateLock = new Object();
120
+
116
121
  @Override
117
122
  public void load() {
118
123
  bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE);
@@ -120,6 +125,34 @@ public class BluetoothLowEnergyPlugin extends Plugin {
120
125
  bluetoothAdapter = bluetoothManager.getAdapter();
121
126
  }
122
127
  scanHandler = new Handler(Looper.getMainLooper());
128
+ bluetoothStateReceiver = new BroadcastReceiver() {
129
+ @Override
130
+ public void onReceive(Context context, Intent intent) {
131
+ if (!BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
132
+ return;
133
+ }
134
+ int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
135
+ if (state == BluetoothAdapter.STATE_OFF) {
136
+ adapterStateChanged(false);
137
+ } else if (state == BluetoothAdapter.STATE_ON) {
138
+ adapterStateChanged(true);
139
+ }
140
+ }
141
+ };
142
+ IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
143
+ getContext().registerReceiver(bluetoothStateReceiver, filter);
144
+ }
145
+
146
+ @Override
147
+ protected void handleOnDestroy() {
148
+ if (bluetoothStateReceiver != null) {
149
+ try {
150
+ getContext().unregisterReceiver(bluetoothStateReceiver);
151
+ } catch (IllegalArgumentException e) {
152
+ // Receiver was not registered
153
+ }
154
+ bluetoothStateReceiver = null;
155
+ }
123
156
  }
124
157
 
125
158
  @PluginMethod
@@ -965,7 +998,7 @@ public class BluetoothLowEnergyPlugin extends Plugin {
965
998
  }
966
999
  }
967
1000
 
968
- advertiseCallback = new AdvertiseCallback() {
1001
+ AdvertiseCallback callback = new AdvertiseCallback() {
969
1002
  @Override
970
1003
  public void onStartSuccess(AdvertiseSettings settingsInEffect) {
971
1004
  // Advertising started
@@ -978,31 +1011,40 @@ public class BluetoothLowEnergyPlugin extends Plugin {
978
1011
  }
979
1012
  };
980
1013
 
981
- try {
982
- bluetoothLeAdvertiser.startAdvertising(settings, dataBuilder.build(), advertiseCallback);
983
- call.resolve();
984
- } catch (SecurityException e) {
985
- restoreBluetoothAdapterNameIfNeeded();
986
- advertiseCallback = null;
987
- call.reject("Permission denied: " + e.getMessage());
988
- } catch (IllegalStateException e) {
1014
+ String rejectMessage = null;
1015
+ synchronized (peripheralStateLock) {
1016
+ advertiseCallback = callback;
1017
+ try {
1018
+ bluetoothLeAdvertiser.startAdvertising(settings, dataBuilder.build(), advertiseCallback);
1019
+ } catch (SecurityException e) {
1020
+ advertiseCallback = null;
1021
+ rejectMessage = "Permission denied: " + e.getMessage();
1022
+ } catch (IllegalStateException e) {
1023
+ advertiseCallback = null;
1024
+ rejectMessage = "Bluetooth is off: " + e.getMessage();
1025
+ }
1026
+ }
1027
+ if (rejectMessage != null) {
989
1028
  restoreBluetoothAdapterNameIfNeeded();
990
- advertiseCallback = null;
991
- call.reject("Bluetooth is off: " + e.getMessage());
1029
+ call.reject(rejectMessage);
1030
+ } else {
1031
+ call.resolve();
992
1032
  }
993
1033
  }
994
1034
 
995
1035
  @PluginMethod
996
1036
  public void stopAdvertising(PluginCall call) {
997
- if (bluetoothLeAdvertiser != null && advertiseCallback != null) {
998
- try {
999
- bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
1000
- } catch (SecurityException e) {
1001
- // Ignore
1002
- } catch (IllegalStateException e) {
1003
- // Ignore when adapter is off
1037
+ synchronized (peripheralStateLock) {
1038
+ if (bluetoothLeAdvertiser != null && advertiseCallback != null) {
1039
+ try {
1040
+ bluetoothLeAdvertiser.stopAdvertising(advertiseCallback);
1041
+ } catch (SecurityException e) {
1042
+ // Ignore
1043
+ } catch (IllegalStateException e) {
1044
+ // Ignore when adapter is off
1045
+ }
1046
+ advertiseCallback = null;
1004
1047
  }
1005
- advertiseCallback = null;
1006
1048
  }
1007
1049
  restoreBluetoothAdapterNameIfNeeded();
1008
1050
  call.resolve();
@@ -1028,96 +1070,102 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1028
1070
  return;
1029
1071
  }
1030
1072
 
1073
+ String rejectMessage = null;
1031
1074
  try {
1032
- ensureGattServer();
1033
- if (gattServer == null) {
1034
- call.reject("Failed to open GATT server");
1035
- return;
1036
- }
1037
-
1038
- String normalizedServiceUuid = normalizeUuid(serviceUuid);
1039
- if (localGattServices.containsKey(normalizedServiceUuid)) {
1040
- call.reject("Service already exists");
1041
- return;
1042
- }
1043
-
1044
- BluetoothGattService service = new BluetoothGattService(
1045
- UUID.fromString(normalizedServiceUuid),
1046
- BluetoothGattService.SERVICE_TYPE_PRIMARY
1047
- );
1048
-
1049
- for (int i = 0; i < characteristicsArray.length(); i++) {
1050
- JSObject characteristicObj = JSObject.fromJSONObject(characteristicsArray.getJSONObject(i));
1051
- if (characteristicObj == null) {
1052
- continue;
1053
- }
1054
-
1055
- String characteristicUuid = characteristicObj.getString("uuid");
1056
- if (characteristicUuid == null) {
1057
- call.reject("Characteristic UUID is required");
1058
- return;
1059
- }
1060
-
1061
- JSObject propertiesObj = characteristicObj.getJSObject("properties");
1062
- int properties = parseCharacteristicProperties(propertiesObj);
1063
- int permissions = parseCharacteristicPermissions(propertiesObj);
1064
-
1065
- BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(
1066
- UUID.fromString(normalizeUuid(characteristicUuid)),
1067
- properties,
1068
- permissions
1069
- );
1070
-
1071
- JSArray valueArray = characteristicObj.has("value") ? JSArray.from(characteristicObj.getJSONArray("value")) : null;
1072
- if (valueArray != null) {
1073
- characteristic.setValue(jsArrayToBytes(valueArray));
1074
- }
1075
-
1076
- if (propertiesObj != null && (propertiesObj.getBoolean("notify", false) || propertiesObj.getBoolean("indicate", false))) {
1077
- BluetoothGattDescriptor ccc = new BluetoothGattDescriptor(
1078
- CLIENT_CHARACTERISTIC_CONFIG,
1079
- BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE
1080
- );
1081
- characteristic.addDescriptor(ccc);
1082
- }
1075
+ synchronized (peripheralStateLock) {
1076
+ ensureGattServer();
1077
+ if (gattServer == null) {
1078
+ rejectMessage = "Failed to open GATT server";
1079
+ } else {
1080
+ String normalizedServiceUuid = normalizeUuid(serviceUuid);
1081
+ if (localGattServices.containsKey(normalizedServiceUuid)) {
1082
+ rejectMessage = "Service already exists";
1083
+ } else {
1084
+ BluetoothGattService service = new BluetoothGattService(
1085
+ UUID.fromString(normalizedServiceUuid),
1086
+ BluetoothGattService.SERVICE_TYPE_PRIMARY
1087
+ );
1083
1088
 
1084
- JSArray descriptorsArray = characteristicObj.has("descriptors") ? JSArray.from(characteristicObj.getJSONArray("descriptors")) : null;
1085
- if (descriptorsArray != null) {
1086
- for (int j = 0; j < descriptorsArray.length(); j++) {
1087
- JSObject descriptorObj = JSObject.fromJSONObject(descriptorsArray.getJSONObject(j));
1088
- if (descriptorObj == null) {
1089
- continue;
1090
- }
1091
- String descriptorUuid = descriptorObj.getString("uuid");
1092
- if (descriptorUuid == null) {
1093
- continue;
1089
+ for (int i = 0; i < characteristicsArray.length() && rejectMessage == null; i++) {
1090
+ JSObject characteristicObj = JSObject.fromJSONObject(characteristicsArray.getJSONObject(i));
1091
+ if (characteristicObj == null) {
1092
+ continue;
1093
+ }
1094
+
1095
+ String characteristicUuid = characteristicObj.getString("uuid");
1096
+ if (characteristicUuid == null) {
1097
+ rejectMessage = "Characteristic UUID is required";
1098
+ break;
1099
+ }
1100
+
1101
+ JSObject propertiesObj = characteristicObj.getJSObject("properties");
1102
+ int properties = parseCharacteristicProperties(propertiesObj);
1103
+ int permissions = parseCharacteristicPermissions(propertiesObj);
1104
+
1105
+ BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(
1106
+ UUID.fromString(normalizeUuid(characteristicUuid)),
1107
+ properties,
1108
+ permissions
1109
+ );
1110
+
1111
+ JSArray valueArray = characteristicObj.has("value") ? JSArray.from(characteristicObj.getJSONArray("value")) : null;
1112
+ if (valueArray != null) {
1113
+ characteristic.setValue(jsArrayToBytes(valueArray));
1114
+ }
1115
+
1116
+ if (propertiesObj != null && (propertiesObj.getBoolean("notify", false) || propertiesObj.getBoolean("indicate", false))) {
1117
+ BluetoothGattDescriptor ccc = new BluetoothGattDescriptor(
1118
+ CLIENT_CHARACTERISTIC_CONFIG,
1119
+ BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE
1120
+ );
1121
+ characteristic.addDescriptor(ccc);
1122
+ }
1123
+
1124
+ JSArray descriptorsArray = characteristicObj.has("descriptors") ? JSArray.from(characteristicObj.getJSONArray("descriptors")) : null;
1125
+ if (descriptorsArray != null) {
1126
+ for (int j = 0; j < descriptorsArray.length(); j++) {
1127
+ JSObject descriptorObj = JSObject.fromJSONObject(descriptorsArray.getJSONObject(j));
1128
+ if (descriptorObj == null) {
1129
+ continue;
1130
+ }
1131
+ String descriptorUuid = descriptorObj.getString("uuid");
1132
+ if (descriptorUuid == null) {
1133
+ continue;
1134
+ }
1135
+ BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
1136
+ UUID.fromString(normalizeUuid(descriptorUuid)),
1137
+ BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE
1138
+ );
1139
+ JSArray descriptorValue = descriptorObj.has("value") ? JSArray.from(descriptorObj.getJSONArray("value")) : null;
1140
+ if (descriptorValue != null) {
1141
+ descriptor.setValue(jsArrayToBytes(descriptorValue));
1142
+ }
1143
+ characteristic.addDescriptor(descriptor);
1144
+ }
1145
+ }
1146
+
1147
+ service.addCharacteristic(characteristic);
1148
+ localGattCharacteristics.put(normalizedServiceUuid + "/" + normalizeUuid(characteristicUuid), characteristic);
1094
1149
  }
1095
- BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(
1096
- UUID.fromString(normalizeUuid(descriptorUuid)),
1097
- BluetoothGattDescriptor.PERMISSION_READ | BluetoothGattDescriptor.PERMISSION_WRITE
1098
- );
1099
- JSArray descriptorValue = descriptorObj.has("value") ? JSArray.from(descriptorObj.getJSONArray("value")) : null;
1100
- if (descriptorValue != null) {
1101
- descriptor.setValue(jsArrayToBytes(descriptorValue));
1150
+
1151
+ if (rejectMessage == null) {
1152
+ boolean added = gattServer.addService(service);
1153
+ if (!added) {
1154
+ rejectMessage = "Failed to add GATT service";
1155
+ } else {
1156
+ localGattServices.put(normalizedServiceUuid, service);
1157
+ }
1102
1158
  }
1103
- characteristic.addDescriptor(descriptor);
1104
1159
  }
1105
1160
  }
1106
-
1107
- service.addCharacteristic(characteristic);
1108
- localGattCharacteristics.put(normalizedServiceUuid + "/" + normalizeUuid(characteristicUuid), characteristic);
1109
1161
  }
1110
-
1111
- boolean added = gattServer.addService(service);
1112
- if (!added) {
1113
- call.reject("Failed to add GATT service");
1114
- return;
1115
- }
1116
-
1117
- localGattServices.put(normalizedServiceUuid, service);
1118
- call.resolve();
1119
1162
  } catch (Exception e) {
1120
- call.reject("Failed to add GATT service: " + e.getMessage());
1163
+ rejectMessage = "Failed to add GATT service: " + e.getMessage();
1164
+ }
1165
+ if (rejectMessage != null) {
1166
+ call.reject(rejectMessage);
1167
+ } else {
1168
+ call.resolve();
1121
1169
  }
1122
1170
  }
1123
1171
 
@@ -1129,21 +1177,26 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1129
1177
  return;
1130
1178
  }
1131
1179
 
1132
- if (gattServer == null) {
1133
- call.reject("GATT server is not initialized");
1134
- return;
1180
+ String rejectMessage = null;
1181
+ synchronized (peripheralStateLock) {
1182
+ if (gattServer == null) {
1183
+ rejectMessage = "GATT server is not initialized";
1184
+ } else {
1185
+ String normalizedServiceUuid = normalizeUuid(serviceUuid);
1186
+ BluetoothGattService service = localGattServices.remove(normalizedServiceUuid);
1187
+ if (service == null) {
1188
+ rejectMessage = "Service not found";
1189
+ } else {
1190
+ localGattCharacteristics.entrySet().removeIf(entry -> entry.getKey().startsWith(normalizedServiceUuid + "/"));
1191
+ gattServer.removeService(service);
1192
+ }
1193
+ }
1135
1194
  }
1136
-
1137
- String normalizedServiceUuid = normalizeUuid(serviceUuid);
1138
- BluetoothGattService service = localGattServices.remove(normalizedServiceUuid);
1139
- if (service == null) {
1140
- call.reject("Service not found");
1141
- return;
1195
+ if (rejectMessage != null) {
1196
+ call.reject(rejectMessage);
1197
+ } else {
1198
+ call.resolve();
1142
1199
  }
1143
-
1144
- localGattCharacteristics.entrySet().removeIf(entry -> entry.getKey().startsWith(normalizedServiceUuid + "/"));
1145
- gattServer.removeService(service);
1146
- call.resolve();
1147
1200
  }
1148
1201
 
1149
1202
  @PluginMethod
@@ -1157,19 +1210,26 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1157
1210
  return;
1158
1211
  }
1159
1212
 
1160
- BluetoothGattCharacteristic characteristic = localGattCharacteristics.get(
1161
- normalizeUuid(serviceUuid) + "/" + normalizeUuid(characteristicUuid)
1162
- );
1163
- if (characteristic == null) {
1164
- call.reject("Characteristic not found");
1165
- return;
1166
- }
1167
-
1213
+ String rejectMessage = null;
1168
1214
  try {
1169
- characteristic.setValue(jsArrayToBytes(valueArray));
1170
- call.resolve();
1215
+ synchronized (peripheralStateLock) {
1216
+ BluetoothGattCharacteristic characteristic = localGattCharacteristics.get(
1217
+ normalizeUuid(serviceUuid) + "/" + normalizeUuid(characteristicUuid)
1218
+ );
1219
+ if (characteristic == null) {
1220
+ rejectMessage = "Characteristic not found";
1221
+ } else {
1222
+ characteristic.setValue(jsArrayToBytes(valueArray));
1223
+ }
1224
+ }
1171
1225
  } catch (Exception e) {
1172
1226
  call.reject("Failed to set characteristic value: " + e.getMessage());
1227
+ return;
1228
+ }
1229
+ if (rejectMessage != null) {
1230
+ call.reject(rejectMessage);
1231
+ } else {
1232
+ call.resolve();
1173
1233
  }
1174
1234
  }
1175
1235
 
@@ -1185,37 +1245,43 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1185
1245
  return;
1186
1246
  }
1187
1247
 
1188
- if (gattServer == null) {
1189
- call.reject("GATT server is not initialized");
1190
- return;
1191
- }
1192
-
1193
- BluetoothGattCharacteristic characteristic = localGattCharacteristics.get(
1194
- normalizeUuid(serviceUuid) + "/" + normalizeUuid(characteristicUuid)
1195
- );
1196
- if (characteristic == null) {
1197
- call.reject("Characteristic not found");
1198
- return;
1199
- }
1200
-
1248
+ String rejectMessage = null;
1201
1249
  try {
1202
- characteristic.setValue(jsArrayToBytes(valueArray));
1203
- boolean indicate = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0;
1204
- if (deviceId != null) {
1205
- BluetoothDevice device = connectedCentrals.get(deviceId);
1206
- if (device == null) {
1207
- call.reject("Central not connected");
1208
- return;
1209
- }
1210
- gattServer.notifyCharacteristicChanged(device, characteristic, indicate);
1211
- } else {
1212
- for (BluetoothDevice device : connectedCentrals.values()) {
1213
- gattServer.notifyCharacteristicChanged(device, characteristic, indicate);
1250
+ synchronized (peripheralStateLock) {
1251
+ if (gattServer == null) {
1252
+ rejectMessage = "GATT server is not initialized";
1253
+ } else {
1254
+ BluetoothGattCharacteristic characteristic = localGattCharacteristics.get(
1255
+ normalizeUuid(serviceUuid) + "/" + normalizeUuid(characteristicUuid)
1256
+ );
1257
+ if (characteristic == null) {
1258
+ rejectMessage = "Characteristic not found";
1259
+ } else {
1260
+ characteristic.setValue(jsArrayToBytes(valueArray));
1261
+ boolean indicate = (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0;
1262
+ if (deviceId != null) {
1263
+ BluetoothDevice device = connectedCentrals.get(deviceId);
1264
+ if (device == null) {
1265
+ rejectMessage = "Central not connected";
1266
+ } else {
1267
+ gattServer.notifyCharacteristicChanged(device, characteristic, indicate);
1268
+ }
1269
+ } else {
1270
+ for (BluetoothDevice device : new ArrayList<>(connectedCentrals.values())) {
1271
+ gattServer.notifyCharacteristicChanged(device, characteristic, indicate);
1272
+ }
1273
+ }
1274
+ }
1214
1275
  }
1215
1276
  }
1216
- call.resolve();
1217
1277
  } catch (Exception e) {
1218
1278
  call.reject("Failed to notify characteristic change: " + e.getMessage());
1279
+ return;
1280
+ }
1281
+ if (rejectMessage != null) {
1282
+ call.reject(rejectMessage);
1283
+ } else {
1284
+ call.resolve();
1219
1285
  }
1220
1286
  }
1221
1287
 
@@ -1479,17 +1545,56 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1479
1545
 
1480
1546
 
1481
1547
  private void ensureGattServer() {
1482
- if (gattServer == null && bluetoothManager != null) {
1483
- try {
1484
- gattServer = bluetoothManager.openGattServer(getContext(), gattServerCallback);
1485
- } catch (SecurityException e) {
1486
- // Ignore
1487
- } catch (IllegalStateException e) {
1488
- // Ignore when adapter is off
1548
+ synchronized (peripheralStateLock) {
1549
+ if (gattServer == null && bluetoothManager != null) {
1550
+ try {
1551
+ gattServer = bluetoothManager.openGattServer(getContext(), gattServerCallback);
1552
+ } catch (SecurityException e) {
1553
+ // Ignore
1554
+ } catch (IllegalStateException e) {
1555
+ // Ignore when adapter is off
1556
+ }
1489
1557
  }
1490
1558
  }
1491
1559
  }
1492
1560
 
1561
+ private void adapterStateChanged(boolean enabled) {
1562
+ List<String> disconnectedCentralIds = new ArrayList<>();
1563
+ synchronized (peripheralStateLock) {
1564
+ if (!enabled) {
1565
+ if (gattServer != null) {
1566
+ try {
1567
+ gattServer.close();
1568
+ } catch (SecurityException e) {
1569
+ // Ignore
1570
+ }
1571
+ gattServer = null;
1572
+ }
1573
+ localGattServices.clear();
1574
+ localGattCharacteristics.clear();
1575
+ advertiseCallback = null;
1576
+ disconnectedCentralIds.addAll(connectedCentrals.keySet());
1577
+ connectedCentrals.clear();
1578
+ } else if (bluetoothAdapter != null) {
1579
+ if ("central".equals(mode) && bluetoothLeScanner == null) {
1580
+ bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
1581
+ } else if ("peripheral".equals(mode) && bluetoothLeAdvertiser == null) {
1582
+ bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
1583
+ }
1584
+ }
1585
+ }
1586
+
1587
+ for (String deviceId : disconnectedCentralIds) {
1588
+ JSObject centralEvent = new JSObject();
1589
+ centralEvent.put("deviceId", deviceId);
1590
+ notifyListeners("centralDisconnected", centralEvent);
1591
+ }
1592
+
1593
+ JSObject event = new JSObject();
1594
+ event.put("enabled", enabled);
1595
+ notifyListeners("adapterStateChanged", event);
1596
+ }
1597
+
1493
1598
  private int parseCharacteristicProperties(JSObject propertiesObj) {
1494
1599
  int properties = 0;
1495
1600
  if (propertiesObj == null) {
@@ -1537,34 +1642,43 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1537
1642
  }
1538
1643
 
1539
1644
  private String characteristicKey(BluetoothGattCharacteristic characteristic) {
1540
- for (Map.Entry<String, BluetoothGattCharacteristic> entry : localGattCharacteristics.entrySet()) {
1541
- if (entry.getValue().equals(characteristic)) {
1542
- return entry.getKey();
1645
+ synchronized (peripheralStateLock) {
1646
+ for (Map.Entry<String, BluetoothGattCharacteristic> entry : localGattCharacteristics.entrySet()) {
1647
+ if (entry.getValue().equals(characteristic)) {
1648
+ return entry.getKey();
1649
+ }
1543
1650
  }
1651
+ return null;
1544
1652
  }
1545
- return null;
1546
1653
  }
1547
1654
 
1548
1655
  private final BluetoothGattServerCallback gattServerCallback = new BluetoothGattServerCallback() {
1549
1656
  @Override
1550
1657
  public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
1551
1658
  String deviceId = device.getAddress();
1552
- if (newState == BluetoothProfile.STATE_CONNECTED) {
1553
- connectedCentrals.put(deviceId, device);
1554
- JSObject event = new JSObject();
1555
- event.put("deviceId", deviceId);
1556
- notifyListeners("centralConnected", event);
1557
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
1558
- connectedCentrals.remove(deviceId);
1559
- JSObject event = new JSObject();
1560
- event.put("deviceId", deviceId);
1561
- notifyListeners("centralDisconnected", event);
1659
+ boolean connected = newState == BluetoothProfile.STATE_CONNECTED;
1660
+ boolean disconnected = newState == BluetoothProfile.STATE_DISCONNECTED;
1661
+ if (!connected && !disconnected) {
1662
+ return;
1562
1663
  }
1664
+ synchronized (peripheralStateLock) {
1665
+ if (connected) {
1666
+ connectedCentrals.put(deviceId, device);
1667
+ } else {
1668
+ connectedCentrals.remove(deviceId);
1669
+ }
1670
+ }
1671
+ JSObject event = new JSObject();
1672
+ event.put("deviceId", deviceId);
1673
+ notifyListeners(connected ? "centralConnected" : "centralDisconnected", event);
1563
1674
  }
1564
1675
 
1565
1676
  @Override
1566
1677
  public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
1567
- String key = characteristicKey(characteristic);
1678
+ String key;
1679
+ synchronized (peripheralStateLock) {
1680
+ key = characteristicKey(characteristic);
1681
+ }
1568
1682
  if (key != null) {
1569
1683
  String[] parts = key.split("/", 2);
1570
1684
  JSObject event = new JSObject();
@@ -1574,12 +1688,14 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1574
1688
  notifyListeners("gattCharacteristicReadRequest", event);
1575
1689
  }
1576
1690
 
1577
- if (gattServer != null) {
1578
- byte[] value = characteristic.getValue();
1579
- if (value == null) {
1580
- value = new byte[0];
1691
+ synchronized (peripheralStateLock) {
1692
+ if (gattServer != null) {
1693
+ byte[] value = characteristic.getValue();
1694
+ if (value == null) {
1695
+ value = new byte[0];
1696
+ }
1697
+ gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1581
1698
  }
1582
- gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1583
1699
  }
1584
1700
  }
1585
1701
 
@@ -1593,8 +1709,11 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1593
1709
  int offset,
1594
1710
  byte[] value
1595
1711
  ) {
1596
- characteristic.setValue(value);
1597
- String key = characteristicKey(characteristic);
1712
+ String key;
1713
+ synchronized (peripheralStateLock) {
1714
+ characteristic.setValue(value);
1715
+ key = characteristicKey(characteristic);
1716
+ }
1598
1717
  if (key != null) {
1599
1718
  String[] parts = key.split("/", 2);
1600
1719
  JSObject event = new JSObject();
@@ -1605,8 +1724,12 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1605
1724
  notifyListeners("gattCharacteristicWriteRequest", event);
1606
1725
  }
1607
1726
 
1608
- if (responseNeeded && gattServer != null) {
1609
- gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1727
+ if (responseNeeded) {
1728
+ synchronized (peripheralStateLock) {
1729
+ if (gattServer != null) {
1730
+ gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1731
+ }
1732
+ }
1610
1733
  }
1611
1734
  }
1612
1735
 
@@ -1620,9 +1743,11 @@ public class BluetoothLowEnergyPlugin extends Plugin {
1620
1743
  int offset,
1621
1744
  byte[] value
1622
1745
  ) {
1623
- descriptor.setValue(value);
1624
- if (responseNeeded && gattServer != null) {
1625
- gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1746
+ synchronized (peripheralStateLock) {
1747
+ descriptor.setValue(value);
1748
+ if (responseNeeded && gattServer != null) {
1749
+ gattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
1750
+ }
1626
1751
  }
1627
1752
  }
1628
1753
  };
package/dist/docs.json CHANGED
@@ -1391,6 +1391,47 @@
1391
1391
  ],
1392
1392
  "slug": "addlistenercentraldisconnected-"
1393
1393
  },
1394
+ {
1395
+ "name": "addListener",
1396
+ "signature": "(eventName: 'adapterStateChanged', listenerFunc: (event: AdapterStateChangedEvent) => void) => Promise<PluginListenerHandle>",
1397
+ "parameters": [
1398
+ {
1399
+ "name": "eventName",
1400
+ "docs": "- The event name",
1401
+ "type": "'adapterStateChanged'"
1402
+ },
1403
+ {
1404
+ "name": "listenerFunc",
1405
+ "docs": "- The listener function",
1406
+ "type": "(event: AdapterStateChangedEvent) => void"
1407
+ }
1408
+ ],
1409
+ "returns": "Promise<PluginListenerHandle>",
1410
+ "tags": [
1411
+ {
1412
+ "name": "param",
1413
+ "text": "eventName - The event name"
1414
+ },
1415
+ {
1416
+ "name": "param",
1417
+ "text": "listenerFunc - The listener function"
1418
+ },
1419
+ {
1420
+ "name": "returns",
1421
+ "text": "Promise that resolves with a handle to remove the listener"
1422
+ },
1423
+ {
1424
+ "name": "since",
1425
+ "text": "8.2.11"
1426
+ }
1427
+ ],
1428
+ "docs": "Add a listener for Bluetooth adapter power state changes.",
1429
+ "complexTypes": [
1430
+ "PluginListenerHandle",
1431
+ "AdapterStateChangedEvent"
1432
+ ],
1433
+ "slug": "addlisteneradapterstatechanged-"
1434
+ },
1394
1435
  {
1395
1436
  "name": "addListener",
1396
1437
  "signature": "(eventName: 'gattCharacteristicReadRequest', listenerFunc: (event: GattCharacteristicReadRequestEvent) => void) => Promise<PluginListenerHandle>",
@@ -3486,6 +3527,32 @@
3486
3527
  }
3487
3528
  ]
3488
3529
  },
3530
+ {
3531
+ "name": "AdapterStateChangedEvent",
3532
+ "slug": "adapterstatechangedevent",
3533
+ "docs": "Event emitted when the Bluetooth adapter is turned on or off.",
3534
+ "tags": [
3535
+ {
3536
+ "text": "8.2.11",
3537
+ "name": "since"
3538
+ }
3539
+ ],
3540
+ "methods": [],
3541
+ "properties": [
3542
+ {
3543
+ "name": "enabled",
3544
+ "tags": [
3545
+ {
3546
+ "text": "8.2.11",
3547
+ "name": "since"
3548
+ }
3549
+ ],
3550
+ "docs": "Whether Bluetooth is enabled (adapter powered on).",
3551
+ "complexTypes": [],
3552
+ "type": "boolean"
3553
+ }
3554
+ ]
3555
+ },
3489
3556
  {
3490
3557
  "name": "GattCharacteristicReadRequestEvent",
3491
3558
  "slug": "gattcharacteristicreadrequestevent",
@@ -530,6 +530,15 @@ export interface BluetoothLowEnergyPlugin {
530
530
  * @since 8.2.0
531
531
  */
532
532
  addListener(eventName: 'centralDisconnected', listenerFunc: (event: CentralDisconnectedEvent) => void): Promise<PluginListenerHandle>;
533
+ /**
534
+ * Add a listener for Bluetooth adapter power state changes.
535
+ *
536
+ * @param eventName - The event name
537
+ * @param listenerFunc - The listener function
538
+ * @returns Promise that resolves with a handle to remove the listener
539
+ * @since 8.2.11
540
+ */
541
+ addListener(eventName: 'adapterStateChanged', listenerFunc: (event: AdapterStateChangedEvent) => void): Promise<PluginListenerHandle>;
533
542
  /**
534
543
  * Add a listener for GATT characteristic read requests (peripheral mode).
535
544
  *
@@ -1542,6 +1551,19 @@ export interface CentralDisconnectedEvent {
1542
1551
  */
1543
1552
  deviceId: string;
1544
1553
  }
1554
+ /**
1555
+ * Event emitted when the Bluetooth adapter is turned on or off.
1556
+ *
1557
+ * @since 8.2.11
1558
+ */
1559
+ export interface AdapterStateChangedEvent {
1560
+ /**
1561
+ * Whether Bluetooth is enabled (adapter powered on).
1562
+ *
1563
+ * @since 8.2.11
1564
+ */
1565
+ enabled: boolean;
1566
+ }
1545
1567
  /**
1546
1568
  * Event emitted when a central reads a local GATT characteristic.
1547
1569
  *
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"AAwvDA,MAAM,OAAO,uBAAuB;IAClC;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,iBAAiB,CAAC,KAAe;QACtC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpE,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,iBAAiB,CAAC,GAAW;QAClC,MAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;YACvC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,oBAAoB,CAAC,GAAW;QACrC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,oBAAoB,CAAC,KAAe;QACzC,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IACzD,CAAC;CACF"}
1
+ {"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/definitions.ts"],"names":[],"mappings":"AAmxDA,MAAM,OAAO,uBAAuB;IAClC;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,iBAAiB,CAAC,KAAe;QACtC,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpE,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,iBAAiB,CAAC,GAAW;QAClC,MAAM,KAAK,GAAa,EAAE,CAAC;QAC3B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;YACvC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;QAC7C,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,oBAAoB,CAAC,GAAW;QACrC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IACnD,CAAC;IAED;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,oBAAoB,CAAC,KAAe;QACzC,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;IACzD,CAAC;CACF"}
@@ -0,0 +1,17 @@
1
+ import Foundation
2
+
3
+ struct AdapterStateEmitter {
4
+ private var lastEmittedEnabled: Bool?
5
+
6
+ mutating func shouldEmit(enabled: Bool) -> Bool {
7
+ if lastEmittedEnabled == enabled {
8
+ return false
9
+ }
10
+ lastEmittedEnabled = enabled
11
+ return true
12
+ }
13
+
14
+ mutating func reset() {
15
+ lastEmittedEnabled = nil
16
+ }
17
+ }
@@ -28,6 +28,7 @@ public class BluetoothLowEnergy: NSObject {
28
28
  private var scanTimer: Timer?
29
29
  private var allowDuplicates = false
30
30
  private var mode: String = "central"
31
+ private var adapterStateEmitter = AdapterStateEmitter()
31
32
 
32
33
  init(plugin: BluetoothLowEnergyPlugin) {
33
34
  self.plugin = plugin
@@ -561,13 +562,22 @@ public class BluetoothLowEnergy: NSObject {
561
562
  guard let data = data else { return [] }
562
563
  return data.map { Int($0) }
563
564
  }
565
+
566
+ private func emitAdapterStateIfNeeded(enabled: Bool) {
567
+ if adapterStateEmitter.shouldEmit(enabled: enabled) {
568
+ plugin?.emitAdapterStateChanged(enabled: enabled)
569
+ }
570
+ }
564
571
  }
565
572
 
566
573
  // MARK: - CBCentralManagerDelegate
567
574
 
568
575
  extension BluetoothLowEnergy: CBCentralManagerDelegate {
569
576
  public func centralManagerDidUpdateState(_ central: CBCentralManager) {
570
- // State updated
577
+ guard mode != "peripheral" else {
578
+ return
579
+ }
580
+ emitAdapterStateIfNeeded(enabled: central.state == .poweredOn)
571
581
  }
572
582
 
573
583
  public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
@@ -636,7 +646,15 @@ extension BluetoothLowEnergy: CBCentralManagerDelegate {
636
646
 
637
647
  extension BluetoothLowEnergy: CBPeripheralManagerDelegate {
638
648
  public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
639
- // State updated
649
+ if peripheral.state != .poweredOn {
650
+ localGattServices.removeAll()
651
+ localGattCharacteristics.removeAll()
652
+ for deviceId in Array(connectedCentrals.keys) {
653
+ plugin?.emitCentralDisconnected(deviceId: deviceId)
654
+ }
655
+ connectedCentrals.removeAll()
656
+ }
657
+ emitAdapterStateIfNeeded(enabled: peripheral.state == .poweredOn)
640
658
  }
641
659
 
642
660
  public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
@@ -5,7 +5,7 @@ import CoreBluetooth
5
5
  // swiftlint:disable type_body_length file_length
6
6
  @objc(BluetoothLowEnergyPlugin)
7
7
  public class BluetoothLowEnergyPlugin: CAPPlugin, CAPBridgedPlugin {
8
- private let pluginVersion: String = "8.2.10"
8
+ private let pluginVersion: String = "8.2.12"
9
9
  public let identifier = "BluetoothLowEnergyPlugin"
10
10
  public let jsName = "BluetoothLowEnergy"
11
11
  public let pluginMethods: [CAPPluginMethod] = [
@@ -524,6 +524,10 @@ public class BluetoothLowEnergyPlugin: CAPPlugin, CAPBridgedPlugin {
524
524
  notifyListeners("centralDisconnected", data: ["deviceId": deviceId])
525
525
  }
526
526
 
527
+ func emitAdapterStateChanged(enabled: Bool) {
528
+ notifyListeners("adapterStateChanged", data: ["enabled": enabled])
529
+ }
530
+
527
531
  func emitGattCharacteristicReadRequest(deviceId: String, service: String, characteristic: String) {
528
532
  notifyListeners("gattCharacteristicReadRequest", data: [
529
533
  "deviceId": deviceId,
@@ -3,9 +3,20 @@ import XCTest
3
3
 
4
4
  class BluetoothLowEnergyTests: XCTestCase {
5
5
 
6
- func testPluginInit() throws {
7
- // Basic test to verify the plugin can be instantiated
8
- XCTAssertTrue(true)
6
+ func testAdapterStateEmitterDedupesSameValue() throws {
7
+ var emitter = AdapterStateEmitter()
8
+ XCTAssertTrue(emitter.shouldEmit(enabled: false))
9
+ XCTAssertFalse(emitter.shouldEmit(enabled: false))
10
+ XCTAssertTrue(emitter.shouldEmit(enabled: true))
11
+ XCTAssertFalse(emitter.shouldEmit(enabled: true))
12
+ }
13
+
14
+ func testAdapterStateEmitterResetAllowsRepeat() throws {
15
+ var emitter = AdapterStateEmitter()
16
+ XCTAssertTrue(emitter.shouldEmit(enabled: true))
17
+ XCTAssertFalse(emitter.shouldEmit(enabled: true))
18
+ emitter.reset()
19
+ XCTAssertTrue(emitter.shouldEmit(enabled: true))
9
20
  }
10
21
 
11
22
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-bluetooth-low-energy",
3
- "version": "8.2.10",
3
+ "version": "8.2.12",
4
4
  "description": "Bluetooth Low Energy (BLE) plugin for Capacitor with support for scanning, connecting, reading, writing, and notifications.",
5
5
  "main": "dist/plugin.cjs.js",
6
6
  "module": "dist/esm/index.js",