@blotch/angular-lynx-native 22.3.1 → 22.3.2

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 (100) hide show
  1. package/README.md +41 -15
  2. package/dist/android/project.d.ts +90 -1
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +369 -5
  5. package/dist/eject.d.ts +15 -1
  6. package/dist/eject.d.ts.map +1 -1
  7. package/dist/eject.js +13 -2
  8. package/dist/features.d.ts +70 -0
  9. package/dist/features.d.ts.map +1 -0
  10. package/dist/features.js +115 -0
  11. package/dist/generate.d.ts +17 -1
  12. package/dist/generate.d.ts.map +1 -1
  13. package/dist/generate.js +12 -4
  14. package/dist/index.d.ts +1 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -1
  17. package/dist/ios/build.d.ts.map +1 -1
  18. package/dist/ios/build.js +8 -2
  19. package/dist/ios/frameworks.d.ts +6 -5
  20. package/dist/ios/frameworks.d.ts.map +1 -1
  21. package/dist/ios/frameworks.js +46 -15
  22. package/dist/ios/project.d.ts +173 -11
  23. package/dist/ios/project.d.ts.map +1 -1
  24. package/dist/ios/project.js +767 -33
  25. package/dist/options.d.ts +140 -1
  26. package/dist/options.d.ts.map +1 -1
  27. package/dist/options.js +127 -0
  28. package/dist/permissions.d.ts +18 -1
  29. package/dist/permissions.d.ts.map +1 -1
  30. package/dist/permissions.js +63 -3
  31. package/package.json +1 -1
  32. package/templates/android/README.md +35 -2
  33. package/templates/android/angular-lynx.properties +2 -0
  34. package/templates/android/app/build.gradle.kts +51 -2
  35. package/templates/android/app/src/main/AndroidManifest.xml +14 -3
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/BarcodeScannerModule.kt +144 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/BiometricsModule.kt +433 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapPresenter.kt +98 -0
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/BitmapRendererContext.kt +175 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/BluetoothModule.kt +1288 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/CalendarModule.kt +127 -0
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DContext.kt +1557 -0
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/Canvas2DOps.kt +63 -0
  44. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasFilter.kt +357 -0
  45. package/templates/android/app/src/main/java/dev/angularlynx/shell/CanvasUI.kt +4 -3
  46. package/templates/android/app/src/main/java/dev/angularlynx/shell/FilePickerModule.kt +263 -0
  47. package/templates/android/app/src/main/java/dev/angularlynx/shell/HapticsModule.kt +82 -0
  48. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +376 -6
  49. package/templates/android/app/src/main/java/dev/angularlynx/shell/ModuleBytes.kt +58 -0
  50. package/templates/android/app/src/main/java/dev/angularlynx/shell/MotionModule.kt +332 -0
  51. package/templates/android/app/src/main/java/dev/angularlynx/shell/NfcModule.kt +274 -0
  52. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +25 -0
  53. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +168 -0
  54. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShareTargetModule.kt +234 -0
  55. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +6 -0
  56. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +47 -3
  57. package/templates/android/app/src/main/java/dev/angularlynx/shell/StoreReviewModule.kt +66 -0
  58. package/templates/android/app/src/main/java/dev/angularlynx/shell/SystemFontFamilies.kt +68 -0
  59. package/templates/android/app/src/main/java/dev/angularlynx/shell/TrackingModule.kt +74 -0
  60. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoFrameTarget.kt +429 -0
  61. package/templates/android/app/src/main/java/dev/angularlynx/shell/VideoUI.kt +676 -0
  62. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLContext.kt +128 -13
  63. package/templates/android/app/src/main/java/dev/angularlynx/shell/WebGLModule.kt +493 -65
  64. package/templates/android/app/src/main/java/dev/angularlynx/shell/WifiModule.kt +429 -0
  65. package/templates/android/app/src/main/res/values/biometrics.xml +9 -0
  66. package/templates/android/app/src/main/res/values/share_target.xml +11 -0
  67. package/templates/android/app/src/main/res/xml/backup_rules.xml +5 -3
  68. package/templates/android/app/src/main/res/xml/data_extraction_rules.xml +6 -3
  69. package/templates/android/build.gradle.kts +1 -1
  70. package/templates/android/gradle/wrapper/gradle-wrapper.properties +2 -2
  71. package/templates/ios/App/AngularLynxBitmapRendererContext.m +188 -0
  72. package/templates/ios/App/AngularLynxCanvas2DContext.m +2467 -0
  73. package/templates/ios/App/AngularLynxCanvas2DOps.h +61 -0
  74. package/templates/ios/App/AngularLynxVideo.h +37 -0
  75. package/templates/ios/App/AngularLynxVideo.m +435 -0
  76. package/templates/ios/App/AngularLynxWebGL.h +69 -7
  77. package/templates/ios/App/AngularLynxWebGL.m +538 -29
  78. package/templates/ios/App/AngularLynxWebGLContext.m +148 -46
  79. package/templates/ios/App/AppDelegate.swift +34 -2
  80. package/templates/ios/App/AppleSignInButton.swift +106 -0
  81. package/templates/ios/App/AppleSignInModule.swift +222 -0
  82. package/templates/ios/App/BarcodeScannerModule.swift +284 -0
  83. package/templates/ios/App/BiometricsModule.swift +256 -0
  84. package/templates/ios/App/BluetoothModule.swift +1086 -0
  85. package/templates/ios/App/CalendarModule.swift +158 -0
  86. package/templates/ios/App/FilePickerModule.swift +240 -0
  87. package/templates/ios/App/HapticsModule.swift +90 -0
  88. package/templates/ios/App/Info.plist +2 -0
  89. package/templates/ios/App/LynxViewController.swift +210 -6
  90. package/templates/ios/App/MotionModule.swift +430 -0
  91. package/templates/ios/App/NfcModule.swift +346 -0
  92. package/templates/ios/App/PhotoLibraryModule.swift +169 -0
  93. package/templates/ios/App/ShareTargetModule.swift +150 -0
  94. package/templates/ios/App/ShellModule.swift +17 -0
  95. package/templates/ios/App/StoreReviewModule.swift +61 -0
  96. package/templates/ios/App/TrackingModule.swift +121 -0
  97. package/templates/ios/App/WifiModule.swift +237 -0
  98. package/templates/ios/App/XElementRegistry.swift +13 -3
  99. package/templates/ios/ShareExtension/Info.plist +42 -0
  100. package/templates/ios/ShareExtension/ShareViewController.swift +387 -0
