subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

commit 90344a4c4a2f70b0eabf6285b5270407505f4797
parent e0c4a9aaa0ece1003d3f723033553a0958b4433b
Author: Jean Schurger <jean@schurger.org>
Date:   Sat, 14 Nov 2026 09:34:59 -0500

Download dives from a dive computer over Bluetooth LE

The app scans for computers that libdivecomputer recognises by name, downloads
their dives over a CoreBluetooth transport (service and characteristic
selection after Subsurface's qt-ble.cpp) and hands them to the import preview.
The fingerprint of the newest dive is kept once the import is done, so the
next download only fetches newer dives.

The download path is tested against a fake Shearwater computer serving real
logs; the Bluetooth link itself still has to be tried on a real computer, and
a failed download offers its technical log for sharing.

Also: Bluetooth usage description (en, fr), French strings, licence note in
Settings, README, version 0.3.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MApp/InfoPlist.xcstrings | 7+++++++
MApp/Localizable.xcstrings | 320+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Model/AppModel.swift | 8++++++++
AApp/Model/DiveComputerLink.swift | 558+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AApp/Views/DiveComputerView.swift | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Views/DiveListView.swift | 3+++
MApp/Views/ImportView.swift | 9+++++++++
MApp/Views/SettingsView.swift | 8++++++++
MPackages/DiveKit/Package.swift | 2+-
MPackages/DiveKit/Sources/DiveComputerKit/Download.swift | 12+++++++-----
MPackages/DiveKit/Tests/DiveComputerKitTests/DiveComputerKitTests.swift | 48++++++++++++++++++++++++++++++++++++++++++++++++
APackages/DiveKit/Tests/DiveComputerKitTests/FakePetrel.swift | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MREADME.md | 21+++++++++++++++++----
Mproject.yml | 5++++-
14 files changed, 1379 insertions(+), 11 deletions(-)

diff --git a/App/InfoPlist.xcstrings b/App/InfoPlist.xcstrings @@ -1,6 +1,13 @@ { "sourceLanguage" : "en", "strings" : { + "NSBluetoothAlwaysUsageDescription" : { + "extractionState" : "manual", + "localizations" : { + "en" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse uses Bluetooth to download the dives stored in your dive computer." } }, + "fr" : { "stringUnit" : { "state" : "translated", "value" : "Sub Rascasse utilise Bluetooth pour télécharger les plongées gardées dans votre ordinateur de plongée." } } + } + }, "NSPhotoLibraryUsageDescription" : { "extractionState" : "manual", "localizations" : { diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings @@ -1,6 +1,16 @@ { "sourceLanguage": "en", "strings": { + "%@ has no dives in memory.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ n'a aucune plongée en mémoire." + } + } + } + }, "%@ into the dive": { "localizations": { "fr": { @@ -41,6 +51,16 @@ } } }, + "%@ · new dives only": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ · nouvelles plongées seulement" + } + } + } + }, "%@, %lld underwater (marked with a wave)": { "localizations": { "fr": { @@ -401,6 +421,16 @@ } } }, + "Allow %@ to use Bluetooth in Settings to reach your dive computer.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autorisez %@ à utiliser Bluetooth dans Réglages pour joindre votre ordinateur de plongée." + } + } + } + }, "Allow photo access": { "localizations": { "fr": { @@ -471,6 +501,26 @@ } } }, + "Bluetooth is off": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bluetooth est éteint" + } + } + } + }, + "Bluetooth not allowed": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Bluetooth non autorisé" + } + } + } + }, "Buddies": { "localizations": { "fr": { @@ -601,6 +651,16 @@ } } }, + "Connecting…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Connexion…" + } + } + } + }, "Cormorant Wreck": { "localizations": { "fr": { @@ -661,6 +721,16 @@ } } }, + "Couldn't talk to this computer over Bluetooth.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible de communiquer avec cet ordinateur par Bluetooth." + } + } + } + }, "Country": { "localizations": { "fr": { @@ -931,6 +1001,16 @@ } } }, + "Dive computer": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ordinateur de plongée" + } + } + } + }, "Dive not found": { "localizations": { "fr": { @@ -1001,6 +1081,16 @@ } } }, + "Done": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Terminé" + } + } + } + }, "Down the wall to the barrel sponges.": { "localizations": { "fr": { @@ -1011,6 +1101,56 @@ } } }, + "Download all dives": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Télécharger toutes les plongées" + } + } + } + }, + "Download cancelled.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Téléchargement annulé." + } + } + } + }, + "Download complete": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Téléchargement terminé" + } + } + } + }, + "Download failed": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Échec du téléchargement" + } + } + } + }, + "Download from a dive computer…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Télécharger depuis un ordinateur de plongée…" + } + } + } + }, "Downloading the logbook…": { "localizations": { "fr": { @@ -1021,6 +1161,16 @@ } } }, + "Downloading… %lld %%": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Téléchargement… %lld %%" + } + } + } + }, "Drag your finger across the profile to read the values.": { "localizations": { "fr": { @@ -1151,6 +1301,16 @@ } } }, + "Free software under the GPL 2.0 licence. Dive computers are read with libdivecomputer (LGPL 2.1). Source code: git.schurger.org/subrascasse": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Logiciel libre sous licence GPL 2.0. Les ordinateurs de plongée sont lus avec libdivecomputer (LGPL 2.1). Code source : git.schurger.org/subrascasse" + } + } + } + }, "Fringing reef, shore entry": { "localizations": { "fr": { @@ -1281,6 +1441,16 @@ } } }, + "Keep the computer close to the iPhone and leave this screen open.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Gardez l'ordinateur près de l'iPhone et laissez cet écran ouvert." + } + } + } + }, "Kelp forest, a wolffish in a crevice.": { "localizations": { "fr": { @@ -1391,6 +1561,16 @@ } } }, + "Looking for dive computers…": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Recherche d'ordinateurs de plongée…" + } + } + } + }, "Manually entered dive": { "localizations": { "fr": { @@ -1511,6 +1691,16 @@ } } }, + "Nearby": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "À proximité" + } + } + } + }, "Never": { "localizations": { "fr": { @@ -1571,6 +1761,16 @@ } } }, + "No Bluetooth on this device": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Pas de Bluetooth sur cet appareil" + } + } + } + }, "No dives": { "localizations": { "fr": { @@ -1601,6 +1801,16 @@ } } }, + "No new dives": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune nouvelle plongée" + } + } + } + }, "No photos around this dive in this iPhone's photo library.": { "localizations": { "fr": { @@ -1731,6 +1941,16 @@ } } }, + "Nothing new on %@ since the last download.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Rien de nouveau sur %@ depuis le dernier téléchargement." + } + } + } + }, "Number of dives per depth range": { "localizations": { "fr": { @@ -1801,6 +2021,16 @@ } } }, + "Other computer": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autre ordinateur" + } + } + } + }, "Password": { "localizations": { "fr": { @@ -1881,6 +2111,16 @@ } } }, + "Put the computer in Bluetooth mode (on a Shearwater: Menu, then Bluetooth), keep it close to the iPhone, then tap its name. The dives are read with libdivecomputer; support has only been checked on a few models so far.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Mettez l'ordinateur en mode Bluetooth (sur un Shearwater : Menu, puis Bluetooth), gardez-le près de l'iPhone, puis touchez son nom. Les plongées sont lues avec libdivecomputer ; seuls quelques modèles ont été vérifiés pour l'instant." + } + } + } + }, "Rating": { "localizations": { "fr": { @@ -2001,6 +2241,16 @@ } } }, + "Share the technical log": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Partager le journal technique" + } + } + } + }, "Sharp thermocline at 9 m.": { "localizations": { "fr": { @@ -2421,6 +2671,36 @@ } } }, + "The computer did not answer. Check that it is still in Bluetooth mode, close to the iPhone.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "L'ordinateur n'a pas répondu. Vérifiez qu'il est toujours en mode Bluetooth, près de l'iPhone." + } + } + } + }, + "The computer stopped answering. Check that it is still in Bluetooth mode, close to the iPhone.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "L'ordinateur a cessé de répondre. Vérifiez qu'il est toujours en mode Bluetooth, près de l'iPhone." + } + } + } + }, + "The connection to the computer was lost.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "La connexion avec l'ordinateur a été perdue." + } + } + } + }, "The copy of the logbook on this iPhone will be erased. Nothing is deleted in the cloud.": { "localizations": { "fr": { @@ -2451,6 +2731,16 @@ } } }, + "The download failed.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Le téléchargement a échoué." + } + } + } + }, "The location can be added later in Subsurface.": { "localizations": { "fr": { @@ -2481,6 +2771,16 @@ } } }, + "This computer is no longer in range.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Cet ordinateur n'est plus à portée." + } + } + } + }, "This email is not valid.": { "localizations": { "fr": { @@ -2571,6 +2871,16 @@ } } }, + "Try again": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Réessayer" + } + } + } + }, "Trying out the new regulator.": { "localizations": { "fr": { @@ -2581,6 +2891,16 @@ } } }, + "Turn Bluetooth on in Control Center to reach your dive computer.": { + "localizations": { + "fr": { + "stringUnit": { + "state": "translated", + "value": "Activez Bluetooth dans le centre de contrôle pour joindre votre ordinateur de plongée." + } + } + } + }, "Turtle Wall": { "localizations": { "fr": { diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -298,6 +298,14 @@ final class AppModel { } } + /// Same, for dives that are already decoded (downloaded from a dive computer), most recent first. + func importCandidates(for dives: [ImportedDive]) -> [ImportCandidate] { + let known = logbook.dives.map(\.when) + return dives.sorted { $0.when > $1.when }.map { dive in + ImportCandidate(dive: dive, alreadyInLog: known.contains { abs($0 - dive.when) < 120 }) + } + } + /// Adds the dives to the logbook, oldest first, creating any missing sites. /// Returns the number of dives added. func importDives(_ dives: [ImportedDive]) async throws -> Int { diff --git a/App/Model/DiveComputerLink.swift b/App/Model/DiveComputerLink.swift @@ -0,0 +1,558 @@ +// SPDX-License-Identifier: GPL-2.0-only +import CoreBluetooth +import DiveComputerKit +import Foundation +import Observation + +/// GATT services that dive computers use as a serial port, in order of preference, and those to stay away from. +/// Same lists as Subsurface (`core/qt-ble.cpp`). +private enum KnownServices { + static let serial: [CBUUID] = [ + "0000fefb-0000-1000-8000-00805f9b34fb", // Heinrichs-Weikamp (Telit/Stollmann) + "2456e1b9-26e2-8f83-e744-f34f01e9d701", // Heinrichs-Weikamp (U-Blox) + "544e326b-5b72-c6b0-1c46-41c1bc448118", // Mares BlueLink Pro + "98ae7120-e62e-11e3-badd-0002a5d5c51b", // Suunto (EON Steel/Core, G5) + "cb3c4555-d670-4670-bc20-b61dbc851e9a", // Pelagic (i770R, i200C, Pro Plus X, Geo 4.0) + "ca7b0001-f785-4c38-b599-c7c5fbadb034", // Pelagic (i330R, DSX) + "fdcdeaaa-295d-470e-bf15-04217b7aa0a0", // ScubaPro (G2, G3) + "fe25c237-0ece-443c-b0aa-e02033e7029d", // Shearwater (Petrel/Perdix/Teric/Peregrine/Tern) + "1aa44039-1667-4b29-87cc-dfecaaf31d97", // Shearwater (Perdix 3) + "0000fcef-0000-1000-8000-00805f9b34fb", // Divesoft + "6e400001-b5a3-f393-e0a9-e50e24dc10b8", // Cressi + "6e400001-b5a3-f393-e0a9-e50e24dcca9e", // Nordic Semi UART + "00000001-8c3b-4f2c-a59e-8c08224f3253", // Halcyon Symbios + "84968ffe-d26d-478a-b953-5010bcf58bca", // Seac + ].map { CBUUID(string: $0) } + + static let firmwareUpgrade: Set<CBUUID> = Set([ + "00001530-1212-efde-1523-785feabcd123", // Nordic + "9e5d1e47-5c13-43a0-8635-82ad38a1386f", // Broadcom #1 + "a86abc2d-d44c-442e-99f7-80059a873e36", // Broadcom #2 + ].map { CBUUID(string: $0) }) + + /// Characteristics never to read from or write to. + static let avoid: Set<CBUUID> = Set([ + "49535343-6daa-4d02-abf6-19569aca69fe", "49535343-aca3-481c-91ec-d85e28a60318", + "49535343-026e-3a9b-954c-97daef17e26e", "49535343-4c8a-39b3-2f49-511cff073b7e", // McLean Extreme + ].map { CBUUID(string: $0) }) +} + +/// The app's single Bluetooth central. Its callbacks arrive on `queue`. +final class BluetoothCentral: NSObject, CBCentralManagerDelegate { + let queue = DispatchQueue(label: "org.schurger.subrascasse.bluetooth") + private(set) var manager: CBCentralManager! + var onState: ((CBManagerState) -> Void)? + var onDiscover: ((CBPeripheral, String, Int) -> Void)? + private let lock = NSLock() + private weak var link: BluetoothLink? + + override init() { + super.init() + manager = CBCentralManager(delegate: self, queue: queue) + } + + func attach(_ link: BluetoothLink?) { + lock.lock(); defer { lock.unlock() } + self.link = link + } + + private var current: BluetoothLink? { + lock.lock(); defer { lock.unlock() } + return link + } + + func centralManagerDidUpdateState(_ central: CBCentralManager) { onState?(central.state) } + + func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, + advertisementData: [String: Any], rssi RSSI: NSNumber) { + let name = (advertisementData[CBAdvertisementDataLocalNameKey] as? String) ?? peripheral.name ?? "" + guard !name.isEmpty else { return } + onDiscover?(peripheral, name, RSSI.intValue) + } + + func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + current?.connectionChanged(peripheral, connected: true, error: nil) + } + + func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { + current?.connectionChanged(peripheral, connected: false, error: error) + } + + func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { + current?.connectionChanged(peripheral, connected: false, error: error) + } +} + +/// A Bluetooth LE link to a dive computer, with the blocking calls libdivecomputer expects. Used from the download +/// thread; CoreBluetooth calls go to the central's queue, and its callbacks wake the download thread up. +final class BluetoothLink: NSObject, DiveComputerTransport, CBPeripheralDelegate { + private static let setupTimeout = 12_000 + + private let central: BluetoothCentral + private let peripheral: CBPeripheral + let deviceName: String + + // Everything below is guarded by `condition`. + private let condition = NSCondition() + private var timeout = setupTimeout + private var connected = false + private var failure: String? + private var closed = false + private var servicesDiscovered = false + private var pendingDiscoveries = 0 + private var pendingSubscriptions = 0 + private var service: CBService? + private var writeCharacteristic: CBCharacteristic? + private var readCharacteristic: CBCharacteristic? + private var notifies = false + private var packets = [Data]() + private var awaitedRead: CBUUID? + private var readValue: Data? + private var writePending = false + private var trace = [String]() + + // Only touched on the central's queue. + private var outbox = [Data]() + + init(central: BluetoothCentral, peripheral: CBPeripheral, name: String) { + self.central = central + self.peripheral = peripheral + self.deviceName = name + } + + /// What happened on the link, for troubleshooting. + var log: [String] { + condition.lock(); defer { condition.unlock() } + return trace + } + + /// Must be called with `condition` locked. + private func note(_ line: String) { + if trace.count < 500 { trace.append(line) } + } + + /// Waits (with `condition` locked) until `done` holds; throws on failure of the link or after the delay. + private func wait(_ milliseconds: Int, orFail what: String, until done: () -> Bool) throws { + let deadline = milliseconds < 0 ? Date.distantFuture : Date().addingTimeInterval(Double(milliseconds) / 1000) + while !done() { + if let failure { throw DiveComputerError.transport(failure) } + if !condition.wait(until: deadline), !done() { + if let failure { throw DiveComputerError.transport(failure) } + throw DiveComputerError.transport(what) + } + } + } + + private func onQueue(_ work: @escaping () -> Void) { central.queue.async(execute: work) } + + // MARK: Opening + + /// Connects, finds the serial service and subscribes to its notifications. + func open() throws { + condition.lock(); defer { condition.unlock() } + central.attach(self) + peripheral.delegate = self + onQueue { self.central.manager.connect(self.peripheral) } + try wait(Self.setupTimeout, orFail: "connection timed out") { connected } + note("connected to \(deviceName)") + + onQueue { self.peripheral.discoverServices(nil) } + try wait(Self.setupTimeout, orFail: "service discovery timed out") { servicesDiscovered } + let all = peripheral.services ?? [] + for found in all { note("service \(found.uuid.uuidString)") } + var candidates = [CBService]() + if let known = KnownServices.serial.lazy.compactMap({ uuid in all.first { $0.uuid == uuid } }).first { + candidates = [known] + } else { + // Standard (16-bit) services and firmware upgrade services are never the serial port. + candidates = all.filter { $0.uuid.data.count > 2 && !KnownServices.firmwareUpgrade.contains($0.uuid) } + } + guard !candidates.isEmpty else { throw DiveComputerError.transport("no usable Bluetooth service") } + + pendingDiscoveries = candidates.count + onQueue { for candidate in candidates { self.peripheral.discoverCharacteristics(nil, for: candidate) } } + try wait(Self.setupTimeout, orFail: "characteristic discovery timed out") { pendingDiscoveries == 0 } + + for candidate in candidates { + let characteristics = (candidate.characteristics ?? []).filter { !KnownServices.avoid.contains($0.uuid) } + for found in characteristics { note(" characteristic \(found.uuid.uuidString) properties 0x\(String(found.properties.rawValue, radix: 16))") } + let notifying = characteristics.filter { !$0.properties.isDisjoint(with: [.notify, .indicate]) } + let readable = characteristics.first { $0.properties.contains(.read) } + // Writing without a response is what serial-port services expect when they offer both. + let writable = characteristics.first { $0.properties.contains(.writeWithoutResponse) } + ?? characteristics.first { $0.properties.contains(.write) } + guard let writable, !notifying.isEmpty || readable != nil else { continue } + service = candidate + writeCharacteristic = writable + readCharacteristic = readable + notifies = !notifying.isEmpty + note("using service \(candidate.uuid.uuidString), writing to \(writable.uuid.uuidString)") + if notifies { + pendingSubscriptions = notifying.count + onQueue { for found in notifying { self.peripheral.setNotifyValue(true, for: found) } } + try wait(Self.setupTimeout, orFail: "subscription timed out") { pendingSubscriptions == 0 } + } + return + } + throw DiveComputerError.transport("no serial service on this device") + } + + // MARK: DiveComputerTransport + + func setTimeout(milliseconds: Int) { + condition.lock(); defer { condition.unlock() } + timeout = milliseconds + } + + func read(maxLength: Int) throws -> Data { + condition.lock(); defer { condition.unlock() } + if packets.isEmpty, !notifies, let readCharacteristic { + // No notifications on this device: ask for the value each time. + onQueue { self.peripheral.readValue(for: readCharacteristic) } + } + try wait(timeout, orFail: "timeout") { !packets.isEmpty } + return packets.removeFirst() + } + + func write(_ data: Data) throws { + condition.lock(); defer { condition.unlock() } + if let failure { throw DiveComputerError.transport(failure) } + guard let target = writeCharacteristic else { throw DiveComputerError.transport("link not open") } + if target.properties.contains(.writeWithoutResponse) { + onQueue { + self.outbox.append(data) + self.drainOutbox(to: target, force: false) + // CoreBluetooth sometimes never says it is ready again: do not wait for it for ever. + if !self.outbox.isEmpty { + self.central.queue.asyncAfter(deadline: .now() + 1) { self.drainOutbox(to: target, force: true) } + } + } + } else { + writePending = true + onQueue { self.peripheral.writeValue(data, for: target, type: .withResponse) } + try wait(Self.setupTimeout, orFail: "write not acknowledged") { !writePending } + } + } + + func readCharacteristic(uuid: [UInt8]) throws -> Data { + condition.lock(); defer { condition.unlock() } + let wanted = CBUUID(data: Data(uuid)) + guard let target = service?.characteristics?.first(where: { $0.uuid == wanted }) else { + throw DiveComputerError.transport("characteristic \(wanted.uuidString) not found") + } + readValue = nil + awaitedRead = wanted + onQueue { self.peripheral.readValue(for: target) } + try wait(Self.setupTimeout, orFail: "characteristic read timed out") { readValue != nil } + return readValue ?? Data() + } + + func close() { + condition.lock() + let already = closed + closed = true + condition.unlock() + guard !already else { return } + onQueue { self.central.manager.cancelPeripheralConnection(self.peripheral) } + } + + /// On the central's queue. + private func drainOutbox(to target: CBCharacteristic, force: Bool) { + while !outbox.isEmpty, force || peripheral.canSendWriteWithoutResponse { + peripheral.writeValue(outbox.removeFirst(), for: target, type: .withoutResponse) + } + } + + // MARK: Callbacks (central's queue) + + func connectionChanged(_ peripheral: CBPeripheral, connected: Bool, error: Error?) { + guard peripheral.identifier == self.peripheral.identifier else { return } + condition.lock(); defer { condition.unlock() } + if connected { + self.connected = true + } else if !closed { + failure = error.map { "disconnected: \($0.localizedDescription)" } ?? "disconnected" + note(failure ?? "") + } + condition.broadcast() + } + + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + condition.lock(); defer { condition.unlock() } + if let error { failure = "service discovery: \(error.localizedDescription)" } + servicesDiscovered = true + condition.broadcast() + } + + func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { + condition.lock(); defer { condition.unlock() } + if let error { note("characteristics of \(service.uuid.uuidString): \(error.localizedDescription)") } + pendingDiscoveries = max(0, pendingDiscoveries - 1) + condition.broadcast() + } + + func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { + condition.lock(); defer { condition.unlock() } + if let error { note("subscribing to \(characteristic.uuid.uuidString): \(error.localizedDescription)") } + pendingSubscriptions = max(0, pendingSubscriptions - 1) + condition.broadcast() + } + + func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { + condition.lock(); defer { condition.unlock() } + if let error { + note("value of \(characteristic.uuid.uuidString): \(error.localizedDescription)") + if characteristic.uuid == awaitedRead { failure = "characteristic read: \(error.localizedDescription)" } + } else if let value = characteristic.value { + if characteristic.uuid == awaitedRead { + awaitedRead = nil + readValue = value + } else { + packets.append(value) + } + } + condition.broadcast() + } + + func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { + condition.lock(); defer { condition.unlock() } + if let error { failure = "write: \(error.localizedDescription)" } + writePending = false + condition.broadcast() + } + + func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) { + condition.lock() + let target = writeCharacteristic + condition.unlock() + if let target { drainOutbox(to: target, force: false) } + } +} + +/// Looks for dive computers nearby, and downloads the dives of the one picked. +@MainActor +@Observable +final class DiveComputerSession { + struct Computer: Identifiable, Equatable { + let id: UUID + let name: String + let model: DiveComputerModel + static func == (a: Computer, b: Computer) -> Bool { a.id == b.id } + } + + enum Bluetooth: Equatable { case starting, ready, off, denied, unavailable } + + enum Phase: Equatable { + case scanning + case connecting(Computer) + case downloading(Computer, Double) + case finished(Computer) + case failed(Computer, String) + } + + private(set) var bluetooth = Bluetooth.starting + private(set) var computers = [Computer]() + private(set) var phase = Phase.scanning + private(set) var dives = [ImportedDiveBox]() + private(set) var troubleshooting = "" + /// True when the last download only asked for the dives newer than the previous one. + private(set) var onlyNewer = false + + @ObservationIgnored private var central: BluetoothCentral? + @ObservationIgnored private var peripherals = [UUID: CBPeripheral]() + @ObservationIgnored private var cancelFlag = CancelFlag() + @ObservationIgnored private var newestFingerprint: Data? + /// False once the sheet is closed: nothing should keep scanning behind it. + @ObservationIgnored private var active = false + + private var isBusy: Bool { + switch phase { + case .connecting, .downloading: return true + default: return false + } + } + + /// Starts Bluetooth (the system asks for the permission the first time) and the search. + func start() { + active = true + if central != nil { + // The sheet is shown again: start over with whatever is around now. + if !isBusy { phase = .scanning } + if bluetooth == .ready, !isBusy { + computers = [] + peripherals = [:] + central?.manager.scanForPeripherals(withServices: nil) + } + return + } + if LaunchOptions.flag("-fakeComputers") { + // Screenshots: the simulator has no Bluetooth. + bluetooth = .ready + computers = ["Petrel 3", "Perdix 2"].compactMap { name in + DiveComputerCatalog.match(bluetoothName: name).map { Computer(id: UUID(), name: name, model: $0) } + } + return + } + let central = BluetoothCentral() + central.onState = { [weak self] state in + Task { @MainActor in self?.stateChanged(state) } + } + central.onDiscover = { [weak self] peripheral, name, _ in + // Matching goes through libdivecomputer's whole list: done here, off the main thread. + guard let model = DiveComputerCatalog.match(bluetoothName: name) else { return } + Task { @MainActor in self?.discovered(peripheral, name: name, model: model) } + } + self.central = central + } + + private func stateChanged(_ state: CBManagerState) { + switch state { + case .poweredOn: + bluetooth = .ready + if active, !isBusy { central?.manager.scanForPeripherals(withServices: nil) } + case .poweredOff: bluetooth = .off + case .unauthorized: bluetooth = .denied + case .unsupported: bluetooth = .unavailable + default: bluetooth = .starting + } + } + + private func discovered(_ peripheral: CBPeripheral, name: String, model: DiveComputerModel) { + guard peripherals[peripheral.identifier] == nil else { return } + peripherals[peripheral.identifier] = peripheral + computers.append(Computer(id: peripheral.identifier, name: name, model: model)) + } + + private static func fingerprintKey(_ computer: Computer) -> String { "diveComputerFingerprint.\(computer.id.uuidString)" } + + func hasEarlierDownload(_ computer: Computer) -> Bool { + UserDefaults.standard.data(forKey: Self.fingerprintKey(computer)) != nil + } + + /// Remembers where the last download stopped, once its dives are in the logbook. + func rememberDownload() { + guard case .finished(let computer) = phase, let newestFingerprint else { return } + UserDefaults.standard.set(newestFingerprint, forKey: Self.fingerprintKey(computer)) + } + + /// Downloads from the computer: only the dives newer than the previous download, unless `everything`. + func download(from computer: Computer, everything: Bool = false) { + let fingerprint = everything ? nil : UserDefaults.standard.data(forKey: Self.fingerprintKey(computer)) + onlyNewer = fingerprint != nil + dives = [] + troubleshooting = "" + newestFingerprint = nil + phase = .connecting(computer) + guard let central, let peripheral = peripherals[computer.id] else { + phase = .failed(computer, String(localized: "This computer is no longer in range.")) + return + } + central.manager.stopScan() + let flag = CancelFlag() + cancelFlag = flag + let link = BluetoothLink(central: central, peripheral: peripheral, name: computer.name) + UIApplicationIdleTimer.disable(true) + + let thread = Thread { [weak self] in + var lines = [String]() + var outcome: Result<DiveComputerDownloadResult, Error> + var lastShown = -1.0 + let download = DiveComputerDownload(model: computer.model, transport: link, progress: { fraction in + guard fraction - lastShown >= 0.01 || fraction >= 1 else { return } + lastShown = fraction + Task { @MainActor in self?.progressed(computer, fraction, flag) } + }, isCancelled: { flag.isSet }) + do { + try link.open() + Task { @MainActor in self?.progressed(computer, 0, flag) } + outcome = .success(try download.run(fingerprint: fingerprint)) + } catch { + outcome = .failure(error) + } + link.close() + central.attach(nil) + lines = link.log + download.logLines + let report = lines.joined(separator: "\n") + let result = outcome + Task { @MainActor in self?.finished(computer, result, log: report, flag) } + } + thread.stackSize = 2 << 20 + thread.name = "dive computer download" + thread.start() + } + + private func progressed(_ computer: Computer, _ fraction: Double, _ flag: CancelFlag) { + guard flag === cancelFlag, !flag.isSet else { return } + phase = .downloading(computer, fraction) + } + + private func finished(_ computer: Computer, _ outcome: Result<DiveComputerDownloadResult, Error>, log: String, _ flag: CancelFlag) { + guard flag === cancelFlag else { return } + UIApplicationIdleTimer.disable(false) + troubleshooting = "\(Brand.name) \(Brand.version), libdivecomputer \(LibDiveComputer.version)\n\(computer.name) (\(computer.model.name))\n" + log + if flag.isSet { + phase = .scanning + if active, bluetooth == .ready { central?.manager.scanForPeripherals(withServices: nil) } + return + } + switch outcome { + case .success(let result): + dives = result.dives.map(ImportedDiveBox.init) + newestFingerprint = result.newestFingerprint + if result.unparsed > 0 { troubleshooting += "\n\(result.unparsed) dive(s) could not be parsed" } + phase = .finished(computer) + case .failure(let error): + troubleshooting += "\n\(error)" + phase = .failed(computer, Self.explain(error)) + } + } + + private static func explain(_ error: Error) -> String { + guard let error = error as? DiveComputerError else { return error.localizedDescription } + switch error { + case .transport(let what) where what.hasPrefix("connection timed out"): + return String(localized: "The computer did not answer. Check that it is still in Bluetooth mode, close to the iPhone.") + case .transport(let what) where what.hasPrefix("disconnected"): + return String(localized: "The connection to the computer was lost.") + case .transport: + return String(localized: "Couldn't talk to this computer over Bluetooth.") + case .library(_, let status) where status == -7: + return String(localized: "The computer stopped answering. Check that it is still in Bluetooth mode, close to the iPhone.") + case .library, .unknownModel: + return String(localized: "The download failed.") + case .cancelled: + return String(localized: "Download cancelled.") + } + } + + func cancel() { + cancelFlag.set() + } + + /// Back to the list of computers. + func reset() { + phase = .scanning + if bluetooth == .ready { central?.manager.scanForPeripherals(withServices: nil) } + } + + func stop() { + active = false + cancelFlag.set() + central?.manager.stopScan() + UIApplicationIdleTimer.disable(false) + } +} + +/// Lets the download thread see that the user gave up. +final class CancelFlag: @unchecked Sendable { + private let lock = NSLock() + private var value = false + var isSet: Bool { + lock.lock(); defer { lock.unlock() } + return value + } + func set() { + lock.lock(); defer { lock.unlock() } + value = true + } +} diff --git a/App/Views/DiveComputerView.swift b/App/Views/DiveComputerView.swift @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-2.0-only +import DiveComputerKit +import SubsurfaceLog +import SwiftUI +import UIKit + +/// A downloaded dive, as the session hands it over. +struct ImportedDiveBox: Identifiable { + let dive: ImportedDive + var id: String { dive.id } +} + +/// Keeps the screen on while a download runs (it stops if the iPhone locks). +enum UIApplicationIdleTimer { + @MainActor static func disable(_ disabled: Bool) { UIApplication.shared.isIdleTimerDisabled = disabled } +} + +/// Downloads dives from a dive computer over Bluetooth, then previews them like a file import. +struct DiveComputerImport: ViewModifier { + @Environment(AppModel.self) private var model + @Binding var isPresented: Bool + @State private var session = DiveComputerSession() + @State private var downloaded: ImportBatch? + @State private var batch: ImportBatch? + + @MainActor private static var launchOptionUsed = false + + func body(content: Content) -> some View { + content + .sheet(isPresented: $isPresented, onDismiss: { + session.stop() + batch = downloaded + downloaded = nil + }) { + DiveComputerSheet(session: session) { name, dives in + let session = session + downloaded = ImportBatch(name: name, candidates: model.importCandidates(for: dives)) { session.rememberDownload() } + isPresented = false + } + } + .sheet(item: $batch) { ImportSheet(batch: $0) } + .onAppear { + guard !Self.launchOptionUsed, LaunchOptions.flag("-diveComputer") else { return } + Self.launchOptionUsed = true + isPresented = true + } + } +} + +struct DiveComputerSheet: View { + @Environment(\.dismiss) private var dismiss + let session: DiveComputerSession + /// Called with the name of the computer and its dives, to move on to the import preview. + let onDives: (String, [ImportedDive]) -> Void + + var body: some View { + NavigationStack { + Group { + switch session.phase { + case .scanning: scanning + case .connecting(let computer): progress(computer, fraction: nil) + case .downloading(let computer, let fraction): progress(computer, fraction: fraction) + case .finished(let computer): finished(computer) + case .failed(let computer, let message): failed(computer, message) + } + } + .navigationTitle("Dive computer") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Close") { + session.stop() + dismiss() + } + } + } + } + .interactiveDismissDisabled(isBusy) + .onAppear { session.start() } + } + + private var isBusy: Bool { + switch session.phase { + case .connecting, .downloading: return true + default: return false + } + } + + // MARK: Looking for computers + + @ViewBuilder private var scanning: some View { + switch session.bluetooth { + case .off: + ContentUnavailableView("Bluetooth is off", systemImage: "antenna.radiowaves.left.and.right.slash", + description: Text("Turn Bluetooth on in Control Center to reach your dive computer.")) + case .denied: + ContentUnavailableView { + Label("Bluetooth not allowed", systemImage: "hand.raised") + } description: { + Text("Allow \(Brand.name) to use Bluetooth in Settings to reach your dive computer.") + } actions: { + Button("Open Settings") { + if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } + } + } + case .unavailable: + ContentUnavailableView("No Bluetooth on this device", systemImage: "antenna.radiowaves.left.and.right.slash") + case .starting, .ready: + List { + Section { + ForEach(session.computers) { computer in + Button { + session.download(from: computer) + } label: { + HStack(spacing: 12) { + Image(systemName: "gauge.with.dots.needle.bottom.50percent") + .font(.title3) + .foregroundStyle(Color.accentColor) + .frame(width: 30) + VStack(alignment: .leading, spacing: 3) { + Text(computer.name).font(.body.weight(.medium)).foregroundStyle(Color.primary) + Text(session.hasEarlierDownload(computer) + ? String(localized: "\(computer.model.name) · new dives only") + : computer.model.name) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 8) + Image(systemName: "arrow.down.circle").foregroundStyle(.secondary) + } + .padding(.vertical, 2) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .contextMenu { + Button { session.download(from: computer, everything: true) } label: { + Label("Download all dives", systemImage: "arrow.down.circle.dotted") + } + } + } + HStack(spacing: 10) { + ProgressView() + Text("Looking for dive computers…").foregroundStyle(.secondary) + } + } header: { + Text("Nearby") + } footer: { + Text("Put the computer in Bluetooth mode (on a Shearwater: Menu, then Bluetooth), keep it close to the iPhone, then tap its name. The dives are read with libdivecomputer; support has only been checked on a few models so far.") + } + } + .listStyle(.insetGrouped) + } + } + + // MARK: Download + + private func progress(_ computer: DiveComputerSession.Computer, fraction: Double?) -> some View { + VStack(spacing: 18) { + Spacer() + Image(systemName: "gauge.with.dots.needle.bottom.50percent") + .font(.system(size: 52)) + .foregroundStyle(Color.accentColor) + Text(computer.name).font(.title3.weight(.semibold)) + if let fraction { + ProgressView(value: fraction) + .frame(maxWidth: 260) + Text("Downloading… \(Int((fraction * 100).rounded())) %") + .font(.callout.monospacedDigit()) + .foregroundStyle(.secondary) + } else { + ProgressView() + Text("Connecting…").font(.callout).foregroundStyle(.secondary) + } + Text("Keep the computer close to the iPhone and leave this screen open.") + .font(.footnote) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .padding(.horizontal, 32) + Spacer() + Button("Cancel", role: .cancel) { session.cancel() } + .padding(.bottom, 24) + } + .frame(maxWidth: .infinity) + } + + private func finished(_ computer: DiveComputerSession.Computer) -> some View { + ContentUnavailableView { + Label(session.dives.isEmpty ? String(localized: "No new dives") : String(localized: "Download complete"), + systemImage: session.dives.isEmpty ? "checkmark.circle" : "arrow.down.circle") + } description: { + if session.dives.isEmpty { + Text(session.onlyNewer + ? String(localized: "Nothing new on \(computer.name) since the last download.") + : String(localized: "\(computer.name) has no dives in memory.")) + } + } actions: { + if session.dives.isEmpty { + if session.onlyNewer { + Button("Download all dives") { session.download(from: computer, everything: true) } + } + Button("Done") { dismiss() } + } else { + ProgressView() + } + } + .onAppear { + guard !session.dives.isEmpty else { return } + onDives(computer.name, session.dives.map(\.dive)) + } + } + + private func failed(_ computer: DiveComputerSession.Computer, _ message: String) -> some View { + ContentUnavailableView { + Label("Download failed", systemImage: "exclamationmark.triangle") + } description: { + Text(message) + } actions: { + Button("Try again") { session.download(from: computer) } + .buttonStyle(.borderedProminent) + Button("Other computer") { session.reset() } + if !session.troubleshooting.isEmpty { + ShareLink(item: session.troubleshooting) { + Label("Share the technical log", systemImage: "square.and.arrow.up") + } + .font(.footnote) + } + } + } +} diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift @@ -7,6 +7,7 @@ struct DiveListView: View { @State private var search = "" @State private var adding = false @State private var importing = false + @State private var downloading = false @State private var path: [String] = [] @State private var appliedLaunchOptions = false @@ -55,6 +56,7 @@ struct DiveListView: View { ToolbarItem(placement: .topBarTrailing) { Menu { Button { adding = true } label: { Label("New dive", systemImage: "square.and.pencil") } + Button { downloading = true } label: { Label("Download from a dive computer…", systemImage: "gauge.with.dots.needle.bottom.50percent") } Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") } } label: { Label("Add", systemImage: "plus") @@ -64,6 +66,7 @@ struct DiveListView: View { .sheet(isPresented: $adding) { NewDiveView() } .task(id: model.logbook.dives.count) { await model.refreshPhotoPresence() } .modifier(FileImport(isPresented: $importing)) + .modifier(DiveComputerImport(isPresented: $downloading)) .onChange(of: model.logbook.dives.count) { // Screenshot option: open a dive that has just been imported. if path.isEmpty, let number = LaunchOptions.value("-showDive").flatMap({ Int($0) }), diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift @@ -49,6 +49,14 @@ struct ImportBatch: Identifiable { let id = UUID() let name: String let candidates: [AppModel.ImportCandidate] + /// Called once the selected dives are in the logbook. + var onImported: (() -> Void)? + + init(name: String, candidates: [AppModel.ImportCandidate], onImported: (() -> Void)? = nil) { + self.name = name + self.candidates = candidates + self.onImported = onImported + } } struct ImportSheet: View { @@ -150,6 +158,7 @@ struct ImportSheet: View { Task { do { _ = try await model.importDives(dives) + batch.onImported?() dismiss() } catch { self.error = AppModel.describe(error) diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift @@ -5,6 +5,7 @@ struct SettingsView: View { @Environment(AppModel.self) private var model @State private var confirmingSignOut = false @State private var importing = false + @State private var downloading = false private var about: String { String(localized: "\(Brand.name) reads and edits the logbook that Subsurface keeps in its cloud, in the same format. It is an independent app, not affiliated with the Subsurface team. It replaces neither a dive computer nor proper training.") @@ -60,6 +61,9 @@ struct SettingsView: View { LabeledContent("Dives", value: "\(model.logbook.dives.count)") LabeledContent("Sites", value: "\(model.logbook.sites.count)") LabeledContent("Trips", value: "\(model.logbook.trips.count)") + Button { downloading = true } label: { + Label("Download from a dive computer…", systemImage: "gauge.with.dots.needle.bottom.50percent") + } Button { importing = true } label: { Label("Import a file…", systemImage: "square.and.arrow.down") } @@ -75,6 +79,9 @@ struct SettingsView: View { Text(about) .font(.footnote) .foregroundStyle(.secondary) + Text("Free software under the GPL 2.0 licence. Dive computers are read with libdivecomputer (LGPL 2.1). Source code: git.schurger.org/subrascasse") + .font(.footnote) + .foregroundStyle(.secondary) } header: { Text("About") } @@ -88,6 +95,7 @@ struct SettingsView: View { .listStyle(.insetGrouped) .navigationTitle("Settings") .modifier(FileImport(isPresented: $importing)) + .modifier(DiveComputerImport(isPresented: $downloading)) .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?") : String(localized: "Sign out?"), isPresented: $confirmingSignOut, titleVisibility: .visible) { Button(model.isDemo ? String(localized: "Leave") : String(localized: "Sign out"), role: .destructive) { diff --git a/Packages/DiveKit/Package.swift b/Packages/DiveKit/Package.swift @@ -17,7 +17,7 @@ let package = Package( .target(name: "SubsurfaceLog", dependencies: ["GitLite"]), // libdivecomputer (LGPL-2.1), vendored unmodified: protocols and parsers of dive computers. .target(name: "CLibDiveComputer", exclude: ["README.md", "COPYING.LGPL-2.1"], - cSettings: [.define("HAVE_PTHREAD_H"), .unsafeFlags(["-w"])]), + cSettings: [.define("HAVE_PTHREAD_H"), .define("ENABLE_LOGGING"), .unsafeFlags(["-w"])]), // Swift layer over libdivecomputer: device list, download over a caller-provided transport, parsing. // Small C shims: libdivecomputer macros that Swift cannot import. .target(name: "CDiveComputerShims", dependencies: ["CLibDiveComputer"]), diff --git a/Packages/DiveKit/Sources/DiveComputerKit/Download.swift b/Packages/DiveKit/Sources/DiveComputerKit/Download.swift @@ -23,7 +23,8 @@ public struct DiveComputerInfo: Sendable, Equatable { public var model: UInt32 = 0 public var firmware: UInt32 = 0 public var serial: UInt32 = 0 - public var productName = "" + /// The exact model, once the computer has said which one it is (the Bluetooth name is not always enough). + public var modelName = "" /// Serial number the way most computers show it. public var serialText: String { serial == 0 ? "" : String(format: "%08x", serial) } @@ -182,9 +183,10 @@ public final class DiveComputerDownload { me.result.info.model = info.model me.result.info.firmware = info.firmware me.result.info.serial = info.serial - me.result.info.productName = withUnsafeBytes(of: info.product_name) { raw in - String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self) - } + // The model number the computer reports selects the exact model within the family. + // (`product_name` is left alone: several drivers do not fill it in.) + let family = me.model.family + me.result.info.modelName = DiveComputerCatalog.all.first { $0.family == family && $0.model == info.model }?.name ?? me.model.name } }, me) if let fingerprint, !fingerprint.isEmpty { @@ -201,7 +203,7 @@ public final class DiveComputerDownload { var parser: OpaquePointer? if dc_parser_new(&parser, me.device, data, Int(size)) == DC_STATUS_SUCCESS, let parser { defer { dc_parser_destroy(parser) } - let name = me.result.info.productName.isEmpty ? me.model.name : "\(me.model.vendor) \(me.result.info.productName)" + let name = me.result.info.modelName.isEmpty ? me.model.name : me.result.info.modelName if var dive = try? DiveComputerParser.dive(from: parser, modelName: name, serial: me.result.info.serialText) { dive.sourceID = me.result.info.serialText + "-" + String(dive.when) me.result.dives.append(dive) diff --git a/Packages/DiveKit/Tests/DiveComputerKitTests/DiveComputerKitTests.swift b/Packages/DiveKit/Tests/DiveComputerKitTests/DiveComputerKitTests.swift @@ -45,4 +45,52 @@ final class DiveComputerKitTests: XCTestCase { } print("CROSSCHECK\n" + report.joined(separator: "\n")) } + + /// The whole download, against a fake computer that serves the logs of a real export. + func testDownloadFromFakePetrel() throws { + guard let path = ProcessInfo.processInfo.environment["SHEARWATER_EXPORT"] else { throw XCTSkip("SHEARWATER_EXPORT not set") } + let logs = try DiveImporter.shearwaterLogs(from: Array(try Data(contentsOf: URL(fileURLWithPath: path)))) + .sorted { $0.dive.when > $1.dive.when } + let petrel = try XCTUnwrap(DiveComputerCatalog.match(bluetoothName: "Petrel 3")) + XCTAssertEqual(FakePetrel.compress([UInt8](repeating: 0, count: 64) + [7]).count % 9, 0) + + let computer = FakePetrel(modelNumber: UInt8(petrel.model), logs: logs.map(\.log)) + var fractions = [Double]() + let result = try DiveComputerDownload(model: petrel, transport: computer, progress: { fractions.append($0) }).run() + XCTAssertEqual(result.dives.count, logs.count) + XCTAssertEqual(result.unparsed, 0) + XCTAssertEqual(result.info.serialText, "1a2b3c4d") + XCTAssertEqual(result.info.firmware, 93) + XCTAssertEqual(result.info.modelName, "Shearwater Petrel 3") + XCTAssertEqual(result.newestFingerprint, Data(logs[0].log[12..<16])) + XCTAssertEqual(fractions.last ?? 0, 1, accuracy: 0.001) + XCTAssertEqual(fractions, fractions.sorted()) + XCTAssertTrue(computer.closed) + for (downloaded, original) in zip(result.dives, logs) { + XCTAssertEqual(downloaded.when, original.dive.when) + XCTAssertEqual(downloaded.samples, try DiveComputerParser.parse(model: petrel, data: Data(original.log)).samples) + XCTAssertEqual(downloaded.maxDepth, original.dive.maxDepth, accuracy: 0.11) + XCTAssertEqual(downloaded.model, "Shearwater Petrel 3") + XCTAssertEqual(downloaded.serial, "1a2b3c4d") + } + + // With the fingerprint of the third dive, only the two newer ones come. + let second = FakePetrel(modelNumber: UInt8(petrel.model), logs: logs.map(\.log)) + let newer = try DiveComputerDownload(model: petrel, transport: second).run(fingerprint: Data(logs[2].log[12..<16])) + XCTAssertEqual(newer.dives.map(\.when), logs.prefix(2).map(\.dive.when)) + XCTAssertLessThan(second.requests, computer.requests / 2) + + // Giving up after the first dive. + let third = FakePetrel(modelNumber: UInt8(petrel.model), logs: logs.map(\.log)) + var received = 0 + let download = DiveComputerDownload(model: petrel, transport: third, progress: { if $0 > 0.2 { received += 1 } }, isCancelled: { received > 0 }) + XCTAssertThrowsError(try download.run()) { XCTAssertEqual($0 as? DiveComputerError, .cancelled) } + + // A computer that stops answering. + let silent = FakePetrel(modelNumber: UInt8(petrel.model), logs: []) + silent.serial = "" + let failing = DiveComputerDownload(model: petrel, transport: silent) + XCTAssertThrowsError(try failing.run()) + XCTAssertFalse(failing.logLines.isEmpty) + } } diff --git a/Packages/DiveKit/Tests/DiveComputerKitTests/FakePetrel.swift b/Packages/DiveKit/Tests/DiveComputerKitTests/FakePetrel.swift @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-2.0-only +import DiveComputerKit +import Foundation + +/// A Shearwater computer on the other end of the link, speaking the protocol libdivecomputer expects over +/// Bluetooth LE: SLIP frames cut into packets with a two-byte header, the "read data by identifier" requests and +/// the block download of the manifest (raw) and of the dives (zero-run-length encoded after a 32-byte XOR). +final class FakePetrel: DiveComputerTransport { + let deviceName = "Petrel 3" + let modelNumber: UInt8 + /// Raw logs, newest first. + let logs: [[UInt8]] + var serial = "1A2B3C4D" + private(set) var closed = false + private(set) var requests = 0 + + private var incoming = [UInt8]() + private var escaped = false + private var outgoing = [Data]() + private var stream = [UInt8]() + private var sent = 0 + + init(modelNumber: UInt8, logs: [[UInt8]]) { + self.modelNumber = modelNumber + self.logs = logs + } + + func setTimeout(milliseconds: Int) {} + + func read(maxLength: Int) throws -> Data { + guard !outgoing.isEmpty else { throw DiveComputerError.transport("timeout") } + return outgoing.removeFirst() + } + + func readCharacteristic(uuid: [UInt8]) throws -> Data { throw DiveComputerError.transport("no such characteristic") } + + func close() { closed = true } + + func write(_ data: Data) throws { + // Two bytes of header (number of packets, index), then SLIP. + for byte in data.dropFirst(2) { + if escaped { + incoming.append(byte == 0xDC ? 0xC0 : 0xDB) + escaped = false + } else if byte == 0xDB { + escaped = true + } else if byte == 0xC0 { + let frame = incoming + incoming = [] + if !frame.isEmpty { handle(frame) } + } else { + incoming.append(byte) + } + } + } + + private func handle(_ frame: [UInt8]) { + guard frame.count >= 5, frame[0] == 0xFF, frame[1] == 0x01, Int(frame[2]) == frame.count - 3 else { return } + requests += 1 + let request = Array(frame[4...]) + switch request[0] { + case 0x22 where request.count == 3: + let id = Int(request[1]) << 8 | Int(request[2]) + let head: [UInt8] = [0x62, request[1], request[2]] + switch id { + case 0x8010: reply(head + Array(serial.utf8)) + case 0x8011: reply(head + Array("V93".utf8)) + case 0x8060: reply(head + [modelNumber]) + case 0x8021: reply(head + [0x01, 0x80, 0, 0, 0, 0, 0, 0, 0]) + default: reply([0x7F, 0x22, 0x31]) + } + case 0x35 where request.count == 10: + let compressed = request[1] == 0x10 + let address = request[3...6].reduce(0) { $0 << 8 | Int($1) } + let size = request[7...9].reduce(0) { $0 << 8 | Int($1) } + if address == 0xE000_0000 { + stream = manifest(size: size) + } else { + let index = (address - 0x8000_0000) / 0x10_0000 + stream = logs.indices.contains(index) ? (compressed ? Self.compress(logs[index]) : logs[index]) : [] + } + sent = 0 + reply([0x75, 0x10, 0x82]) + case 0x36: + let chunk = Array(stream[sent..<min(stream.count, sent + 126)]) + sent += chunk.count + reply([0x76, request[1]] + chunk) + case 0x37: + reply([0x77, 0x00]) + default: + reply([0x7F, request[0], 0x11]) + } + } + + private func manifest(size: Int) -> [UInt8] { + var out = [UInt8]() + for (index, log) in logs.enumerated() { + var record = [UInt8](repeating: 0, count: 32) + record[0] = 0xA5 + record[1] = 0xC4 + record.replaceSubrange(4..<8, with: log[12..<16]) + let address = index * 0x10_0000 + record[20] = UInt8(address >> 24 & 0xFF) + record[21] = UInt8(address >> 16 & 0xFF) + record[22] = UInt8(address >> 8 & 0xFF) + record[23] = UInt8(address & 0xFF) + out += record + } + return out + [UInt8](repeating: 0, count: max(0, size - out.count)) + } + + /// XOR of each byte with the one 32 bytes earlier, then 9-bit values: 1 + a byte, or 0 + a run of zeros. + static func compress(_ data: [UInt8]) -> [UInt8] { + var delta = data + for index in stride(from: data.count - 1, through: 32, by: -1) { delta[index] = data[index] ^ data[index - 32] } + var values = [UInt16]() + var index = 0 + while index < delta.count { + if delta[index] == 0 { + var run = 0 + while index < delta.count, delta[index] == 0, run < 255 { run += 1; index += 1 } + values.append(UInt16(run)) + } else { + values.append(0x100 | UInt16(delta[index])) + index += 1 + } + } + values.append(0) + while values.count % 8 != 0 { values.append(0) } + var out = [UInt8]() + var accumulator = 0, bits = 0 + for value in values { + accumulator = accumulator << 9 | Int(value) + bits += 9 + while bits >= 8 { + out.append(UInt8(accumulator >> (bits - 8) & 0xFF)) + bits -= 8 + } + accumulator &= (1 << bits) - 1 + } + return out + } + + private func reply(_ payload: [UInt8]) { + let packet: [UInt8] = [0x01, 0xFF, UInt8(payload.count + 1), 0x00] + payload + var slip = [UInt8]() + for byte in packet { + switch byte { + case 0xC0: slip += [0xDB, 0xDC] + case 0xDB: slip += [0xDB, 0xDD] + default: slip.append(byte) + } + } + slip.append(0xC0) + let pieces = stride(from: 0, to: slip.count, by: 18).map { Array(slip[$0..<min(slip.count, $0 + 18)]) } + for (index, piece) in pieces.enumerated() { + outgoing.append(Data([UInt8(pieces.count), UInt8(index)] + piece)) + } + } +} diff --git a/README.md b/README.md @@ -19,6 +19,10 @@ The app is available in English and French. - Import of a Shearwater Cloud export (`.zip` or `dive_data.db`) or of the Dive Shearwater app database (`watermelon.db`, found in `~/Library/Containers/com.shearwater.dive/Data/Documents` when the iOS app runs on a Mac): full profiles, gases, deco stops, pressure, sites created as needed, duplicates skipped. +- Download from a dive computer over Bluetooth LE, with libdivecomputer: the app lists the computers nearby that + libdivecomputer recognises by name, downloads the dives (only the new ones after the first time) and previews + them like a file import. Checked so far with Shearwater logs only (Petrel 3); Heinrichs-Weikamp computers + need a flow-control step that is not written yet. - Dives from Open Rémora (a dive computer for Apple Watch): at launch, when coming back to the foreground and when `subrascasse://open-remora` is opened, the app reads `OpenRemora/Plongees/*.json` in the `group.org.schurger.dive` app group, adds the dives to the logbook and removes the files (the contract is @@ -30,7 +34,7 @@ The app is available in English and French. - Creation of a Subsurface cloud account (email, password, code received by email). - Demo logbook (a button on the sign-in screen, or the `-demo` launch option). -Not there yet: downloading from a dive computer, Subsurface XML import, dive planner. +Not there yet: Subsurface XML import, dive planner. ## Architecture @@ -42,6 +46,11 @@ Not there yet: downloading from a dive computer, Subsurface XML import, dive pla kept byte-identical. - `Repository` handles sync: an offline change queue, replayed on top of the server state. - Importers for the Shearwater and Open Rémora formats. +- `Packages/DiveKit/Sources/CLibDiveComputer`: libdivecomputer, vendored unchanged (see its `README.md` for the + exact revision), built as a package target. +- `Packages/DiveKit/Sources/DiveComputerKit`: Swift on top of it. `Catalog` lists the models and matches one from + a Bluetooth name, `Parser` turns a raw dive into the importer's `ImportedDive`, `Download` runs a download over + a `DiveComputerTransport` that the app provides (`App/Model/DiveComputerLink.swift`, CoreBluetooth). - `Packages/DiveKit/Sources/divelog-cli`: a macOS command-line tool running the same code as the app (list a cloud logbook, inspect or import a file). - `App`: the SwiftUI interface. The display name and the bundle identifier live only in `project.yml` and @@ -51,8 +60,11 @@ Not there yet: downloading from a dive computer, Subsurface XML import, dive pla - The storage format was written from the Subsurface sources (`core/save-git.cpp`, `core/load-git.cpp`, GPL-2.0): https://github.com/subsurface/subsurface -- The Shearwater PNF format is decoded after libdivecomputer (`shearwater_predator_parser.c`): - https://github.com/libdivecomputer/libdivecomputer +- Dive computers are read with libdivecomputer (LGPL-2.1), in the branch that Subsurface maintains: + https://github.com/subsurface/libdc (upstream: https://github.com/libdivecomputer/libdivecomputer). Our own + decoder of Shearwater export files follows its `shearwater_predator_parser.c`, and the tests check one against + the other. +- The choice of the Bluetooth service and characteristics follows Subsurface's `core/qt-ble.cpp` (GPL-2.0). - The format reader was validated on two public sample logbooks: https://github.com/Egbertdepauw/anchorline (real exports) and https://github.com/Ventrilok/divelens @@ -66,7 +78,8 @@ Not there yet: downloading from a dive computer, Subsurface XML import, dive pla `make test-kit FILTER=TestName` runs a single test. Launch options: `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, `-newDive`, -`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`. +`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`, `-diveComputer` +(opens the download sheet; with `-fakeComputers` it lists made-up computers, the simulator having no Bluetooth). ### Validating on a real logbook diff --git a/project.yml b/project.yml @@ -13,7 +13,7 @@ settings: base: DEVELOPMENT_TEAM: CM5RQKJH56 CODE_SIGN_STYLE: Automatic - MARKETING_VERSION: "0.2" + MARKETING_VERSION: "0.3" CURRENT_PROJECT_VERSION: "1" SWIFT_VERSION: "5.0" targets: @@ -27,6 +27,8 @@ targets: product: GitLite - package: DiveKit product: SubsurfaceLog + - package: DiveKit + product: DiveComputerKit settings: base: PRODUCT_BUNDLE_IDENTIFIER: org.schurger.subrascasse @@ -48,6 +50,7 @@ targets: UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait, UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight] # French translation in App/InfoPlist.xcstrings. NSPhotoLibraryUsageDescription: "Sub Rascasse flags the dives you have photos or videos of and shows them on the dive page. They stay on your iPhone; nothing is sent." + NSBluetoothAlwaysUsageDescription: "Sub Rascasse uses Bluetooth to download the dives stored in your dive computer." # Open Remora opens "subrascasse://open-remora" after dropping a dive. CFBundleURLTypes: - CFBundleURLName: org.schurger.subrascasse