react-native-ble-manager 11.5.7 → 12.0.0-rc.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.
Files changed (40) hide show
  1. package/README.md +16 -3
  2. package/RNBleManager.podspec +24 -0
  3. package/android/build.gradle +116 -43
  4. package/android/gradle.properties +1 -0
  5. package/android/src/main/java/it/innove/BleManager.java +174 -148
  6. package/android/src/main/java/it/innove/BleManagerPackage.java +15 -14
  7. package/android/src/main/java/it/innove/CompanionScanner.java +13 -3
  8. package/android/src/main/java/it/innove/DefaultPeripheral.java +4 -4
  9. package/android/src/main/java/it/innove/DefaultScanManager.java +16 -16
  10. package/android/src/main/java/it/innove/Peripheral.java +20 -17
  11. package/dist/cjs/NativeBleManager.d.ts +241 -0
  12. package/dist/cjs/NativeBleManager.js +5 -0
  13. package/dist/cjs/NativeBleManager.js.map +1 -0
  14. package/dist/cjs/index.d.ts +15 -3
  15. package/dist/cjs/index.js +89 -38
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/types.d.ts +11 -11
  18. package/dist/esm/NativeBleManager.d.ts +241 -0
  19. package/dist/esm/NativeBleManager.js +3 -0
  20. package/dist/esm/NativeBleManager.js.map +1 -0
  21. package/dist/esm/index.d.ts +15 -3
  22. package/dist/esm/index.js +92 -41
  23. package/dist/esm/index.js.map +1 -1
  24. package/dist/esm/types.d.ts +11 -11
  25. package/ios/BleManager-Bridging-Header.h +7 -1
  26. package/ios/BleManager.h +39 -2
  27. package/ios/BleManager.mm +277 -0
  28. package/ios/Helper.swift +6 -6
  29. package/ios/RNBleManager.h +7 -0
  30. package/ios/{BleManager.swift → SwiftBleManager.swift} +322 -355
  31. package/package.json +107 -56
  32. package/src/NativeBleManager.ts +409 -0
  33. package/src/index.ts +162 -77
  34. package/src/types.ts +31 -31
  35. package/android/src/main/java/it/innove/LegacyScanManager.java +0 -112
  36. package/ios/BleManager.m +0 -153
  37. package/ios/BleManager.xcodeproj/project.pbxproj +0 -324
  38. package/ios/BleManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -7
  39. package/ios/BleManager.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +0 -8
  40. package/react-native-ble-manager.podspec +0 -17
@@ -2,17 +2,14 @@ import Foundation
2
2
  import CoreBluetooth
3
3
 
4
4
 