@@ -0,0 +1,1086 @@
1
+ import CoreBluetooth
2
+ import Foundation
3
+ import Lynx
4
+
5
+ // cspell:words CBUUID
6
+
7
+ /// The native module behind the runtime's `LynxBluetooth`, which calls it as
8
+ /// `NativeModules.AngularLynxBluetooth` (from the background thread, where
9
+ /// NativeModules lives): a Bluetooth LE central that scans, connects, reads,
10
+ /// writes and subscribes while the app is in the foreground.
11
+ ///
12
+ /// Only an app whose angular.json sets `permissions.bluetooth` has this file.
13
+ /// App Store Connect flags an app whose code uses CoreBluetooth without
14
+ /// `NSBluetoothAlwaysUsageDescription`, which the generator writes only then,
15
+ /// so it leaves the file out otherwise, and the shell registers the class by
16
+ /// its Objective-C name instead of naming it.
17
+ ///
18
+ /// Every method calls back once, with its result or `{ error, message }`.
19
+ /// What the app didn't ask for at that moment (a scan's sightings,
20
+ /// notifications, the radio turning off, a device going out of range) arrives
21
+ /// as the `angularLynxBluetooth` global event, an object with a `type`. A
22
+ /// scan's `device` and `scanStopped` events carry the `scan` id its
23
+ /// `startScan` was given.
24
+ ///
25
+ /// CoreBluetooth's objects belong to the queue their manager was made with, so
26
+ /// everything here, the methods Lynx calls on its JavaScript thread and
27
+ /// CoreBluetooth's delegate callbacks alike, runs on `queue`, and the state
28
+ /// needs no lock.
29
+ @objc(AngularLynxBluetoothModule)
30
+ final class BluetoothModule: NSObject, LynxContextModule, CBCentralManagerDelegate,
31
+ CBPeripheralDelegate
32
+ {
33
+ static var name: String { "AngularLynxBluetooth" }
34
+
35
+ static var methodLookup: [String: String] {
36
+ [
37
+ "getState": NSStringFromSelector(#selector(getState(_:))),
38
+ "requestPermission": NSStringFromSelector(#selector(requestPermission(_:))),
39
+ "startScan": NSStringFromSelector(#selector(startScan(_:callback:))),
40
+ "stopScan": NSStringFromSelector(#selector(stopScan(_:))),
41
+ "connect": NSStringFromSelector(#selector(connect(_:options:callback:))),
42
+ "disconnect": NSStringFromSelector(#selector(disconnect(_:callback:))),
43
+ "read": NSStringFromSelector(#selector(read(_:service:characteristic:callback:))),
44
+ "write": NSStringFromSelector(
45
+ #selector(write(_:service:characteristic:value:withResponse:callback:))),
46
+ "setNotifications": NSStringFromSelector(
47
+ #selector(setNotifications(_:service:characteristic:enabled:callback:))),
48
+ ]
49
+ }
50
+
51
+ private static let eventName = "angularLynxBluetooth"
52
+
53
+ /// The shortest time between two reports of a peripheral a scan keeps
54
+ /// seeing. CoreBluetooth reports every advertisement it hears when asked
55
+ /// for duplicates, many a second per peripheral, which is how a scan
56
+ /// follows the signal strength, but far more events than an app can use.
57
+ private static let sightingInterval: TimeInterval = 1
58
+ /// The longest attribute value ATT allows, which caps a write without
59
+ /// response however large the MTU.
60
+ private static let maxAttributeLength = 512
61
+
62
+ /// What CoreBluetooth leaves off a UUID built on the Bluetooth base UUID,
63
+ /// which it names by its 16- or 32-bit short form.
64
+ private static let baseUUIDSuffix = "-0000-1000-8000-00805f9b34fb"
65
+
66
+ /// What a `connect` answers once its deadline passes.
67
+ private static let connectTimeout = Failure(
68
+ code: "timeout", message: "The device didn't connect in time.")
69
+
70
+ private weak var context: LynxContext?
71
+ private let queue = DispatchQueue(label: "dev.angularlynx.bluetooth")
72
+
73
+ /// Made on first use: making it is what shows iOS's Bluetooth prompt, so
74
+ /// `getState` alone never makes it.
75
+ private var central: CBCentralManager?
76
+ private var destroyed = false
77
+
78
+ /// Calls that wait for the manager's first answer: while the prompt is up,
79
+ /// it doesn't know whether it may use the radio.
80
+ private var stateWaiters: [() -> Void] = []
81
+
82
+ private var scanning = false
83
+ /// The id the runtime gave the running scan, which its `device` and
84
+ /// `scanStopped` events carry, so it can tell them from those of the scan
85
+ /// it replaced.
86
+ private var scanID = 0
87
+ /// The id of the newest `startScan`. One still waiting for the manager when
88
+ /// a newer one arrives doesn't start: the runtime has replaced its scan
89
+ /// already, and the newer one may be running.
90
+ private var newestScan = 0
91
+ /// Counts `stopScan` calls, so a `startScan` still waiting for the prompt
92
+ /// doesn't start a scan the app stopped meanwhile.
93
+ private var stopCount = 0
94
+ private var lastSighting: [String: TimeInterval] = [:]
95
+
96
+ /// Every peripheral a scan saw. CoreBluetooth connects only to a
97
+ /// `CBPeripheral` it handed out, and frees one nothing keeps.
98
+ private var peripherals: [String: CBPeripheral] = [:]
99
+ /// The names peripherals advertised. A name often comes in the scan
100
+ /// response, a separate report from the advertisement, and CoreBluetooth
101
+ /// knows a peripheral's own name only once it has connected to it.
102
+ private var advertisedNames: [String: String] = [:]
103
+ private var connections: [String: Connection] = [:]
104
+
105
+ override init() {
106
+ super.init()
107
+ }
108
+
109
+ // Swift can't import an optional initializer as optional, so Lynx's
110
+ // initWithParam: and initWithLynxContext:WithParam: are required here.
111
+ init(param: Any) {
112
+ super.init()
113
+ }
114
+
115
+ init(lynxContext context: LynxContext) {
116
+ self.context = context
117
+ super.init()
118
+ }
119
+
120
+ init(lynxContext context: LynxContext, withParam param: Any) {
121
+ self.context = context
122
+ super.init()
123
+ }
124
+
125
+ /// Stops the scan and ends every connection, since the radio would
126
+ /// otherwise keep them for a page that's gone. The calls still waiting
127
+ /// aren't answered: there's no page left to answer.
128
+ func destroy() {
129
+ queue.async {
130
+ self.destroyed = true
131
+ self.stateWaiters.removeAll()
132
+ guard let central = self.central else { return }
133
+ if self.scanning {
134
+ central.stopScan()
135
+ }
136
+ for connection in self.connections.values {
137
+ connection.timeout?.cancel()
138
+ central.cancelPeripheralConnection(connection.peripheral)
139
+ }
140
+ self.scanning = false
141
+ self.connections.removeAll()
142
+ central.delegate = nil
143
+ self.central = nil
144
+ }
145
+ }
146
+
147
+ // MARK: - Methods
148
+
149
+ /// `{ state }`, without asking the person: before anything has made the
150
+ /// manager, iOS tells only whether they refused, so a radio's power reads as
151
+ /// `unknown` until then.
152
+ @objc func getState(_ callback: @escaping LynxCallbackBlock) {
153
+ queue.async {
154
+ callback(["state": self.state()])
155
+ }
156
+ }
157
+
158
+ /// `{ state }` once the person has answered iOS's prompt, which making the
159
+ /// manager shows if they haven't been asked.
160
+ @objc func requestPermission(_ callback: @escaping LynxCallbackBlock) {
161
+ queue.async {
162
+ self.whenSettled(callback) { _ in
163
+ callback(["state": self.state()])
164
+ }
165
+ }
166
+ }
167
+
168
+ /// Starts a scan for peripherals advertising any of `options.services`, or
169
+ /// every peripheral when it's empty, replacing the scan already running. A
170
+ /// start that waited for the manager calls back `{}` without scanning when
171
+ /// a newer one came in meanwhile.
172
+ @objc func startScan(_ options: [String: Any]?, callback: @escaping LynxCallbackBlock) {
173
+ let names = options?["services"] as? [String] ?? []
174
+ let id = (options?["scan"] as? NSNumber)?.intValue ?? 0
175
+ queue.async {
176
+ self.newestScan = id
177
+ var services: [CBUUID] = []
178
+ for name in names {
179
+ guard let uuid = Self.coreBluetoothUUID(name) else {
180
+ callback(Failure(code: "failed", message: "\(name) isn't a Bluetooth UUID.").result)
181
+ return
182
+ }
183
+ services.append(uuid)
184
+ }
185
+ let stops = self.stopCount
186
+ self.whenPoweredOn(callback) { central in
187
+ guard id == self.newestScan else {
188
+ callback([:])
189
+ return
190
+ }
191
+ guard stops == self.stopCount else {
192
+ callback(
193
+ Failure(code: "failed", message: "stopScan() was called before the scan started.")
194
+ .result)
195
+ return
196
+ }
197
+ // A new scan reports each peripheral as soon as it sees it again.
198
+ self.lastSighting.removeAll()
199
+ self.scanning = true
200
+ self.scanID = id
201
+ central.scanForPeripherals(
202
+ withServices: services.isEmpty ? nil : services,
203
+ options: [CBCentralManagerScanOptionAllowDuplicatesKey: true])
204
+ callback([:])
205
+ }
206
+ }
207
+ }
208
+
209
+ @objc func stopScan(_ callback: @escaping LynxCallbackBlock) {
210
+ queue.async {
211
+ self.stopCount += 1
212
+ if self.scanning {
213
+ self.scanning = false
214
+ self.central?.stopScan()
215
+ }
216
+ callback([:])
217
+ }
218
+ }
219
+
220
+ /// Connects to the peripheral, discovers all its services and their
221
+ /// characteristics, and calls back with them, or with `timeout` when that
222
+ /// takes longer than `options.timeout` milliseconds. CoreBluetooth's own
223
+ /// connection attempts never time out, so without one (or with `0`) this
224
+ /// waits until the peripheral is in range.
225
+ @objc func connect(_ id: String, options: [String: Any]?, callback: @escaping LynxCallbackBlock)
226
+ {
227
+ let timeout = options?["timeout"] as? Double ?? 0
228
+ queue.async {
229
+ self.connect(id, timeout: timeout, callback)
230
+ }
231
+ }
232
+
233
+ @objc func disconnect(_ id: String, callback: @escaping LynxCallbackBlock) {
234
+ queue.async {
235
+ guard let connection = self.connections[id] else {
236
+ callback([:])
237
+ return
238
+ }
239
+ connection.disconnectWaiters.append(callback)
240
+ if connection.phase != .closing {
241
+ self.abandon(
242
+ connection,
243
+ Failure(code: "failed", message: "disconnect() was called before the device connected."))
244
+ }
245
+ }
246
+ }
247
+
248
+ @objc func read(
249
+ _ id: String, service: String, characteristic: String,
250
+ callback: @escaping LynxCallbackBlock
251
+ ) {
252
+ queue.async {
253
+ guard let target = self.target(id, service, characteristic, orFail: callback) else { return }
254
+ guard target.characteristic.properties.contains(.read) else {
255
+ callback(
256
+ Failure(code: "failed", message: "The characteristic \(characteristic) can't be read.")
257
+ .result)
258
+ return
259
+ }
260
+ target.connection.reads[ObjectIdentifier(target.characteristic), default: []].append(
261
+ callback)
262
+ target.connection.peripheral.readValue(for: target.characteristic)
263
+ }
264
+ }
265
+
266
+ /// Writes `value` (base64). With a response, it calls back once the
267
+ /// peripheral confirms; without, once CoreBluetooth has taken the write,
268
+ /// which it can only while its buffer has room.
269
+ @objc func write(
270
+ _ id: String, service: String, characteristic: String, value: String, withResponse: Bool,
271
+ callback: @escaping LynxCallbackBlock
272
+ ) {
273
+ queue.async {
274
+ guard let target = self.target(id, service, characteristic, orFail: callback) else { return }
275
+ guard let data = Data(base64Encoded: value) else {
276
+ callback(Failure(code: "failed", message: "The value isn't base64.").result)
277
+ return
278
+ }
279
+ let connection = target.connection
280
+ let properties = target.characteristic.properties
281
+ // CoreBluetooth ignores a write the characteristic doesn't declare,
282
+ // without calling back, so it's refused here.
283
+ if withResponse {
284
+ guard properties.contains(.write) else {
285
+ callback(
286
+ Failure(
287
+ code: "failed",
288
+ message: "The characteristic \(characteristic) can't be written with a response."
289
+ ).result)
290
+ return
291
+ }
292
+ // CoreBluetooth sends a longer value as a long write, which a
293
+ // device that keeps to ATT's limit refuses or cuts short.
294
+ guard data.count <= Self.maxAttributeLength else {
295
+ callback(Self.tooLong(data.count, limit: Self.maxAttributeLength).result)
296
+ return
297
+ }
298
+ connection.writes[ObjectIdentifier(target.characteristic), default: []].append(callback)
299
+ connection.peripheral.writeValue(data, for: target.characteristic, type: .withResponse)
300
+ return
301
+ }
302
+ guard properties.contains(.writeWithoutResponse) else {
303
+ callback(
304
+ Failure(
305
+ code: "failed",
306
+ message: "The characteristic \(characteristic) can't be written without a response."
307
+ ).result)
308
+ return
309
+ }
310
+ let limit = Self.maxWriteLength(connection.peripheral)
311
+ guard data.count <= limit else {
312
+ callback(Self.tooLong(data.count, limit: limit).result)
313
+ return
314
+ }
315
+ connection.unsent.append(
316
+ PendingWrite(characteristic: target.characteristic, data: data, callback: callback))
317
+ self.flushWrites(connection)
318
+ }
319
+ }
320
+
321
+ /// Turns notifications on or off, and calls back once the peripheral has
322
+ /// taken the change. CoreBluetooth uses notifications when the
323
+ /// characteristic has them, and indications otherwise.
324
+ @objc func setNotifications(
325
+ _ id: String, service: String, characteristic: String, enabled: Bool,
326
+ callback: @escaping LynxCallbackBlock
327
+ ) {
328
+ queue.async {
329
+ guard let target = self.target(id, service, characteristic, orFail: callback) else { return }
330
+ let connection = target.connection
331
+ let key = ObjectIdentifier(target.characteristic)
332
+ // CoreBluetooth needn't call back for a change that changes nothing.
333
+ if connection.subscriptions[key] == nil, target.characteristic.isNotifying == enabled {
334
+ callback([:])
335
+ return
336
+ }
337
+ let properties = target.characteristic.properties
338
+ guard properties.contains(.notify) || properties.contains(.indicate) else {
339
+ callback(
340
+ Failure(
341
+ code: "failed",
342
+ message: "The characteristic \(characteristic) has no notifications or indications."
343
+ ).result)
344
+ return
345
+ }
346
+ connection.subscriptions[key, default: []].append(callback)
347
+ connection.peripheral.setNotifyValue(enabled, for: target.characteristic)
348
+ }
349
+ }
350
+
351
+ // MARK: - The manager
352
+
353
+ private func manager() -> CBCentralManager? {
354
+ if let central {
355
+ return central
356
+ }
357
+ guard !destroyed else { return nil }
358
+ let made = CBCentralManager(delegate: self, queue: queue)
359
+ central = made
360
+ return made
361
+ }
362
+
363
+ /// Whether the manager knows if it may use the radio. iOS may report it
364
+ /// unauthorized while its prompt still waits for the person, and reports
365
+ /// again once they answer.
366
+ private func isSettled(_ central: CBCentralManager) -> Bool {
367
+ switch central.state {
368
+ case .unknown:
369
+ return false
370
+ case .unauthorized:
371
+ return CBManager.authorization != .notDetermined
372
+ default:
373
+ return true
374
+ }
375
+ }
376
+
377
+ /// Runs `action` once the manager knows whether it may use the radio,
378
+ /// making it first, which shows iOS's prompt if the person hasn't been asked.
379
+ private func whenSettled(
380
+ _ callback: @escaping LynxCallbackBlock, _ action: @escaping (CBCentralManager) -> Void
381
+ ) {
382
+ guard let central = manager() else {
383
+ callback(Failure(code: "failed", message: "The page has closed.").result)
384
+ return
385
+ }
386
+ guard isSettled(central) else {
387
+ stateWaiters.append { [self] in
388
+ whenSettled(callback, action)
389
+ }
390
+ return
391
+ }
392
+ action(central)
393
+ }
394
+
395
+ /// Runs `action` once the radio is on, or calls back with why it can't be.
396
+ private func whenPoweredOn(
397
+ _ callback: @escaping LynxCallbackBlock, _ action: @escaping (CBCentralManager) -> Void
398
+ ) {
399
+ whenSettled(callback) { central in
400
+ guard central.state == .poweredOn else {
401
+ callback(Self.failure(for: central.state).result)
402
+ return
403
+ }
404
+ action(central)
405
+ }
406
+ }
407
+
408
+ private func state() -> String {
409
+ guard let central else {
410
+ switch CBManager.authorization {
411
+ case .denied, .restricted:
412
+ return "unauthorized"
413
+ default:
414
+ return "unknown"
415
+ }
416
+ }
417
+ guard isSettled(central) else { return "unknown" }
418
+ switch central.state {
419
+ case .unknown:
420
+ return "unknown"
421
+ case .resetting:
422
+ return "resetting"
423
+ case .unsupported:
424
+ return "unsupported"
425
+ case .unauthorized:
426
+ return "unauthorized"
427
+ case .poweredOff:
428
+ return "poweredOff"
429
+ case .poweredOn:
430
+ return "poweredOn"
431
+ @unknown default:
432
+ return "unknown"
433
+ }
434
+ }
435
+
436
+ func centralManagerDidUpdateState(_ central: CBCentralManager) {
437
+ send(["type": "state", "state": state()])
438
+ // CoreBluetooth ends every connection and the scan when the radio stops,
439
+ // without reporting each one, and doesn't resume them when it's back.
440
+ if central.state != .poweredOn {
441
+ lose(Self.failure(for: central.state))
442
+ }
443
+ // Below poweredOff, every CBPeripheral the manager handed out is invalid:
444
+ // the next connect retrieves or rediscovers its peripheral.
445
+ if central.state.rawValue < CBManagerState.poweredOff.rawValue {
446
+ peripherals.removeAll()
447
+ }
448
+ if isSettled(central) {
449
+ let waiting = stateWaiters
450
+ stateWaiters.removeAll()
451
+ waiting.forEach { $0() }
452
+ }
453
+ }
454
+
455
+ /// Ends the scan and every connection after the radio stopped, telling the
456
+ /// app about each one it was using.
457
+ private func lose(_ failure: Failure) {
458
+ if scanning {
459
+ scanning = false
460
+ send([
461
+ "type": "scanStopped", "scan": scanID, "error": failure.code, "message": failure.message,
462
+ ])
463
+ }
464
+ for connection in Array(connections.values) {
465
+ let event: [String: Any]? =
466
+ connection.phase == .ready && !connection.askedToClose
467
+ ? [
468
+ "type": "disconnected", "id": connection.id, "error": failure.code,
469
+ "message": failure.message,
470
+ ] : nil
471
+ end(connection, failure, event: event)
472
+ }
473
+ }
474
+
475
+ // MARK: - Scanning
476
+
477
+ func centralManager(
478
+ _ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
479
+ advertisementData: [String: Any], rssi RSSI: NSNumber
480
+ ) {
481
+ // Sightings already queued when the scan stopped.
482
+ guard scanning else { return }
483
+ let id = Self.id(of: peripheral)
484
+ peripherals[id] = peripheral
485
+ if let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String {
486
+ advertisedNames[id] = name
487
+ }
488
+ let now = ProcessInfo.processInfo.systemUptime
489
+ if let last = lastSighting[id], now - last < Self.sightingInterval {
490
+ return
491
+ }
492
+ lastSighting[id] = now
493
+
494
+ // The overflow list holds the services of an iPhone advertising in the
495
+ // background, which iOS moves out of the advertisement itself.
496
+ let uuids =
497
+ (advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID] ?? [])
498
+ + (advertisementData[CBAdvertisementDataOverflowServiceUUIDsKey] as? [CBUUID] ?? [])
499
+ var services: [String] = []
500
+ for uuid in uuids.map(Self.string) where !services.contains(uuid) {
501
+ services.append(uuid)
502
+ }
503
+ var serviceData: [String: String] = [:]
504
+ for (uuid, data) in advertisementData[CBAdvertisementDataServiceDataKey] as? [CBUUID: Data]
505
+ ?? [:]
506
+ {
507
+ serviceData[Self.string(uuid)] = data.base64EncodedString()
508
+ }
509
+ // CoreBluetooth hands over the manufacturer data whole: its first two
510
+ // bytes are the company's Bluetooth SIG identifier, little-endian.
511
+ var manufacturerData: [String: String] = [:]
512
+ if let raw = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data, raw.count >= 2
513
+ {
514
+ let company = Int(raw[raw.startIndex]) | Int(raw[raw.startIndex + 1]) << 8
515
+ manufacturerData[String(company)] = raw.dropFirst(2).base64EncodedString()
516
+ }
517
+ let device: [String: Any] = [
518
+ "id": id,
519
+ "name": (advertisedNames[id] ?? peripheral.name).map { $0 as Any } ?? NSNull(),
520
+ "rssi": RSSI.intValue,
521
+ "services": services,
522
+ "serviceData": serviceData,
523
+ "manufacturerData": manufacturerData,
524
+ ]
525
+ send(["type": "device", "scan": scanID, "device": device])
526
+ }
527
+
528
+ // MARK: - Connections
529
+
530
+ private func connect(_ id: String, timeout: Double, _ callback: @escaping LynxCallbackBlock) {
531
+ whenPoweredOn(callback) { central in
532
+ if let connection = self.connections[id] {
533
+ self.join(connection, timeout: timeout, callback)
534
+ } else if let peripheral = self.peripheral(id, central) {
535
+ self.open(peripheral, id: id, timeout: timeout, central: central, callback)
536
+ } else {
537
+ callback(Failure(code: "notFound", message: "No Bluetooth device has the id \(id).").result)
538
+ }
539
+ }
540
+ }
541
+
542
+ /// A `connect` for a peripheral that already has a connection, which it
543
+ /// shares rather than starting a second.
544
+ private func join(
545
+ _ connection: Connection, timeout: Double, _ callback: @escaping LynxCallbackBlock
546
+ ) {
547
+ switch connection.phase {
548
+ case .ready:
549
+ callback(describe(connection))
550
+ case .connecting, .discovering:
551
+ connection.connectWaiters.append(callback)
552
+ case .closing:
553
+ // The old connection is still going: connect again once it has. The
554
+ // deadline runs from now, so a close that's slow to be reported
555
+ // counts against it, as connecting would.
556
+ let deadline = timeout > 0 ? DispatchTime.now() + timeout / 1000 : nil
557
+ connection.afterClose.append(Reconnect(callback: callback, deadline: deadline))
558
+ guard let deadline else { return }
559
+ queue.asyncAfter(deadline: deadline) { [weak self, weak connection] in
560
+ guard let self, let connection else { return }
561
+ self.expireReconnects(connection)
562
+ }
563
+ }
564
+ }
565
+
566
+ /// Fails the `connect` calls still waiting for the old connection to
567
+ /// close once their deadline has passed.
568
+ private func expireReconnects(_ connection: Connection) {
569
+ let now = DispatchTime.now()
570
+ let expired = connection.afterClose.filter { $0.expired(at: now) }
571
+ connection.afterClose.removeAll { $0.expired(at: now) }
572
+ expired.forEach { $0.callback(Self.connectTimeout.result) }
573
+ }
574
+
575
+ /// Connects for a `connect` that waited for the old connection to close,
576
+ /// with what's left of its deadline.
577
+ private func reconnect(_ id: String, _ waiting: Reconnect) {
578
+ guard let deadline = waiting.deadline else {
579
+ connect(id, timeout: 0, waiting.callback)
580
+ return
581
+ }
582
+ let now = DispatchTime.now()
583
+ guard now < deadline else {
584
+ waiting.callback(Self.connectTimeout.result)
585
+ return
586
+ }
587
+ let left = Double(deadline.uptimeNanoseconds - now.uptimeNanoseconds) / 1_000_000
588
+ connect(id, timeout: left, waiting.callback)
589
+ }
590
+
591
+ /// The peripheral a scan saw, or else one iOS knows from before (it keeps
592
+ /// the ones this app has connected to).
593
+ private func peripheral(_ id: String, _ central: CBCentralManager) -> CBPeripheral? {
594
+ if let seen = peripherals[id] {
595
+ return seen
596
+ }
597
+ guard let uuid = UUID(uuidString: id),
598
+ let known = central.retrievePeripherals(withIdentifiers: [uuid]).first
599
+ else { return nil }
600
+ peripherals[id] = known
601
+ return known
602
+ }
603
+
604
+ private func open(
605
+ _ peripheral: CBPeripheral, id: String, timeout: Double, central: CBCentralManager,
606
+ _ callback: @escaping LynxCallbackBlock
607
+ ) {
608
+ let connection = Connection(id: id, peripheral: peripheral)
609
+ connection.connectWaiters.append(callback)
610
+ connections[id] = connection
611
+ peripheral.delegate = self
612
+ central.connect(peripheral, options: nil)
613
+ guard timeout > 0 else { return }
614
+ let expiry = DispatchWorkItem { [weak self, weak connection] in
615
+ guard let self, let connection, self.connections[connection.id] === connection,
616
+ connection.phase == .connecting || connection.phase == .discovering
617
+ else { return }
618
+ self.abandon(connection, Self.connectTimeout)
619
+ }
620
+ connection.timeout = expiry
621
+ queue.asyncAfter(deadline: .now() + timeout / 1000, execute: expiry)
622
+ }
623
+
624
+ /// Gives up on a connection the module wants to end: fails the `connect`
625
+ /// calls still waiting with `failure`, and cancels it.
626
+ private func abandon(_ connection: Connection, _ failure: Failure) {
627
+ connection.timeout?.cancel()
628
+ connection.askedToClose = true
629
+ let waiting = connection.connectWaiters
630
+ connection.connectWaiters.removeAll()
631
+ waiting.forEach { $0(failure.result) }
632
+ central?.cancelPeripheralConnection(connection.peripheral)
633
+ if connection.phase == .connecting {
634
+ // An attempt that never connected ends here: whether CoreBluetooth
635
+ // reports its cancellation isn't something to wait on.
636
+ end(
637
+ connection,
638
+ Failure(code: "notConnected", message: "The connection was closed."))
639
+ } else {
640
+ // A connected peripheral is always reported disconnected, and until
641
+ // then a new connect would race the old link.
642
+ connection.phase = .closing
643
+ }
644
+ }
645
+
646
+ /// Forgets the connection and answers everything still waiting on it:
647
+ /// `connect` and the operations with `failure`, `disconnect` with `{}`.
648
+ private func end(_ connection: Connection, _ failure: Failure, event: [String: Any]? = nil) {
649
+ guard connections[connection.id] === connection else { return }
650
+ connections[connection.id] = nil
651
+ connection.timeout?.cancel()
652
+ let connecting = connection.connectWaiters
653
+ let disconnecting = connection.disconnectWaiters
654
+ let next = connection.afterClose
655
+ connection.connectWaiters.removeAll()
656
+ connection.disconnectWaiters.removeAll()
657
+ connection.afterClose.removeAll()
658
+ connecting.forEach { $0(failure.result) }
659
+ connection.failOperations(failure)
660
+ disconnecting.forEach { $0([:]) }
661
+ if let event {
662
+ send(event)
663
+ }
664
+ next.forEach { reconnect(connection.id, $0) }
665
+ }
666
+
667
+ func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
668
+ guard let connection = connections[Self.id(of: peripheral)], connection.phase == .connecting
669
+ else { return }
670
+ connection.phase = .discovering
671
+ peripheral.discoverServices(nil)
672
+ }
673
+
674
+ func centralManager(
675
+ _ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?
676
+ ) {
677
+ guard let connection = connections[Self.id(of: peripheral)], connection.phase == .connecting
678
+ else { return }
679
+ end(
680
+ connection,
681
+ error.map(Self.failure(for:))
682
+ ?? Failure(code: "failed", message: "The device couldn't be connected."))
683
+ }
684
+
685
+ func centralManager(
686
+ _ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?
687
+ ) {
688
+ // A connection still connecting hasn't connected, so this reports an
689
+ // earlier attempt the module canceled.
690
+ guard let connection = connections[Self.id(of: peripheral)], connection.phase != .connecting
691
+ else { return }
692
+ if connection.askedToClose {
693
+ end(connection, Failure(code: "notConnected", message: "The connection was closed."))
694
+ return
695
+ }
696
+ let reason = error.map(Self.failure(for:))
697
+ var event: [String: Any]?
698
+ if connection.phase == .ready {
699
+ var disconnected: [String: Any] = ["type": "disconnected", "id": connection.id]
700
+ if let reason {
701
+ disconnected["error"] = reason.code
702
+ disconnected["message"] = reason.message
703
+ }
704
+ event = disconnected
705
+ }
706
+ end(
707
+ connection, reason ?? Failure(code: "notConnected", message: "The device disconnected."),
708
+ event: event)
709
+ }
710
+
711
+ func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
712
+ guard let connection = connections[Self.id(of: peripheral)],
713
+ connection.phase == .discovering
714
+ else { return }
715
+ if let error {
716
+ abandon(connection, Self.failure(for: error))
717
+ return
718
+ }
719
+ let services = peripheral.services ?? []
720
+ connection.servicesLeft = services.count
721
+ if services.isEmpty {
722
+ ready(connection)
723
+ return
724
+ }
725
+ services.forEach { peripheral.discoverCharacteristics(nil, for: $0) }
726
+ }
727
+
728
+ func peripheral(
729
+ _ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?
730
+ ) {
731
+ guard let connection = connections[Self.id(of: peripheral)],
732
+ connection.phase == .discovering
733
+ else { return }
734
+ if let error {
735
+ abandon(connection, Self.failure(for: error))
736
+ return
737
+ }
738
+ connection.servicesLeft -= 1
739
+ if connection.servicesLeft == 0 {
740
+ ready(connection)
741
+ }
742
+ }
743
+
744
+ /// The peripheral changed its services (a firmware update, say). The
745
+ /// app's copy of them, and its subscriptions, are of the old ones, so the
746
+ /// connection ends: connecting again discovers the new ones.
747
+ func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
748
+ guard let connection = connections[Self.id(of: peripheral)], connection.phase == .ready,
749
+ !invalidatedServices.isEmpty
750
+ else { return }
751
+ let failure = Failure(code: "failed", message: "The device changed its services.")
752
+ send([
753
+ "type": "disconnected", "id": connection.id, "error": failure.code,
754
+ "message": failure.message,
755
+ ])
756
+ abandon(connection, failure)
757
+ }
758
+
759
+ private func ready(_ connection: Connection) {
760
+ connection.phase = .ready
761
+ connection.timeout?.cancel()
762
+ connection.timeout = nil
763
+ let result = describe(connection)
764
+ let waiting = connection.connectWaiters
765
+ connection.connectWaiters.removeAll()
766
+ waiting.forEach { $0(result) }
767
+ }
768
+
769
+ private func describe(_ connection: Connection) -> [String: Any] {
770
+ let peripheral = connection.peripheral
771
+ let services = (peripheral.services ?? []).map { service -> [String: Any] in
772
+ [
773
+ "uuid": Self.string(service.uuid),
774
+ "characteristics": (service.characteristics ?? []).map { characteristic -> [String: Any] in
775
+ ["uuid": Self.string(characteristic.uuid), "properties": Self.names(characteristic.properties)]
776
+ },
777
+ ]
778
+ }
779
+ return [
780
+ "id": connection.id,
781
+ "name": (peripheral.name ?? advertisedNames[connection.id]).map { $0 as Any } ?? NSNull(),
782
+ "maxWriteLength": Self.maxWriteLength(peripheral),
783
+ "services": services,
784
+ ]
785
+ }
786
+
787
+ // MARK: - Reads, writes and notifications
788
+
789
+ private struct Target {
790
+ let connection: Connection
791
+ let characteristic: CBCharacteristic
792
+ }
793
+
794
+ /// The connected peripheral's characteristic, or `nil` after calling back
795
+ /// with why there's none.
796
+ private func target(
797
+ _ id: String, _ service: String, _ characteristic: String, orFail callback: LynxCallbackBlock
798
+ ) -> Target? {
799
+ guard let connection = connections[id], connection.phase == .ready else {
800
+ callback(Failure(code: "notConnected", message: "The device \(id) isn't connected.").result)
801
+ return nil
802
+ }
803
+ let serviceUUID = Self.normalize(service)
804
+ let characteristicUUID = Self.normalize(characteristic)
805
+ guard
806
+ let found = connection.peripheral.services?.first(where: {
807
+ Self.string($0.uuid) == serviceUUID
808
+ })
809
+ else {
810
+ callback(Failure(code: "notFound", message: "The device has no service \(service).").result)
811
+ return nil
812
+ }
813
+ guard
814
+ let match = found.characteristics?.first(where: {
815
+ Self.string($0.uuid) == characteristicUUID
816
+ })
817
+ else {
818
+ callback(
819
+ Failure(
820
+ code: "notFound",
821
+ message: "The service \(service) has no characteristic \(characteristic)."
822
+ ).result)
823
+ return nil
824
+ }
825
+ return Target(connection: connection, characteristic: match)
826
+ }
827
+
828
+ /// Hands CoreBluetooth the writes without response it has room for, in the
829
+ /// order the app made them.
830
+ private func flushWrites(_ connection: Connection) {
831
+ let peripheral = connection.peripheral
832
+ while !connection.unsent.isEmpty, peripheral.canSendWriteWithoutResponse {
833
+ let write = connection.unsent.removeFirst()
834
+ peripheral.writeValue(write.data, for: write.characteristic, type: .withoutResponse)
835
+ write.callback([:])
836
+ }
837
+ }
838
+
839
+ func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
840
+ // A connection that's closing keeps its writes: they fail as it ends,
841
+ // rather than reach a peripheral the app let go of.
842
+ guard let connection = connections[Self.id(of: peripheral)], connection.phase == .ready
843
+ else { return }
844
+ flushWrites(connection)
845
+ }
846
+
847
+ /// A read's answer or a notification: CoreBluetooth reports both here. A
848
+ /// value for a characteristic with a read waiting answers the oldest read,
849
+ /// since CoreBluetooth answers a characteristic's reads in order.
850
+ func peripheral(
851
+ _ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?
852
+ ) {
853
+ guard let connection = connections[Self.id(of: peripheral)] else { return }
854
+ if let callback = Self.next(&connection.reads, characteristic) {
855
+ callback(
856
+ Self.outcome(error) {
857
+ ["value": (characteristic.value ?? Data()).base64EncodedString()]
858
+ })
859
+ // CoreBluetooth can't tell a read's answer from a notification, so
860
+ // while the app is subscribed the value reaches its listeners too: a
861
+ // notification the read took isn't lost, and the listeners also hear
862
+ // what was read, as Web Bluetooth's do.
863
+ guard characteristic.isNotifying else { return }
864
+ }
865
+ guard error == nil, connection.phase == .ready, let value = characteristic.value,
866
+ let service = characteristic.service
867
+ else { return }
868
+ send([
869
+ "type": "value",
870
+ "id": connection.id,
871
+ "service": Self.string(service.uuid),
872
+ "characteristic": Self.string(characteristic.uuid),
873
+ "value": value.base64EncodedString(),
874
+ ])
875
+ }
876
+
877
+ func peripheral(
878
+ _ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?
879
+ ) {
880
+ guard let connection = connections[Self.id(of: peripheral)],
881
+ let callback = Self.next(&connection.writes, characteristic)
882
+ else { return }
883
+ callback(Self.outcome(error) { [:] })
884
+ }
885
+
886
+ func peripheral(
887
+ _ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic,
888
+ error: Error?
889
+ ) {
890
+ guard let connection = connections[Self.id(of: peripheral)],
891
+ let callback = Self.next(&connection.subscriptions, characteristic)
892
+ else { return }
893
+ callback(Self.outcome(error) { [:] })
894
+ }
895
+
896
+ // MARK: - Helpers
897
+
898
+ private func send(_ payload: [String: Any]) {
899
+ context?.sendGlobalEvent(Self.eventName, withParams: [payload])
900
+ }
901
+
902
+ /// Takes the oldest callback waiting on `characteristic`.
903
+ private static func next(
904
+ _ table: inout [ObjectIdentifier: [LynxCallbackBlock]], _ characteristic: CBCharacteristic
905
+ ) -> LynxCallbackBlock? {
906
+ let key = ObjectIdentifier(characteristic)
907
+ guard var waiting = table[key], !waiting.isEmpty else { return nil }
908
+ let first = waiting.removeFirst()
909
+ table[key] = waiting.isEmpty ? nil : waiting
910
+ return first
911
+ }
912
+
913
+ private static func outcome(_ error: Error?, _ success: () -> [String: Any]) -> [String: Any] {
914
+ guard let error else { return success() }
915
+ return failure(for: error).result
916
+ }
917
+
918
+ private static func id(of peripheral: CBPeripheral) -> String {
919
+ peripheral.identifier.uuidString.lowercased()
920
+ }
921
+
922
+ private static func failure(for error: Error) -> Failure {
923
+ var code = "failed"
924
+ if let error = error as? CBError {
925
+ switch error.code {
926
+ case .connectionTimeout:
927
+ code = "timeout"
928
+ case .notConnected, .peripheralDisconnected:
929
+ code = "notConnected"
930
+ default:
931
+ break
932
+ }
933
+ }
934
+ return Failure(code: code, message: error.localizedDescription)
935
+ }
936
+
937
+ private static func failure(for state: CBManagerState) -> Failure {
938
+ switch state {
939
+ case .unsupported:
940
+ return Failure(code: "unsupported", message: "This device doesn't have Bluetooth LE.")
941
+ case .unauthorized:
942
+ return Failure(
943
+ code: "unauthorized",
944
+ message: "The app isn't allowed to use Bluetooth. It can be allowed in Settings.")
945
+ case .poweredOff:
946
+ return Failure(code: "poweredOff", message: "Bluetooth is turned off.")
947
+ case .resetting:
948
+ return Failure(code: "failed", message: "Bluetooth is restarting. Try again in a moment.")
949
+ default:
950
+ return Failure(code: "failed", message: "Bluetooth isn't ready.")
951
+ }
952
+ }
953
+
954
+ /// The most bytes a write without response carries: what the MTU allows,
955
+ /// but never more than an attribute holds.
956
+ /// What a write answers when its value is longer than it can carry, in
957
+ /// the words the Android module uses.
958
+ private static func tooLong(_ length: Int, limit: Int) -> Failure {
959
+ Failure(
960
+ code: "failed", message: "The value is \(length) bytes, and this write takes at most \(limit).")
961
+ }
962
+
963
+ private static func maxWriteLength(_ peripheral: CBPeripheral) -> Int {
964
+ min(peripheral.maximumWriteValueLength(for: .withoutResponse), maxAttributeLength)
965
+ }
966
+
967
+ private static func names(_ properties: CBCharacteristicProperties) -> [String] {
968
+ let known: [(CBCharacteristicProperties, String)] = [
969
+ (.read, "read"),
970
+ (.write, "write"),
971
+ (.writeWithoutResponse, "writeWithoutResponse"),
972
+ (.notify, "notify"),
973
+ (.indicate, "indicate"),
974
+ ]
975
+ return known.filter { properties.contains($0.0) }.map { $0.1 }
976
+ }
977
+
978
+ /// A UUID as the runtime writes them: 128 bits, lowercase, hyphenated.
979
+ /// CoreBluetooth gives one built on the Bluetooth base UUID by its 4 or 8
980
+ /// hex digits.
981
+ private static func string(_ uuid: CBUUID) -> String {
982
+ normalize(uuid.uuidString) ?? uuid.uuidString.lowercased()
983
+ }
984
+
985
+ /// `text` as a full lowercase UUID, with a short form expanded onto the
986
+ /// Bluetooth base UUID, or `nil` when it isn't one.
987
+ private static func normalize(_ text: String) -> String? {
988
+ let lower = text.lowercased()
989
+ let hex = !lower.isEmpty && lower.allSatisfy { $0.isASCII && $0.isHexDigit }
990
+ if hex && lower.count == 4 {
991
+ return "0000\(lower)\(baseUUIDSuffix)"
992
+ }
993
+ if hex && lower.count == 8 {
994
+ return "\(lower)\(baseUUIDSuffix)"
995
+ }
996
+ return UUID(uuidString: lower) == nil ? nil : lower
997
+ }
998
+
999
+ /// The `CBUUID` for a UUID string, or `nil` when it isn't one: CBUUID
1000
+ /// raises an Objective-C exception, which ends the app, for anything else.
1001
+ /// One built on the base UUID gets its short form, the form CoreBluetooth
1002
+ /// reports advertised services in.
1003
+ private static func coreBluetoothUUID(_ text: String) -> CBUUID? {
1004
+ guard let full = normalize(text) else { return nil }
1005
+ guard full.hasSuffix(baseUUIDSuffix) else { return CBUUID(string: full) }
1006
+ let head = String(full.prefix(8))
1007
+ return CBUUID(string: head.hasPrefix("0000") ? String(head.dropFirst(4)) : head)
1008
+ }
1009
+ }
1010
+
1011
+ private struct Failure {
1012
+ let code: String
1013
+ let message: String
1014
+
1015
+ var result: [String: Any] { ["error": code, "message": message] }
1016
+ }
1017
+
1018
+ /// A `connect` waiting for its peripheral's old connection to close, and
1019
+ /// the time it gives up at: none for a `connect` without a timeout.
1020
+ private struct Reconnect {
1021
+ let callback: LynxCallbackBlock
1022
+ let deadline: DispatchTime?
1023
+
1024
+ func expired(at now: DispatchTime) -> Bool {
1025
+ deadline.map { $0 <= now } ?? false
1026
+ }
1027
+ }
1028
+
1029
+ private struct PendingWrite {
1030
+ let characteristic: CBCharacteristic
1031
+ let data: Data
1032
+ let callback: LynxCallbackBlock
1033
+ }
1034
+
1035
+ /// One peripheral's connection, from `connect` until CoreBluetooth reports it
1036
+ /// ended, with the callbacks waiting on it. Operations wait per
1037
+ /// characteristic: CoreBluetooth queues them itself and answers each
1038
+ /// characteristic's in order, so different characteristics can be read at
1039
+ /// once.
1040
+ private final class Connection {
1041
+ enum Phase {
1042
+ /// Waiting for CoreBluetooth to connect.
1043
+ case connecting
1044
+ /// Connected, finding the services and their characteristics.
1045
+ case discovering
1046
+ /// What `connect` answered with: reads, writes and notifications work.
1047
+ case ready
1048
+ /// Canceled, waiting for CoreBluetooth to report the link ended.
1049
+ case closing
1050
+ }
1051
+
1052
+ let id: String
1053
+ let peripheral: CBPeripheral
1054
+ var phase = Phase.connecting
1055
+ /// Whether the module ended it (`disconnect`, a timeout, a failed
1056
+ /// discovery), which the app doesn't hear about as a `disconnected` event.
1057
+ var askedToClose = false
1058
+ var servicesLeft = 0
1059
+ var timeout: DispatchWorkItem?
1060
+ var connectWaiters: [LynxCallbackBlock] = []
1061
+ var disconnectWaiters: [LynxCallbackBlock] = []
1062
+ /// `connect` calls that came while it was closing.
1063
+ var afterClose: [Reconnect] = []
1064
+ var reads: [ObjectIdentifier: [LynxCallbackBlock]] = [:]
1065
+ var writes: [ObjectIdentifier: [LynxCallbackBlock]] = [:]
1066
+ var subscriptions: [ObjectIdentifier: [LynxCallbackBlock]] = [:]
1067
+ /// Writes without response waiting for room in CoreBluetooth's buffer.
1068
+ var unsent: [PendingWrite] = []
1069
+
1070
+ init(id: String, peripheral: CBPeripheral) {
1071
+ self.id = id
1072
+ self.peripheral = peripheral
1073
+ }
1074
+
1075
+ func failOperations(_ failure: Failure) {
1076
+ let waiting =
1077
+ reads.values.flatMap { $0 } + writes.values.flatMap { $0 }
1078
+ + subscriptions.values.flatMap { $0 } + unsent.map(\.callback)
1079
+ reads.removeAll()
1080
+ writes.removeAll()
1081
+ subscriptions.removeAll()
1082
+ unsent.removeAll()
1083
+ waiting.forEach { $0(failure.result) }
1084
+ }
1085
+
1086
+ }