@capgo/capacitor-bluetooth-low-energy 8.1.7 → 8.2.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.
@@ -6,6 +6,9 @@ public class BluetoothLowEnergy: NSObject {
6
6
  fileprivate weak var plugin: BluetoothLowEnergyPlugin?
7
7
  private var centralManager: CBCentralManager?
8
8
  private var peripheralManager: CBPeripheralManager?
9
+ private var localGattServices: [CBUUID: CBMutableService] = [:]
10
+ private var localGattCharacteristics: [String: CBMutableCharacteristic] = [:]
11
+ private var connectedCentrals: [String: CBCentral] = [:]
9
12
 
10
13
  private var discoveredPeripherals: [String: CBPeripheral] = [:]
11
14
  private var connectedPeripherals: [String: CBPeripheral] = [:]
@@ -368,6 +371,157 @@ public class BluetoothLowEnergy: NSObject {
368
371
  peripheralManager?.stopAdvertising()
369
372
  }
370
373
 
374
+ func addGattService(serviceUUID: String, characteristics: [[String: Any]], completion: @escaping (Error?) -> Void) {
375
+ guard mode == "peripheral" else {
376
+ completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "GATT server is only available in peripheral mode"]))
377
+ return
378
+ }
379
+ guard let peripheralManager = peripheralManager else {
380
+ completion(NSError(domain: "BluetoothLowEnergy", code: 2, userInfo: [NSLocalizedDescriptionKey: "Peripheral manager not initialized"]))
381
+ return
382
+ }
383
+ guard peripheralManager.state == .poweredOn else {
384
+ completion(NSError(domain: "BluetoothLowEnergy", code: 3, userInfo: [NSLocalizedDescriptionKey: "Bluetooth is not powered on"]))
385
+ return
386
+ }
387
+
388
+ let serviceId = CBUUID(string: serviceUUID)
389
+ if localGattServices[serviceId] != nil {
390
+ completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Service already exists"]))
391
+ return
392
+ }
393
+
394
+ var mutableCharacteristics: [CBMutableCharacteristic] = []
395
+ for characteristicDef in characteristics {
396
+ guard let characteristicUUID = characteristicDef["uuid"] as? String,
397
+ let propertiesDict = characteristicDef["properties"] as? [String: Bool] else {
398
+ completion(NSError(domain: "BluetoothLowEnergy", code: 5, userInfo: [NSLocalizedDescriptionKey: "Invalid characteristic definition"]))
399
+ return
400
+ }
401
+
402
+ var properties: CBCharacteristicProperties = []
403
+ if propertiesDict["broadcast"] == true { properties.insert(.broadcast) }
404
+ if propertiesDict["read"] == true { properties.insert(.read) }
405
+ if propertiesDict["writeWithoutResponse"] == true { properties.insert(.writeWithoutResponse) }
406
+ if propertiesDict["write"] == true { properties.insert(.write) }
407
+ if propertiesDict["notify"] == true { properties.insert(.notify) }
408
+ if propertiesDict["indicate"] == true { properties.insert(.indicate) }
409
+ if propertiesDict["authenticatedSignedWrites"] == true { properties.insert(.authenticatedSignedWrites) }
410
+ if propertiesDict["extendedProperties"] == true { properties.insert(.extendedProperties) }
411
+
412
+ var permissions: CBAttributePermissions = []
413
+ if propertiesDict["read"] == true { permissions.insert(.readable) }
414
+ if propertiesDict["write"] == true || propertiesDict["writeWithoutResponse"] == true { permissions.insert(.writeable) }
415
+
416
+ let characteristic = CBMutableCharacteristic(type: CBUUID(string: characteristicUUID), properties: properties, value: nil, permissions: permissions)
417
+ if let value = characteristicDef["value"] as? [Int] {
418
+ characteristic.value = Data(value.map { UInt8(truncatingIfNeeded: $0) })
419
+ }
420
+
421
+ if properties.contains(.notify) || properties.contains(.indicate) {
422
+ let ccc = CBMutableDescriptor(type: CBUUID(string: "2902"), value: Data())
423
+ characteristic.descriptors = [ccc]
424
+ }
425
+
426
+ if let descriptors = characteristicDef["descriptors"] as? [[String: Any]] {
427
+ var mutableDescriptors = characteristic.descriptors ?? []
428
+ for descriptorDef in descriptors {
429
+ guard let descriptorUUID = descriptorDef["uuid"] as? String else { continue }
430
+ let descriptorValue: Data
431
+ if let value = descriptorDef["value"] as? [Int] {
432
+ descriptorValue = Data(value.map { UInt8(truncatingIfNeeded: $0) })
433
+ } else {
434
+ descriptorValue = Data()
435
+ }
436
+ mutableDescriptors.append(CBMutableDescriptor(type: CBUUID(string: descriptorUUID), value: descriptorValue))
437
+ }
438
+ characteristic.descriptors = mutableDescriptors
439
+ }
440
+
441
+ localGattCharacteristics[characteristicKey(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID)] = characteristic
442
+ mutableCharacteristics.append(characteristic)
443
+ }
444
+
445
+ let service = CBMutableService(type: serviceId, primary: true)
446
+ service.characteristics = mutableCharacteristics
447
+ localGattServices[serviceId] = service
448
+ peripheralManager.add(service)
449
+ completion(nil)
450
+ }
451
+
452
+ func removeGattService(serviceUUID: String, completion: @escaping (Error?) -> Void) {
453
+ guard let peripheralManager = peripheralManager else {
454
+ completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "Peripheral manager not initialized"]))
455
+ return
456
+ }
457
+ let serviceId = CBUUID(string: serviceUUID)
458
+ guard let service = localGattServices.removeValue(forKey: serviceId) else {
459
+ completion(NSError(domain: "BluetoothLowEnergy", code: 2, userInfo: [NSLocalizedDescriptionKey: "Service not found"]))
460
+ return
461
+ }
462
+ localGattCharacteristics = localGattCharacteristics.filter { !$0.key.hasPrefix(serviceUUID + "/") }
463
+ peripheralManager.remove(service)
464
+ completion(nil)
465
+ }
466
+
467
+ func setGattCharacteristicValue(serviceUUID: String, characteristicUUID: String, value: [Int], completion: @escaping (Error?) -> Void) {
468
+ guard let characteristic = localGattCharacteristics[characteristicKey(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID)] else {
469
+ completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"]))
470
+ return
471
+ }
472
+ characteristic.value = Data(value.map { UInt8(truncatingIfNeeded: $0) })
473
+ completion(nil)
474
+ }
475
+
476
+ func notifyGattCharacteristicChanged(serviceUUID: String, characteristicUUID: String, value: [Int], deviceId: String?, completion: @escaping (Error?) -> Void) {
477
+ guard let peripheralManager = peripheralManager else {
478
+ completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "Peripheral manager not initialized"]))
479
+ return
480
+ }
481
+ guard let characteristic = localGattCharacteristics[characteristicKey(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID)] else {
482
+ completion(NSError(domain: "BluetoothLowEnergy", code: 2, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"]))
483
+ return
484
+ }
485
+ let data = Data(value.map { UInt8(truncatingIfNeeded: $0) })
486
+ characteristic.value = data
487
+ let centrals: [CBCentral]
488
+ if let deviceId = deviceId, let central = connectedCentrals[deviceId] {
489
+ centrals = [central]
490
+ } else {
491
+ centrals = Array(connectedCentrals.values)
492
+ }
493
+ let indicate = characteristic.properties.contains(.indicate)
494
+ let success = peripheralManager.updateValue(data, for: characteristic, onSubscribedCentrals: centrals.isEmpty ? nil : centrals)
495
+ if !success && !centrals.isEmpty {
496
+ completion(NSError(domain: "BluetoothLowEnergy", code: 3, userInfo: [NSLocalizedDescriptionKey: "Failed to notify characteristic change"]))
497
+ return
498
+ }
499
+ _ = indicate
500
+ completion(nil)
501
+ }
502
+
503
+ private func trackCentralConnection(_ central: CBCentral) {
504
+ let deviceId = central.identifier.uuidString
505
+ if connectedCentrals[deviceId] == nil {
506
+ connectedCentrals[deviceId] = central
507
+ plugin?.emitCentralConnected(deviceId: deviceId)
508
+ }
509
+ }
510
+
511
+ private func characteristicKey(serviceUUID: String, characteristicUUID: String) -> String {
512
+ return "\(serviceUUID)/\(characteristicUUID)"
513
+ }
514
+
515
+ private func characteristicInfo(for characteristic: CBMutableCharacteristic) -> (service: String, characteristic: String)? {
516
+ for (key, value) in localGattCharacteristics where value === characteristic {
517
+ let parts = key.split(separator: "/", maxSplits: 1).map(String.init)
518
+ if parts.count == 2 {
519
+ return (parts[0], parts[1])
520
+ }
521
+ }
522
+ return nil
523
+ }
524
+
371
525
  // MARK: - Private Helpers
372
526
 
373
527
  private func findCharacteristic(peripheral: CBPeripheral, serviceUUID: String, characteristicUUID: String) -> CBCharacteristic? {
@@ -484,6 +638,66 @@ extension BluetoothLowEnergy: CBPeripheralManagerDelegate {
484
638
  public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
485
639
  // State updated
486
640
  }
641
+
642
+ public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
643
+ let deviceId = central.identifier.uuidString
644
+ let wasConnected = connectedCentrals[deviceId] != nil
645
+ connectedCentrals[deviceId] = central
646
+ if !wasConnected {
647
+ plugin?.emitCentralConnected(deviceId: deviceId)
648
+ }
649
+ }
650
+
651
+ public func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
652
+ let deviceId = central.identifier.uuidString
653
+ connectedCentrals.removeValue(forKey: deviceId)
654
+ plugin?.emitCentralDisconnected(deviceId: deviceId)
655
+ }
656
+
657
+ public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
658
+ guard let mutableCharacteristic = request.characteristic as? CBMutableCharacteristic else {
659
+ peripheral.respond(to: request, withResult: .attributeNotFound)
660
+ return
661
+ }
662
+
663
+ trackCentralConnection(request.central)
664
+ if let info = characteristicInfo(for: mutableCharacteristic) {
665
+ plugin?.emitGattCharacteristicReadRequest(
666
+ deviceId: request.central.identifier.uuidString,
667
+ service: info.service,
668
+ characteristic: info.characteristic
669
+ )
670
+ }
671
+
672
+ request.value = mutableCharacteristic.value
673
+ peripheral.respond(to: request, withResult: .success)
674
+ }
675
+
676
+ public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
677
+ for request in requests {
678
+ guard let mutableCharacteristic = request.characteristic as? CBMutableCharacteristic else {
679
+ peripheral.respond(to: request, withResult: .attributeNotFound)
680
+ continue
681
+ }
682
+
683
+ trackCentralConnection(request.central)
684
+ if let value = request.value {
685
+ mutableCharacteristic.value = value
686
+ if let info = characteristicInfo(for: mutableCharacteristic) {
687
+ plugin?.emitGattCharacteristicWriteRequest(
688
+ deviceId: request.central.identifier.uuidString,
689
+ service: info.service,
690
+ characteristic: info.characteristic,
691
+ value: value.map { Int($0) }
692
+ )
693
+ }
694
+ }
695
+
696
+ if request.characteristic.properties.contains(.write) {
697
+ peripheral.respond(to: request, withResult: .success)
698
+ }
699
+ }
700
+ }
487
701
  }