5
- @objc(BleManager)
6
- class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegate {
7
-
8
- static var shared:BleManager?
5
+ @objc public class SwiftBleManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
6
+ static var shared:SwiftBleManager?
9
7
  static var sharedManager:CBCentralManager?
10
-
11
- private var hasListeners:Bool = false
12
-
8
+
9
+ private weak var bleManager: BleManager?
13
10
  private var manager: CBCentralManager?
14
11
  private var scanTimer: Timer?
15
-
12
+
16
13
  private var peripherals: Dictionary<String, Peripheral>
17
14
  private var connectCallbacks: Dictionary<String, [RCTResponseSenderBlock]>
18
15
  private var readCallbacks: Dictionary<String, [RCTResponseSenderBlock]>
@@ -24,19 +21,19 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
24
21
  private var writeQueue: Array<Any>
25
22
  private var notificationCallbacks: Dictionary<String, [RCTResponseSenderBlock]>
26
23
  private var stopNotificationCallbacks: Dictionary<String, [RCTResponseSenderBlock]>
27
-
24
+
28
25
  private var connectedPeripherals: Set<String>
29
-
26
+
30
27
  private var retrieveServicesLatches: Dictionary<String, Set<CBService>>
31
28
  private var characteristicsLatches: Dictionary<String, Set<CBCharacteristic>>
32
-
29
+
33
30
  private let serialQueue = DispatchQueue(label: "BleManager.serialQueue")
34
-
31
+
35
32
  private var exactAdvertisingName: [String]
36
-
33
+
37
34
  static var verboseLogging = false
38
-
39
- private override init() {
35
+
36
+ @objc public init(bleManager:BleManager) {
40
37
  peripherals = [:]
41
38
  connectCallbacks = [:]
42
39
  readCallbacks = [:]
@@ -52,31 +49,19 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
52
49
  characteristicsLatches = [:]
53
50
  exactAdvertisingName = []
54
51
  connectedPeripherals = []
55
-
52
+ self.bleManager = bleManager
53
+
56
54
  super.init()
57
-
55
+
58
56
  NSLog("BleManager created");
59
-
60
- BleManager.shared = self
61
-
62
-
57
+
58
+ SwiftBleManager.shared = self
59
+
60
+
63
61
  NotificationCenter.default.addObserver(self, selector: #selector(bridgeReloading), name: NSNotification.Name(rawValue: "RCTBridgeWillReloadNotification"), object: nil)
64
62
  }
65
63
 
66
- @objc override static func requiresMainQueueSetup() -> Bool { return true }
67
-
68
- @objc override func supportedEvents() -> [String]! {
69
- return ["BleManagerDidUpdateValueForCharacteristic", "BleManagerStopScan", "BleManagerDiscoverPeripheral", "BleManagerConnectPeripheral", "BleManagerDisconnectPeripheral", "BleManagerDidUpdateState", "BleManagerCentralManagerWillRestoreState", "BleManagerDidUpdateNotificationStateFor"]
70
- }
71
-
72
- @objc override func startObserving() {
73
- hasListeners = true
74
- }
75
-
76
- @objc override func stopObserving() {
77
- hasListeners = false
78
- }
79
-
64
+
80
65
  @objc func bridgeReloading() {
81
66
  if let manager = manager {
82
67
  if let scanTimer = self.scanTimer {
@@ -84,32 +69,33 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
84
69
  self.scanTimer = nil
85
70
  manager.stopScan()
86
71
  }
87
-
72
+
88
73
  manager.delegate = nil
89
74
  }
90
-
75
+
91
76
  serialQueue.sync {
92
77
  for p in peripherals.values {
93
78
  p.instance.delegate = nil
94
79
  }
95
80
  }
96
-
81
+
97
82
  peripherals = [:]
98
83
  }
99
-
84
+
85
+
100
86
  // Helper method to find a peripheral by UUID
101
87
  func findPeripheral(byUUID uuid: String) -> Peripheral? {
102
88
  var foundPeripheral: Peripheral? = nil
103
-
89
+
104
90
  serialQueue.sync {
105
91
  if let peripheral = peripherals[uuid] {
106
92
  foundPeripheral = peripheral;
107
93
  }
108
94
  }
109
-
95
+
110
96
  return foundPeripheral
111
97
  }
112
-
98
+
113
99
  // Helper method to insert callback in different queues
114
100
  func insertCallback(_ callback: @escaping RCTResponseSenderBlock, intoDictionary dictionary: inout Dictionary<String, [RCTResponseSenderBlock]>, withKey key: String) {
115
101
  serialQueue.sync {
@@ -118,7 +104,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
118
104
  dictionary[key] = peripheralCallbacks
119
105
  }
120
106
  }
121
-
107
+
122
108
  // Helper method to call the callbacks for a specific peripheral and clear the queue
123
109
  func invokeAndClearDictionary(_ dictionary: inout Dictionary<String, [RCTResponseSenderBlock]>, withKey key: String, usingParameters parameters: [Any]) {
124
110
  serialQueue.sync {
@@ -131,22 +117,22 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
131
117
  for callback in peripheralCallbacks {
132
118
  callback(parameters)
133
119
  }
134
-
120
+
135
121
  dictionary.removeValue(forKey: key)
136
122
  }
137
123
  }
138
-
124
+
139
125
  @objc func getContext(_ peripheralUUIDString: String, serviceUUIDString: String, characteristicUUIDString: String, prop: CBCharacteristicProperties, callback: @escaping RCTResponseSenderBlock) -> BLECommandContext? {
140
126
  let serviceUUID = CBUUID(string: serviceUUIDString)
141
127
  let characteristicUUID = CBUUID(string: characteristicUUIDString)
142
-
128
+
143
129
  guard let peripheral = peripherals[peripheralUUIDString] else {
144
130
  let error = String(format: "Could not find peripheral with UUID %@", peripheralUUIDString)
145
131
  NSLog(error)
146
132
  callback([error])
147
133
  return nil
148
134
  }
149
-
135
+
150
136
  guard let service = Helper.findService(fromUUID: serviceUUID, peripheral: peripheral.instance) else {
151
137
  let error = String(format: "Could not find service with UUID %@ on peripheral with UUID %@",
152
138
  serviceUUIDString,
@@ -155,19 +141,19 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
155
141
  callback([error])
156
142
  return nil
157
143
  }
158
-
144
+
159
145
  var characteristic = Helper.findCharacteristic(fromUUID: characteristicUUID, service: service, prop: prop)
160
-
146
+
161
147
  // Special handling for INDICATE. If characteristic with notify is not found, check for indicate.
162
148
  if prop == CBCharacteristicProperties.notify && characteristic == nil {
163
149
  characteristic = Helper.findCharacteristic(fromUUID: characteristicUUID, service: service, prop: CBCharacteristicProperties.indicate)
164
150
  }
165
-
151
+
166
152
  // As a last resort, try to find ANY characteristic with this UUID, even if it doesn't have the correct properties
167
153
  if characteristic == nil {
168
154
  characteristic = Helper.findCharacteristic(fromUUID: characteristicUUID, service: service)
169
155
  }
170
-
156
+
171
157
  guard let finalCharacteristic = characteristic else {
172
158
  let error = String(format: "Could not find characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
173
159
  characteristicUUIDString,
@@ -177,55 +163,55 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
177
163
  callback([error])
178
164
  return nil
179
165
  }
180
-
166
+
181
167
  let context = BLECommandContext()
182
168
  context.peripheral = peripheral
183
169
  context.service = service
184
170
  context.characteristic = finalCharacteristic
185
171
  return context
186
172
  }
187
-
188
-
173
+
174
+
189
175
  @objc public func start(_ options: NSDictionary,
190
176
  callback: RCTResponseSenderBlock) {
191
- if BleManager.verboseLogging {
177
+ if SwiftBleManager.verboseLogging {
192
178
  NSLog("BleManager initialized")
193
179
  }
194
180
  var initOptions = [String: Any]()
195
-
181
+
196
182
  if let showAlert = options["showAlert"] as? Bool {
197
183
  initOptions[CBCentralManagerOptionShowPowerAlertKey] = showAlert
198
184
  }
199
-
185
+
200
186
  if let verboseLogging = options["verboseLogging"] as? Bool {
201
- BleManager.verboseLogging = verboseLogging
187
+ SwiftBleManager.verboseLogging = verboseLogging
202
188
  }
203
-
189
+
204
190
  var queue: DispatchQueue
205
191
  if let queueIdentifierKey = options["queueIdentifierKey"] as? String {
206
192
  queue = DispatchQueue(label: queueIdentifierKey, qos: DispatchQoS.background)
207
193
  } else {
208
194
  queue = DispatchQueue.main
209
195
  }
210
-
196
+
211
197
  if let restoreIdentifierKey = options["restoreIdentifierKey"] as? String {
212
198
  initOptions[CBCentralManagerOptionRestoreIdentifierKey] = restoreIdentifierKey
213
-
214
- if let sharedManager = BleManager.sharedManager {
199
+
200
+ if let sharedManager = SwiftBleManager.sharedManager {
215
201
  manager = sharedManager
216
202
  manager?.delegate = self
217
203
  } else {
218
204
  manager = CBCentralManager(delegate: self, queue: queue, options: initOptions)
219
- BleManager.sharedManager = manager
205
+ SwiftBleManager.sharedManager = manager
220
206
  }
221
207
  } else {
222
208
  manager = CBCentralManager(delegate: self, queue: queue, options: initOptions)
223
- BleManager.sharedManager = manager
209
+ SwiftBleManager.sharedManager = manager
224
210
  }
225
-
211
+
226
212
  callback([])
227
213
  }
228
-
214
+
229
215
  @objc public func scan(_ serviceUUIDStrings: [Any],
230
216
  timeoutSeconds: NSNumber,
231
217
  allowDuplicates: Bool,
@@ -236,7 +222,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
236
222
  } else {
237
223
  NSLog("scan")
238
224
  }
239
-
225
+
240
226
  // Clear the peripherals before scanning again, otherwise cannot connect again after disconnection
241
227
  // Only clear peripherals that are not connected - otherwise connections fail silently (without any
242
228
  // onDisconnect* callback).
@@ -247,24 +233,24 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
247
233
  peripherals.removeValue(forKey: uuid)
248
234
  }
249
235
  }
250
-
236
+
251
237
  var serviceUUIDs = [CBUUID]()
252
238
  if let serviceUUIDStrings = serviceUUIDStrings as? [String] {
253
239
  serviceUUIDs = serviceUUIDStrings.map { CBUUID(string: $0) }
254
240
  }
255
-
241
+
256
242
  var options: [String: Any]?
257
243
  if allowDuplicates {
258
244
  options = [CBCentralManagerScanOptionAllowDuplicatesKey: true]
259
245
  }
260
-
246
+
261
247
  exactAdvertisingName.removeAll()
262
248
  if let names = scanningOptions["exactAdvertisingName"] as? [String] {
263
249
  exactAdvertisingName.append(contentsOf: names)
264
250
  }
265
-
251
+
266
252
  manager?.scanForPeripherals(withServices: serviceUUIDs, options: options)
267
-
253
+
268
254
  if timeoutSeconds.doubleValue > 0 {
269
255
  if let scanTimer = scanTimer {
270
256
  scanTimer.invalidate()
@@ -274,50 +260,46 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
274
260
  self.scanTimer = Timer.scheduledTimer(timeInterval: timeoutSeconds.doubleValue, target: self, selector: #selector(self.stopTimer), userInfo: nil, repeats: false)
275
261
  }
276
262
  }
277
-
263
+
278
264
  callback([])
279
265
  }
280
-
266
+
281
267
  @objc func stopTimer() {
282
268
  NSLog("Stop scan");
283
269
  scanTimer = nil;
284
270
  manager?.stopScan()
285
- if hasListeners {
286
- sendEvent(withName: "BleManagerStopScan", body: ["status": 10])
287
- }
271
+ bleManager?.emit(onStopScan: ["status": 10])
288
272
  }
289
-
290
-
273
+
274
+
291
275
  @objc public func stopScan(_ callback: @escaping RCTResponseSenderBlock) {
292
276
  if let scanTimer = self.scanTimer {
293
277
  scanTimer.invalidate()
294
278
  self.scanTimer = nil
295
279
  }
296
-
280
+
297
281
  manager?.stopScan()
298
-
299
- if hasListeners {
300
- sendEvent(withName: "BleManagerStopScan", body: ["status": 0])
301
- }
302
-
282
+
283
+ bleManager?.emit(onStopScan: ["status": 0])
284
+
303
285
  callback([])
304
286
  }
305
-
306
-
307
- @objc func connect(_ peripheralUUID: String,
287
+
288
+
289
+ @objc public func connect(_ peripheralUUID: String,
308
290
  options: NSDictionary,
309
291
  callback: @escaping RCTResponseSenderBlock) {
310
-
292
+
311
293
  if let peripheral = peripherals[peripheralUUID] {
312
294
  // Found the peripheral, connect to it
313
295
  NSLog("Connecting to peripheral with UUID: \(peripheralUUID)")
314
-
296
+
315
297
  insertCallback(callback, intoDictionary: &connectCallbacks, withKey: peripheral.instance.uuidAsString())
316
298
  manager?.connect(peripheral.instance)
317
299
  } else {
318
300
  // Try to retrieve the peripheral
319
301
  NSLog("Retrieving peripheral with UUID: \(peripheralUUID)")
320
-
302
+
321
303
  if let uuid = UUID(uuidString: peripheralUUID) {
322
304
  let peripheralArray = manager?.retrievePeripherals(withIdentifiers: [uuid])
323
305
  if let retrievedPeripheral = peripheralArray?.first {
@@ -325,7 +307,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
325
307
  peripherals[retrievedPeripheral.uuidAsString()] = Peripheral(peripheral:retrievedPeripheral)
326
308
  }
327
309
  NSLog("Successfully retrieved and connecting to peripheral with UUID: \(peripheralUUID)")
328
-
310
+
329
311
  // Connect to the retrieved peripheral
330
312
  insertCallback(callback, intoDictionary: &connectCallbacks, withKey: retrievedPeripheral.uuidAsString())
331
313
  manager?.connect(retrievedPeripheral, options: nil)
@@ -340,13 +322,13 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
340
322
  }
341
323
  }
342
324
  }
343
-
344
- @objc func disconnect(_ peripheralUUID: String,
325
+
326
+ @objc public func disconnect(_ peripheralUUID: String,
345
327
  force: Bool,
346
328
  callback: @escaping RCTResponseSenderBlock) {
347
329
  if let peripheral = peripherals[peripheralUUID] {
348
330
  NSLog("Disconnecting from peripheral with UUID: \(peripheralUUID)")
349
-
331
+
350
332
  if let services = peripheral.instance.services {
351
333
  for service in services {
352
334
  if let characteristics = service.characteristics {
@@ -359,46 +341,46 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
359
341
  }
360
342
  }
361
343
  }
362
-
344
+
363
345
  manager?.cancelPeripheralConnection(peripheral.instance)
364
346
  callback([])
365
-
347
+
366
348
  } else {
367
349
  let error = "Could not find peripheral \(peripheralUUID)."
368
350
  NSLog(error)
369
351
  callback([error])
370
352
  }
371
353
  }
372
-
373
- @objc func retrieveServices(_ peripheralUUID: String,
354
+
355
+ @objc public func retrieveServices(_ peripheralUUID: String,
374
356
  services: [String],
375
357
  callback: @escaping RCTResponseSenderBlock) {
376
358
  NSLog("retrieveServices \(services)")
377
-
359
+
378
360
  if let peripheral = peripherals[peripheralUUID], peripheral.instance.state == .connected {
379
361
  insertCallback(callback, intoDictionary: &retrieveServicesCallbacks, withKey: peripheral.instance.uuidAsString())
380
-
362
+
381
363
  var uuids: [CBUUID] = []
382
364
  for string in services {
383
365
  let uuid = CBUUID(string: string)
384
366
  uuids.append(uuid)
385
367
  }
386
-
368
+
387
369
  if !uuids.isEmpty {
388
370
  peripheral.instance.discoverServices(uuids)
389
371
  } else {
390
372
  peripheral.instance.discoverServices(nil)
391
373
  }
392
-
374
+
393
375
  } else {
394
376
  callback(["Peripheral not found or not connected"])
395
377
  }
396
378
  }
397
-
398
- @objc func readRSSI(_ peripheralUUID: String,
379
+
380
+ @objc public func readRSSI(_ peripheralUUID: String,
399
381
  callback: @escaping RCTResponseSenderBlock) {
400
382
  NSLog("readRSSI")
401
-
383
+
402
384
  if let peripheral = peripherals[peripheralUUID], peripheral.instance.state == .connected {
403
385
  insertCallback(callback, intoDictionary: &readRSSICallbacks, withKey: peripheral.instance.uuidAsString())
404
386
  peripheral.instance.readRSSI()
@@ -406,93 +388,93 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
406
388
  callback(["Peripheral not found or not connected"])
407
389
  }
408
390
  }
409
-
410
- @objc func readDescriptor(_ peripheralUUID: String,
391
+
392
+ @objc public func readDescriptor(_ peripheralUUID: String,
411
393
  serviceUUID: String,
412
394
  characteristicUUID: String,
413
395
  descriptorUUID: String,
414
396
  callback: @escaping RCTResponseSenderBlock) {
415
397
  NSLog("readDescriptor")
416
-
398
+
417
399
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.read, callback: callback) else {
418
400
  return
419
401
  }
420
-
402
+
421
403
  let peripheral = context.peripheral
422
404
  let characteristic = context.characteristic
423
-
405
+
424
406
  guard let descriptor = Helper.findDescriptor(fromUUID: CBUUID(string: descriptorUUID), characteristic: characteristic!) else {
425
407
  let error = "Could not find descriptor with UUID \(descriptorUUID) on characteristic with UUID \(String(describing: characteristic?.uuid.uuidString)) on peripheral with UUID \(peripheralUUID)"
426
408
  NSLog(error)
427
409
  callback([error])
428
410
  return
429
411
  }
430
-
412
+
431
413
  if let peripheral = peripheral?.instance {
432
414
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: characteristic!, andDescriptor: descriptor)
433
415
  insertCallback(callback, intoDictionary: &readDescriptorCallbacks, withKey: key)
434
-
416
+
435
417
  }
436
-
418
+
437
419
  peripheral?.instance.readValue(for: descriptor)
438
420
  }
439
-
440
- @objc func writeDescriptor(_ peripheralUUID: String,
421
+
422
+ @objc public func writeDescriptor(_ peripheralUUID: String,
441
423
  serviceUUID: String,
442
424
  characteristicUUID: String,
443
425
  descriptorUUID: String,
444
426
  message: [UInt8],
445
427
  callback: @escaping RCTResponseSenderBlock) {
446
428
  NSLog("writeDescriptor")
447
-
429
+
448
430
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.read, callback: callback) else {
449
431
  return
450
432
  }
451
-
433
+
452
434
  let peripheral = context.peripheral
453
435
  let characteristic = context.characteristic
454
-
436
+
455
437
  guard let descriptor = Helper.findDescriptor(fromUUID: CBUUID(string: descriptorUUID), characteristic: characteristic!) else {
456
438
  let error = "Could not find descriptor with UUID \(descriptorUUID) on characteristic with UUID \(String(describing: characteristic?.uuid.uuidString)) on peripheral with UUID \(peripheralUUID)"
457
439
  NSLog(error)
458
440
  callback([error])
459
441
  return
460
442
  }
461
-
443
+
462
444
  if let peripheral = peripheral?.instance {
463
445
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: characteristic!, andDescriptor: descriptor)
464
446
  insertCallback(callback, intoDictionary: &writeDescriptorCallbacks, withKey: key)
465
-
447
+
466
448
  }
467
-
449
+
468
450
  let dataMessage = Data(message)
469
451
  peripheral?.instance.writeValue(dataMessage, for: descriptor)
470
452
  }
471
-
472
- @objc func getDiscoveredPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
453
+
454
+ @objc public func getDiscoveredPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
473
455
  NSLog("Get discovered peripherals")
474
456
  var discoveredPeripherals: [[String: Any]] = []
475
-
457
+
476
458
  serialQueue.sync {
477
459
  for (_, peripheral) in peripherals {
478
460
  discoveredPeripherals.append(peripheral.advertisingInfo())
479
461
  }
480
462
  }
481
-
463
+
482
464
  callback([NSNull(), discoveredPeripherals])
483
465
  }
484
-
485
- @objc func getConnectedPeripherals(_ serviceUUIDStrings: [String],
466
+
467
+ @objc public func getConnectedPeripherals(_ serviceUUIDStrings: [String],
486
468
  callback: @escaping RCTResponseSenderBlock) {
487
469
  NSLog("Get connected peripherals")
488
470
  var serviceUUIDs: [CBUUID] = []
489
-
471
+
490
472
  for uuidString in serviceUUIDStrings {
491
473
  serviceUUIDs.append(CBUUID(string: uuidString))
492
474
  }
493
-
475
+
494
476
  var connectedPeripherals: [Peripheral] = []
495
-
477
+
496
478
  if serviceUUIDs.isEmpty {
497
479
  serialQueue.sync {
498
480
  connectedPeripherals = peripherals.filter({ $0.value.instance.state == .connected }).map({ p in
@@ -501,7 +483,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
501
483
  }
502
484
  } else {
503
485
  let connectedCBPeripherals: [CBPeripheral] = manager?.retrieveConnectedPeripherals(withServices: serviceUUIDs) ?? []
504
-
486
+
505
487
  serialQueue.sync {
506
488
  for ph in connectedCBPeripherals {
507
489
  if let peripheral = peripherals[ph.uuidAsString()] {
@@ -512,65 +494,65 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
512
494
  }
513
495
  }
514
496
  }
515
-
497
+
516
498
  var foundedPeripherals: [[String: Any]] = []
517
-
499
+
518
500
  for peripheral in connectedPeripherals {
519
501
  foundedPeripherals.append(peripheral.advertisingInfo())
520
502
  }
521
-
503
+
522
504
  callback([NSNull(), foundedPeripherals])
523
505
  }
524
-
525
- @objc func isPeripheralConnected(_ peripheralUUID: String,
506
+
507
+ @objc public func isPeripheralConnected(_ peripheralUUID: String,
526
508
  callback: @escaping RCTResponseSenderBlock) {
527
-
509
+
528
510
  if let peripheral = peripherals[peripheralUUID] {
529
511
  callback([NSNull(), peripheral.instance.state == .connected])
530
512
  } else {
531
513
  callback(["Peripheral not found"])
532
514
  }
533
515
  }
534
-
535
- @objc func isScanning(_ callback: @escaping RCTResponseSenderBlock) {
516
+
517
+ @objc public func isScanning(_ callback: @escaping RCTResponseSenderBlock) {
536
518
  if let manager = manager {
537
519
  callback([NSNull(), manager.isScanning])
538
520
  } else {
539
521
  callback(["CBCentralManager not found"])
540
522
  }
541
523
  }
542
-
543
- @objc func checkState(_ callback: @escaping RCTResponseSenderBlock) {
524
+
525
+ @objc public func checkState(_ callback: @escaping RCTResponseSenderBlock) {
544
526
  if let manager = manager {
545
527
  centralManagerDidUpdateState(manager)
546
-
528
+
547
529
  let stateName = Helper.centralManagerStateToString(manager.state)
548
530
  callback([stateName])
549
531
  }
550
532
  }
551
-
552
- @objc func write(_ peripheralUUID: String,
533
+
534
+ @objc public func write(_ peripheralUUID: String,
553
535
  serviceUUID: String,
554
536
  characteristicUUID: String,
555
537
  message: [UInt8],
556
538
  maxByteSize: Int,
557
539
  callback: @escaping RCTResponseSenderBlock) {
558
540
  NSLog("write")
559
-
541
+
560
542
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.write, callback: callback) else {
561
543
  return
562
544
  }
563
-
545
+
564
546
  let dataMessage = Data(message)
565
-
547
+
566
548
  if let peripheral = context.peripheral, let characteristic = context.characteristic {
567
549
  let key = Helper.key(forPeripheral:peripheral.instance, andCharacteristic: characteristic)
568
550
  insertCallback(callback, intoDictionary: &writeCallbacks, withKey: key)
569
-
570
- if BleManager.verboseLogging {
551
+
552
+ if SwiftBleManager.verboseLogging {
571
553
  NSLog("Message to write(\(dataMessage.count)): \(dataMessage.hexadecimalString())")
572
554
  }
573
-
555
+
574
556
  if dataMessage.count > maxByteSize {
575
557
  var count = 0
576
558
  var offset = 0
@@ -580,16 +562,16 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
580
562
  count += maxByteSize
581
563
  offset += maxByteSize
582
564
  }
583
-
565
+
584
566
  if count < dataMessage.count {
585
567
  let splitMessage = dataMessage.subdata(in: offset..<dataMessage.count)
586
568
  writeQueue.append(splitMessage)
587
569
  }
588
-
589
- if BleManager.verboseLogging {
570
+
571
+ if SwiftBleManager.verboseLogging {
590
572
  NSLog("Queued splitted message: \(writeQueue.count)")
591
573
  }
592
-
574
+
593
575
  if case let firstMessage as Data = writeQueue.removeFirst() {
594
576
  peripheral.instance.writeValue(firstMessage, for: characteristic, type: .withResponse)
595
577
  }
@@ -598,8 +580,8 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
598
580
  }
599
581
  }
600
582
  }
601
-
602
- @objc func writeWithoutResponse(_ peripheralUUID: String,
583
+
584
+ @objc public func writeWithoutResponse(_ peripheralUUID: String,
603
585
  serviceUUID: String,
604
586
  characteristicUUID: String,
605
587
  message: [UInt8],
@@ -607,94 +589,94 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
607
589
  queueSleepTime: Int,
608
590
  callback: @escaping RCTResponseSenderBlock) {
609
591
  NSLog("writeWithoutResponse")
610
-
592
+
611
593
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.writeWithoutResponse, callback: callback) else {
612
594
  return
613
595
  }
614
-
596
+
615
597
  let dataMessage = Data(message)
616
-
617
- if BleManager.verboseLogging {
598
+
599
+ if SwiftBleManager.verboseLogging {
618
600
  NSLog("Message to write(\(dataMessage.count)): \(dataMessage.hexadecimalString())")
619
601
  }
620
-
602
+
621
603
  if dataMessage.count > maxByteSize {
622
604
  var offset = 0
623
605
  let peripheral = context.peripheral
624
606
  guard let characteristic = context.characteristic else { return }
625
-
607
+
626
608
  repeat {
627
609
  let thisChunkSize = min(maxByteSize, dataMessage.count - offset)
628
610
  let chunk = dataMessage.subdata(in: offset..<offset + thisChunkSize)
629
-
611
+
630
612
  offset += thisChunkSize
631
613
  peripheral?.instance.writeValue(chunk, for: characteristic, type: .withoutResponse)
632
-
614
+
633
615
  let sleepTimeSeconds = TimeInterval(queueSleepTime) / 1000
634
616
  Thread.sleep(forTimeInterval: sleepTimeSeconds)
635
617
  } while offset < dataMessage.count
636
-
618
+
637
619
  callback([])
638
620
  } else {
639
621
  let peripheral = context.peripheral
640
622
  guard let characteristic = context.characteristic else { return }
641
-
623
+
642
624
  peripheral?.instance.writeValue(dataMessage, for: characteristic, type: .withoutResponse)
643
625
  callback([])
644
626
  }
645
627
  }
646
-
647
- @objc func read(_ peripheralUUID: String,
628
+
629
+ @objc public func read(_ peripheralUUID: String,
648
630
  serviceUUID: String,
649
631
  characteristicUUID: String,
650
632
  callback: @escaping RCTResponseSenderBlock) {
651
633
  NSLog("read")
652
-
634
+
653
635
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.read, callback: callback) else {
654
636
  return
655
637
  }
656
-
638
+
657
639
  let peripheral = context.peripheral
658
640
  let characteristic = context.characteristic
659
-
641
+
660
642
  let key = Helper.key(forPeripheral:peripheral!.instance as CBPeripheral, andCharacteristic: characteristic!)
661
643
  insertCallback(callback, intoDictionary: &readCallbacks, withKey: key)
662
-
644
+
663
645
  peripheral?.instance.readValue(for: characteristic!) // callback sends value
664
646
  }
665
-
666
- @objc func startNotification(_ peripheralUUID: String,
647
+
648
+ @objc public func startNotification(_ peripheralUUID: String,
667
649
  serviceUUID: String,
668
650
  characteristicUUID: String,
669
651
  callback: @escaping RCTResponseSenderBlock) {
670
652
  NSLog("startNotification")
671
-
653
+
672
654
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.notify, callback: callback) else {
673
655
  return
674
656
  }
675
-
657
+
676
658
  guard let peripheral = context.peripheral else { return }
677
659
  guard let characteristic = context.characteristic else { return }
678
-
660
+
679
661
  let key = Helper.key(forPeripheral: (peripheral.instance as CBPeripheral?)!, andCharacteristic: characteristic)
680
662
  insertCallback(callback, intoDictionary: &notificationCallbacks, withKey: key)
681
-
663
+
682
664
  peripheral.instance.setNotifyValue(true, for: characteristic)
683
665
  }
684
-
685
- @objc func stopNotification(_ peripheralUUID: String,
666
+
667
+ @objc public func stopNotification(_ peripheralUUID: String,
686
668
  serviceUUID: String,
687
669
  characteristicUUID: String,
688
670
  callback: @escaping RCTResponseSenderBlock) {
689
671
  NSLog("stopNotification")
690
-
672
+
691
673
  guard let context = getContext(peripheralUUID, serviceUUIDString: serviceUUID, characteristicUUIDString: characteristicUUID, prop: CBCharacteristicProperties.notify, callback: callback) else {
692
674
  return
693
675
  }
694
-
676
+
695
677
  let peripheral = context.peripheral
696
678
  guard let characteristic = context.characteristic else { return }
697
-
679
+
698
680
  if characteristic.isNotifying {
699
681
  let key = Helper.key(forPeripheral: (peripheral?.instance as CBPeripheral?)!, andCharacteristic: characteristic)
700
682
  insertCallback(callback, intoDictionary: &stopNotificationCallbacks, withKey: key)
@@ -705,16 +687,16 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
705
687
  callback([])
706
688
  }
707
689
  }
708
-
709
- @objc func getMaximumWriteValueLengthForWithoutResponse(_ peripheralUUID: String,
690
+
691
+ @objc public func getMaximumWriteValueLengthForWithoutResponse(_ peripheralUUID: String,
710
692
  callback: @escaping RCTResponseSenderBlock) {
711
693
  NSLog("getMaximumWriteValueLengthForWithoutResponse")
712
-
694
+
713
695
  guard let peripheral = peripherals[peripheralUUID] else {
714
696
  callback(["Peripheral not found or not connected"])
715
697
  return
716
698
  }
717
-
699
+
718
700
  if peripheral.instance.state == .connected {
719
701
  let max = NSNumber(value: peripheral.instance.maximumWriteValueLength(for: .withoutResponse))
720
702
  callback([NSNull(), max])
@@ -722,16 +704,16 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
722
704
  callback(["Peripheral not found or not connected"])
723
705
  }
724
706
  }
725
-
726
- @objc func getMaximumWriteValueLengthForWithResponse(_ peripheralUUID: String,
707
+
708
+ @objc public func getMaximumWriteValueLengthForWithResponse(_ peripheralUUID: String,
727
709
  callback: @escaping RCTResponseSenderBlock) {
728
710
  NSLog("getMaximumWriteValueLengthForWithResponse")
729
-
711
+
730
712
  guard let peripheral = peripherals[peripheralUUID] else {
731
713
  callback(["Peripheral not found or not connected"])
732
714
  return
733
715
  }
734
-
716
+
735
717
  if peripheral.instance.state == .connected {
736
718
  let max = NSNumber(value: peripheral.instance.maximumWriteValueLength(for: .withResponse))
737
719
  callback([NSNull(), max])
@@ -739,8 +721,8 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
739
721
  callback(["Peripheral not found or not connected"])
740
722
  }
741
723
  }
742
-
743
- func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
724
+
725
+ public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
744
726
  if let restoredPeripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral], restoredPeripherals.count > 0 {
745
727
  serialQueue.sync {
746
728
  var data = [[String: Any]]()
@@ -750,18 +732,17 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
750
732
  data.append(p.advertisingInfo())
751
733
  peripheral.delegate = self
752
734
  }
753
-
754
- self.sendEvent(withName:"BleManagerCentralManagerWillRestoreState", body: ["peripherals": data])
735
+ self.bleManager?.emit(onCentralManagerWillRestoreState: ["peripherals": data])
755
736
  }
756
737
  }
757
738
  }
758
-
759
-
760
- func centralManager(_ central: CBCentralManager,
739
+
740
+
741
+ public func centralManager(_ central: CBCentralManager,
761
742
  didConnect peripheral: CBPeripheral) {
762
743
  NSLog("Peripheral Connected: \(peripheral.uuidAsString() )")
763
744
  peripheral.delegate = self
764
-
745
+
765
746
  /*
766
747
  The state of the peripheral isn't necessarily updated until a small
767
748
  delay after didConnectPeripheral is called and in the meantime
@@ -771,87 +752,81 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
771
752
  Timer.scheduledTimer(withTimeInterval: 0.002, repeats: false) { timer in
772
753
  // didFailToConnectPeripheral should have been called already if not connected by now
773
754
  self.invokeAndClearDictionary(&self.connectCallbacks, withKey: peripheral.uuidAsString(), usingParameters: [NSNull()])
774
-
775
- if self.hasListeners {
776
- self.connectedPeripherals.insert(peripheral.uuidAsString())
777
- self.sendEvent(withName: "BleManagerConnectPeripheral", body: ["peripheral": peripheral.uuidAsString()])
778
- }
755
+
756
+ self.connectedPeripherals.insert(peripheral.uuidAsString())
757
+ self.bleManager?.emit(onConnectPeripheral: ["peripheral": peripheral.uuidAsString()])
779
758
  }
780
759
  }
781
760
  }
782
-
783
- func centralManager(_ central: CBCentralManager,
761
+
762
+ public func centralManager(_ central: CBCentralManager,
784
763
  didFailToConnect peripheral: CBPeripheral,
785
764
  error: Error?) {
786
765
  let errorStr = "Peripheral connection failure: \(peripheral.uuidAsString() ) (\(error?.localizedDescription ?? "")"
787
766
  NSLog(errorStr)
788
-
767
+
789
768
  invokeAndClearDictionary(&connectCallbacks, withKey: peripheral.uuidAsString(), usingParameters: [errorStr])
790
769
  }
791
-
792
- func centralManager(_ central: CBCentralManager,
770
+
771
+ public func centralManager(_ central: CBCentralManager,
793
772
  didDisconnectPeripheral peripheral:
794
773
  CBPeripheral, error: Error?) {
795
774
  let peripheralUUIDString:String = peripheral.uuidAsString()
796
775
  NSLog("Peripheral Disconnected: \(peripheralUUIDString)")
797
-
776
+
798
777
  if let error = error {
799
778
  NSLog("Error: \(error)")
800
779
  }
801
-
780
+
802
781
  let errorStr = "Peripheral did disconnect: \(peripheralUUIDString)"
803
-
782
+
804
783
  invokeAndClearDictionary(&connectCallbacks, withKey: peripheralUUIDString, usingParameters: [errorStr])
805
784
  invokeAndClearDictionary(&readRSSICallbacks, withKey: peripheralUUIDString, usingParameters: [errorStr])
806
785
  invokeAndClearDictionary(&retrieveServicesCallbacks, withKey: peripheralUUIDString, usingParameters: [errorStr])
807
-
808
-
786
+
787
+
809
788
  for key in readCallbacks.keys {
810
789
  if let keyString = key as String?, keyString.hasPrefix(peripheralUUIDString) {
811
790
  invokeAndClearDictionary(&readCallbacks, withKey: key, usingParameters: [errorStr])
812
791
  }
813
792
  }
814
-
793
+
815
794
  for key in writeCallbacks.keys {
816
795
  if let keyString = key as String?, keyString.hasPrefix(peripheralUUIDString) {
817
796
  invokeAndClearDictionary(&writeCallbacks, withKey: key, usingParameters: [errorStr])
818
797
  }
819
798
  }
820
-
799
+
821
800
  for key in notificationCallbacks.keys {
822
801
  if let keyString = key as String?, keyString.hasPrefix(peripheralUUIDString) {
823
802
  invokeAndClearDictionary(&notificationCallbacks, withKey: key, usingParameters: [errorStr])
824
803
  }
825
804
  }
826
-
805
+
827
806
  for key in readDescriptorCallbacks.keys {
828
807
  if let keyString = key as String?, keyString.hasPrefix(peripheralUUIDString) {
829
808
  invokeAndClearDictionary(&readDescriptorCallbacks, withKey: key, usingParameters: [errorStr])
830
809
  }
831
810
  }
832
-
811
+
833
812
  for key in stopNotificationCallbacks.keys {
834
813
  if let keyString = key as String?, keyString.hasPrefix(peripheralUUIDString) {
835
814
  invokeAndClearDictionary(&stopNotificationCallbacks, withKey: key, usingParameters: [errorStr])
836
815
  }
837
816
  }
838
-
839
- if hasListeners {
840
- connectedPeripherals.remove(peripheralUUIDString)
841
- if let e:Error = error {
842
- sendEvent(withName: "BleManagerDisconnectPeripheral", body: ["peripheral": peripheralUUIDString, "domain": e._domain, "code": e._code, "description": e.localizedDescription])
843
- } else {
844
- sendEvent(withName: "BleManagerDisconnectPeripheral", body: ["peripheral": peripheralUUIDString])
845
- }
817
+
818
+ connectedPeripherals.remove(peripheralUUIDString)
819
+ if let e:Error = error {
820
+ self.bleManager?.emit(onDisconnectPeripheral: ["peripheral": peripheralUUIDString, "domain": e._domain, "code": e._code, "description": e.localizedDescription])
821
+ } else {
822
+ self.bleManager?.emit(onDisconnectPeripheral: ["peripheral": peripheralUUIDString])
846
823
  }
847
824
  }
848
-
849
-
850
- func centralManagerDidUpdateState(_ central: CBCentralManager) {
825
+
826
+
827
+ public func centralManagerDidUpdateState(_ central: CBCentralManager) {
851
828
  let stateName = Helper.centralManagerStateToString(central.state)
852
- if hasListeners {
853
- sendEvent(withName: "BleManagerDidUpdateState", body: ["state": stateName])
854
- }
829
+ self.bleManager?.emit(onDidUpdateState: ["state": stateName])
855
830
  if stateName == "off" {
856
831
  for peripheralUUID in connectedPeripherals {
857
832
  if let peripheral = peripherals[peripheralUUID] {
@@ -862,14 +837,14 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
862
837
  }
863
838
  }
864
839
  }
865
-
840
+
866
841
  func handleDiscoveredPeripheral(_ peripheral: CBPeripheral,
867
842
  advertisementData: [String : Any],
868
843
  rssi : NSNumber) {
869
- if BleManager.verboseLogging {
844
+ if SwiftBleManager.verboseLogging {
870
845
  NSLog("Discover peripheral: \(peripheral.name ?? "NO NAME")");
871
846
  }
872
-
847
+
873
848
  var cp: Peripheral? = nil
874
849
  serialQueue.sync {
875
850
  if let p = peripherals[peripheral.uuidAsString()] {
@@ -881,13 +856,11 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
881
856
  peripherals[peripheral.uuidAsString()] = cp
882
857
  }
883
858
  }
884
-
885
- if (hasListeners) {
886
- sendEvent(withName: "BleManagerDiscoverPeripheral", body: cp?.advertisingInfo())
887
- }
859
+
860
+ self.bleManager?.emit(onDiscoverPeripheral: cp?.advertisingInfo())
888
861
  }
889
-
890
- func centralManager(_ central: CBCentralManager,
862
+
863
+ public func centralManager(_ central: CBCentralManager,
891
864
  didDiscover peripheral: CBPeripheral,
892
865
  advertisementData: [String : Any],
893
866
  rssi RSSI: NSNumber) {
@@ -906,27 +879,27 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
906
879
  } else {
907
880
  handleDiscoveredPeripheral(peripheral, advertisementData: advertisementData, rssi: RSSI)
908
881
  }
909
-
910
-
882
+
883
+
911
884
  }
912
-
913
- func peripheral(_ peripheral: CBPeripheral,
885
+
886
+ public func peripheral(_ peripheral: CBPeripheral,
914
887
  didDiscoverServices error: Error?) {
915
888
  if let error = error {
916
889
  NSLog("Error: \(error)")
917
890
  return
918
891
  }
919
- if BleManager.verboseLogging {
892
+ if SwiftBleManager.verboseLogging {
920
893
  NSLog("Services Discover")
921
894
  }
922
-
895
+
923
896
  var servicesForPeripheral = Set<CBService>()
924
897
  servicesForPeripheral.formUnion(peripheral.services ?? [])
925
898
  retrieveServicesLatches[peripheral.uuidAsString()] = servicesForPeripheral
926
-
899
+
927
900
  if let services = peripheral.services {
928
901
  for service in services {
929
- if BleManager.verboseLogging {
902
+ if SwiftBleManager.verboseLogging {
930
903
  NSLog("Service \(service.uuid.uuidString) \(service.description)")
931
904
  }
932
905
  peripheral.discoverIncludedServices(nil, for: service) // discover included services
@@ -934,8 +907,8 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
934
907
  }
935
908
  }
936
909
  }
937
-
938
- func peripheral(_ peripheral: CBPeripheral,
910
+
911
+ public func peripheral(_ peripheral: CBPeripheral,
939
912
  didDiscoverIncludedServicesFor service: CBService,
940
913
  error: Error?) {
941
914
  if let error = error {
@@ -944,30 +917,30 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
944
917
  }
945
918
  peripheral.discoverCharacteristics(nil, for: service) // discover characteristics for included service
946
919
  }
947
-
948
- func peripheral(_ peripheral: CBPeripheral,
920
+
921
+ public func peripheral(_ peripheral: CBPeripheral,
949
922
  didDiscoverCharacteristicsFor service: CBService,
950
923
  error: Error?) {
951
924
  if let error = error {
952
925
  NSLog("Error: \(error)")
953
926
  return
954
927
  }
955
- if BleManager.verboseLogging {
928
+ if SwiftBleManager.verboseLogging {
956
929
  NSLog("Characteristics For Service Discover")
957
930
  }
958
-
931
+
959
932
  var characteristicsForService = Set<CBCharacteristic>()
960
933
  characteristicsForService.formUnion(service.characteristics ?? [])
961
934
  characteristicsLatches[service.uuid.uuidString] = characteristicsForService
962
-
935
+
963
936
  if let characteristics = service.characteristics {
964
937
  for characteristic in characteristics {
965
938
  peripheral.discoverDescriptors(for: characteristic)
966
939
  }
967
940
  }
968
941
  }
969
-
970
- func peripheral(_ peripheral: CBPeripheral,
942
+
943
+ public func peripheral(_ peripheral: CBPeripheral,
971
944
  didDiscoverDescriptorsFor characteristic: CBCharacteristic,
972
945
  error: Error?) {
973
946
  if let error = error {
@@ -976,21 +949,21 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
976
949
  }
977
950
  let peripheralUUIDString:String = peripheral.uuidAsString()
978
951
  let serviceUUIDString:String = (characteristic.service?.uuid.uuidString)!
979
-
980
- if BleManager.verboseLogging {
952
+
953
+ if SwiftBleManager.verboseLogging {
981
954
  NSLog("Descriptor For Characteristic Discover \(serviceUUIDString) \(characteristic.uuid.uuidString)")
982
955
  }
983
-
956
+
984
957
  if var servicesLatch = retrieveServicesLatches[peripheralUUIDString], var characteristicsLatch = characteristicsLatches[serviceUUIDString] {
985
-
958
+
986
959
  characteristicsLatch.remove(characteristic)
987
960
  characteristicsLatches[serviceUUIDString] = characteristicsLatch
988
-
961
+
989
962
  if characteristicsLatch.isEmpty {
990
963
  // All characteristics for this service have been checked
991
964
  servicesLatch.remove(characteristic.service!)
992
965
  retrieveServicesLatches[peripheralUUIDString] = servicesLatch
993
-
966
+
994
967
  if servicesLatch.isEmpty {
995
968
  // All characteristics and services have been checked
996
969
  if let peripheral = peripherals[peripheral.uuidAsString()] {
@@ -1000,58 +973,58 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1000
973
  retrieveServicesLatches.removeValue(forKey: peripheralUUIDString)
1001
974
  }
1002
975
  }
1003
-
976
+
1004
977
  }
1005
978
  }
1006
-
1007
- func peripheral(_ peripheral: CBPeripheral,
979
+
980
+ public func peripheral(_ peripheral: CBPeripheral,
1008
981
  didReadRSSI RSSI: NSNumber,
1009
982
  error: Error?) {
1010
- if BleManager.verboseLogging {
983
+ if SwiftBleManager.verboseLogging {
1011
984
  print("didReadRSSI \(RSSI)")
1012
985
  }
1013
-
986
+
1014
987
  if let error = error {
1015
988
  invokeAndClearDictionary(&readRSSICallbacks, withKey: peripheral.uuidAsString(), usingParameters: [error.localizedDescription, RSSI])
1016
989
  } else {
1017
990
  invokeAndClearDictionary(&readRSSICallbacks, withKey: peripheral.uuidAsString(), usingParameters: [NSNull(), RSSI])
1018
991
  }
1019
992
  }
1020
-
1021
- func peripheral(_ peripheral: CBPeripheral,
993
+
994
+ public func peripheral(_ peripheral: CBPeripheral,
1022
995
  didUpdateValueFor descriptor: CBDescriptor,
1023
996
  error: Error?) {
1024
997
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: descriptor.characteristic!, andDescriptor: descriptor)
1025
-
998
+
1026
999
  if let error = error {
1027
1000
  NSLog("Error reading descriptor value for \(descriptor.uuid) on characteristic \(descriptor.characteristic!.uuid) :\(error)")
1028
1001
  invokeAndClearDictionary(&readDescriptorCallbacks, withKey: key, usingParameters: [error.localizedDescription, NSNull()])
1029
1002
  return
1030
1003
  }
1031
-
1004
+
1032
1005
  if let descriptorValue = descriptor.value as? Data {
1033
1006
  NSLog("Read value [descriptor: \(descriptor.uuid), characteristic: \(descriptor.characteristic!.uuid)]: (\(descriptorValue.count)) \(descriptorValue.hexadecimalString())")
1034
1007
  } else {
1035
1008
  NSLog("Read value [descriptor: \(descriptor.uuid), characteristic: \(descriptor.characteristic!.uuid)]: \(String(describing: descriptor.value))")
1036
1009
  }
1037
-
1010
+
1038
1011
  if readDescriptorCallbacks[key] != nil {
1039
1012
  // The most future proof way of doing this that I could find, other option would be running strcmp on CBUUID strings
1040
1013
  // https://developer.apple.com/documentation/corebluetooth/cbuuid/characteristic_descriptors
1041
1014
  if let descriptorValue = descriptor.value as? Data {
1042
- if (BleManager.verboseLogging) {
1015
+ if (SwiftBleManager.verboseLogging) {
1043
1016
  NSLog("Descriptor value is Data")
1044
1017
  }
1045
1018
  invokeAndClearDictionary(&readDescriptorCallbacks, withKey: key, usingParameters: [NSNull(), descriptorValue.toArray()])
1046
1019
  } else if let descriptorValue = descriptor.value as? NSNumber {
1047
- if (BleManager.verboseLogging) {
1020
+ if (SwiftBleManager.verboseLogging) {
1048
1021
  NSLog("Descriptor value is NSNumber")
1049
1022
  }
1050
1023
  var value = descriptorValue.uint64Value
1051
1024
  let byteData = Data(bytes: &value, count: MemoryLayout.size(ofValue: value))
1052
1025
  invokeAndClearDictionary(&readDescriptorCallbacks, withKey: key, usingParameters: [NSNull(), byteData.toArray()])
1053
1026
  } else if let descriptorValue = descriptor.value as? String {
1054
- if (BleManager.verboseLogging) {
1027
+ if (SwiftBleManager.verboseLogging) {
1055
1028
  NSLog("Descriptor value is String")
1056
1029
  }
1057
1030
  if let byteData = descriptorValue.data(using: .utf8) {
@@ -1065,65 +1038,59 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1065
1038
  }
1066
1039
  }
1067
1040
  }
1068
-
1069
- func peripheral(_ peripheral: CBPeripheral,
1041
+
1042
+ public func peripheral(_ peripheral: CBPeripheral,
1070
1043
  didUpdateValueFor characteristic: CBCharacteristic,
1071
1044
  error: Error?) {
1072
1045
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: characteristic)
1073
-
1046
+
1074
1047
  if let error = error {
1075
1048
  NSLog("Error \(characteristic.uuid) :\(error)")
1076
1049
  invokeAndClearDictionary(&readCallbacks, withKey: key, usingParameters: [error.localizedDescription, NSNull()])
1077
1050
  return
1078
1051
  }
1079
-
1080
- if BleManager.verboseLogging, let value = characteristic.value {
1052
+
1053
+ if SwiftBleManager.verboseLogging, let value = characteristic.value {
1081
1054
  NSLog("Read value [\(characteristic.uuid)]: \( value.hexadecimalString())")
1082
1055
  }
1083
-
1056
+
1084
1057
  serialQueue.sync {
1085
1058
  if readCallbacks[key] != nil {
1086
1059
  invokeAndClearDictionary_THREAD_UNSAFE(&readCallbacks, withKey: key, usingParameters: [NSNull(), characteristic.value!.toArray()])
1087
1060
  } else {
1088
- if hasListeners {
1089
- sendEvent(withName: "BleManagerDidUpdateValueForCharacteristic", body: [
1090
- "peripheral": peripheral.uuidAsString(),
1091
- "characteristic": characteristic.uuid.uuidString.lowercased(),
1092
- "service": characteristic.service!.uuid.uuidString.lowercased(),
1093
- "value": characteristic.value!.toArray()
1094
- ])
1095
- }
1061
+ self.bleManager?.emitOnDidUpdateValue(forCharacteristic: [
1062
+ "peripheral": peripheral.uuidAsString(),
1063
+ "characteristic": characteristic.uuid.uuidString.lowercased(),
1064
+ "service": characteristic.service!.uuid.uuidString.lowercased(),
1065
+ "value": characteristic.value!.toArray()
1066
+ ])
1096
1067
  }
1097
1068
  }
1098
1069
  }
1099
-
1100
- func peripheral(_ peripheral: CBPeripheral,
1070
+
1071
+ public func peripheral(_ peripheral: CBPeripheral,
1101
1072
  didUpdateNotificationStateFor characteristic: CBCharacteristic,
1102
1073
  error: Error?) {
1103
1074
  if let error = error {
1104
1075
  NSLog("Error in didUpdateNotificationStateForCharacteristic: \(error)")
1105
-
1106
- if hasListeners {
1107
- sendEvent(withName: "BleManagerDidUpdateNotificationStateFor", body: [
1108
- "peripheral": peripheral.uuidAsString(),
1109
- "characteristic": characteristic.uuid.uuidString.lowercased(),
1110
- "isNotifying": false,
1111
- "domain": error._domain,
1112
- "code": error._code
1113
- ])
1114
- }
1076
+
1077
+ self.bleManager?.emitOnDidUpdateNotificationState(for: [
1078
+ "peripheral": peripheral.uuidAsString(),
1079
+ "characteristic": characteristic.uuid.uuidString.lowercased(),
1080
+ "isNotifying": false,
1081
+ "domain": error._domain,
1082
+ "code": error._code
1083
+ ])
1115
1084
  } else {
1116
- if hasListeners {
1117
- sendEvent(withName: "BleManagerDidUpdateNotificationStateFor", body: [
1118
- "peripheral": peripheral.uuidAsString(),
1119
- "characteristic": characteristic.uuid.uuidString.lowercased(),
1120
- "isNotifying": characteristic.isNotifying
1121
- ])
1122
- }
1085
+ self.bleManager?.emitOnDidUpdateNotificationState(for: [
1086
+ "peripheral": peripheral.uuidAsString(),
1087
+ "characteristic": characteristic.uuid.uuidString.lowercased(),
1088
+ "isNotifying": characteristic.isNotifying
1089
+ ])
1123
1090
  }
1124
-
1091
+
1125
1092
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: characteristic)
1126
-
1093
+
1127
1094
  if let error = error {
1128
1095
  if notificationCallbacks[key] != nil {
1129
1096
  invokeAndClearDictionary(&notificationCallbacks, withKey: key, usingParameters: [error])
@@ -1133,7 +1100,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1133
1100
  }
1134
1101
  } else {
1135
1102
  if characteristic.isNotifying {
1136
- if BleManager.verboseLogging {
1103
+ if SwiftBleManager.verboseLogging {
1137
1104
  NSLog("Notification began on \(characteristic.uuid)")
1138
1105
  }
1139
1106
  if notificationCallbacks[key] != nil {
@@ -1141,7 +1108,7 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1141
1108
  }
1142
1109
  } else {
1143
1110
  // Notification has stopped
1144
- if BleManager.verboseLogging {
1111
+ if SwiftBleManager.verboseLogging {
1145
1112
  NSLog("Notification ended on \(characteristic.uuid)")
1146
1113
  }
1147
1114
  if stopNotificationCallbacks[key] != nil {
@@ -1150,12 +1117,12 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1150
1117
  }
1151
1118
  }
1152
1119
  }
1153
-
1154
- func peripheral(_ peripheral: CBPeripheral,
1120
+
1121
+ public func peripheral(_ peripheral: CBPeripheral,
1155
1122
  didWriteValueFor descriptor: CBDescriptor,
1156
1123
  error: Error?) {
1157
1124
  NSLog("didWrite descriptor")
1158
-
1125
+
1159
1126
  let key = Helper.key(forPeripheral: peripheral, andCharacteristic: descriptor.characteristic!, andDescriptor: descriptor)
1160
1127
  let callbacks = writeDescriptorCallbacks[key]
1161
1128
  if callbacks != nil {
@@ -1167,15 +1134,15 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1167
1134
  }
1168
1135
  }
1169
1136
  }
1170
-
1171
- func peripheral(_ peripheral: CBPeripheral,
1137
+
1138
+ public func peripheral(_ peripheral: CBPeripheral,
1172
1139
  didWriteValueFor characteristic: CBCharacteristic,
1173
1140
  error: Error?) {
1174
1141
  NSLog("didWrite")
1175
-
1142
+
1176
1143
  let key = Helper.key(forPeripheral:peripheral, andCharacteristic: characteristic)
1177
1144
  let peripheralWriteCallbacks = writeCallbacks[key]
1178
-
1145
+
1179
1146
  if peripheralWriteCallbacks != nil {
1180
1147
  if let error = error {
1181
1148
  NSLog("\(error)")
@@ -1191,76 +1158,76 @@ class BleManager: RCTEventEmitter, CBCentralManagerDelegate, CBPeripheralDelegat
1191
1158
  }
1192
1159
  }
1193
1160
  }
1194
-
1195
-
1161
+
1162
+
1196
1163
  static func getCentralManager() -> CBCentralManager? {
1197
1164
  return sharedManager
1198
1165
  }
1199
-
1200
- static func getInstance() -> BleManager? {
1166
+
1167
+ static func getInstance() -> SwiftBleManager? {
1201
1168
  return shared
1202
1169
  }
1203
-
1204
- @objc func enableBluetooth(_ callback: @escaping RCTResponseSenderBlock) {
1170
+
1171
+ @objc public func enableBluetooth(_ callback: @escaping RCTResponseSenderBlock) {
1205
1172
  callback(["Not supported"])
1206
1173
  }
1207
-
1208
- @objc func getBondedPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
1174
+
1175
+ @objc public func getBondedPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
1209
1176
  callback(["Not supported"])
1210
1177
  }
1211
-
1212
- @objc func createBond(_ peripheralUUID: String,
1178
+
1179
+ @objc public func createBond(_ peripheralUUID: String,
1213
1180
  devicePin: String,
1214
1181
  callback: @escaping RCTResponseSenderBlock) {
1215
1182
  callback(["Not supported"])
1216
1183
  }
1217
-
1218
- @objc func removeBond(_ peripheralUUID: String,
1184
+
1185
+ @objc public func removeBond(_ peripheralUUID: String,
1219
1186
  callback: @escaping RCTResponseSenderBlock) {
1220
1187
  callback(["Not supported"])
1221
1188
  }
1222
-
1223
- @objc func removePeripheral(_ peripheralUUID: String,
1189
+
1190
+ @objc public func removePeripheral(_ peripheralUUID: String,
1224
1191
  callback: @escaping RCTResponseSenderBlock) {
1225
1192
  callback(["Not supported"])
1226
1193
  }
1227
-
1228
- @objc func requestMTU(_ peripheralUUID: String,
1194
+
1195
+ @objc public func requestMTU(_ peripheralUUID: String,
1229
1196
  mtu: Int,
1230
1197
  callback: @escaping RCTResponseSenderBlock) {
1231
1198
  callback(["Not supported"])
1232
1199
  }
1233
-
1234
- @objc func requestConnectionPriority(_ peripheralUUID: String,
1235
- mtu: Int,
1200
+
1201
+ @objc public func requestConnectionPriority(_ peripheralUUID: String,
1202
+ connectionPriority: Int,
1236
1203
  callback: @escaping RCTResponseSenderBlock) {
1237
1204
  callback(["Not supported"])
1238
1205
  }
1239
-
1240
- @objc func refreshCache(_ peripheralUUID: String,
1206
+
1207
+ @objc public func refreshCache(_ peripheralUUID: String,
1241
1208
  callback: @escaping RCTResponseSenderBlock) {
1242
1209
  callback(["Not supported"])
1243
1210
  }
1244
-
1245
- @objc func setName(_ name: String,
1246
- callback: @escaping RCTResponseSenderBlock) {
1247
- callback(["Not supported"])
1211
+
1212
+ @objc public func setName(_ name: String) {
1213
+ // Not supported
1248
1214
  }
1249
-
1250
- @objc func getAssociatedPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
1215
+
1216
+ @objc public func getAssociatedPeripherals(_ callback: @escaping RCTResponseSenderBlock) {
1251
1217
  callback(["Not supported"])
1252
1218
  }
1253
-
1254
- @objc func removeAssociatedPeripheral(_ peripheralUUID: String,
1219
+
1220
+ @objc public func removeAssociatedPeripheral(_ peripheralUUID: String,
1255
1221
  callback: @escaping RCTResponseSenderBlock) {
1256
1222
  callback(["Not supported"])
1257
1223
  }
1258
-
1259
- @objc func supportsCompanion(_ callback: @escaping RCTResponseSenderBlock) {
1260
- callback(["Not supported"])
1224
+
1225
+ @objc public func supportsCompanion(_ callback: @escaping RCTResponseSenderBlock) {
1226
+ callback([NSNull(), false])
1261
1227
  }
1262
-
1228
+
1263
1229
  @objc public func companionScan(_ serviceUUIDs: [Any],
1230
+ option: NSDictionary,
1264
1231
  callback:RCTResponseSenderBlock) {
1265
1232
  callback(["Not supported"])
1266
1233
  }