DiveComputerLink.swift (24544B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import CoreBluetooth 3 import DiveComputerKit 4 import Foundation 5 import Observation 6 7 /// GATT services that dive computers use as a serial port, in order of preference, and those to stay away from. 8 /// Same lists as Subsurface (`core/qt-ble.cpp`). 9 private enum KnownServices { 10 static let serial: [CBUUID] = [ 11 "0000fefb-0000-1000-8000-00805f9b34fb", // Heinrichs-Weikamp (Telit/Stollmann) 12 "2456e1b9-26e2-8f83-e744-f34f01e9d701", // Heinrichs-Weikamp (U-Blox) 13 "544e326b-5b72-c6b0-1c46-41c1bc448118", // Mares BlueLink Pro 14 "98ae7120-e62e-11e3-badd-0002a5d5c51b", // Suunto (EON Steel/Core, G5) 15 "cb3c4555-d670-4670-bc20-b61dbc851e9a", // Pelagic (i770R, i200C, Pro Plus X, Geo 4.0) 16 "ca7b0001-f785-4c38-b599-c7c5fbadb034", // Pelagic (i330R, DSX) 17 "fdcdeaaa-295d-470e-bf15-04217b7aa0a0", // ScubaPro (G2, G3) 18 "fe25c237-0ece-443c-b0aa-e02033e7029d", // Shearwater (Petrel/Perdix/Teric/Peregrine/Tern) 19 "1aa44039-1667-4b29-87cc-dfecaaf31d97", // Shearwater (Perdix 3) 20 "0000fcef-0000-1000-8000-00805f9b34fb", // Divesoft 21 "6e400001-b5a3-f393-e0a9-e50e24dc10b8", // Cressi 22 "6e400001-b5a3-f393-e0a9-e50e24dcca9e", // Nordic Semi UART 23 "00000001-8c3b-4f2c-a59e-8c08224f3253", // Halcyon Symbios 24 "84968ffe-d26d-478a-b953-5010bcf58bca", // Seac 25 ].map { CBUUID(string: $0) } 26 27 static let firmwareUpgrade: Set<CBUUID> = Set([ 28 "00001530-1212-efde-1523-785feabcd123", // Nordic 29 "9e5d1e47-5c13-43a0-8635-82ad38a1386f", // Broadcom #1 30 "a86abc2d-d44c-442e-99f7-80059a873e36", // Broadcom #2 31 ].map { CBUUID(string: $0) }) 32 33 /// Characteristics never to read from or write to. 34 static let avoid: Set<CBUUID> = Set([ 35 "49535343-6daa-4d02-abf6-19569aca69fe", "49535343-aca3-481c-91ec-d85e28a60318", 36 "49535343-026e-3a9b-954c-97daef17e26e", "49535343-4c8a-39b3-2f49-511cff073b7e", // McLean Extreme 37 ].map { CBUUID(string: $0) }) 38 } 39 40 /// The app's single Bluetooth central. Its callbacks arrive on `queue`. 41 final class BluetoothCentral: NSObject, CBCentralManagerDelegate { 42 let queue = DispatchQueue(label: "org.schurger.subrascasse.bluetooth") 43 private(set) var manager: CBCentralManager! 44 var onState: ((CBManagerState) -> Void)? 45 var onDiscover: ((CBPeripheral, String, Int) -> Void)? 46 private let lock = NSLock() 47 private weak var link: BluetoothLink? 48 49 override init() { 50 super.init() 51 manager = CBCentralManager(delegate: self, queue: queue) 52 } 53 54 func attach(_ link: BluetoothLink?) { 55 lock.lock(); defer { lock.unlock() } 56 self.link = link 57 } 58 59 private var current: BluetoothLink? { 60 lock.lock(); defer { lock.unlock() } 61 return link 62 } 63 64 func centralManagerDidUpdateState(_ central: CBCentralManager) { onState?(central.state) } 65 66 func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, 67 advertisementData: [String: Any], rssi RSSI: NSNumber) { 68 let name = (advertisementData[CBAdvertisementDataLocalNameKey] as? String) ?? peripheral.name ?? "" 69 guard !name.isEmpty else { return } 70 onDiscover?(peripheral, name, RSSI.intValue) 71 } 72 73 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 74 current?.connectionChanged(peripheral, connected: true, error: nil) 75 } 76 77 func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { 78 current?.connectionChanged(peripheral, connected: false, error: error) 79 } 80 81 func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { 82 current?.connectionChanged(peripheral, connected: false, error: error) 83 } 84 } 85 86 /// A Bluetooth LE link to a dive computer, with the blocking calls libdivecomputer expects. Used from the download 87 /// thread; CoreBluetooth calls go to the central's queue, and its callbacks wake the download thread up. 88 final class BluetoothLink: NSObject, DiveComputerTransport, CBPeripheralDelegate { 89 private static let setupTimeout = 12_000 90 91 private let central: BluetoothCentral 92 private let peripheral: CBPeripheral 93 let deviceName: String 94 95 // Everything below is guarded by `condition`. 96 private let condition = NSCondition() 97 private var timeout = setupTimeout 98 private var connected = false 99 private var failure: String? 100 private var closed = false 101 private var servicesDiscovered = false 102 private var pendingDiscoveries = 0 103 private var pendingSubscriptions = 0 104 private var service: CBService? 105 private var writeCharacteristic: CBCharacteristic? 106 private var readCharacteristic: CBCharacteristic? 107 private var notifies = false 108 private var packets = [Data]() 109 private var awaitedRead: CBUUID? 110 private var readValue: Data? 111 private var writePending = false 112 private var trace = [String]() 113 114 // Only touched on the central's queue. 115 private var outbox = [Data]() 116 117 init(central: BluetoothCentral, peripheral: CBPeripheral, name: String) { 118 self.central = central 119 self.peripheral = peripheral 120 self.deviceName = name 121 } 122 123 /// What happened on the link, for troubleshooting. 124 var log: [String] { 125 condition.lock(); defer { condition.unlock() } 126 return trace 127 } 128 129 /// Must be called with `condition` locked. 130 private func note(_ line: String) { 131 if trace.count < 500 { trace.append(line) } 132 } 133 134 /// Waits (with `condition` locked) until `done` holds; throws on failure of the link or after the delay. 135 private func wait(_ milliseconds: Int, orFail what: String, until done: () -> Bool) throws { 136 let deadline = milliseconds < 0 ? Date.distantFuture : Date().addingTimeInterval(Double(milliseconds) / 1000) 137 while !done() { 138 if let failure { throw DiveComputerError.transport(failure) } 139 if !condition.wait(until: deadline), !done() { 140 if let failure { throw DiveComputerError.transport(failure) } 141 throw DiveComputerError.transport(what) 142 } 143 } 144 } 145 146 private func onQueue(_ work: @escaping () -> Void) { central.queue.async(execute: work) } 147 148 // MARK: Opening 149 150 /// Connects, finds the serial service and subscribes to its notifications. 151 func open() throws { 152 condition.lock(); defer { condition.unlock() } 153 central.attach(self) 154 peripheral.delegate = self 155 onQueue { self.central.manager.connect(self.peripheral) } 156 try wait(Self.setupTimeout, orFail: "connection timed out") { connected } 157 note("connected to \(deviceName)") 158 159 onQueue { self.peripheral.discoverServices(nil) } 160 try wait(Self.setupTimeout, orFail: "service discovery timed out") { servicesDiscovered } 161 let all = peripheral.services ?? [] 162 for found in all { note("service \(found.uuid.uuidString)") } 163 var candidates = [CBService]() 164 if let known = KnownServices.serial.lazy.compactMap({ uuid in all.first { $0.uuid == uuid } }).first { 165 candidates = [known] 166 } else { 167 // Standard (16-bit) services and firmware upgrade services are never the serial port. 168 candidates = all.filter { $0.uuid.data.count > 2 && !KnownServices.firmwareUpgrade.contains($0.uuid) } 169 } 170 guard !candidates.isEmpty else { throw DiveComputerError.transport("no usable Bluetooth service") } 171 172 pendingDiscoveries = candidates.count 173 onQueue { for candidate in candidates { self.peripheral.discoverCharacteristics(nil, for: candidate) } } 174 try wait(Self.setupTimeout, orFail: "characteristic discovery timed out") { pendingDiscoveries == 0 } 175 176 for candidate in candidates { 177 let characteristics = (candidate.characteristics ?? []).filter { !KnownServices.avoid.contains($0.uuid) } 178 for found in characteristics { note(" characteristic \(found.uuid.uuidString) properties 0x\(String(found.properties.rawValue, radix: 16))") } 179 let notifying = characteristics.filter { !$0.properties.isDisjoint(with: [.notify, .indicate]) } 180 let readable = characteristics.first { $0.properties.contains(.read) } 181 // Writing without a response is what serial-port services expect when they offer both. 182 let writable = characteristics.first { $0.properties.contains(.writeWithoutResponse) } 183 ?? characteristics.first { $0.properties.contains(.write) } 184 guard let writable, !notifying.isEmpty || readable != nil else { continue } 185 service = candidate 186 writeCharacteristic = writable 187 readCharacteristic = readable 188 notifies = !notifying.isEmpty 189 note("using service \(candidate.uuid.uuidString), writing to \(writable.uuid.uuidString)") 190 if notifies { 191 pendingSubscriptions = notifying.count 192 onQueue { for found in notifying { self.peripheral.setNotifyValue(true, for: found) } } 193 try wait(Self.setupTimeout, orFail: "subscription timed out") { pendingSubscriptions == 0 } 194 } 195 return 196 } 197 throw DiveComputerError.transport("no serial service on this device") 198 } 199 200 // MARK: DiveComputerTransport 201 202 func setTimeout(milliseconds: Int) { 203 condition.lock(); defer { condition.unlock() } 204 timeout = milliseconds 205 } 206 207 func read(maxLength: Int) throws -> Data { 208 condition.lock(); defer { condition.unlock() } 209 if packets.isEmpty, !notifies, let readCharacteristic { 210 // No notifications on this device: ask for the value each time. 211 onQueue { self.peripheral.readValue(for: readCharacteristic) } 212 } 213 try wait(timeout, orFail: "timeout") { !packets.isEmpty } 214 return packets.removeFirst() 215 } 216 217 func write(_ data: Data) throws { 218 condition.lock(); defer { condition.unlock() } 219 if let failure { throw DiveComputerError.transport(failure) } 220 guard let target = writeCharacteristic else { throw DiveComputerError.transport("link not open") } 221 if target.properties.contains(.writeWithoutResponse) { 222 onQueue { 223 self.outbox.append(data) 224 self.drainOutbox(to: target, force: false) 225 // CoreBluetooth sometimes never says it is ready again: do not wait for it for ever. 226 if !self.outbox.isEmpty { 227 self.central.queue.asyncAfter(deadline: .now() + 1) { self.drainOutbox(to: target, force: true) } 228 } 229 } 230 } else { 231 writePending = true 232 onQueue { self.peripheral.writeValue(data, for: target, type: .withResponse) } 233 try wait(Self.setupTimeout, orFail: "write not acknowledged") { !writePending } 234 } 235 } 236 237 func readCharacteristic(uuid: [UInt8]) throws -> Data { 238 condition.lock(); defer { condition.unlock() } 239 let wanted = CBUUID(data: Data(uuid)) 240 guard let target = service?.characteristics?.first(where: { $0.uuid == wanted }) else { 241 throw DiveComputerError.transport("characteristic \(wanted.uuidString) not found") 242 } 243 readValue = nil 244 awaitedRead = wanted 245 onQueue { self.peripheral.readValue(for: target) } 246 try wait(Self.setupTimeout, orFail: "characteristic read timed out") { readValue != nil } 247 return readValue ?? Data() 248 } 249 250 func close() { 251 condition.lock() 252 let already = closed 253 closed = true 254 condition.unlock() 255 guard !already else { return } 256 onQueue { self.central.manager.cancelPeripheralConnection(self.peripheral) } 257 } 258 259 /// On the central's queue. 260 private func drainOutbox(to target: CBCharacteristic, force: Bool) { 261 while !outbox.isEmpty, force || peripheral.canSendWriteWithoutResponse { 262 peripheral.writeValue(outbox.removeFirst(), for: target, type: .withoutResponse) 263 } 264 } 265 266 // MARK: Callbacks (central's queue) 267 268 func connectionChanged(_ peripheral: CBPeripheral, connected: Bool, error: Error?) { 269 guard peripheral.identifier == self.peripheral.identifier else { return } 270 condition.lock(); defer { condition.unlock() } 271 if connected { 272 self.connected = true 273 } else if !closed { 274 failure = error.map { "disconnected: \($0.localizedDescription)" } ?? "disconnected" 275 note(failure ?? "") 276 } 277 condition.broadcast() 278 } 279 280 func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 281 condition.lock(); defer { condition.unlock() } 282 if let error { failure = "service discovery: \(error.localizedDescription)" } 283 servicesDiscovered = true 284 condition.broadcast() 285 } 286 287 func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 288 condition.lock(); defer { condition.unlock() } 289 if let error { note("characteristics of \(service.uuid.uuidString): \(error.localizedDescription)") } 290 pendingDiscoveries = max(0, pendingDiscoveries - 1) 291 condition.broadcast() 292 } 293 294 func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { 295 condition.lock(); defer { condition.unlock() } 296 if let error { note("subscribing to \(characteristic.uuid.uuidString): \(error.localizedDescription)") } 297 pendingSubscriptions = max(0, pendingSubscriptions - 1) 298 condition.broadcast() 299 } 300 301 func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 302 condition.lock(); defer { condition.unlock() } 303 if let error { 304 note("value of \(characteristic.uuid.uuidString): \(error.localizedDescription)") 305 if characteristic.uuid == awaitedRead { failure = "characteristic read: \(error.localizedDescription)" } 306 } else if let value = characteristic.value { 307 if characteristic.uuid == awaitedRead { 308 awaitedRead = nil 309 readValue = value 310 } else { 311 packets.append(value) 312 } 313 } 314 condition.broadcast() 315 } 316 317 func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { 318 condition.lock(); defer { condition.unlock() } 319 if let error { failure = "write: \(error.localizedDescription)" } 320 writePending = false 321 condition.broadcast() 322 } 323 324 func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) { 325 condition.lock() 326 let target = writeCharacteristic 327 condition.unlock() 328 if let target { drainOutbox(to: target, force: false) } 329 } 330 } 331 332 /// Looks for dive computers nearby, and downloads the dives of the one picked. 333 @MainActor 334 @Observable 335 final class DiveComputerSession { 336 struct Computer: Identifiable, Equatable { 337 let id: UUID 338 let name: String 339 let model: DiveComputerModel 340 static func == (a: Computer, b: Computer) -> Bool { a.id == b.id } 341 } 342 343 enum Bluetooth: Equatable { case starting, ready, off, denied, unavailable } 344 345 enum Phase: Equatable { 346 case scanning 347 case connecting(Computer) 348 case downloading(Computer, Double) 349 case finished(Computer) 350 case failed(Computer, String) 351 } 352 353 private(set) var bluetooth = Bluetooth.starting 354 private(set) var computers = [Computer]() 355 private(set) var phase = Phase.scanning 356 private(set) var dives = [ImportedDiveBox]() 357 private(set) var troubleshooting = "" 358 /// True when the last download only asked for the dives newer than the previous one. 359 private(set) var onlyNewer = false 360 361 @ObservationIgnored private var central: BluetoothCentral? 362 @ObservationIgnored private var peripherals = [UUID: CBPeripheral]() 363 @ObservationIgnored private var cancelFlag = CancelFlag() 364 @ObservationIgnored private var newestFingerprint: Data? 365 /// False once the sheet is closed: nothing should keep scanning behind it. 366 @ObservationIgnored private var active = false 367 368 private var isBusy: Bool { 369 switch phase { 370 case .connecting, .downloading: return true 371 default: return false 372 } 373 } 374 375 /// Starts Bluetooth (the system asks for the permission the first time) and the search. 376 func start() { 377 active = true 378 if central != nil { 379 // The sheet is shown again: start over with whatever is around now. 380 if !isBusy { phase = .scanning } 381 if bluetooth == .ready, !isBusy { 382 computers = [] 383 peripherals = [:] 384 central?.manager.scanForPeripherals(withServices: nil) 385 } 386 return 387 } 388 if LaunchOptions.flag("-fakeComputers") { 389 // Screenshots: the simulator has no Bluetooth. 390 bluetooth = .ready 391 computers = ["Petrel 3", "Perdix 2"].compactMap { name in 392 DiveComputerCatalog.match(bluetoothName: name).map { Computer(id: UUID(), name: name, model: $0) } 393 } 394 return 395 } 396 let central = BluetoothCentral() 397 central.onState = { [weak self] state in 398 Task { @MainActor in self?.stateChanged(state) } 399 } 400 central.onDiscover = { [weak self] peripheral, name, _ in 401 // Matching goes through libdivecomputer's whole list: done here, off the main thread. 402 guard let model = DiveComputerCatalog.match(bluetoothName: name) else { return } 403 Task { @MainActor in self?.discovered(peripheral, name: name, model: model) } 404 } 405 self.central = central 406 } 407 408 private func stateChanged(_ state: CBManagerState) { 409 switch state { 410 case .poweredOn: 411 bluetooth = .ready 412 if active, !isBusy { central?.manager.scanForPeripherals(withServices: nil) } 413 case .poweredOff: bluetooth = .off 414 case .unauthorized: bluetooth = .denied 415 case .unsupported: bluetooth = .unavailable 416 default: bluetooth = .starting 417 } 418 } 419 420 private func discovered(_ peripheral: CBPeripheral, name: String, model: DiveComputerModel) { 421 guard peripherals[peripheral.identifier] == nil else { return } 422 peripherals[peripheral.identifier] = peripheral 423 computers.append(Computer(id: peripheral.identifier, name: name, model: model)) 424 } 425 426 private static func fingerprintKey(_ computer: Computer) -> String { "diveComputerFingerprint.\(computer.id.uuidString)" } 427 428 func hasEarlierDownload(_ computer: Computer) -> Bool { 429 UserDefaults.standard.data(forKey: Self.fingerprintKey(computer)) != nil 430 } 431 432 /// Remembers where the last download stopped, once its dives are in the logbook. 433 func rememberDownload() { 434 guard case .finished(let computer) = phase, let newestFingerprint else { return } 435 UserDefaults.standard.set(newestFingerprint, forKey: Self.fingerprintKey(computer)) 436 } 437 438 /// Downloads from the computer: only the dives newer than the previous download, unless `everything`. 439 func download(from computer: Computer, everything: Bool = false) { 440 let fingerprint = everything ? nil : UserDefaults.standard.data(forKey: Self.fingerprintKey(computer)) 441 onlyNewer = fingerprint != nil 442 dives = [] 443 troubleshooting = "" 444 newestFingerprint = nil 445 phase = .connecting(computer) 446 guard let central, let peripheral = peripherals[computer.id] else { 447 phase = .failed(computer, String(localized: "This computer is no longer in range.")) 448 return 449 } 450 central.manager.stopScan() 451 let flag = CancelFlag() 452 cancelFlag = flag 453 let link = BluetoothLink(central: central, peripheral: peripheral, name: computer.name) 454 UIApplicationIdleTimer.disable(true) 455 456 let thread = Thread { [weak self] in 457 var lines = [String]() 458 var outcome: Result<DiveComputerDownloadResult, Error> 459 var lastShown = -1.0 460 let download = DiveComputerDownload(model: computer.model, transport: link, progress: { fraction in 461 guard fraction - lastShown >= 0.01 || fraction >= 1 else { return } 462 lastShown = fraction 463 Task { @MainActor in self?.progressed(computer, fraction, flag) } 464 }, isCancelled: { flag.isSet }) 465 do { 466 try link.open() 467 Task { @MainActor in self?.progressed(computer, 0, flag) } 468 outcome = .success(try download.run(fingerprint: fingerprint)) 469 } catch { 470 outcome = .failure(error) 471 } 472 link.close() 473 central.attach(nil) 474 lines = link.log + download.logLines 475 let report = lines.joined(separator: "\n") 476 let result = outcome 477 Task { @MainActor in self?.finished(computer, result, log: report, flag) } 478 } 479 thread.stackSize = 2 << 20 480 thread.name = "dive computer download" 481 thread.start() 482 } 483 484 private func progressed(_ computer: Computer, _ fraction: Double, _ flag: CancelFlag) { 485 guard flag === cancelFlag, !flag.isSet else { return } 486 phase = .downloading(computer, fraction) 487 } 488 489 private func finished(_ computer: Computer, _ outcome: Result<DiveComputerDownloadResult, Error>, log: String, _ flag: CancelFlag) { 490 guard flag === cancelFlag else { return } 491 UIApplicationIdleTimer.disable(false) 492 troubleshooting = "\(Brand.name) \(Brand.version), libdivecomputer \(LibDiveComputer.version)\n\(computer.name) (\(computer.model.name))\n" + log 493 if flag.isSet { 494 phase = .scanning 495 if active, bluetooth == .ready { central?.manager.scanForPeripherals(withServices: nil) } 496 return 497 } 498 switch outcome { 499 case .success(let result): 500 dives = result.dives.map(ImportedDiveBox.init) 501 newestFingerprint = result.newestFingerprint 502 if result.unparsed > 0 { troubleshooting += "\n\(result.unparsed) dive(s) could not be parsed" } 503 phase = .finished(computer) 504 case .failure(let error): 505 troubleshooting += "\n\(error)" 506 phase = .failed(computer, Self.explain(error)) 507 } 508 } 509 510 private static func explain(_ error: Error) -> String { 511 guard let error = error as? DiveComputerError else { return error.localizedDescription } 512 switch error { 513 case .transport(let what) where what.hasPrefix("connection timed out"): 514 return String(localized: "The computer did not answer. Check that it is still in Bluetooth mode, close to the iPhone.") 515 case .transport(let what) where what.hasPrefix("disconnected"): 516 return String(localized: "The connection to the computer was lost.") 517 case .transport: 518 return String(localized: "Couldn't talk to this computer over Bluetooth.") 519 case .library(_, let status) where status == -7: 520 return String(localized: "The computer stopped answering. Check that it is still in Bluetooth mode, close to the iPhone.") 521 case .library, .unknownModel: 522 return String(localized: "The download failed.") 523 case .cancelled: 524 return String(localized: "Download cancelled.") 525 } 526 } 527 528 func cancel() { 529 cancelFlag.set() 530 } 531 532 /// Back to the list of computers. 533 func reset() { 534 phase = .scanning 535 if bluetooth == .ready { central?.manager.scanForPeripherals(withServices: nil) } 536 } 537 538 func stop() { 539 active = false 540 cancelFlag.set() 541 central?.manager.stopScan() 542 UIApplicationIdleTimer.disable(false) 543 } 544 } 545 546 /// Lets the download thread see that the user gave up. 547 final class CancelFlag: @unchecked Sendable { 548 private let lock = NSLock() 549 private var value = false 550 var isSet: Bool { 551 lock.lock(); defer { lock.unlock() } 552 return value 553 } 554 func set() { 555 lock.lock(); defer { lock.unlock() } 556 value = true 557 } 558 }