488
702
 
489
703
  // MARK: - PeripheralDelegate
@@ -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.1.7"
8
+ private let pluginVersion: String = "8.2.0"
9
9
  public let identifier = "BluetoothLowEnergyPlugin"
10
10
  public let jsName = "BluetoothLowEnergy"
11
11
  public let pluginMethods: [CAPPluginMethod] = [
@@ -38,6 +38,10 @@ public class BluetoothLowEnergyPlugin: CAPPlugin, CAPBridgedPlugin {
38
38
  CAPPluginMethod(name: "requestConnectionPriority", returnType: CAPPluginReturnPromise),
39
39
  CAPPluginMethod(name: "startAdvertising", returnType: CAPPluginReturnPromise),
40
40
  CAPPluginMethod(name: "stopAdvertising", returnType: CAPPluginReturnPromise),
41
+ CAPPluginMethod(name: "addGattService", returnType: CAPPluginReturnPromise),
42
+ CAPPluginMethod(name: "removeGattService", returnType: CAPPluginReturnPromise),
43
+ CAPPluginMethod(name: "setGattCharacteristicValue", returnType: CAPPluginReturnPromise),
44
+ CAPPluginMethod(name: "notifyGattCharacteristicChanged", returnType: CAPPluginReturnPromise),
41
45
  CAPPluginMethod(name: "startForegroundService", returnType: CAPPluginReturnPromise),
42
46
  CAPPluginMethod(name: "stopForegroundService", returnType: CAPPluginReturnPromise),
43
47
  CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise)
@@ -411,6 +415,79 @@ public class BluetoothLowEnergyPlugin: CAPPlugin, CAPBridgedPlugin {
411
415
  call.resolve()
412
416
  }
413
417
 
418
+ @objc func addGattService(_ call: CAPPluginCall) {
419
+ guard let serviceUUID = call.getString("service") else {
420
+ call.reject("Service UUID is required")
421
+ return
422
+ }
423
+ guard let characteristics = call.getArray("characteristics") as? [JSObject] else {
424
+ call.reject("Characteristics array is required")
425
+ return
426
+ }
427
+ let characteristicDefs = characteristics.map { obj -> [String: Any] in
428
+ var def: [String: Any] = [:]
429
+ def["uuid"] = obj["uuid"] as? String
430
+ def["properties"] = obj["properties"] as? [String: Bool]
431
+ def["value"] = obj["value"] as? [Int]
432
+ def["descriptors"] = obj["descriptors"] as? [[String: Any]]
433
+ return def
434
+ }
435
+ implementation?.addGattService(serviceUUID: serviceUUID, characteristics: characteristicDefs) { error in
436
+ if let error = error {
437
+ call.reject(error.localizedDescription)
438
+ } else {
439
+ call.resolve()
440
+ }
441
+ }
442
+ }
443
+
444
+ @objc func removeGattService(_ call: CAPPluginCall) {
445
+ guard let serviceUUID = call.getString("service") else {
446
+ call.reject("Service UUID is required")
447
+ return
448
+ }
449
+ implementation?.removeGattService(serviceUUID: serviceUUID) { error in
450
+ if let error = error {
451
+ call.reject(error.localizedDescription)
452
+ } else {
453
+ call.resolve()
454
+ }
455
+ }
456
+ }
457
+
458
+ @objc func setGattCharacteristicValue(_ call: CAPPluginCall) {
459
+ guard let serviceUUID = call.getString("service"),
460
+ let characteristicUUID = call.getString("characteristic"),
461
+ let value = call.getArray("value") as? [Int] else {
462
+ call.reject("Service, characteristic, and value are required")
463
+ return
464
+ }
465
+ implementation?.setGattCharacteristicValue(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID, value: value) { error in
466
+ if let error = error {
467
+ call.reject(error.localizedDescription)
468
+ } else {
469
+ call.resolve()
470
+ }
471
+ }
472
+ }
473
+
474
+ @objc func notifyGattCharacteristicChanged(_ call: CAPPluginCall) {
475
+ guard let serviceUUID = call.getString("service"),
476
+ let characteristicUUID = call.getString("characteristic"),
477
+ let value = call.getArray("value") as? [Int] else {
478
+ call.reject("Service, characteristic, and value are required")
479
+ return
480
+ }
481
+ let deviceId = call.getString("deviceId")
482
+ implementation?.notifyGattCharacteristicChanged(serviceUUID: serviceUUID, characteristicUUID: characteristicUUID, value: value, deviceId: deviceId) { error in
483
+ if let error = error {
484
+ call.reject(error.localizedDescription)
485
+ } else {
486
+ call.resolve()
487
+ }
488
+ }
489
+ }
490
+
414
491
  @objc func startForegroundService(_ call: CAPPluginCall) {
415
492
  // iOS doesn't have foreground services like Android
416
493
  // Background execution is handled through Background Modes capability
@@ -439,6 +516,31 @@ public class BluetoothLowEnergyPlugin: CAPPlugin, CAPBridgedPlugin {
439
516
  notifyListeners("deviceDisconnected", data: ["deviceId": deviceId])
440
517
  }
441
518
 
519
+ func emitCentralConnected(deviceId: String) {
520
+ notifyListeners("centralConnected", data: ["deviceId": deviceId])
521
+ }
522
+
523
+ func emitCentralDisconnected(deviceId: String) {
524
+ notifyListeners("centralDisconnected", data: ["deviceId": deviceId])
525
+ }
526
+
527
+ func emitGattCharacteristicReadRequest(deviceId: String, service: String, characteristic: String) {
528
+ notifyListeners("gattCharacteristicReadRequest", data: [
529
+ "deviceId": deviceId,
530
+ "service": service,
531
+ "characteristic": characteristic
532
+ ])
533
+ }
534
+
535
+ func emitGattCharacteristicWriteRequest(deviceId: String, service: String, characteristic: String, value: [Int]) {
536
+ notifyListeners("gattCharacteristicWriteRequest", data: [
537
+ "deviceId": deviceId,
538
+ "service": service,
539
+ "characteristic": characteristic,
540
+ "value": value
541
+ ])
542
+ }
543
+
442
544
  func emitCharacteristicChanged(deviceId: String, service: String, characteristic: String, value: [Int]) {
443
545
  notifyListeners("characteristicChanged", data: [
444
546
  "deviceId": deviceId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capgo/capacitor-bluetooth-low-energy",
3
- "version": "8.1.7",
3
+ "version": "8.2.0",
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",