HousingClient.swift (19374B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 // Bluetooth connection to the housing. The only write: the pump (1624), with an automatic stop 3 // at the vacuum threshold or after a timeout, as the official app does (docs/PROTOCOL.md). 4 @preconcurrency import CoreBluetooth 5 import Foundation 6 import Observation 7 8 @MainActor 9 @Observable 10 final class HousingClient: NSObject { 11 enum Status: Equatable { 12 case bluetoothUnavailable(String) 13 case scanning 14 case connecting(String) 15 case connected(String) 16 case disconnected(String) 17 18 var label: String { 19 switch self { 20 case .bluetoothUnavailable(let why): String(localized: "Bluetooth unavailable: \(why)") 21 case .scanning: String(localized: "Looking for the housing…") 22 case .connecting(let name): String(localized: "Connecting to \(name)…") 23 case .connected(let name): String(localized: "Connected to \(name)") 24 case .disconnected(let why): String(localized: "Disconnected (\(why)), reconnecting…") 25 } 26 } 27 } 28 29 struct LogLine: Identifiable { 30 let id = UUID() 31 let date: Date 32 let text: String 33 } 34 35 private(set) var status: Status = .bluetoothUnavailable(String(localized: "starting")) 36 private(set) var readings = HousingReadings() 37 private(set) var deviceInfo: [DeviceInfoField: String] = [:] 38 private(set) var log: [LogLine] = [] 39 private(set) var lastSensorUpdate: Date? 40 private(set) var vacuum = VacuumSequence() 41 /// Buttons left to the camera by the vacuum sequence. 42 @ObservationIgnored var cameraButton: ((ButtonEvent) -> Void)? 43 /// Called at each press, whoever it is meant for (to silence an alarm). 44 @ObservationIgnored var anyButton: (() -> Void)? 45 46 /// Every sample of the external pressure (characteristic 1625), in Pa, with its time in seconds: the wall 47 /// clock for a real housing, the clock of the simulated dive for the simulated one. 48 @ObservationIgnored var externalPressure: ((_ pa: Double, _ time: Double) -> Void)? 49 /// The Bluetooth link to a real housing was just lost. 50 @ObservationIgnored var linkLost: (() -> Void)? 51 /// A new housing session starts (reconnection asked by the user, simulation started or stopped). 52 @ObservationIgnored var sessionStarted: (() -> Void)? 53 /// Time of the sample being ingested, when it is not the wall clock (simulated dive). 54 @ObservationIgnored private var sampleTime: Double? 55 56 func bypassVacuum() { vacuum.bypass() } 57 58 @ObservationIgnored private var central: CBCentralManager! 59 @ObservationIgnored private var peripheral: CBPeripheral? 60 @ObservationIgnored private var pumpCharacteristic: CBCharacteristic? 61 @ObservationIgnored private var pumpTimeout: Task<Void, Never>? 62 63 /// True between our start order and our stop order. 64 private(set) var pumpRequested = false 65 /// True when a real housing is connected. 66 var isConnected: Bool { 67 if case .connected = status { return !simulated } 68 return false 69 } 70 71 var canPump: Bool { pumpCharacteristic != nil || simulation != nil } 72 73 /// Stop threshold observed with the official app: first sample below 80 kPa. 74 static let vacuumTargetPa = 80_000.0 75 /// Safeguard: the official app pumps for about 10 s. 76 static let pumpMaxSeconds = 15.0 77 78 /// True when the user asked to disconnect: no automatic reconnection. 79 private(set) var released = false 80 81 /// In the capture, the official app sends no power-off order: it drops the connection 82 /// (HCI 0x16) and the housing turns off. We do the same. 83 // MARK: Simulated housing (demo, interface review, reviewers without a housing) 84 85 private struct Simulation { 86 var pressurePa = 100_960.0 87 var temperatureC = 21.0 88 var pumpOn = false 89 var battery = 92.0 90 /// Simulated dive: depth at every second (empty: at the surface), time since its start, and the 91 /// time of its start on the clock given with the samples. 92 var diveDepths: [Double] = [] 93 var diveTime = 0.0 94 var diveBase = 0.0 95 } 96 97 /// External pressure of the simulated housing at the surface, and what a metre of water adds 98 /// (units of the characteristic: tens of Pa; EN 13319 water). 99 private static let simulatedSurface = 9_940.0 100 private static let simulatedPerMetre = 1_000.28 101 102 private static func littleEndian(_ value: UInt32) -> Data { 103 Data([UInt8(value & 0xFF), UInt8(value >> 8 & 0xFF), UInt8(value >> 16 & 0xFF), UInt8(value >> 24)]) 104 } 105 106 /// A simulated dive is in progress on the simulated housing. 107 var simulatedDiveRunning: Bool { simulation?.diveDepths.isEmpty == false } 108 109 /// Simulated housing only: plays a dive on the external pressure sensor, `depths` being the depth at every 110 /// second. `skip` seconds of it are fed at once (screenshots of a given moment), the rest in real time. 111 func startSimulatedDive(depths: [Double], skip: Double = 0) { 112 guard var sim = simulation, sim.diveDepths.isEmpty, !depths.isEmpty else { return } 113 let skip = max(0, min(skip, Double(depths.count - 1))) 114 let base = Date().timeIntervalSinceReferenceDate - skip 115 var t = 0.0 116 while t < skip { 117 sampleTime = base + t 118 ingest(HousingUUID.externalPressure, 119 Self.littleEndian(UInt32(Self.simulatedSurface + depths[Int(t)] * Self.simulatedPerMetre))) 120 t += 1 121 } 122 sampleTime = nil 123 sim.diveDepths = depths 124 sim.diveTime = skip 125 sim.diveBase = base 126 simulation = sim 127 note(String(localized: "Simulated dive started")) 128 } 129 130 @ObservationIgnored private var simulation: Simulation? 131 @ObservationIgnored private var simulationTask: Task<Void, Never>? 132 private(set) var simulated = false 133 134 func startSimulation() { 135 guard simulation == nil else { return } 136 central.stopScan() 137 if let peripheral { central.cancelPeripheralConnection(peripheral) } 138 peripheral = nil 139 released = true // do not pick up a real housing during the demo 140 simulation = Simulation() 141 simulated = true 142 vacuum = VacuumSequence() 143 vacuum.testDuration = 20 // demo: shortened test 144 vacuum.bypass() // straight to the camera; long press right to show the vacuum sequence 145 readings = HousingReadings() 146 status = .connected(String(localized: "simulated housing")) 147 deviceInfo = [.model: String(localized: "Simulated housing")] 148 sessionStarted?() 149 note(String(localized: "Simulation started")) 150 ingest(HousingUUID.alarm, Data([0x00])) 151 ingest(HousingUUID.pumpState, Data([0x02])) 152 simulationTask = Task { [weak self] in 153 while !Task.isCancelled { 154 try? await Task.sleep(for: .milliseconds(350)) 155 self?.simulationTick() 156 } 157 } 158 } 159 160 func stopSimulation() { 161 guard simulation != nil else { return } 162 simulationTask?.cancel() 163 pumpTimeout?.cancel() 164 simulation = nil 165 simulated = false 166 pumpRequested = false 167 readings = HousingReadings() 168 deviceInfo = [:] 169 note(String(localized: "Simulation stopped")) 170 reconnect() 171 } 172 173 /// Press on a button of the simulated housing (buttons shown on screen). 174 func simulatedPress(_ button: HousingButton, long: Bool = false) { 175 guard simulation != nil else { return } 176 ingest(HousingUUID.button, Data([button.rawValue << 4 | (long ? 1 : 0)])) 177 } 178 179 private func simulationTick() { 180 guard var sim = simulation else { return } 181 if sim.pumpOn { 182 sim.pressurePa -= 2_100 * 0.35 // ~2 kPa/s, like the real housing 183 sim.battery = max(5, sim.battery - 0.15) 184 } else if case .opening = vacuum.step { 185 sim.pressurePa = min(99_300, sim.pressurePa + 6_000) // plug open: air comes back in 186 } else if sim.pressurePa < 90_000 { 187 sim.pressurePa += 30.0 / 60 * 0.35 // ~30 Pa/min, normal residual leak 188 sim.temperatureC = min(26, sim.temperatureC + 0.002) 189 } 190 sim.pressurePa += Double.random(in: -8...8) 191 var external = Self.simulatedSurface 192 if !sim.diveDepths.isEmpty { 193 sim.diveTime += 0.35 194 let i = Int(sim.diveTime) 195 if i + 1 < sim.diveDepths.count { 196 let a = sim.diveDepths[i], b = sim.diveDepths[i + 1] 197 external += (a + (b - a) * (sim.diveTime - Double(i))) * Self.simulatedPerMetre 198 sampleTime = sim.diveBase + sim.diveTime 199 } else { 200 sim.diveDepths = [] 201 } 202 } 203 simulation = sim 204 func le(_ value: UInt32) -> Data { Self.littleEndian(value) } 205 ingest(HousingUUID.externalPressure, le(UInt32(external))) 206 sampleTime = nil 207 ingest(HousingUUID.temperature, le(UInt32(sim.temperatureC * 100))) 208 ingest(HousingUUID.internalPressure, le(UInt32(sim.pressurePa))) 209 if Int(sim.battery) != readings.batteryPercent { ingest(HousingUUID.batteryLevel, Data([UInt8(sim.battery)])) } 210 } 211 212 func release() { 213 if simulation != nil { stopSimulation(); return } 214 guard let peripheral else { return } 215 if pumpRequested { stopPump(reason: String(localized: "disconnection")) } 216 released = true 217 central.stopScan() 218 central.cancelPeripheralConnection(peripheral) 219 note(String(localized: "Disconnection requested")) 220 } 221 222 /// Handles a value from the housing, real or simulated. 223 private func ingest(_ uuid: CBUUID, _ data: Data) { 224 if let field = HousingUUID.deviceInfoStrings[uuid] { 225 deviceInfo[field] = String(decoding: data, as: UTF8.self) 226 return 227 } 228 let before = vacuum.step 229 if let line = readings.apply(uuid, data) { note(line) } 230 if uuid == HousingUUID.button, let event = ButtonEvent(data) { 231 anyButton?() 232 let forCamera = vacuum.cameraHasButtons && !(event.button == .right && event.isLong) 233 run(vacuum.button(event, now: .now)) 234 if forCamera { cameraButton?(event) } 235 } 236 if uuid == HousingUUID.internalPressure || uuid == HousingUUID.temperature { 237 run(vacuum.sensors(pressurePa: readings.internalPressurePa, temperatureC: readings.temperatureC, now: .now)) 238 } 239 if uuid == HousingUUID.internalPressure { DevLog.shared.sensors(readings, vacuum) } 240 if uuid == HousingUUID.externalPressure, let pa = readings.externalPressurePa { 241 externalPressure?(pa, sampleTime ?? Date().timeIntervalSinceReferenceDate) 242 } 243 // Pump running although we did not ask for it (connection lost while pumping): stop it. 244 if uuid == HousingUUID.pumpState, readings.pumpState == .running, !pumpRequested, simulation == nil { 245 stopPump(reason: String(localized: "found running")) 246 } 247 if vacuum.step != before { note(String(localized: "Sequence: \(String(describing: vacuum.step))")) } 248 if uuid == HousingUUID.internalPressure, pumpRequested, 249 let p = readings.internalPressurePa, p < Self.vacuumTargetPa { 250 stopPump(reason: String(localized: "vacuum reached, \(String(Int(p))) Pa")) 251 } 252 if [HousingUUID.internalPressure, HousingUUID.externalPressure, HousingUUID.temperature].contains(uuid) { 253 lastSensorUpdate = .now 254 } 255 } 256 257 private func run(_ effects: [VacuumSequence.Effect]) { 258 for effect in effects { 259 switch effect { 260 case .startPump: startPump() 261 case .stopPump: if pumpRequested { stopPump(reason: String(localized: "sequence")) } 262 case .disconnect: release() 263 } 264 } 265 } 266 267 func reconnect() { 268 released = false 269 vacuum = VacuumSequence() 270 peripheral = nil 271 sessionStarted?() 272 startScan() 273 } 274 275 func startPump() { 276 guard !pumpRequested, simulation != nil || (peripheral != nil && pumpCharacteristic != nil) else { return } 277 if let p = readings.internalPressurePa, p < Self.vacuumTargetPa { 278 note(String(localized: "Pump: vacuum already reached (\(String(Int(p))) Pa)")) 279 return 280 } 281 pumpRequested = true 282 if simulation != nil { 283 simulation?.pumpOn = true 284 ingest(HousingUUID.pumpState, Data([0x01])) 285 } else if let peripheral, let pumpCharacteristic { 286 peripheral.writeValue(Data([0x01]), for: pumpCharacteristic, type: .withResponse) 287 } 288 note(String(localized: "Pump: start requested")) 289 pumpTimeout = Task { [weak self] in 290 try? await Task.sleep(for: .seconds(Self.pumpMaxSeconds)) 291 guard !Task.isCancelled else { return } 292 self?.stopPump(reason: String(localized: "\(String(Int(Self.pumpMaxSeconds))) s timeout")) 293 } 294 } 295 296 func stopPump(reason: String) { 297 pumpTimeout?.cancel() 298 pumpTimeout = nil 299 if simulation != nil { 300 simulation?.pumpOn = false 301 pumpRequested = false 302 ingest(HousingUUID.pumpState, Data([0x02])) 303 note(String(localized: "Pump: stop requested (\(reason))")) 304 return 305 } 306 guard let peripheral, let pumpCharacteristic else { pumpRequested = false; return } 307 // Always send the stop, even when we do not think we started it. 308 peripheral.writeValue(Data([0x00]), for: pumpCharacteristic, type: .withResponse) 309 pumpRequested = false 310 note(String(localized: "Pump: stop requested (\(reason))")) 311 } 312 313 override init() { 314 super.init() 315 central = CBCentralManager(delegate: self, queue: .main) 316 } 317 318 private func note(_ text: String) { 319 log.insert(LogLine(date: .now, text: text), at: 0) 320 DevLog.shared.event(text) 321 if log.count > 200 { log.removeLast(log.count - 200) } 322 } 323 324 private func startScan() { 325 // Already connected to the system (by another app, for instance)? 326 if let known = central.retrieveConnectedPeripherals(withServices: [HousingUUID.housingService]).first { 327 connect(known) 328 return 329 } 330 status = .scanning 331 // The housing does not advertise its services: filter on the name. 332 central.scanForPeripherals(withServices: nil, options: nil) 333 } 334 335 private func connect(_ target: CBPeripheral) { 336 central.stopScan() 337 peripheral = target 338 target.delegate = self 339 status = .connecting(target.name ?? HousingUUID.advertisedName) 340 central.connect(target) 341 } 342 } 343 344 extension HousingClient: CBCentralManagerDelegate { 345 nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) { 346 MainActor.assumeIsolated { 347 guard simulation == nil else { return } // the demo keeps its state 348 switch central.state { 349 case .poweredOn: 350 note(String(localized: "Bluetooth ready")) 351 startScan() 352 case .poweredOff: status = .bluetoothUnavailable(String(localized: "powered off")) 353 case .unauthorized: status = .bluetoothUnavailable(String(localized: "access denied in Settings")) 354 case .unsupported: status = .bluetoothUnavailable(String(localized: "not supported")) 355 default: status = .bluetoothUnavailable(String(localized: "waiting")) 356 } 357 } 358 } 359 360 nonisolated func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, 361 advertisementData: [String: Any], rssi RSSI: NSNumber) { 362 let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? peripheral.name 363 guard name == HousingUUID.advertisedName else { return } 364 MainActor.assumeIsolated { 365 guard !released else { return } 366 note(String(localized: "Housing found (\("\(RSSI)") dBm)")) 367 connect(peripheral) 368 } 369 } 370 371 nonisolated func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 372 MainActor.assumeIsolated { 373 status = .connected(peripheral.name ?? HousingUUID.advertisedName) 374 note(String(localized: "Connected")) 375 peripheral.discoverServices(HousingUUID.services) 376 } 377 } 378 379 nonisolated func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, 380 error: Error?) { 381 MainActor.assumeIsolated { 382 note(String(localized: "Connection failed: \(error?.localizedDescription ?? "?")")) 383 startScan() 384 } 385 } 386 387 nonisolated func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, 388 error: Error?) { 389 MainActor.assumeIsolated { 390 let why = error?.localizedDescription ?? String(localized: "connection closed") 391 pumpCharacteristic = nil 392 pumpTimeout?.cancel() 393 pumpRequested = false 394 vacuum.connectionLost() 395 linkLost?() 396 status = .disconnected(why) 397 note(String(localized: "Disconnected: \(why)")) 398 // A pending connection request does not expire: the housing is picked up as soon as it comes back. 399 if !released { central.connect(peripheral) } 400 } 401 } 402 } 403 404 extension HousingClient: CBPeripheralDelegate { 405 nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 406 MainActor.assumeIsolated { 407 for service in peripheral.services ?? [] where HousingUUID.services.contains(service.uuid) { 408 peripheral.discoverCharacteristics(nil, for: service) 409 } 410 } 411 } 412 413 nonisolated func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, 414 error: Error?) { 415 MainActor.assumeIsolated { 416 for characteristic in service.characteristics ?? [] { 417 if characteristic.uuid == HousingUUID.pump { pumpCharacteristic = characteristic } 418 if characteristic.properties.contains(.notify) { 419 peripheral.setNotifyValue(true, for: characteristic) 420 } 421 if characteristic.properties.contains(.read) { 422 peripheral.readValue(for: characteristic) 423 } 424 } 425 } 426 } 427 428 nonisolated func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, 429 error: Error?) { 430 guard let error else { return } 431 let text = error.localizedDescription 432 MainActor.assumeIsolated { note(String(localized: "Write refused: \(text)")) } 433 } 434 435 nonisolated func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, 436 error: Error?) { 437 guard let data = characteristic.value else { return } 438 let uuid = characteristic.uuid 439 MainActor.assumeIsolated { ingest(uuid, data) } 440 } 441 }