craft-native 0.0.150 → 0.0.152

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.
@@ -0,0 +1,699 @@
1
+ import CoreBluetooth
2
+ import Foundation
3
+ import UIKit
4
+
5
+ /// A heart-rate call that did not happen: the message a page sees, and the
6
+ /// bridge's error code.
7
+ struct CraftHeartRateError: Error {
8
+ let message: String
9
+ var code: String = "CRAFT_ERROR"
10
+ }
11
+
12
+ /// One Heart Rate Measurement (characteristic 0x2A37 of the Bluetooth SIG's
13
+ /// Heart Rate Service, 0x180D), decoded.
14
+ ///
15
+ /// The payload is a flags byte and then the fields the flags announce, all
16
+ /// little-endian:
17
+ ///
18
+ /// bit 0 the heart rate is a uint16 (else a uint8)
19
+ /// bits 1-2 sensor contact: bit 2 says the strap reports it at all,
20
+ /// bit 1 that the skin is touching (a strap worn loose reads 0)
21
+ /// bit 3 a uint16 of energy expended, kilojoules, follows the rate
22
+ /// bit 4 uint16 RR intervals follow, as many as fit, in 1/1024 s
23
+ ///
24
+ /// Every strap and every watch that broadcasts its heart rate (Polar, Garmin,
25
+ /// Wahoo, an Apple Watch with a broadcasting app) sends this one shape.
26
+ struct CraftHeartRateMeasurement: Equatable {
27
+ /// Beats per minute.
28
+ let bpm: Int
29
+ /// Whether the strap is touching skin; nil when it cannot tell.
30
+ let sensorContact: Bool?
31
+ /// Kilojoules since the strap was last reset; nil when it does not count them.
32
+ let energyExpended: Int?
33
+ /// The time between beats, in milliseconds, oldest first.
34
+ let rrIntervals: [Double]
35
+
36
+ /// Nil for a payload too short for what its flags announce.
37
+ static func parse(_ bytes: [UInt8]) -> CraftHeartRateMeasurement? {
38
+ guard let flags = bytes.first else { return nil }
39
+ var offset = 1
40
+ func uint8() -> Int? {
41
+ guard offset < bytes.count else { return nil }
42
+ defer { offset += 1 }
43
+ return Int(bytes[offset])
44
+ }
45
+ func uint16() -> Int? {
46
+ guard offset + 1 < bytes.count else { return nil }
47
+ defer { offset += 2 }
48
+ return Int(bytes[offset]) | Int(bytes[offset + 1]) << 8
49
+ }
50
+ guard let bpm = flags & 0x01 != 0 ? uint16() : uint8() else { return nil }
51
+ let contact: Bool? = flags & 0x04 != 0 ? flags & 0x02 != 0 : nil
52
+ var energy: Int?
53
+ if flags & 0x08 != 0 {
54
+ guard let value = uint16() else { return nil }
55
+ energy = value
56
+ }
57
+ var intervals: [Double] = []
58
+ if flags & 0x10 != 0 {
59
+ while let value = uint16() { intervals.append(Double(value) * 1000 / 1024) }
60
+ }
61
+ return CraftHeartRateMeasurement(bpm: bpm, sensorContact: contact, energyExpended: energy, rrIntervals: intervals)
62
+ }
63
+
64
+ static func parse(_ data: Data) -> CraftHeartRateMeasurement? { parse([UInt8](data)) }
65
+
66
+ /// The payload a strap would send for these values: the simulator's
67
+ /// stand-in speaks it, so its readings take the same path as a strap's.
68
+ static func encode(bpm: Int, sensorContact: Bool? = true, energyExpended: Int? = nil, rrIntervals: [Double] = []) -> [UInt8] {
69
+ var flags: UInt8 = 0
70
+ var body: [UInt8] = []
71
+ func append16(_ value: Int) { body.append(UInt8(value & 0xFF)); body.append(UInt8((value >> 8) & 0xFF)) }
72
+ if bpm > 255 {
73
+ flags |= 0x01
74
+ append16(bpm)
75
+ } else {
76
+ body.append(UInt8(max(0, bpm)))
77
+ }
78
+ if let contact = sensorContact { flags |= 0x04 | (contact ? 0x02 : 0) }
79
+ if let energy = energyExpended {
80
+ flags |= 0x08
81
+ append16(energy)
82
+ }
83
+ if !rrIntervals.isEmpty {
84
+ flags |= 0x10
85
+ for interval in rrIntervals { append16(Int((interval * 1024 / 1000).rounded())) }
86
+ }
87
+ return [flags] + body
88
+ }
89
+ }
90
+
91
+ /// A heart-rate strap, or a watch broadcasting its heart rate, read during a
92
+ /// workout: the page's `craft.heartRate` (CraftApp.swift) and a native
93
+ /// screen's `HeartRate` module (CraftNativeActions.swift), one service for
94
+ /// both.
95
+ ///
96
+ /// CoreBluetooth central for the standard Heart Rate Service (0x180D):
97
+ /// - `scan` finds what advertises the service nearby (and a strap the phone
98
+ /// is already connected to, which does not advertise), each one a
99
+ /// `{type: 'device'}` event with its name and signal strength.
100
+ /// - `connect` subscribes to Heart Rate Measurement (0x2A37); every reading
101
+ /// is a `{type: 'reading'}` event with bpm and, when the strap sends them,
102
+ /// RR intervals. The device is remembered, and `reconnect` finds it again
103
+ /// next time without a scan.
104
+ /// - A strap that drops out (out of range, the battery, a sweaty contact) is
105
+ /// asked for again until `disconnect`: CoreBluetooth's pending connect
106
+ /// never times out, so it comes back by itself when the strap does.
107
+ /// - `startRecording` keeps every reading on disk until `stopRecording`, as
108
+ /// the location recording keeps fixes: the readings survive the web view
109
+ /// being suspended with the screen locked (the `bluetooth-central`
110
+ /// background mode keeps them coming) and the app being closed.
111
+ ///
112
+ /// Connection changes are `{type: 'state'}` events. All of them reach the
113
+ /// page as `craftHeartRate` and every native screen the same way.
114
+ ///
115
+ /// Simulator builds have no Bluetooth; with the `CraftFakeHeartRateMonitor`
116
+ /// default set (`xcrun simctl spawn booted defaults write <bundle id>
117
+ /// CraftFakeHeartRateMonitor -bool YES`) a made-up strap stands in, whose
118
+ /// readings are encoded as 0x2A37 payloads and decoded like a real one's.
119
+ ///
120
+ /// Everything runs on main: the central manager delivers there, and every
121
+ /// caller hops there first.
122
+ final class CraftHeartRate: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
123
+ typealias Completion = (Result<Any, CraftHeartRateError>) -> Void
124
+
125
+ static let shared = CraftHeartRate()
126
+
127
+ static let serviceUUID = CBUUID(string: "180D")
128
+ static let measurementUUID = CBUUID(string: "2A37")
129
+ /// How long `connect` waits before answering TIMEOUT. The connection is
130
+ /// still asked for after that: a strap only wakes when it is worn.
131
+ static let connectTimeout: TimeInterval = 15
132
+ /// A reading older than this is no longer "now".
133
+ static let staleAfter: TimeInterval = 10
134
+ /// Fourteen hours of one reading a second: more is not one workout.
135
+ static let maxRecordedSamples = 50_000
136
+
137
+ /// The web view's coordinator, which sends an event to the page and every
138
+ /// native screen. False (or unset, in an app without a web view) and the
139
+ /// event goes to the native screens alone.
140
+ var pageSink: (([String: Any]) -> Bool)?
141
+
142
+ private var central: CBCentralManager?
143
+ private var stateWaiters: [() -> Void] = []
144
+ private var discovered: [UUID: (peripheral: CBPeripheral?, name: String, rssi: Int)] = [:]
145
+ private var scanning = false
146
+ private var scanStop: DispatchWorkItem?
147
+ private var peripheral: CBPeripheral?
148
+ private var deviceId: UUID?
149
+ private var deviceName: String?
150
+ private var connection = "disconnected"
151
+ /// Between connect and disconnect: a lost strap is asked for again.
152
+ private var wantsConnection = false
153
+ private var connectWaiters: [Completion] = []
154
+ private var connectDeadline: DispatchWorkItem?
155
+ private var latest: CraftHeartRateMeasurement?
156
+ private var latestAt: Date?
157
+
158
+ private var recordingId: String?
159
+ private var recordingStartedAt: Double?
160
+ private var recordingPaused = false
161
+ private var recordedCount = 0
162
+ private var restored = false
163
+
164
+ private static let rememberedKey = "CraftHeartRate.lastDevice"
165
+
166
+ // MARK: The simulator's stand-in
167
+
168
+ /// A strap that is not there: one device, readings once a second.
169
+ private var simulated: Bool = {
170
+ #if targetEnvironment(simulator)
171
+ return UserDefaults.standard.bool(forKey: "CraftFakeHeartRateMonitor")
172
+ #else
173
+ return false
174
+ #endif
175
+ }()
176
+ private static let simulatedId = UUID(uuidString: "00000000-0000-4000-8000-00000000180D")!
177
+ private var simulatedTimer: Timer?
178
+ private var simulatedBeat = 0
179
+
180
+ // MARK: Entry
181
+
182
+ /// One call from a page or a native screen, by method name.
183
+ func perform(method: String, args: [Any], completion: @escaping Completion) {
184
+ let options = args.first as? [String: Any] ?? [:]
185
+ DispatchQueue.main.async {
186
+ self.restoreRecording()
187
+ switch method {
188
+ case "getState": completion(.success(self.state()))
189
+ case "requestAuthorization": self.requestAuthorization(completion: completion)
190
+ case "scan": self.scan(seconds: (options["timeout"] as? NSNumber)?.doubleValue, completion: completion)
191
+ case "stopScan":
192
+ self.stopScan()
193
+ completion(.success(self.state()))
194
+ case "getDevices": completion(.success(self.devices()))
195
+ case "connect": self.connect(id: options["id"] as? String, wait: true, completion: completion)
196
+ case "reconnect": self.connect(id: nil, wait: false, completion: completion)
197
+ case "disconnect": self.disconnect(forget: options["forget"] as? Bool ?? false, completion: completion)
198
+ case "startRecording": self.startRecording(completion: completion)
199
+ case "pauseRecording": self.setRecordingPaused(true, completion: completion)
200
+ case "resumeRecording": self.setRecordingPaused(false, completion: completion)
201
+ case "stopRecording": self.stopRecording(completion: completion)
202
+ case "getRecordingState": completion(.success(self.recordingSummary(count: true)))
203
+ case "readRecording": completion(.success(self.loadSamples(since: (options["since"] as? NSNumber)?.doubleValue)))
204
+ default: completion(.failure(CraftHeartRateError(message: "Unsupported HeartRate method", code: "UNKNOWN_ACTION")))
205
+ }
206
+ }
207
+ }
208
+
209
+ // MARK: State
210
+
211
+ static func authorizationName(_ value: CBManagerAuthorization) -> String {
212
+ switch value {
213
+ case .allowedAlways: return "authorized"
214
+ case .denied: return "denied"
215
+ case .restricted: return "restricted"
216
+ case .notDetermined: return "notDetermined"
217
+ @unknown default: return "denied"
218
+ }
219
+ }
220
+
221
+ static func bluetoothName(_ value: CBManagerState) -> String {
222
+ switch value {
223
+ case .poweredOn: return "poweredOn"
224
+ case .poweredOff: return "poweredOff"
225
+ case .unauthorized: return "unauthorized"
226
+ case .unsupported: return "unsupported"
227
+ case .resetting: return "resetting"
228
+ case .unknown: return "unknown"
229
+ @unknown default: return "unknown"
230
+ }
231
+ }
232
+
233
+ private var authorization: String { simulated ? "authorized" : Self.authorizationName(CBManager.authorization) }
234
+
235
+ /// "unknown" until something has asked for Bluetooth: reading it would
236
+ /// make the central manager, and that is what shows iOS's prompt.
237
+ private var bluetooth: String {
238
+ if simulated { return "poweredOn" }
239
+ guard let central else { return "unknown" }
240
+ return Self.bluetoothName(central.state)
241
+ }
242
+
243
+ private func remembered() -> [String: Any]? {
244
+ guard let device = UserDefaults.standard.dictionary(forKey: Self.rememberedKey),
245
+ device["id"] is String else { return nil }
246
+ return device
247
+ }
248
+
249
+ private func remember(id: UUID, name: String) {
250
+ UserDefaults.standard.set(["id": id.uuidString, "name": name], forKey: Self.rememberedKey)
251
+ }
252
+
253
+ func state() -> [String: Any] {
254
+ let fresh = latestAt.map { Date().timeIntervalSince($0) <= Self.staleAfter } ?? false
255
+ let device: Any = deviceId.map { ["id": $0.uuidString, "name": deviceName ?? "Heart rate monitor"] as [String: Any] } ?? NSNull()
256
+ return [
257
+ "available": bluetooth != "unsupported",
258
+ "bluetooth": bluetooth,
259
+ "authorization": authorization,
260
+ "scanning": scanning,
261
+ "connection": connection,
262
+ "device": device,
263
+ "lastDevice": remembered() ?? NSNull(),
264
+ "bpm": (fresh ? latest?.bpm : nil) ?? NSNull(),
265
+ "lastReadingAt": latestAt.map { $0.timeIntervalSince1970 * 1000 } ?? NSNull(),
266
+ "recording": recordingSummary(count: false),
267
+ ]
268
+ }
269
+
270
+ private func emit(_ detail: [String: Any]) {
271
+ if pageSink?(detail) != true { CraftWebServices.forward("craftHeartRate", data: detail) }
272
+ }
273
+
274
+ private func emitState() {
275
+ var detail = state()
276
+ detail["type"] = "state"
277
+ emit(detail)
278
+ }
279
+
280
+ // MARK: Bluetooth
281
+
282
+ /// The central manager, made on first use: that is when iOS asks.
283
+ private func whenReady(_ run: @escaping () -> Void) {
284
+ if simulated { return run() }
285
+ if central == nil {
286
+ central = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: false])
287
+ }
288
+ if central!.state == .unknown || central!.state == .resetting {
289
+ stateWaiters.append(run)
290
+ } else {
291
+ run()
292
+ }
293
+ }
294
+
295
+ /// A reason the radio cannot be used now, or nil when it can.
296
+ private func unusable() -> CraftHeartRateError? {
297
+ switch bluetooth {
298
+ case "poweredOn": return nil
299
+ case "poweredOff": return CraftHeartRateError(message: "Bluetooth is off", code: "BLUETOOTH_OFF")
300
+ case "unauthorized": return CraftHeartRateError(message: "Bluetooth access was not allowed", code: "NOT_AUTHORIZED")
301
+ case "unsupported": return CraftHeartRateError(message: "This device has no Bluetooth", code: "UNSUPPORTED")
302
+ default: return CraftHeartRateError(message: "Bluetooth is not ready", code: "BLUETOOTH_UNAVAILABLE")
303
+ }
304
+ }
305
+
306
+ private func requestAuthorization(completion: @escaping Completion) {
307
+ whenReady { completion(.success(self.authorization)) }
308
+ }
309
+
310
+ func centralManagerDidUpdateState(_ central: CBCentralManager) {
311
+ let waiting = stateWaiters
312
+ if central.state != .unknown && central.state != .resetting {
313
+ stateWaiters.removeAll()
314
+ waiting.forEach { $0() }
315
+ }
316
+ if central.state == .poweredOn {
317
+ // Bluetooth back on (or on at last): ask for the strap again.
318
+ if wantsConnection, let peripheral, peripheral.state == .disconnected {
319
+ connection = "reconnecting"
320
+ central.connect(peripheral)
321
+ }
322
+ } else if central.state != .unknown {
323
+ scanning = false
324
+ if wantsConnection && connection != "disconnected" { connection = "reconnecting" }
325
+ }
326
+ emitState()
327
+ }
328
+
329
+ // MARK: Scanning
330
+
331
+ private func devices() -> [[String: Any]] {
332
+ discovered
333
+ .map { id, device in ["id": id.uuidString, "name": device.name, "rssi": device.rssi] as [String: Any] }
334
+ .sorted { ($0["rssi"] as? Int ?? -200) > ($1["rssi"] as? Int ?? -200) }
335
+ }
336
+
337
+ private func found(id: UUID, peripheral: CBPeripheral?, name: String, rssi: Int) {
338
+ let known = discovered[id] != nil
339
+ discovered[id] = (peripheral, name, rssi)
340
+ if !known { emit(["type": "device", "device": ["id": id.uuidString, "name": name, "rssi": rssi]]) }
341
+ }
342
+
343
+ private func scan(seconds: Double?, completion: @escaping Completion) {
344
+ whenReady {
345
+ if let reason = self.unusable() { return completion(.failure(reason)) }
346
+ self.discovered.removeAll()
347
+ self.scanning = true
348
+ if self.simulated {
349
+ self.found(id: Self.simulatedId, peripheral: nil, name: "Simulated HRM", rssi: -48)
350
+ } else if let central = self.central {
351
+ // A strap already connected to this phone (by Settings or
352
+ // another app) no longer advertises; it is still a choice.
353
+ for peripheral in central.retrieveConnectedPeripherals(withServices: [Self.serviceUUID]) {
354
+ self.found(id: peripheral.identifier, peripheral: peripheral, name: peripheral.name ?? "Heart rate monitor", rssi: 0)
355
+ }
356
+ central.scanForPeripherals(withServices: [Self.serviceUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
357
+ }
358
+ self.scanStop?.cancel()
359
+ let stop = DispatchWorkItem { [weak self] in self?.stopScan() }
360
+ self.scanStop = stop
361
+ DispatchQueue.main.asyncAfter(deadline: .now() + min(max(seconds ?? 15, 1), 60), execute: stop)
362
+ self.emitState()
363
+ completion(.success(self.state()))
364
+ }
365
+ }
366
+
367
+ private func stopScan() {
368
+ scanStop?.cancel()
369
+ scanStop = nil
370
+ guard scanning else { return }
371
+ scanning = false
372
+ if central?.state == .poweredOn { central?.stopScan() }
373
+ emitState()
374
+ }
375
+
376
+ func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
377
+ let name = (advertisementData[CBAdvertisementDataLocalNameKey] as? String) ?? peripheral.name ?? "Heart rate monitor"
378
+ // 127 is CoreBluetooth's "no reading".
379
+ found(id: peripheral.identifier, peripheral: peripheral, name: name, rssi: RSSI.intValue == 127 ? -100 : RSSI.intValue)
380
+ }
381
+
382
+ // MARK: Connecting
383
+
384
+ private func connect(id: String?, wait: Bool, completion: @escaping Completion) {
385
+ let target = id ?? remembered()?["id"] as? String
386
+ guard let target, let uuid = UUID(uuidString: target) else {
387
+ if wait { return completion(.failure(CraftHeartRateError(message: "connect needs the id of a device from scan", code: "INVALID_ARGUMENT"))) }
388
+ return completion(.success(state()))
389
+ }
390
+ whenReady {
391
+ if let reason = self.unusable() { return completion(.failure(reason)) }
392
+ // Already there, or on the way: nothing to start again.
393
+ if self.deviceId == uuid && self.wantsConnection {
394
+ if self.connection == "connected" || !wait { return completion(.success(self.state())) }
395
+ self.connectWaiters.append(completion)
396
+ self.armConnectDeadline()
397
+ return
398
+ }
399
+ self.release()
400
+ let saved = self.remembered()
401
+ let savedName = (saved?["id"] as? String) == target ? saved?["name"] as? String : nil
402
+ let name = self.discovered[uuid]?.name ?? savedName ?? "Heart rate monitor"
403
+ if self.simulated {
404
+ guard uuid == Self.simulatedId else { return completion(.failure(CraftHeartRateError(message: "No heart-rate monitor with that id is nearby", code: "NOT_FOUND"))) }
405
+ } else {
406
+ let peripheral = self.discovered[uuid]?.peripheral ?? self.central?.retrievePeripherals(withIdentifiers: [uuid]).first
407
+ guard let peripheral else { return completion(.failure(CraftHeartRateError(message: "No heart-rate monitor with that id is nearby", code: "NOT_FOUND"))) }
408
+ peripheral.delegate = self
409
+ self.peripheral = peripheral
410
+ }
411
+ self.deviceId = uuid
412
+ self.deviceName = name
413
+ self.wantsConnection = true
414
+ self.connection = "connecting"
415
+ self.remember(id: uuid, name: name)
416
+ if wait {
417
+ self.connectWaiters.append(completion)
418
+ self.armConnectDeadline()
419
+ }
420
+ if self.simulated {
421
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in self?.simulatedConnected() }
422
+ } else if let peripheral = self.peripheral {
423
+ self.central?.connect(peripheral)
424
+ }
425
+ self.emitState()
426
+ if !wait { completion(.success(self.state())) }
427
+ }
428
+ }
429
+
430
+ /// `connect` answers TIMEOUT after a while; the strap is still asked
431
+ /// for, since it may wake up once it is worn.
432
+ private func armConnectDeadline() {
433
+ guard connectDeadline == nil else { return }
434
+ let deadline = DispatchWorkItem { [weak self] in
435
+ guard let self, self.connection != "connected" else { return }
436
+ self.settleConnect(.failure(CraftHeartRateError(message: "The heart-rate monitor did not answer. Wear it to wake it up.", code: "TIMEOUT")))
437
+ }
438
+ connectDeadline = deadline
439
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.connectTimeout, execute: deadline)
440
+ }
441
+
442
+ private func settleConnect(_ result: Result<Any, CraftHeartRateError>) {
443
+ connectDeadline?.cancel()
444
+ connectDeadline = nil
445
+ let waiting = connectWaiters
446
+ connectWaiters.removeAll()
447
+ waiting.forEach { $0(result) }
448
+ }
449
+
450
+ /// Lets go of the current strap without telling anyone.
451
+ private func release() {
452
+ wantsConnection = false
453
+ simulatedTimer?.invalidate()
454
+ simulatedTimer = nil
455
+ if let peripheral, let central, peripheral.state != .disconnected { central.cancelPeripheralConnection(peripheral) }
456
+ peripheral = nil
457
+ deviceId = nil
458
+ deviceName = nil
459
+ latest = nil
460
+ latestAt = nil
461
+ connection = "disconnected"
462
+ settleConnect(.failure(CraftHeartRateError(message: "Another heart-rate monitor was chosen", code: "CANCELLED")))
463
+ }
464
+
465
+ private func disconnect(forget: Bool, completion: @escaping Completion) {
466
+ release()
467
+ if forget { UserDefaults.standard.removeObject(forKey: Self.rememberedKey) }
468
+ emitState()
469
+ completion(.success(state()))
470
+ }
471
+
472
+ func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
473
+ guard peripheral.identifier == deviceId else { return }
474
+ peripheral.delegate = self
475
+ peripheral.discoverServices([Self.serviceUUID])
476
+ }
477
+
478
+ func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
479
+ guard peripheral.identifier == deviceId, wantsConnection else { return }
480
+ // Asked for again: a failed attempt is usually a strap going to sleep.
481
+ connection = "reconnecting"
482
+ central.connect(peripheral)
483
+ emitState()
484
+ }
485
+
486
+ func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
487
+ guard peripheral.identifier == deviceId else { return }
488
+ latest = nil
489
+ latestAt = nil
490
+ if wantsConnection {
491
+ connection = "reconnecting"
492
+ central.connect(peripheral)
493
+ } else {
494
+ connection = "disconnected"
495
+ }
496
+ emitState()
497
+ }
498
+
499
+ func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
500
+ guard let service = peripheral.services?.first(where: { $0.uuid == Self.serviceUUID }) else {
501
+ notAHeartRateMonitor(peripheral)
502
+ return
503
+ }
504
+ peripheral.discoverCharacteristics([Self.measurementUUID], for: service)
505
+ }
506
+
507
+ func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
508
+ guard let measurement = service.characteristics?.first(where: { $0.uuid == Self.measurementUUID }) else {
509
+ notAHeartRateMonitor(peripheral)
510
+ return
511
+ }
512
+ peripheral.setNotifyValue(true, for: measurement)
513
+ }
514
+
515
+ func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
516
+ guard characteristic.uuid == Self.measurementUUID, peripheral.identifier == deviceId else { return }
517
+ if characteristic.isNotifying {
518
+ connection = "connected"
519
+ emitState()
520
+ settleConnect(.success(state()))
521
+ } else if let error {
522
+ settleConnect(.failure(CraftHeartRateError(message: error.localizedDescription, code: "CONNECT_FAILED")))
523
+ }
524
+ }
525
+
526
+ func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
527
+ guard characteristic.uuid == Self.measurementUUID, peripheral.identifier == deviceId, let value = characteristic.value else { return }
528
+ received([UInt8](value))
529
+ }
530
+
531
+ private func notAHeartRateMonitor(_ peripheral: CBPeripheral) {
532
+ wantsConnection = false
533
+ central?.cancelPeripheralConnection(peripheral)
534
+ connection = "disconnected"
535
+ settleConnect(.failure(CraftHeartRateError(message: "That device does not send a heart rate", code: "NOT_HEART_RATE_MONITOR")))
536
+ emitState()
537
+ }
538
+
539
+ // MARK: Readings
540
+
541
+ private func received(_ bytes: [UInt8]) {
542
+ // A strap reads 0 between losing the skin and giving up; that is no
543
+ // heart rate, and neither is anything a heart could not do.
544
+ guard let reading = CraftHeartRateMeasurement.parse(bytes), reading.bpm >= 20, reading.bpm <= 250 else { return }
545
+ let now = Date()
546
+ latest = reading
547
+ latestAt = now
548
+ let timestamp = (now.timeIntervalSince1970 * 1000).rounded()
549
+ let intervals = reading.rrIntervals.map { ($0 * 10).rounded() / 10 }
550
+ var detail: [String: Any] = [
551
+ "type": "reading",
552
+ "bpm": reading.bpm,
553
+ "rrIntervals": intervals,
554
+ "contact": reading.sensorContact ?? NSNull(),
555
+ "energyExpended": reading.energyExpended ?? NSNull(),
556
+ "timestamp": timestamp,
557
+ ]
558
+ if let deviceId { detail["deviceId"] = deviceId.uuidString }
559
+ appendSample(["timestamp": timestamp, "bpm": reading.bpm, "rr": intervals])
560
+ emit(detail)
561
+ }
562
+
563
+ private func simulatedConnected() {
564
+ guard simulated, wantsConnection, deviceId == Self.simulatedId else { return }
565
+ connection = "connected"
566
+ emitState()
567
+ settleConnect(.success(state()))
568
+ simulatedTimer?.invalidate()
569
+ simulatedTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
570
+ guard let self else { return }
571
+ self.simulatedBeat += 1
572
+ // A steady run with a slow swell, the way a real one drifts.
573
+ let bpm = 142 + Int((sin(Double(self.simulatedBeat) / 20) * 12).rounded())
574
+ let interval = 60_000 / Double(bpm)
575
+ self.received(CraftHeartRateMeasurement.encode(bpm: bpm, sensorContact: true, rrIntervals: [interval]))
576
+ }
577
+ }
578
+
579
+ // MARK: Recording
580
+
581
+ private var directory: URL {
582
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
583
+ }
584
+ private var stateURL: URL { directory.appendingPathComponent("craft-heart-rate-recording-state.json") }
585
+ private var samplesURL: URL { directory.appendingPathComponent("craft-heart-rate-recording.jsonl") }
586
+
587
+ /// A recording that was running when the app last closed carries on.
588
+ private func restoreRecording() {
589
+ guard !restored else { return }
590
+ restored = true
591
+ guard let data = try? Data(contentsOf: stateURL),
592
+ let saved = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
593
+ saved["active"] as? Bool == true else { return }
594
+ recordingId = saved["id"] as? String
595
+ recordingStartedAt = saved["startedAt"] as? Double
596
+ recordingPaused = saved["paused"] as? Bool ?? false
597
+ recordedCount = loadSamples(since: nil).count
598
+ }
599
+
600
+ private func persistRecording() {
601
+ let saved: [String: Any] = [
602
+ "active": recordingId != nil,
603
+ "paused": recordingPaused,
604
+ "id": recordingId ?? NSNull(),
605
+ "startedAt": recordingStartedAt ?? NSNull(),
606
+ ]
607
+ do {
608
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
609
+ try JSONSerialization.data(withJSONObject: saved).write(to: stateURL, options: .atomic)
610
+ protect(stateURL)
611
+ } catch {
612
+ print("Unable to persist the heart-rate recording state: \(error)")
613
+ }
614
+ }
615
+
616
+ private func protect(_ url: URL) {
617
+ try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: url.path)
618
+ var values = URLResourceValues()
619
+ values.isExcludedFromBackup = true
620
+ var protectedURL = url
621
+ try? protectedURL.setResourceValues(values)
622
+ }
623
+
624
+ private func recordingSummary(count: Bool) -> [String: Any] {
625
+ var summary: [String: Any] = [
626
+ "id": recordingId ?? NSNull(),
627
+ "active": recordingId != nil,
628
+ "paused": recordingPaused,
629
+ "startedAt": recordingStartedAt ?? NSNull(),
630
+ ]
631
+ if count { summary["sampleCount"] = recordedCount }
632
+ return summary
633
+ }
634
+
635
+ private func startRecording(completion: @escaping Completion) {
636
+ do {
637
+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
638
+ try Data().write(to: samplesURL, options: .atomic)
639
+ protect(samplesURL)
640
+ } catch {
641
+ return completion(.failure(CraftHeartRateError(message: "Unable to create the heart-rate recording", code: "RECORDING_STORAGE_ERROR")))
642
+ }
643
+ recordingId = UUID().uuidString
644
+ recordingStartedAt = (Date().timeIntervalSince1970 * 1000).rounded()
645
+ recordingPaused = false
646
+ recordedCount = 0
647
+ persistRecording()
648
+ completion(.success(recordingSummary(count: true)))
649
+ }
650
+
651
+ private func setRecordingPaused(_ paused: Bool, completion: @escaping Completion) {
652
+ guard recordingId != nil else {
653
+ return completion(.failure(CraftHeartRateError(message: "No active heart-rate recording", code: "NO_ACTIVE_RECORDING")))
654
+ }
655
+ recordingPaused = paused
656
+ persistRecording()
657
+ completion(.success(recordingSummary(count: true)))
658
+ }
659
+
660
+ private func stopRecording(completion: @escaping Completion) {
661
+ var summary = recordingSummary(count: true)
662
+ summary["active"] = false
663
+ summary["samples"] = loadSamples(since: nil)
664
+ recordingId = nil
665
+ recordingStartedAt = nil
666
+ recordingPaused = false
667
+ recordedCount = 0
668
+ persistRecording()
669
+ try? FileManager.default.removeItem(at: samplesURL)
670
+ completion(.success(summary))
671
+ }
672
+
673
+ private func appendSample(_ sample: [String: Any]) {
674
+ guard recordingId != nil, !recordingPaused, recordedCount < Self.maxRecordedSamples,
675
+ let json = try? JSONSerialization.data(withJSONObject: sample) else { return }
676
+ var line = json
677
+ line.append(0x0A)
678
+ do {
679
+ let handle = try FileHandle(forWritingTo: samplesURL)
680
+ try handle.seekToEnd()
681
+ try handle.write(contentsOf: line)
682
+ try handle.close()
683
+ recordedCount += 1
684
+ } catch {
685
+ print("Unable to append a heart-rate sample: \(error)")
686
+ }
687
+ }
688
+
689
+ /// The recording's samples, oldest first; only those after `since` (ms) when given.
690
+ private func loadSamples(since: Double?) -> [[String: Any]] {
691
+ guard let text = try? String(contentsOf: samplesURL, encoding: .utf8) else { return [] }
692
+ return text.split(separator: "\n").compactMap { line in
693
+ guard let data = line.data(using: .utf8),
694
+ let sample = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }
695
+ if let since, ((sample["timestamp"] as? NSNumber)?.doubleValue ?? 0) <= since { return nil }
696
+ return sample
697
+ }
698
+ }
699
+ }