@capgo/capacitor-bluetooth-low-energy 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CapgoCapacitorBluetoothLowEnergy.podspec +17 -0
- package/LICENSE +373 -0
- package/Package.swift +28 -0
- package/README.md +1154 -0
- package/android/build.gradle +59 -0
- package/android/src/main/AndroidManifest.xml +18 -0
- package/android/src/main/java/ee/forgr/plugin/bluetooth_low_energy/BluetoothLowEnergyPlugin.java +1149 -0
- package/dist/docs.json +2856 -0
- package/dist/esm/definitions.d.ts +1333 -0
- package/dist/esm/definitions.js +72 -0
- package/dist/esm/definitions.js.map +1 -0
- package/dist/esm/index.d.ts +4 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/web.d.ts +112 -0
- package/dist/esm/web.js +319 -0
- package/dist/esm/web.js.map +1 -0
- package/dist/plugin.cjs.js +406 -0
- package/dist/plugin.cjs.js.map +1 -0
- package/dist/plugin.js +409 -0
- package/dist/plugin.js.map +1 -0
- package/ios/Sources/BluetoothLowEnergyPlugin/BluetoothLowEnergy.swift +623 -0
- package/ios/Sources/BluetoothLowEnergyPlugin/BluetoothLowEnergyPlugin.swift +448 -0
- package/ios/Tests/BluetoothLowEnergyPluginTests/BluetoothLowEnergyTests.swift +11 -0
- package/package.json +87 -0
|
@@ -0,0 +1,623 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import CoreBluetooth
|
|
3
|
+
|
|
4
|
+
// swiftlint:disable type_body_length file_length function_parameter_count for_where
|
|
5
|
+
public class BluetoothLowEnergy: NSObject {
|
|
6
|
+
fileprivate weak var plugin: BluetoothLowEnergyPlugin?
|
|
7
|
+
private var centralManager: CBCentralManager?
|
|
8
|
+
private var peripheralManager: CBPeripheralManager?
|
|
9
|
+
|
|
10
|
+
private var discoveredPeripherals: [String: CBPeripheral] = [:]
|
|
11
|
+
private var connectedPeripherals: [String: CBPeripheral] = [:]
|
|
12
|
+
private var peripheralDelegates: [String: PeripheralDelegate] = [:]
|
|
13
|
+
|
|
14
|
+
private var scanCallback: ((Error?) -> Void)?
|
|
15
|
+
private var connectCallbacks: [String: (Error?) -> Void] = [:]
|
|
16
|
+
private var disconnectCallbacks: [String: (Error?) -> Void] = [:]
|
|
17
|
+
fileprivate var discoverServicesCallbacks: [String: (Error?) -> Void] = [:]
|
|
18
|
+
fileprivate var readCharacteristicCallbacks: [String: (Result<[Int], Error>) -> Void] = [:]
|
|
19
|
+
fileprivate var writeCharacteristicCallbacks: [String: (Error?) -> Void] = [:]
|
|
20
|
+
fileprivate var notifyCallbacks: [String: (Error?) -> Void] = [:]
|
|
21
|
+
fileprivate var readDescriptorCallbacks: [String: (Result<[Int], Error>) -> Void] = [:]
|
|
22
|
+
fileprivate var writeDescriptorCallbacks: [String: (Error?) -> Void] = [:]
|
|
23
|
+
fileprivate var readRssiCallbacks: [String: (Result<Int, Error>) -> Void] = [:]
|
|
24
|
+
|
|
25
|
+
private var scanTimer: Timer?
|
|
26
|
+
private var allowDuplicates = false
|
|
27
|
+
private var mode: String = "central"
|
|
28
|
+
|
|
29
|
+
init(plugin: BluetoothLowEnergyPlugin) {
|
|
30
|
+
self.plugin = plugin
|
|
31
|
+
super.init()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
func initialize(mode: String, completion: @escaping (Error?) -> Void) {
|
|
35
|
+
self.mode = mode
|
|
36
|
+
|
|
37
|
+
if mode == "peripheral" {
|
|
38
|
+
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
|
|
39
|
+
} else {
|
|
40
|
+
centralManager = CBCentralManager(delegate: self, queue: nil)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Wait for the manager to be ready
|
|
44
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
|
|
45
|
+
completion(nil)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
func isAvailable() -> Bool {
|
|
50
|
+
if mode == "peripheral" {
|
|
51
|
+
return peripheralManager?.state != .unsupported
|
|
52
|
+
}
|
|
53
|
+
return centralManager?.state != .unsupported
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
func isEnabled() -> Bool {
|
|
57
|
+
if mode == "peripheral" {
|
|
58
|
+
return peripheralManager?.state == .poweredOn
|
|
59
|
+
}
|
|
60
|
+
return centralManager?.state == .poweredOn
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
func getPermissionStatus() -> String {
|
|
64
|
+
if #available(iOS 13.1, *) {
|
|
65
|
+
switch CBCentralManager.authorization {
|
|
66
|
+
case .allowedAlways:
|
|
67
|
+
return "granted"
|
|
68
|
+
case .denied:
|
|
69
|
+
return "denied"
|
|
70
|
+
case .restricted:
|
|
71
|
+
return "denied"
|
|
72
|
+
case .notDetermined:
|
|
73
|
+
return "prompt"
|
|
74
|
+
@unknown default:
|
|
75
|
+
return "prompt"
|
|
76
|
+
}
|
|
77
|
+
} else {
|
|
78
|
+
return "granted"
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
func requestPermissions(completion: @escaping (String) -> Void) {
|
|
83
|
+
// Initializing the central manager triggers the permission prompt
|
|
84
|
+
if centralManager == nil {
|
|
85
|
+
centralManager = CBCentralManager(delegate: self, queue: nil)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
|
|
89
|
+
completion(self.getPermissionStatus())
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
func startScan(services: [CBUUID]?, timeout: Double, allowDuplicates: Bool, completion: @escaping (Error?) -> Void) {
|
|
94
|
+
guard let centralManager = centralManager else {
|
|
95
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "Central manager not initialized"]))
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
guard centralManager.state == .poweredOn else {
|
|
100
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 2, userInfo: [NSLocalizedDescriptionKey: "Bluetooth is not powered on"]))
|
|
101
|
+
return
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
self.allowDuplicates = allowDuplicates
|
|
105
|
+
scanCallback = completion
|
|
106
|
+
|
|
107
|
+
var options: [String: Any] = [:]
|
|
108
|
+
if allowDuplicates {
|
|
109
|
+
options[CBCentralManagerScanOptionAllowDuplicatesKey] = true
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
centralManager.scanForPeripherals(withServices: services, options: options)
|
|
113
|
+
|
|
114
|
+
if timeout > 0 {
|
|
115
|
+
scanTimer = Timer.scheduledTimer(withTimeInterval: timeout / 1000.0, repeats: false) { [weak self] _ in
|
|
116
|
+
self?.stopScan()
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
completion(nil)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
func stopScan() {
|
|
124
|
+
scanTimer?.invalidate()
|
|
125
|
+
scanTimer = nil
|
|
126
|
+
centralManager?.stopScan()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
func connect(deviceId: String, autoConnect: Bool, completion: @escaping (Error?) -> Void) {
|
|
130
|
+
guard let peripheral = discoveredPeripherals[deviceId] else {
|
|
131
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 3, userInfo: [NSLocalizedDescriptionKey: "Device not found"]))
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
connectCallbacks[deviceId] = completion
|
|
136
|
+
|
|
137
|
+
var options: [String: Any]?
|
|
138
|
+
if autoConnect {
|
|
139
|
+
options = [CBConnectPeripheralOptionNotifyOnConnectionKey: true]
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
centralManager?.connect(peripheral, options: options)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
func disconnect(deviceId: String, completion: @escaping (Error?) -> Void) {
|
|
146
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
147
|
+
completion(nil)
|
|
148
|
+
return
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
disconnectCallbacks[deviceId] = completion
|
|
152
|
+
centralManager?.cancelPeripheralConnection(peripheral)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
func discoverServices(deviceId: String, completion: @escaping (Error?) -> Void) {
|
|
156
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
157
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"]))
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
discoverServicesCallbacks[deviceId] = completion
|
|
162
|
+
peripheral.discoverServices(nil)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
func getServices(deviceId: String) -> [[String: Any]] {
|
|
166
|
+
guard let peripheral = connectedPeripherals[deviceId],
|
|
167
|
+
let services = peripheral.services else {
|
|
168
|
+
return []
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return services.map { service in
|
|
172
|
+
var serviceDict: [String: Any] = [
|
|
173
|
+
"uuid": service.uuid.uuidString
|
|
174
|
+
]
|
|
175
|
+
|
|
176
|
+
if let characteristics = service.characteristics {
|
|
177
|
+
serviceDict["characteristics"] = characteristics.map { characteristic in
|
|
178
|
+
var charDict: [String: Any] = [
|
|
179
|
+
"uuid": characteristic.uuid.uuidString,
|
|
180
|
+
"properties": [
|
|
181
|
+
"broadcast": characteristic.properties.contains(.broadcast),
|
|
182
|
+
"read": characteristic.properties.contains(.read),
|
|
183
|
+
"writeWithoutResponse": characteristic.properties.contains(.writeWithoutResponse),
|
|
184
|
+
"write": characteristic.properties.contains(.write),
|
|
185
|
+
"notify": characteristic.properties.contains(.notify),
|
|
186
|
+
"indicate": characteristic.properties.contains(.indicate),
|
|
187
|
+
"authenticatedSignedWrites": characteristic.properties.contains(.authenticatedSignedWrites),
|
|
188
|
+
"extendedProperties": characteristic.properties.contains(.extendedProperties)
|
|
189
|
+
]
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
if let descriptors = characteristic.descriptors {
|
|
193
|
+
charDict["descriptors"] = descriptors.map { descriptor in
|
|
194
|
+
["uuid": descriptor.uuid.uuidString]
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
charDict["descriptors"] = []
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return charDict
|
|
201
|
+
}
|
|
202
|
+
} else {
|
|
203
|
+
serviceDict["characteristics"] = []
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return serviceDict
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
func getConnectedDevices() -> [[String: Any]] {
|
|
211
|
+
return connectedPeripherals.map { (deviceId, peripheral) in
|
|
212
|
+
[
|
|
213
|
+
"deviceId": deviceId,
|
|
214
|
+
"name": peripheral.name as Any
|
|
215
|
+
]
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
func readCharacteristic(deviceId: String, serviceUUID: String, characteristicUUID: String, completion: @escaping (Result<[Int], Error>) -> Void) {
|
|
220
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
221
|
+
completion(.failure(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"])))
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
guard let characteristic = findCharacteristic(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID) else {
|
|
226
|
+
completion(.failure(NSError(domain: "BluetoothLowEnergy", code: 5, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"])))
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
231
|
+
readCharacteristicCallbacks[key] = completion
|
|
232
|
+
peripheral.readValue(for: characteristic)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
func writeCharacteristic(deviceId: String, serviceUUID: String, characteristicUUID: String, value: [UInt8], writeType: String, completion: @escaping (Error?) -> Void) {
|
|
236
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
237
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"]))
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
guard let characteristic = findCharacteristic(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID) else {
|
|
242
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 5, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"]))
|
|
243
|
+
return
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
let data = Data(value)
|
|
247
|
+
let type: CBCharacteristicWriteType = writeType == "withoutResponse" ? .withoutResponse : .withResponse
|
|
248
|
+
|
|
249
|
+
if type == .withResponse {
|
|
250
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
251
|
+
writeCharacteristicCallbacks[key] = completion
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
peripheral.writeValue(data, for: characteristic, type: type)
|
|
255
|
+
|
|
256
|
+
if type == .withoutResponse {
|
|
257
|
+
completion(nil)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
func startCharacteristicNotifications(deviceId: String, serviceUUID: String, characteristicUUID: String, completion: @escaping (Error?) -> Void) {
|
|
262
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
263
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"]))
|
|
264
|
+
return
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
guard let characteristic = findCharacteristic(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID) else {
|
|
268
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 5, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"]))
|
|
269
|
+
return
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
273
|
+
notifyCallbacks[key] = completion
|
|
274
|
+
peripheral.setNotifyValue(true, for: characteristic)
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
func stopCharacteristicNotifications(deviceId: String, serviceUUID: String, characteristicUUID: String, completion: @escaping (Error?) -> Void) {
|
|
278
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
279
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"]))
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
guard let characteristic = findCharacteristic(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID) else {
|
|
284
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 5, userInfo: [NSLocalizedDescriptionKey: "Characteristic not found"]))
|
|
285
|
+
return
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
289
|
+
notifyCallbacks[key] = completion
|
|
290
|
+
peripheral.setNotifyValue(false, for: characteristic)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
func readDescriptor(deviceId: String, serviceUUID: String, characteristicUUID: String, descriptorUUID: String, completion: @escaping (Result<[Int], Error>) -> Void) {
|
|
294
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
295
|
+
completion(.failure(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"])))
|
|
296
|
+
return
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
guard let descriptor = findDescriptor(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID, descriptorUUID: descriptorUUID) else {
|
|
300
|
+
completion(.failure(NSError(domain: "BluetoothLowEnergy", code: 6, userInfo: [NSLocalizedDescriptionKey: "Descriptor not found"])))
|
|
301
|
+
return
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)-\(descriptorUUID)"
|
|
305
|
+
readDescriptorCallbacks[key] = completion
|
|
306
|
+
peripheral.readValue(for: descriptor)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
func writeDescriptor(deviceId: String, serviceUUID: String, characteristicUUID: String, descriptorUUID: String, value: [UInt8], completion: @escaping (Error?) -> Void) {
|
|
310
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
311
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"]))
|
|
312
|
+
return
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
guard let descriptor = findDescriptor(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID, descriptorUUID: descriptorUUID) else {
|
|
316
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 6, userInfo: [NSLocalizedDescriptionKey: "Descriptor not found"]))
|
|
317
|
+
return
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)-\(descriptorUUID)"
|
|
321
|
+
writeDescriptorCallbacks[key] = completion
|
|
322
|
+
peripheral.writeValue(Data(value), for: descriptor)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
func readRssi(deviceId: String, completion: @escaping (Result<Int, Error>) -> Void) {
|
|
326
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
327
|
+
completion(.failure(NSError(domain: "BluetoothLowEnergy", code: 4, userInfo: [NSLocalizedDescriptionKey: "Device not connected"])))
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
readRssiCallbacks[deviceId] = completion
|
|
332
|
+
peripheral.readRSSI()
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
func getMtu(deviceId: String) -> Int {
|
|
336
|
+
guard let peripheral = connectedPeripherals[deviceId] else {
|
|
337
|
+
return 20
|
|
338
|
+
}
|
|
339
|
+
return peripheral.maximumWriteValueLength(for: .withoutResponse) + 3
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
func startAdvertising(name: String?, services: [CBUUID]?, completion: @escaping (Error?) -> Void) {
|
|
343
|
+
guard let peripheralManager = peripheralManager else {
|
|
344
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 1, userInfo: [NSLocalizedDescriptionKey: "Peripheral manager not initialized"]))
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
guard peripheralManager.state == .poweredOn else {
|
|
349
|
+
completion(NSError(domain: "BluetoothLowEnergy", code: 2, userInfo: [NSLocalizedDescriptionKey: "Bluetooth is not powered on"]))
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
var advertisementData: [String: Any] = [:]
|
|
354
|
+
if let name = name {
|
|
355
|
+
advertisementData[CBAdvertisementDataLocalNameKey] = name
|
|
356
|
+
}
|
|
357
|
+
if let services = services {
|
|
358
|
+
advertisementData[CBAdvertisementDataServiceUUIDsKey] = services
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
peripheralManager.startAdvertising(advertisementData)
|
|
362
|
+
completion(nil)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
func stopAdvertising() {
|
|
366
|
+
peripheralManager?.stopAdvertising()
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// MARK: - Private Helpers
|
|
370
|
+
|
|
371
|
+
private func findCharacteristic(peripheral: CBPeripheral, serviceUUID: String, characteristicUUID: String) -> CBCharacteristic? {
|
|
372
|
+
guard let services = peripheral.services else { return nil }
|
|
373
|
+
|
|
374
|
+
let targetServiceUUID = CBUUID(string: serviceUUID)
|
|
375
|
+
let targetCharacteristicUUID = CBUUID(string: characteristicUUID)
|
|
376
|
+
|
|
377
|
+
for service in services {
|
|
378
|
+
if service.uuid == targetServiceUUID {
|
|
379
|
+
if let characteristics = service.characteristics {
|
|
380
|
+
for characteristic in characteristics where characteristic.uuid == targetCharacteristicUUID {
|
|
381
|
+
return characteristic
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return nil
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private func findDescriptor(peripheral: CBPeripheral, serviceUUID: String, characteristicUUID: String, descriptorUUID: String) -> CBDescriptor? {
|
|
390
|
+
guard let characteristic = findCharacteristic(peripheral: peripheral, serviceUUID: serviceUUID, characteristicUUID: characteristicUUID) else {
|
|
391
|
+
return nil
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
let targetDescriptorUUID = CBUUID(string: descriptorUUID)
|
|
395
|
+
|
|
396
|
+
if let descriptors = characteristic.descriptors {
|
|
397
|
+
for descriptor in descriptors where descriptor.uuid == targetDescriptorUUID {
|
|
398
|
+
return descriptor
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return nil
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private func dataToIntArray(_ data: Data?) -> [Int] {
|
|
405
|
+
guard let data = data else { return [] }
|
|
406
|
+
return data.map { Int($0) }
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// MARK: - CBCentralManagerDelegate
|
|
411
|
+
|
|
412
|
+
extension BluetoothLowEnergy: CBCentralManagerDelegate {
|
|
413
|
+
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
|
414
|
+
// State updated
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
|
|
418
|
+
let deviceId = peripheral.identifier.uuidString
|
|
419
|
+
discoveredPeripherals[deviceId] = peripheral
|
|
420
|
+
|
|
421
|
+
var device: [String: Any] = [
|
|
422
|
+
"deviceId": deviceId,
|
|
423
|
+
"name": peripheral.name as Any,
|
|
424
|
+
"rssi": RSSI.intValue
|
|
425
|
+
]
|
|
426
|
+
|
|
427
|
+
if let manufacturerData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data {
|
|
428
|
+
device["manufacturerData"] = manufacturerData.map { String(format: "%02x", $0) }.joined()
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if let serviceUUIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] {
|
|
432
|
+
device["serviceUuids"] = serviceUUIDs.map { $0.uuidString }
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
plugin?.emitDeviceScanned(device: device)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
|
439
|
+
let deviceId = peripheral.identifier.uuidString
|
|
440
|
+
connectedPeripherals[deviceId] = peripheral
|
|
441
|
+
|
|
442
|
+
let delegate = PeripheralDelegate(ble: self, deviceId: deviceId)
|
|
443
|
+
peripheralDelegates[deviceId] = delegate
|
|
444
|
+
peripheral.delegate = delegate
|
|
445
|
+
|
|
446
|
+
connectCallbacks[deviceId]?(nil)
|
|
447
|
+
connectCallbacks.removeValue(forKey: deviceId)
|
|
448
|
+
|
|
449
|
+
plugin?.emitDeviceConnected(deviceId: deviceId)
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
|
|
453
|
+
let deviceId = peripheral.identifier.uuidString
|
|
454
|
+
let err = error ?? NSError(domain: "BluetoothLowEnergy", code: 7, userInfo: [NSLocalizedDescriptionKey: "Failed to connect"])
|
|
455
|
+
connectCallbacks[deviceId]?(err)
|
|
456
|
+
connectCallbacks.removeValue(forKey: deviceId)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
|
|
460
|
+
let deviceId = peripheral.identifier.uuidString
|
|
461
|
+
connectedPeripherals.removeValue(forKey: deviceId)
|
|
462
|
+
peripheralDelegates.removeValue(forKey: deviceId)
|
|
463
|
+
|
|
464
|
+
disconnectCallbacks[deviceId]?(error)
|
|
465
|
+
disconnectCallbacks.removeValue(forKey: deviceId)
|
|
466
|
+
|
|
467
|
+
plugin?.emitDeviceDisconnected(deviceId: deviceId)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// MARK: - CBPeripheralManagerDelegate
|
|
472
|
+
|
|
473
|
+
extension BluetoothLowEnergy: CBPeripheralManagerDelegate {
|
|
474
|
+
public func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
|
|
475
|
+
// State updated
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// MARK: - PeripheralDelegate
|
|
480
|
+
|
|
481
|
+
class PeripheralDelegate: NSObject, CBPeripheralDelegate {
|
|
482
|
+
private weak var ble: BluetoothLowEnergy?
|
|
483
|
+
private let deviceId: String
|
|
484
|
+
|
|
485
|
+
init(ble: BluetoothLowEnergy, deviceId: String) {
|
|
486
|
+
self.ble = ble
|
|
487
|
+
self.deviceId = deviceId
|
|
488
|
+
super.init()
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
|
492
|
+
if let error = error {
|
|
493
|
+
ble?.discoverServicesCallbacks[deviceId]?(error)
|
|
494
|
+
ble?.discoverServicesCallbacks.removeValue(forKey: deviceId)
|
|
495
|
+
return
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// Discover characteristics for all services
|
|
499
|
+
var pendingServices = peripheral.services?.count ?? 0
|
|
500
|
+
if pendingServices == 0 {
|
|
501
|
+
ble?.discoverServicesCallbacks[deviceId]?(nil)
|
|
502
|
+
ble?.discoverServicesCallbacks.removeValue(forKey: deviceId)
|
|
503
|
+
return
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
for service in peripheral.services ?? [] {
|
|
507
|
+
peripheral.discoverCharacteristics(nil, for: service)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
|
|
512
|
+
// Discover descriptors for all characteristics
|
|
513
|
+
for characteristic in service.characteristics ?? [] {
|
|
514
|
+
peripheral.discoverDescriptors(for: characteristic)
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: Error?) {
|
|
519
|
+
// Check if all services have been fully discovered
|
|
520
|
+
var allDiscovered = true
|
|
521
|
+
for service in peripheral.services ?? [] {
|
|
522
|
+
if service.characteristics == nil {
|
|
523
|
+
allDiscovered = false
|
|
524
|
+
break
|
|
525
|
+
}
|
|
526
|
+
for char in service.characteristics ?? [] {
|
|
527
|
+
if char.descriptors == nil {
|
|
528
|
+
allDiscovered = false
|
|
529
|
+
break
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
if allDiscovered {
|
|
535
|
+
ble?.discoverServicesCallbacks[deviceId]?(nil)
|
|
536
|
+
ble?.discoverServicesCallbacks.removeValue(forKey: deviceId)
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
|
|
541
|
+
let serviceUUID = characteristic.service?.uuid.uuidString ?? ""
|
|
542
|
+
let characteristicUUID = characteristic.uuid.uuidString
|
|
543
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
544
|
+
|
|
545
|
+
if let callback = ble?.readCharacteristicCallbacks[key] {
|
|
546
|
+
if let error = error {
|
|
547
|
+
callback(.failure(error))
|
|
548
|
+
} else {
|
|
549
|
+
let value = characteristic.value?.map { Int($0) } ?? []
|
|
550
|
+
callback(.success(value))
|
|
551
|
+
}
|
|
552
|
+
ble?.readCharacteristicCallbacks.removeValue(forKey: key)
|
|
553
|
+
} else {
|
|
554
|
+
// This is a notification
|
|
555
|
+
let value = characteristic.value?.map { Int($0) } ?? []
|
|
556
|
+
ble?.plugin?.emitCharacteristicChanged(
|
|
557
|
+
deviceId: deviceId,
|
|
558
|
+
service: serviceUUID,
|
|
559
|
+
characteristic: characteristicUUID,
|
|
560
|
+
value: value
|
|
561
|
+
)
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
|
|
566
|
+
let serviceUUID = characteristic.service?.uuid.uuidString ?? ""
|
|
567
|
+
let characteristicUUID = characteristic.uuid.uuidString
|
|
568
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
569
|
+
|
|
570
|
+
ble?.writeCharacteristicCallbacks[key]?(error)
|
|
571
|
+
ble?.writeCharacteristicCallbacks.removeValue(forKey: key)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
|
|
575
|
+
let serviceUUID = characteristic.service?.uuid.uuidString ?? ""
|
|
576
|
+
let characteristicUUID = characteristic.uuid.uuidString
|
|
577
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)"
|
|
578
|
+
|
|
579
|
+
ble?.notifyCallbacks[key]?(error)
|
|
580
|
+
ble?.notifyCallbacks.removeValue(forKey: key)
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor descriptor: CBDescriptor, error: Error?) {
|
|
584
|
+
let serviceUUID = descriptor.characteristic?.service?.uuid.uuidString ?? ""
|
|
585
|
+
let characteristicUUID = descriptor.characteristic?.uuid.uuidString ?? ""
|
|
586
|
+
let descriptorUUID = descriptor.uuid.uuidString
|
|
587
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)-\(descriptorUUID)"
|
|
588
|
+
|
|
589
|
+
if let callback = ble?.readDescriptorCallbacks[key] {
|
|
590
|
+
if let error = error {
|
|
591
|
+
callback(.failure(error))
|
|
592
|
+
} else {
|
|
593
|
+
var value: [Int] = []
|
|
594
|
+
if let data = descriptor.value as? Data {
|
|
595
|
+
value = data.map { Int($0) }
|
|
596
|
+
}
|
|
597
|
+
callback(.success(value))
|
|
598
|
+
}
|
|
599
|
+
ble?.readDescriptorCallbacks.removeValue(forKey: key)
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
|
|
604
|
+
let serviceUUID = descriptor.characteristic?.service?.uuid.uuidString ?? ""
|
|
605
|
+
let characteristicUUID = descriptor.characteristic?.uuid.uuidString ?? ""
|
|
606
|
+
let descriptorUUID = descriptor.uuid.uuidString
|
|
607
|
+
let key = "\(deviceId)-\(serviceUUID)-\(characteristicUUID)-\(descriptorUUID)"
|
|
608
|
+
|
|
609
|
+
ble?.writeDescriptorCallbacks[key]?(error)
|
|
610
|
+
ble?.writeDescriptorCallbacks.removeValue(forKey: key)
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
|
|
614
|
+
if let callback = ble?.readRssiCallbacks[deviceId] {
|
|
615
|
+
if let error = error {
|
|
616
|
+
callback(.failure(error))
|
|
617
|
+
} else {
|
|
618
|
+
callback(.success(RSSI.intValue))
|
|
619
|
+
}
|
|
620
|
+
ble?.readRssiCallbacks.removeValue(forKey: deviceId)
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|