open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

commit afbaae2f07567ecb0bfe9a1656773d78dd2068aa
parent 9f571f8db1568e71336e7ce46a23b49e77a5987f
Author: Jean Schurger <jean@schurger.org>
Date:   Sat, 14 Nov 2026 10:00:04 -0500

Use RemoraKit (sibling repository) for the engine, the dive logic and the shared interface

Packages/RemoraDeco moves to the RemoraKit repository, referenced as
../remora-kit. The watch DiveSession becomes an adapter over the shared
DiveMonitor: it feeds it from the submersion sensor and keeps haptics,
the workout, Apple's dive session, the Action button and "Ready to
dive". Format, the terms, the settings screens, alarm styling and the
dive read-outs now come from RemoraUI; the keys that moved are removed
from the app String Catalogs. Stored formats, French wording and the
Sub Rascasse contract are unchanged.

The Makefile syncs RemoraKit next to the app directory on the build Mac
and `make test-deco` runs the package tests there. New screenshot
arguments on the watch: -showSettings, -showAdvancedSettings.

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

Diffstat:
MMakefile | 12+++++++++---
MOpenRemora/DiveNotifier.swift | 1+
MOpenRemora/HomeView.swift | 12++++--------
MOpenRemora/Localizable.xcstrings | 320-------------------------------------------------------------------------------
MOpenRemora/OpenRemoraApp.swift | 3++-
MOpenRemoraWatch/DiveDetailView.swift | 1+
MOpenRemoraWatch/DiveSession.swift | 230+++++++++++++++++--------------------------------------------------------------
MOpenRemoraWatch/DiveView.swift | 111+++----------------------------------------------------------------------------
MOpenRemoraWatch/Localizable.xcstrings | 440-------------------------------------------------------------------------------
MOpenRemoraWatch/LogStore.swift | 2+-
MOpenRemoraWatch/OpenRemoraApp.swift | 17+++++++++++++++--
MOpenRemoraWatch/RootView.swift | 1+
MOpenRemoraWatch/SettingsView.swift | 70+++++++---------------------------------------------------------------
MOpenRemoraWatch/SubmersionSource.swift | 16+++++-----------
DPackages/RemoraDeco/Package.swift | 13-------------
DPackages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift | 169-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/AscentRateMonitor.swift | 42------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift | 171-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/DiveRecorder.swift | 70----------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/Logbook.swift | 113-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/Physics.swift | 76----------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/SubsurfaceImport.swift | 144-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift | 45---------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/Tissues.swift | 132-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/UDDF.swift | 81-------------------------------------------------------------------------------
DPackages/RemoraDeco/Sources/RemoraDeco/UserSettings.swift | 110-------------------------------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/AltitudeTests.swift | 57---------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift | 369-------------------------------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/LogbookTests.swift | 108-------------------------------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/SampleDiveExportTests.swift | 30------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/SettingsTests.swift | 94-------------------------------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/ShearwaterComparisonTests.swift | 140-------------------------------------------------------------------------------
DPackages/RemoraDeco/Tests/RemoraDecoTests/SubsurfaceImportTests.swift | 93-------------------------------------------------------------------------------
MREADME.md | 33+++++++++++++++++++++------------
DShared/DemoProfile.swift | 44--------------------------------------------
DShared/Format.swift | 91-------------------------------------------------------------------------------
MShared/PhoneSync.swift | 20++++++--------------
DShared/TermsView.swift | 48------------------------------------------------
Mdocs/DESIGN.md | 2+-
Mdocs/VALIDATION.md | 2+-
Mproject.yml | 15+++++++++++----
41 files changed, 139 insertions(+), 3409 deletions(-)

diff --git a/Makefile b/Makefile @@ -1,16 +1,22 @@ # The sources are edited here (a Linux host); Swift and Xcode run on a Mac reachable over SSH. # CHUNGA is the SSH host, REMOTE the directory on the Mac (relative to the home directory). +# RemoraKit (a separate repository) is expected next to this one, here (KIT) and on the Mac +# (REMOTE_KIT): project.yml refers to it as ../remora-kit. CHUNGA ?= chunga REMOTE ?= src/perso/open-remora +KIT ?= ../remora-kit +REMOTE_KIT ?= $(dir $(REMOTE))remora-kit +RSYNC = rsync -a --delete --exclude .git --exclude '*.xcodeproj' --exclude build --exclude .build .PHONY: sync test-deco sync: - rsync -a --delete --exclude .git --exclude '*.xcodeproj' --exclude build --exclude .build ./ $(CHUNGA):$(REMOTE)/ + $(RSYNC) ./ $(CHUNGA):$(REMOTE)/ + $(RSYNC) $(KIT)/ $(CHUNGA):$(REMOTE_KIT)/ -# Decompression engine alone (Swift package, no user interface) +# RemoraKit tests: decompression engine, dive logic and shared formatting (Swift package, on macOS) test-deco: sync - ssh $(CHUNGA) 'cd $(REMOTE)/Packages/RemoraDeco && swift test 2>&1' + ssh $(CHUNGA) 'cd $(REMOTE_KIT) && swift test 2>&1' WATCH_DEST ?= generic/platform=watchOS Simulator diff --git a/OpenRemora/DiveNotifier.swift b/OpenRemora/DiveNotifier.swift @@ -6,6 +6,7 @@ import UIKit @preconcurrency import ActivityKit #endif import RemoraDeco +import RemoraUI /// iPhone notifications: /// - when a dive is received (tapping it opens Sub Rascasse, which imports it); diff --git a/OpenRemora/HomeView.swift b/OpenRemora/HomeView.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI import RemoraDeco +import RemoraUI /// Single screen of the iPhone app: watch status, settings (read-only), last dive and post-dive waiting /// times, link to Sub Rascasse. The full logbook is in Sub Rascasse. @@ -22,8 +23,8 @@ struct HomeView: View { subRascasseSection Section { NavigationLink { HelpView() } label: { Label("User guide", systemImage: "book") } - Link(destination: Terms.link) { Label("Terms of use", systemImage: "doc.text") } - Link(destination: Terms.privacy) { Label("Privacy", systemImage: "hand.raised") } + Link(destination: AppTerms.link) { Label("Terms of use", systemImage: "doc.text") } + Link(destination: AppTerms.privacy) { Label("Privacy", systemImage: "hand.raised") } } footer: { Text("Open Rémora is a secondary dive computer, not certified. Always dive with a primary computer.") } @@ -64,12 +65,7 @@ struct HomeView: View { private func settingsSection(_ s: UserSettings) -> some View { Section { - row("Gas", s.gas.description) - row("Maximum operating depth", "\(Format.depth(s.maximumOperatingDepth())) m") - row("Water", s.water.label) - row("NDL alarm", s.ndlAlarmMinutes == 0 ? String(localized: "Off") : String(localized: "Below \(s.ndlAlarmMinutes) min")) - row("Conservatism", s.conservatism == .custom ? String(localized: "Custom (\(s.gradientFactors.description))") : s.conservatism.label) - row("Maximum ppO2", "\(Format.decimal(s.ppO2Max, digits: 1)) bar") + SettingsSummary(settings: s) } header: { Text("Settings") } footer: { diff --git a/OpenRemora/Localizable.xcstrings b/OpenRemora/Localizable.xcstrings @@ -71,16 +71,6 @@ } } }, - "%lld%%": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "%lld %%" - } - } - } - }, "According to Open Rémora and the DAN rule, you can fly. Also follow your primary computer.": { "localizations": { "fr": { @@ -141,26 +131,6 @@ } } }, - "Always dive with a primary dive computer, and follow it when the two disagree.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plongez toujours avec un ordinateur de plongée principal, et suivez-le en cas d'écart." - } - } - } - }, - "Ascent too fast": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Remontée trop rapide" - } - } - } - }, "Before the dive": { "localizations": { "fr": { @@ -171,86 +141,6 @@ } } }, - "Before you dive": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Avant de plonger" - } - } - } - }, - "Below %lld min": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Sous %lld min" - } - } - } - }, - "Ceiling broken": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plafond franchi" - } - } - } - }, - "Conservatism": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Prudence" - } - } - } - }, - "Critical ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 critique" - } - } - } - }, - "Custom": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Personnalisée" - } - } - } - }, - "Custom (%@)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Personnalisée (%@)" - } - } - } - }, - "Depth limit": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Profondeur limite" - } - } - } - }, "Dive no. %lld received": { "localizations": { "fr": { @@ -261,16 +151,6 @@ } } }, - "Dive within the limits of your training. You are responsible for your settings and your gas.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plongez dans les limites de votre formation. Vous êtes responsable de vos réglages et de votre mélange." - } - } - } - }, "During the dive": { "localizations": { "fr": { @@ -291,16 +171,6 @@ } } }, - "Fast ascent": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Remontée rapide" - } - } - } - }, "Flying: no more restriction": { "localizations": { "fr": { @@ -321,26 +191,6 @@ } } }, - "Fresh": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Douce" - } - } - } - }, - "Gas": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Mélange" - } - } - } - }, "Going up to 2000 m: wait another %@": { "localizations": { "fr": { @@ -351,36 +201,6 @@ } } }, - "High (GF 30/70)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Élevée (GF 30/70)" - } - } - } - }, - "High ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 élevée" - } - } - } - }, - "I understand and accept": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "J'ai compris, j'accepte" - } - } - } - }, "Install Open Rémora on the watch (Watch app)": { "localizations": { "fr": { @@ -431,26 +251,6 @@ } } }, - "Low (GF 50/85)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Faible (GF 50/85)" - } - } - } - }, - "Low NDL": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "NDL bas" - } - } - } - }, "Mandatory stops": { "localizations": { "fr": { @@ -461,56 +261,6 @@ } } }, - "Maximum operating depth": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Profondeur maximale du mélange" - } - } - } - }, - "Maximum ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 maximale" - } - } - } - }, - "Medium (GF 40/80)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Moyenne (GF 40/80)" - } - } - } - }, - "NDL alarm": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Alarme de NDL" - } - } - } - }, - "No computation guarantees the absence of decompression sickness.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Aucun calcul ne garantit l'absence d'accident de décompression." - } - } - } - }, "No paired Apple Watch": { "localizations": { "fr": { @@ -541,16 +291,6 @@ } } }, - "Off": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Désactivée" - } - } - } - }, "On the watch, tap “Ready to dive”: the app stays open until you get in the water. Check the gas, the conservatism and the battery.": { "localizations": { "fr": { @@ -601,16 +341,6 @@ } } }, - "Open Rémora is not a certified dive computer.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Open Rémora n'est pas un ordinateur de plongée certifié." - } - } - } - }, "Open Sub Rascasse": { "localizations": { "fr": { @@ -641,26 +371,6 @@ } } }, - "Safety stop missed": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Palier de sécurité sauté" - } - } - } - }, - "Salt": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Salée" - } - } - } - }, "Settings": { "localizations": { "fr": { @@ -711,16 +421,6 @@ } } }, - "Standard (EN 13319)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Standard (EN 13319)" - } - } - } - }, "Terms of use": { "localizations": { "fr": { @@ -811,16 +511,6 @@ } } }, - "Water": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Eau" - } - } - } - }, "Without it, the dive still starts by itself on submersion.": { "localizations": { "fr": { @@ -830,16 +520,6 @@ } } } - }, - "•": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "•" - } - } - } } }, "version": "1.0" diff --git a/OpenRemora/OpenRemoraApp.swift b/OpenRemora/OpenRemoraApp.swift @@ -1,5 +1,6 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI +import RemoraUI /// iPhone app: the bridge between the watch and Sub Rascasse (which acts as the logbook). /// Settings are changed on the watch; here they are only displayed. @@ -10,7 +11,7 @@ struct OpenRemoraApp: App { var body: some Scene { WindowGroup { HomeView() - .requiresTerms() + .requiresTerms(AppTerms.terms) .environment(store) .task { if CommandLine.arguments.contains("-demo") { store.seedDemo() } else { diff --git a/OpenRemoraWatch/DiveDetailView.swift b/OpenRemoraWatch/DiveDetailView.swift @@ -2,6 +2,7 @@ import SwiftUI import Charts import RemoraDeco +import RemoraUI /// Dive summary: the profile first, tap it to browse it with the crown. struct DiveDetailView: View { diff --git a/OpenRemoraWatch/DiveSession.swift b/OpenRemoraWatch/DiveSession.swift @@ -4,43 +4,35 @@ import Observation import WatchKit import RemoraDeco -/// The dive in progress: receives the readings (sensor or simulation), runs the computer and the alarms. +/// The dive in progress on the watch. The dive logic itself (start on submersion, depth held when the reading +/// is missing, alarms, end at the surface, demo dives) is `DiveMonitor` from RemoraDeco, shared with other +/// apps; this adapter feeds it from the watch sensor and adds what belongs to the watch: haptics, the workout +/// session, Apple's dive session, the Action button and "Ready to dive". @MainActor @Observable final class DiveSession { - private(set) var isDiving = false + let monitor: DiveMonitor /// "Ready to dive": the workout session is running, the app stays active until submersion. private(set) var isReady = false - private(set) var isSimulation = false - private(set) var status: DiveComputer.Status? - private(set) var temperature: Double? - private(set) var sensorMessage: String? - /// Underwater without a depth reading (sensor limit exceeded, error, silence): the computer assumes - /// the diver stays at the last known depth and says so in large type. - private(set) var depthUnknown = false - /// Dive that just ended: the home screen opens its summary. - var finishedDive: DiveLog? - - private let store: LogStore - private var recorder: DiveRecorder? - private var surfacedAt: Double? - private var wentUnder = false - private(set) var warnings = Set<DiveComputer.Warning>() - private var safetyStop = DiveComputer.SafetyStop.notRequired - private var sensor: SubmersionSource? - private var simulation: Task<Void, Never>? - private var watchdog: Task<Void, Never>? - private var lastReadingAt: Date? - private var lastPressure: Double? - private var surfacePressure = standardSurfacePressure - private var lastHaptic: [DiveComputer.Warning: Date] = [:] - private var lastAlarmHaptic: Date? + var isDiving: Bool { monitor.isDiving } + var isSimulation: Bool { monitor.isSimulation } + var status: DiveComputer.Status? { monitor.status } + var temperature: Double? { monitor.temperature } + var sensorMessage: String? { monitor.sourceMessage } + /// Underwater without a depth reading: the computer holds the last known depth and says so in large type. + var depthUnknown: Bool { monitor.depthUnknown } + var warnings: Set<DiveComputer.Warning> { monitor.warnings } /// Alarm in progress: a violation, or depth unknown. The whole screen flashes red. - var isAlarming: Bool { depthUnknown || warnings.contains(where: \.isViolation) || Self.forcedAlarm } - /// Screenshots only (`-testAlarm`). - private static let forcedAlarm = CommandLine.arguments.contains("-testAlarm") + var isAlarming: Bool { monitor.isAlarming } /// Warnings in progress (violations excluded): only the value concerned blinks. - var activeWarnings: Set<DiveComputer.Warning> { warnings.filter { !$0.isViolation } } + var activeWarnings: Set<DiveComputer.Warning> { monitor.activeWarnings } + /// Dive that just ended: the home screen opens its summary. + var finishedDive: DiveLog? { + get { monitor.finishedDive } + set { monitor.finishedDive = newValue } + } + + private var sensor: SubmersionSource? let workout = DiveWorkout() /// Apple's dive session: app in the foreground and touch screen locked. let runtime = DiveRuntime() @@ -60,14 +52,31 @@ final class DiveSession { var onDiveSaved: (() -> Void)? init(store: LogStore) { - self.store = store + monitor = DiveMonitor(store: store, feedback: { cue in + WKInterfaceDevice.current().play(Self.haptic(for: cue)) + }) + monitor.simulationSite = String(localized: "Demo") + // Screenshots only (`-testAlarm`). + monitor.forcedAlarm = CommandLine.arguments.contains("-testAlarm") Self.current = self + monitor.onDiveStarted = { [weak self] simulation in self?.diveStarted(simulation: simulation) } + monitor.onDiveEnded = { [weak self] saved, simulation in self?.diveEnded(saved, simulation: simulation) } runtime.onChange = { [weak self] locked, text in self?.screenLocked = locked self?.diagnostics.runtime = text } } + /// The vibration of each cue of the dive logic. + private static func haptic(for cue: DiveCue) -> WKHapticType { + switch cue { + case .depthLost, .alarm: .failure + case .safetyStopStarted: .start + case .safetyStopDone, .diveSaved: .success + case .warning: .notification + } + } + /// Battery level (0 to 1); nil when unknown. var batteryLevel: Double? { let device = WKInterfaceDevice.current() @@ -128,67 +137,10 @@ final class DiveSession { /// Listens to the sensor: the dive starts by itself on submersion. func listen() { guard sensor == nil, SubmersionSource.isAvailable else { return } - sensor = SubmersionSource { [weak self] reading in self?.handle(reading) } - } - - private func handle(_ reading: SubmersionSource.Reading) { - switch reading { - case .message(let text): sensorMessage = text - case .temperature(let celsius): temperature = celsius - case .pressure(let time, let surface, let absolute, let submerged): - guard !isSimulation else { return } - if !isDiving { - guard let absolute, absolute > surface + 0.03 else { return } // ≈ 30 cm of water - start(surfacePressure: surface, simulation: false) - } - lastReadingAt = Date() - if let absolute { - depthUnknown = false - lastPressure = absolute - ingest(time: time, pressure: absolute) - } else if submerged, let held = lastPressure { - // Underwater without a reading: stay at the last known depth (tissues keep loading), - // never a false return to the surface. - signalDepthUnknown() - ingest(time: time, pressure: held) - } else { - depthUnknown = false - lastPressure = surface - ingest(time: time, pressure: surface) - } - } - } - - private func signalDepthUnknown() { - if !depthUnknown { WKInterfaceDevice.current().play(.failure) } - depthUnknown = true - } - - /// Real dive: when the sensor is silent for more than 5 s, time still moves forward. - /// Near the surface, the diver is considered out (the dive ends after one minute); - /// deeper, the last known depth is held and this is signalled. - private func startWatchdog() { - watchdog?.cancel() - watchdog = Task { [weak self] in - while !Task.isCancelled { - try? await Task.sleep(for: .seconds(2)) - guard let self, self.isDiving, !self.isSimulation else { return } - guard let last = self.lastReadingAt, Date().timeIntervalSince(last) > 5, - let held = self.lastPressure else { continue } - let shallow = held < self.surfacePressure + 0.15 // ≈ 1.5 m - if !shallow { self.signalDepthUnknown() } - self.ingest(time: Date().timeIntervalSinceReferenceDate, - pressure: shallow ? self.surfacePressure : held) - } - } + sensor = SubmersionSource { [weak self] reading in self?.monitor.receive(reading) } } - private func start(surfacePressure: Double, simulation: Bool) { - let configuration = (try? store.settings.configuration()) ?? DiveComputer.Configuration() - recorder = DiveRecorder(configuration: configuration, surfacePressure: surfacePressure, - start: Date(), logbook: store.logbook) - isSimulation = simulation - isDiving = true + private func diveStarted(simulation: Bool) { // Real dive without "Ready to dive": the session starts on submersion. if !simulation, !isReady { diagnostics.reset() @@ -197,106 +149,24 @@ final class DiveSession { } isReady = false divePage = 0 - self.surfacePressure = surfacePressure - lastPressure = nil - lastReadingAt = Date() - depthUnknown = false - lastHaptic = [:] - lastAlarmHaptic = nil - if !simulation { startWatchdog() } - surfacedAt = nil - wentUnder = false - warnings = [] - safetyStop = .notRequired - status = nil } - private func ingest(time: Double, pressure: Double) { - guard var r = recorder else { return } - let s = r.record(time: time, pressure: pressure, temperature: temperature) - recorder = r - status = s - - // Safety stop: one vibration at the start and at the end of the countdown. - switch (safetyStop, s.safetyStop) { - case (.pending, .running), (.notRequired, .running): WKInterfaceDevice.current().play(.start) - case (.running, .done): WKInterfaceDevice.current().play(.success) - default: break - } - safetyStop = s.safetyStop - - // Vibrations (wall clock, not the dive clock). - // Alarm (violation, depth unknown): strong vibration every 2 s for as long as it lasts. - // Warning: one vibration when it appears, repeated every 15 s for as long as it lasts. - let now = Date() - warnings = s.warnings - if isAlarming { - if lastAlarmHaptic.map({ now.timeIntervalSince($0) >= 2 }) ?? true { - lastAlarmHaptic = now - WKInterfaceDevice.current().play(.failure) - } - } else { - lastAlarmHaptic = nil - let due = s.warnings.filter { w in lastHaptic[w].map { now.timeIntervalSince($0) >= 15 } ?? true } - if !due.isEmpty { - for w in due { lastHaptic[w] = now } - WKInterfaceDevice.current().play(.notification) - } - } - // A warning that went away and came back vibrates again, but no more than once every 15 s. - lastHaptic = lastHaptic.filter { now.timeIntervalSince($0.value) < 15 || s.warnings.contains($0.key) } - - // Automatic end: one minute at the surface after going below 1 m. - if s.depth > 1 { wentUnder = true } - if s.depth < 0.3 { - if surfacedAt == nil { surfacedAt = time } - if wentUnder, let since = surfacedAt, time - since >= 60 { end() } - } else { - surfacedAt = nil + /// `saved` is nil when nothing was kept (the diver never went down). + private func diveEnded(_ saved: DiveLog?, simulation: Bool) { + if !simulation { + runtime.stop() + Task { await workout.finish(with: saved) } } + if saved != nil { onDiveSaved?() } } /// Ends the dive and adds it to the logbook (nothing is kept when the diver never went down). - func end() { - simulation?.cancel() - simulation = nil - watchdog?.cancel() - watchdog = nil - depthUnknown = false - guard let r = recorder else { return } - recorder = nil - isDiving = false - if !isSimulation { runtime.stop() } - guard wentUnder else { - if !isSimulation { Task { await workout.finish(with: nil) } } - return - } - var dive = r.finish() - if isSimulation { - dive.source = .simulation - dive.site = String(localized: "Demo") - } - let saved = store.add(dive) - finishedDive = saved - WKInterfaceDevice.current().play(.success) - if !isSimulation { Task { await workout.finish(with: saved) } } - onDiveSaved?() - } + func end() { monitor.end() } /// Dry demo dive, accelerated. func startSimulation(_ profile: DemoProfile = .reef, speed: Double = 30) { guard !isDiving, !isReady else { return } - start(surfacePressure: standardSurfacePressure, simulation: true) - guard let scale = recorder?.computer.scale else { return } - let depths = profile.depths + Array(repeating: 0, count: 61) - simulation = Task { [weak self] in - for (t, d) in depths.enumerated() { - guard !Task.isCancelled, let self, self.isDiving else { return } - self.temperature = DemoProfile.temperature(atDepth: d) - self.ingest(time: Double(t), pressure: scale.pressure(atDepth: d)) - try? await Task.sleep(for: .seconds(1 / speed)) - } - } + monitor.startSimulation(profile, speed: speed) } } diff --git a/OpenRemoraWatch/DiveView.swift b/OpenRemoraWatch/DiveView.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI import RemoraDeco +import RemoraUI /// Dive screen. Underwater the touch screen is locked: the crown moves from one page to the next. /// Page 1: depth, ascent rate, NDL or stop; page 2: details; page 3: compass. @@ -33,12 +34,7 @@ struct DiveView: View { } .overlay(alignment: .bottom) { if session.depthUnknown { - Text("DEPTH UNKNOWN\nFollow your primary computer") - .font(.system(size: 13, weight: .heavy, design: .rounded)) - .multilineTextAlignment(.center) - .padding(6) - .frame(maxWidth: .infinity) - .background(.red, in: RoundedRectangle(cornerRadius: 8)) + DepthUnknownBanner() } } .overlay(alignment: .top) { @@ -58,30 +54,6 @@ struct DiveView: View { } -/// Alarm: the whole screen flashes red. -private struct AlarmFlash: View { - var body: some View { - TimelineView(.periodic(from: .now, by: 0.4)) { context in - let on = Int(context.date.timeIntervalSinceReferenceDate / 0.4) % 2 == 0 - Color.red.opacity(on ? 0.85 : 0.15).ignoresSafeArea() - } - } -} - -extension View { - /// Warning: the value concerned blinks (nothing moves when `active` is false). - @ViewBuilder func blinking(_ active: Bool) -> some View { - if active { - TimelineView(.periodic(from: .now, by: 0.4)) { context in - let on = Int(context.date.timeIntervalSinceReferenceDate / 0.4) % 2 == 0 - self.opacity(on ? 1 : 0.15) - } - } else { - self - } - } -} - // MARK: - Page 1 private struct MainDivePage: View { @@ -112,7 +84,7 @@ private struct MainDivePage: View { .blinking(session.activeWarnings.contains(.depthLimit)) Text("m").font(.title3).foregroundStyle(.secondary) } - if let s { Instruction(status: s) } + if let s { DiveInstruction(status: s) } } .frame(maxWidth: .infinity) } @@ -131,83 +103,6 @@ private struct MainDivePage: View { } } -/// What to do now: alarm, stop (countdown), safety stop, or no-stop. -private struct Instruction: View { - let status: DiveComputer.Status - - var body: some View { - let s = status - VStack(spacing: 1) { - if let warning = s.warnings.sorted(by: { $0.rank < $1.rank }).first { - Text(warning.label.uppercased()) - .font(.system(size: 14, weight: .bold, design: .rounded)) - .foregroundStyle(warning.isViolation ? .white : warning.color) - .minimumScaleFactor(0.6) - .lineLimit(1) - .blinking([.ppO2High, .missedSafetyStop].contains(warning)) - } - if let stop = s.plan.stops.first { - HStack(alignment: .firstTextBaseline, spacing: 4) { - Text("STOP \(Int(stop.depth)) m") - .font(.system(size: 16, weight: .bold, design: .rounded)) - Text(Format.clock(Double(stop.seconds ?? stop.minutes * 60))) - .font(.system(size: 22, weight: .bold, design: .rounded)) - .monospacedDigit() - } - .foregroundStyle(.orange) - Text("surface in \(Int(s.plan.timeToSurface.rounded(.up))) min") - .font(.caption2).foregroundStyle(.secondary) - } else if case .running(let remaining) = s.safetyStop { - Text("SAFETY STOP").font(.system(size: 12, weight: .bold, design: .rounded)).foregroundStyle(.cyan) - Text(Format.clock(remaining)) - .font(.system(size: 26, weight: .bold, design: .rounded)) - .monospacedDigit() - .foregroundStyle(.cyan) - } else { - let low = s.warnings.contains(.lowNoDecompression) - HStack(alignment: .firstTextBaseline, spacing: 4) { - Text("NDL").font(.system(size: 15, weight: .semibold, design: .rounded)).foregroundStyle(.secondary) - Text(Format.ndl(s.plan.noDecompressionLimit)) - .font(.system(size: 26, weight: .bold, design: .rounded)) - .monospacedDigit() - .foregroundStyle(low ? .orange : .green) - .blinking(low) - Text("min").font(.caption).foregroundStyle(.secondary) - } - switch s.safetyStop { - case .pending where s.depth < 9: - Text("Safety stop 3 min at 5 m").font(.caption2).foregroundStyle(.cyan) - case .done: - Text("Safety stop done ✓").font(.caption2).foregroundStyle(.green) - default: - EmptyView() - } - } - } - } -} - -/// Vertical ascent rate scale: 5 segments (3, 6, 9, 10, 12 m/min) that fill from the bottom; -/// green, yellow above 10 m/min, red above 12. -struct AscentScale: View { - let rate: Double - static let thresholds: [Double] = [3, 6, 9, 10, 12] - - var body: some View { - VStack(spacing: 3) { - Image(systemName: "arrow.up").font(.system(size: 9, weight: .heavy)).foregroundStyle(.secondary) - ForEach(Self.thresholds.indices.reversed(), id: \.self) { i in - RoundedRectangle(cornerRadius: 2) - .fill(rate >= Self.thresholds[i] ? color : Color.gray.opacity(0.25)) - .frame(width: 10, height: i >= 3 ? 14 : 10) - } - } - .accessibilityLabel("Ascent \(Int(max(0, rate))) metres per minute") - } - - private var color: Color { rate > 12 ? .red : rate > 10 ? .yellow : .green } -} - // MARK: - Page 2 private struct DetailsDivePage: View { diff --git a/OpenRemoraWatch/Localizable.xcstrings b/OpenRemoraWatch/Localizable.xcstrings @@ -51,16 +51,6 @@ } } }, - "%lld%%": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "%lld %%" - } - } - } - }, "%lld°": { "localizations": { "fr": { @@ -71,16 +61,6 @@ } } }, - "21% (air)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "21 % (air)" - } - } - } - }, "ACTION BUTTON %lld": { "localizations": { "fr": { @@ -131,26 +111,6 @@ } } }, - "Advanced": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Avancés" - } - } - } - }, - "Advanced settings": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Réglages avancés" - } - } - } - }, "Alarms": { "localizations": { "fr": { @@ -171,36 +131,6 @@ } } }, - "Always dive with a primary dive computer, and follow it when the two disagree.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plongez toujours avec un ordinateur de plongée principal, et suivez-le en cas d'écart." - } - } - } - }, - "Ascent %lld metres per minute": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Remontée %lld mètres par minute" - } - } - } - }, - "Ascent too fast": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Remontée trop rapide" - } - } - } - }, "Average depth": { "localizations": { "fr": { @@ -231,26 +161,6 @@ } } }, - "Before you dive": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Avant de plonger" - } - } - } - }, - "Below %lld min": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Sous %lld min" - } - } - } - }, "Beyond the sensor limit": { "localizations": { "fr": { @@ -281,16 +191,6 @@ } } }, - "Ceiling broken": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plafond franchi" - } - } - } - }, "Clear": { "localizations": { "fr": { @@ -371,36 +271,6 @@ } } }, - "Critical ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 critique" - } - } - } - }, - "Custom": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Personnalisée" - } - } - } - }, - "DEPTH UNKNOWN\nFollow your primary computer": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "PROFONDEUR INCONNUE\nSuivez votre ordinateur principal" - } - } - } - }, "Demo": { "localizations": { "fr": { @@ -431,16 +301,6 @@ } } }, - "Depth limit": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Profondeur limite" - } - } - } - }, "Depth sensor error": { "localizations": { "fr": { @@ -481,16 +341,6 @@ } } }, - "Dive within the limits of your training. You are responsible for your settings and your gas.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Plongez dans les limites de votre formation. Vous êtes responsable de vos réglages et de votre mélange." - } - } - } - }, "Duration": { "localizations": { "fr": { @@ -521,26 +371,6 @@ } } }, - "Fast ascent": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Remontée rapide" - } - } - } - }, - "Fresh": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Douce" - } - } - } - }, "From there, it goes to Sub Rascasse.": { "localizations": { "fr": { @@ -551,26 +381,6 @@ } } }, - "GF high %lld%%": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "GF haut %lld %%" - } - } - } - }, - "GF low %lld%%": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "GF bas %lld %%" - } - } - } - }, "Gas": { "localizations": { "fr": { @@ -591,36 +401,6 @@ } } }, - "High (GF 30/70)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Élevée (GF 30/70)" - } - } - } - }, - "High ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 élevée" - } - } - } - }, - "I understand and accept": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "J'ai compris, j'accepte" - } - } - } - }, "Last trial": { "localizations": { "fr": { @@ -641,26 +421,6 @@ } } }, - "Low (GF 50/85)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Faible (GF 50/85)" - } - } - } - }, - "Low NDL": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "NDL bas" - } - } - } - }, "Low accuracy: draw a figure 8 with your wrist": { "localizations": { "fr": { @@ -711,36 +471,6 @@ } } }, - "Maximum operating depth: %@ m": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Profondeur maximale du mélange : %@ m" - } - } - } - }, - "Maximum ppO2": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "ppO2 maximale" - } - } - } - }, - "Medium (GF 40/80)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Moyenne (GF 40/80)" - } - } - } - }, "N": { "localizations": { "fr": { @@ -751,16 +481,6 @@ } } }, - "NDL": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "NDL" - } - } - } - }, "NDL %@ min": { "localizations": { "fr": { @@ -771,16 +491,6 @@ } } }, - "NDL alarm": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Alarme de NDL" - } - } - } - }, "NDL: time left without a mandatory stop. The watch vibrates and the value blinks below this threshold.": { "localizations": { "fr": { @@ -861,16 +571,6 @@ } } }, - "No computation guarantees the absence of decompression sickness.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Aucun calcul ne garantit l'absence d'accident de décompression." - } - } - } - }, "No depth sensor on this watch": { "localizations": { "fr": { @@ -901,16 +601,6 @@ } } }, - "Off": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Désactivée" - } - } - } - }, "On the iPhone": { "localizations": { "fr": { @@ -931,26 +621,6 @@ } } }, - "Open Rémora is not a certified dive computer.": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Open Rémora n'est pas un ordinateur de plongée certifié." - } - } - } - }, - "Oxygen": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Oxygène" - } - } - } - }, "Profile": { "localizations": { "fr": { @@ -1001,16 +671,6 @@ } } }, - "SAFETY STOP": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "PALIER DE SÉCURITÉ" - } - } - } - }, "SE": { "localizations": { "fr": { @@ -1021,16 +681,6 @@ } } }, - "STOP %lld m": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "PALIER %lld m" - } - } - } - }, "STOP %lld m · %@": { "localizations": { "fr": { @@ -1061,46 +711,6 @@ } } }, - "Safety stop 3 min at 5 m": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Palier de sécurité 3 min à 5 m" - } - } - } - }, - "Safety stop done ✓": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Palier de sécurité fait ✓" - } - } - } - }, - "Safety stop missed": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Palier de sécurité sauté" - } - } - } - }, - "Salt": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Salée" - } - } - } - }, "Screen locked: long press on the crown": { "localizations": { "fr": { @@ -1171,16 +781,6 @@ } } }, - "Standard (EN 13319)": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Standard (EN 13319)" - } - } - } - }, "Start": { "localizations": { "fr": { @@ -1231,16 +831,6 @@ } } }, - "Terms of use": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "Conditions d'utilisation" - } - } - } - }, "The bearing set here stays displayed during the dive (compass page, two crown clicks).": { "localizations": { "fr": { @@ -1451,16 +1041,6 @@ } } }, - "min": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "min" - } - } - } - }, "never donated": { "localizations": { "fr": { @@ -1550,26 +1130,6 @@ } } } - }, - "surface in %lld min": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "surface dans %lld min" - } - } - } - }, - "•": { - "localizations": { - "fr": { - "stringUnit": { - "state": "translated", - "value": "•" - } - } - } } }, "version": "1.0" diff --git a/OpenRemoraWatch/LogStore.swift b/OpenRemoraWatch/LogStore.swift @@ -5,7 +5,7 @@ import RemoraDeco /// Logbook and settings, saved as JSON on the watch. @MainActor @Observable -final class LogStore { +final class LogStore: DiveLogStore { private(set) var logbook = Logbook() var settings = UserSettings() /// Called every time the settings are saved (sending to the iPhone). diff --git a/OpenRemoraWatch/OpenRemoraApp.swift b/OpenRemoraWatch/OpenRemoraApp.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI import RemoraDeco +import RemoraUI @main struct OpenRemoraApp: App { @@ -28,11 +29,23 @@ struct OpenRemoraApp: App { var body: some Scene { WindowGroup { - RootView() - .requiresTerms() + root + .requiresTerms(AppTerms.terms) .environment(store) .environment(compass) .environment(session) } } + + /// Screenshots: `-showSettings` and `-showAdvancedSettings` open straight on those screens. + @ViewBuilder private var root: some View { + if CommandLine.arguments.contains("-showSettings") { + NavigationStack { SettingsView() } + } else if CommandLine.arguments.contains("-showAdvancedSettings") { + @Bindable var store = store + NavigationStack { AdvancedDiveSettingsView(settings: $store.settings) } + } else { + RootView() + } + } } diff --git a/OpenRemoraWatch/RootView.swift b/OpenRemoraWatch/RootView.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI import RemoraDeco +import RemoraUI struct RootView: View { @Environment(LogStore.self) private var store diff --git a/OpenRemoraWatch/SettingsView.swift b/OpenRemoraWatch/SettingsView.swift @@ -1,74 +1,18 @@ // SPDX-License-Identifier: GPL-2.0-only import SwiftUI import RemoraDeco +import RemoraUI +/// The settings screens come from RemoraUI; the watch adds its own footers and saves every change. struct SettingsView: View { @Environment(LogStore.self) private var store var body: some View { @Bindable var store = store - List { - Section { - Picker("Oxygen", selection: $store.settings.oxygenPercent) { - ForEach(Array(UserSettings.Limits.oxygenPercent), id: \.self) { p in - Text(p == 21 ? "21% (air)" : "\(p)%").tag(p) - } - } - Picker("Water", selection: $store.settings.water) { - ForEach(Water.allCases, id: \.self) { Text($0.label).tag($0) } - } - } footer: { - Text("Maximum operating depth: \(Format.depth(store.settings.maximumOperatingDepth())) m") - } - - Section { - Picker("NDL alarm", selection: $store.settings.ndlAlarmMinutes) { - ForEach(UserSettings.Limits.ndlAlarmMinutes, id: \.self) { m in - Text(m == 0 ? "Off" : "Below \(m) min").tag(m) - } - } - } footer: { - Text("NDL: time left without a mandatory stop. The watch vibrates and the value blinks below this threshold.") - } - - Section { - NavigationLink("Advanced settings") { AdvancedSettingsView() } - } footer: { - Text("Altitude is measured by the watch: nothing to set.") - } - } - .navigationTitle("Settings") - .onChange(of: store.settings) { store.saveSettings() } - } -} - -struct AdvancedSettingsView: View { - @Environment(LogStore.self) private var store - - var body: some View { - @Bindable var store = store - List { - Section("Conservatism") { - Picker("Conservatism", selection: $store.settings.conservatism) { - ForEach(UserSettings.Conservatism.allCases, id: \.self) { Text($0.label).tag($0) } - } - if store.settings.conservatism == .custom { - Stepper("GF low \(store.settings.customGFLowPercent)%", - value: $store.settings.customGFLowPercent, - in: UserSettings.Limits.gfLowPercent.lowerBound...store.settings.customGFHighPercent, step: 5) - Stepper("GF high \(store.settings.customGFHighPercent)%", - value: $store.settings.customGFHighPercent, - in: max(UserSettings.Limits.gfHighPercent.lowerBound, store.settings.customGFLowPercent)...100, step: 5) - } - } - Section("Oxygen") { - Picker("Maximum ppO2", selection: $store.settings.ppO2Max) { - ForEach([1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { v in - Text(verbatim: "\(Format.decimal(v, digits: 1)) bar").tag(v) - } - } - } - } - .navigationTitle("Advanced") + DiveSettingsView( + settings: $store.settings, + ndlAlarmNote: String(localized: "NDL: time left without a mandatory stop. The watch vibrates and the value blinks below this threshold."), + altitudeNote: String(localized: "Altitude is measured by the watch: nothing to set.")) + .onChange(of: store.settings) { store.saveSettings() } } } diff --git a/OpenRemoraWatch/SubmersionSource.swift b/OpenRemoraWatch/SubmersionSource.swift @@ -1,30 +1,24 @@ // SPDX-License-Identifier: GPL-2.0-only import Foundation @preconcurrency import CoreMotion +import RemoraDeco /// Depth sensor of the Apple Watch Ultra (Core Motion). /// With the "shallow depth" entitlement, readings stop at around 6 m. +/// It feeds the shared dive logic with `DiveReading` values. final class SubmersionSource: NSObject, CMWaterSubmersionManagerDelegate, @unchecked Sendable { - enum Reading: Sendable { - /// `time` in seconds, pressures in bar. `absolute` is nil out of the water, but also when the sensor - /// no longer measures underwater (beyond its limit, error): `submerged` tells them apart. - case pressure(time: Double, surface: Double, absolute: Double?, submerged: Bool) - case temperature(Double) - case message(String?) - } - static var isAvailable: Bool { CMWaterSubmersionManager.waterSubmersionAvailable } private let manager = CMWaterSubmersionManager() - private let handler: @MainActor (Reading) -> Void + private let handler: @MainActor (DiveReading) -> Void - init(handler: @escaping @MainActor (Reading) -> Void) { + init(handler: @escaping @MainActor (DiveReading) -> Void) { self.handler = handler super.init() manager.delegate = self } - private func send(_ reading: Reading) { + private func send(_ reading: DiveReading) { let handler = handler Task { @MainActor in handler(reading) } } diff --git a/Packages/RemoraDeco/Package.swift b/Packages/RemoraDeco/Package.swift @@ -1,13 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -// swift-tools-version: 6.0 -import PackageDescription - -let package = Package( - name: "RemoraDeco", - platforms: [.watchOS(.v10), .iOS(.v17), .macOS(.v14)], - products: [.library(name: "RemoraDeco", targets: ["RemoraDeco"])], - targets: [ - .target(name: "RemoraDeco"), - .testTarget(name: "RemoraDecoTests", dependencies: ["RemoraDeco"]), - ] -) diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift b/Packages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift @@ -1,169 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Ascent and stop settings. -public struct DecoSettings: Sendable, Hashable { - public var gradientFactors: GradientFactors = .conservative - public var ascentRate: Double = 9 // m/min - /// Assumed rate used to credit off-gassing during the ascent in the no-stop time (m/min). - /// Deliberately fast: partial credit, matched to a Shearwater (see ShearwaterComparisonTests). - public var noStopAscentRate: Double = 30 - public var stopIncrement: Double = 3 // m - public var lastStopDepth: Double = 3 // m - public var safetyStopDepth: Double = 5 // m - public var safetyStopMinutes: Double = 3 - public var safetyStopTriggerDepth: Double = 10 // m of maximum depth reached - - public init() {} -} - -public struct DecoStop: Sendable, Hashable { - public let depth: Double // m - public let minutes: Int - /// Stop duration to the nearest 10 s (countdown display; first stop only). - public var seconds: Int? - - public init(depth: Double, minutes: Int, seconds: Int? = nil) { - self.depth = depth - self.minutes = minutes - self.seconds = seconds - } -} - -public struct AscentPlan: Sendable, Hashable { - /// Remaining no-stop time at the current depth (min); `nil` = unlimited; 0 = in decompression. - public let noDecompressionLimit: Double? - /// Mandatory stops, deepest first (empty outside decompression). - public let stops: [DecoStop] - /// Total ascent time (mandatory stops included, safety stop excluded), min. - public let timeToSurface: Double - /// Reference depth of the `low` factor (first stop), to be kept for the whole dive. - public let gradientAnchorDepth: Double? - - public var inDecompression: Bool { !stops.isEmpty } -} - -public enum AscentPlanner { - /// Computes the ascent from `pressure` with the current tissue state. - /// `anchorDepth`: first stop already set earlier in the dive (the `low` factor stays anchored there). - /// - /// Outside decompression, the criterion is the one commercial computers use: a direct ascent must - /// reach the surface under the `high` factor (the `low` factor only serves to place the stops). - /// The no-stop time is the longest stay (whole minutes, 99 at most) at the current depth that still - /// allows it; `nil` = more than 99 min. - public static func plan(tissues: TissueState, pressure: Double, gas: Gas, - scale: DepthScale, settings: DecoSettings, - anchorDepth: Double? = nil) -> AscentPlan { - let depthNow = scale.depth(atPressure: pressure) - - func surfacesClear(after minutes: Int) -> Bool { - var t = tissues - t.stay(atPressure: pressure, gas: gas, minutes: Double(minutes)) - t.change(from: pressure, to: scale.surfacePressure, gas: gas, - minutes: depthNow / settings.noStopAscentRate) - return t.ceiling(gradientFactor: settings.gradientFactors.high) <= scale.surfacePressure + 1e-9 - } - - if anchorDepth != nil || !surfacesClear(after: 0) { - let now = ascent(tissues: tissues, pressure: pressure, gas: gas, scale: scale, - settings: settings, anchorDepth: anchorDepth) - if !now.stops.isEmpty || !surfacesClear(after: 0) { return now } - } - - var limit: Double? - if !surfacesClear(after: 99) { - var low = 0, high = 99 // `low` passes, `high` does not - while high - low > 1 { - let middle = (low + high) / 2 - if surfacesClear(after: middle) { low = middle } else { high = middle } - } - limit = Double(low) - } - return AscentPlan(noDecompressionLimit: limit, stops: [], timeToSurface: depthNow / settings.ascentRate, - gradientAnchorDepth: anchorDepth) - } - - /// Immediate ascent: required stops (none = direct ascent possible) and duration. - static func ascent(tissues: TissueState, pressure: Double, gas: Gas, - scale: DepthScale, settings: DecoSettings, - anchorDepth: Double?) -> AscentPlan { - let gf = settings.gradientFactors - let depthNow = scale.depth(atPressure: pressure) - - var t = tissues - var depth = depthNow - var anchor = anchorDepth - var stops: [DecoStop] = [] - var tts = 0.0 - - func gfAt(_ d: Double) -> Double { - guard let a = anchor, a > 0 else { return gf.low } - return gf.high - (gf.high - gf.low) * min(1, max(0, d / a)) - } - - func nextStop(below d: Double) -> Double { - let step = settings.stopIncrement - let next = (((d - 1e-6) / step).rounded(.up) - 1) * step - return next < settings.lastStopDepth ? 0 : next - } - - func ascend(_ state: TissueState, from: Double, to: Double) -> TissueState { - var s = state - s.change(from: scale.pressure(atDepth: from), to: scale.pressure(atDepth: to), - gas: gas, minutes: (from - to) / settings.ascentRate) - return s - } - - func clear(_ state: TissueState, at d: Double) -> Bool { - state.ceiling(gradientFactor: gfAt(d)) <= scale.pressure(atDepth: d) + 1e-9 - } - - // Diver between two stops (or above their own) who cannot go up to the next one: their stop is on - // the grid, at their depth or deeper, never at an arbitrary depth. Revision 0.2: before, a diver - // who had come up to 2.4 m was offered a "stop at 2 m". - if depth > 0, !clear(t, at: nextStop(below: depth)) { - let step = settings.stopIncrement - var grid = max(settings.lastStopDepth, (depth / step - 1e-6).rounded(.up) * step) - if abs(grid - depth) > 1e-6 { - while !clear(t, at: grid) && grid < 60 { grid += step } - depth = grid - } - } - - while depth > 0 { - let next = nextStop(below: depth) - let trial = ascend(t, from: depth, to: next) - // Conservative: the next stop must be tolerated BEFORE going up (no credit for the way up). - if clear(t, at: next) { - t = trial - tts += (depth - next) / settings.ascentRate - depth = next - continue - } - // Stop at `depth`: the anchor follows the first (deepest) stop, then we wait minute by minute. - if anchor.map({ depth > $0 }) ?? true { anchor = depth } - // First stop: duration to the nearest 10 s, for the countdown (on a copy: the plan keeps its - // whole minutes, which are more conservative). - var seconds: Int? - if stops.isEmpty { - var fine = t - var s = 0 - repeat { - fine.stay(atPressure: scale.pressure(atDepth: depth), gas: gas, minutes: 10.0 / 60) - s += 10 - } while !clear(fine, at: next) && s < 999 * 60 - seconds = s - } - var waited = 0 - repeat { - t.stay(atPressure: scale.pressure(atDepth: depth), gas: gas, minutes: 1) - waited += 1 - } while !clear(t, at: next) && waited < 999 - stops.append(DecoStop(depth: depth, minutes: waited, seconds: seconds)) - tts += Double(waited) - } - - return AscentPlan(noDecompressionLimit: 0, stops: stops, - timeToSurface: tts, gradientAnchorDepth: anchor) - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/AscentRateMonitor.swift b/Packages/RemoraDeco/Sources/RemoraDeco/AscentRateMonitor.swift @@ -1,42 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Ascent rate smoothed over a short window (the watch sensor is sampled at ~1 Hz). -public struct AscentRateMonitor: Sendable { - public enum Level: Sendable, Hashable { case normal, fast, tooFast } - - public var window: Double = 5 // s - public var warningRate: Double = 10 // m/min - public var alarmRate: Double = 12 // m/min - - private var samples: [(time: Double, depth: Double)] = [] - - public init() {} - - public mutating func add(time: Double, depth: Double) { - samples.append((time, depth)) - samples.removeAll { time - $0.time > window } - } - - /// Ascent rate in m/min (positive when ascending), by least squares over the window. - public var rate: Double { - guard samples.count >= 2 else { return 0 } - let n = Double(samples.count) - let mt = samples.map(\.time).reduce(0, +) / n - let md = samples.map(\.depth).reduce(0, +) / n - var num = 0.0, den = 0.0 - for s in samples { - num += (s.time - mt) * (s.depth - md) - den += (s.time - mt) * (s.time - mt) - } - guard den > 0 else { return 0 } - return -num / den * 60 - } - - public var level: Level { - let r = rate - if r > alarmRate { return .tooFast } - if r > warningRate { return .fast } - return .normal - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift b/Packages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift @@ -1,171 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Dive computer: receives the pressure samples from the watch and keeps the state of the dive. -public struct DiveComputer: Sendable { - public struct Configuration: Sendable, Hashable { - public var gas: Gas = .air - public var water: Water = .en13319 - public var deco = DecoSettings() - public var ppO2Warning: Double = 1.4 - public var ppO2Alarm: Double = 1.6 - /// Warning depth, before the 40 m limit of the watch. - public var depthLimit: Double = 38 - /// Warning when the NDL (no-stop time) drops below this value (min); 0 = off. - public var lowNoDecompression: Double = 5 - public init() {} - } - - public enum Warning: String, Sendable, Hashable, Codable, CaseIterable { - case ascentFast, ascentTooFast - case ceilingViolated - case ppO2High, ppO2Critical - case missedSafetyStop - case depthLimit - case lowNoDecompression - } - - /// Safety stop (3 min between 3 and 6 m after going below 10 m, outside decompression). - public enum SafetyStop: Sendable, Hashable { - case notRequired - case pending - /// Running: seconds remaining. - case running(remaining: Double) - case done - case missed - } - - public struct Status: Sendable { - public let elapsed: Double // min - public let depth: Double // m - public let maxDepth: Double // m - public let ascentRate: Double // m/min - public let ppO2: Double - public let plan: AscentPlan - public let ceilingDepth: Double // m (0 = no ceiling) - public let safetyStopRecommended: Bool - public let safetyStop: SafetyStop - public let warnings: Set<Warning> - } - - public let configuration: Configuration - public let scale: DepthScale - public private(set) var tissues: TissueState - public private(set) var maxDepth = 0.0 - public private(set) var gradientAnchorDepth: Double? - private var start: Double? - private var last: (time: Double, pressure: Double)? - private var ascent = AscentRateMonitor() - private var safetyStopTime = 0.0 // s spent in the safety stop zone - private var safetyStopState = SafetyStop.notRequired - private var plan: AscentPlan? - - /// `surfacePressure`: measured by the watch just before submersion. - /// `tissues`: state inherited from the previous dive (repetitive dives), otherwise saturated at the surface. - public init(configuration: Configuration = Configuration(), surfacePressure: Double, - tissues: TissueState? = nil) { - self.configuration = configuration - self.scale = DepthScale(surfacePressure: surfacePressure, water: configuration.water) - self.tissues = tissues ?? .saturated(surfacePressure: surfacePressure) - } - - /// New sample: `time` in seconds (monotonic clock), absolute `pressure` in bar. - public mutating func update(time: Double, pressure: Double) { - let elapsedStep = last.map { max(0, time - $0.time) } ?? 0 - if let last, time > last.time { - tissues.change(from: last.pressure, to: pressure, gas: configuration.gas, - minutes: (time - last.time) / 60) - } - if start == nil { start = time } - last = (time, pressure) - let depth = scale.depth(atPressure: pressure) - maxDepth = max(maxDepth, depth) - ascent.add(time: time, depth: depth) - - let newPlan = AscentPlanner.plan(tissues: tissues, pressure: pressure, gas: configuration.gas, - scale: scale, settings: configuration.deco, - anchorDepth: gradientAnchorDepth) - // The gradient factor anchor follows the deepest first stop and stays for the whole dive. - if let anchor = newPlan.gradientAnchorDepth { gradientAnchorDepth = max(gradientAnchorDepth ?? 0, anchor) } - plan = newPlan - updateSafetyStop(depth: depth, seconds: elapsedStep) - } - - /// Advances the safety stop. Zone: 3 to 6.5 m; it restarts from zero when going back below 7 m. - private mutating func updateSafetyStop(depth: Double, seconds: Double) { - let deco = configuration.deco - guard maxDepth >= deco.safetyStopTriggerDepth else { return } - if case .done = safetyStopState { return } - // Missed, then back down: the stop is to be done again. - if case .missed = safetyStopState, depth <= deco.safetyStopDepth + 2 { return } - if plan?.inDecompression == true { safetyStopState = .pending; safetyStopTime = 0; return } - let required = deco.safetyStopMinutes * 60 - if depth >= 3, depth <= deco.safetyStopDepth + 1.5 { - safetyStopTime += seconds - safetyStopState = safetyStopTime >= required ? .done : .running(remaining: required - safetyStopTime) - } else if depth > deco.safetyStopDepth + 2 { - safetyStopTime = 0 - safetyStopState = .pending - } else if depth < 1 { - safetyStopState = .missed - } - } - - public var safetyStop: SafetyStop { safetyStopState } - - public var status: Status { - let pressure = last?.pressure ?? scale.surfacePressure - let depth = scale.depth(atPressure: pressure) - let plan = self.plan ?? AscentPlanner.plan(tissues: tissues, pressure: pressure, - gas: configuration.gas, scale: scale, - settings: configuration.deco) - let ceiling = scale.depth(atPressure: tissues.ceiling(gradientFactor: currentGF(depth: depth))) - let ppO2 = configuration.gas.ppO2(atPressure: pressure) - - var warnings = Set<Warning>() - switch ascent.level { - case .fast: warnings.insert(.ascentFast) - case .tooFast: warnings.insert(.ascentTooFast) - case .normal: break - } - if ceiling > 0, depth < ceiling - 0.3 { warnings.insert(.ceilingViolated) } - // Above the required stop (stops come in 3 m steps, deeper than the continuous ceiling). - if let stop = plan.stops.first, depth < stop.depth - 0.6 { warnings.insert(.ceilingViolated) } - if ppO2 > configuration.ppO2Alarm { warnings.insert(.ppO2Critical) } - else if ppO2 > configuration.ppO2Warning { warnings.insert(.ppO2High) } - if depth >= configuration.depthLimit { warnings.insert(.depthLimit) } - if !plan.inDecompression, let ndl = plan.noDecompressionLimit, ndl < configuration.lowNoDecompression, - depth > configuration.deco.safetyStopDepth + 2 { warnings.insert(.lowNoDecompression) } - if case .missed = safetyStopState { warnings.insert(.missedSafetyStop) } - - let elapsed = ((last?.time ?? 0) - (start ?? 0)) / 60 - return Status(elapsed: elapsed, depth: depth, maxDepth: maxDepth, ascentRate: ascent.rate, - ppO2: ppO2, plan: plan, ceilingDepth: ceiling, - safetyStopRecommended: !plan.inDecompression - && maxDepth >= configuration.deco.safetyStopTriggerDepth, - safetyStop: safetyStopState, warnings: warnings) - } - - private func currentGF(depth: Double) -> Double { - let gf = configuration.deco.gradientFactors - guard let anchor = gradientAnchorDepth, anchor > 0 else { return gf.high } - return gf.high - (gf.high - gf.low) * min(1, max(0, depth / anchor)) - } - - /// Arrival at altitude: tissues saturated at the origin pressure (sea level by default), then - /// off-gassed for `hoursAgo` at the local pressure. Without this, a dive in a mountain lake on the - /// day of travel would be computed as if the diver lived there. - public static func arrival(from originPressure: Double = standardSurfacePressure, - to surfacePressure: Double, hoursAgo: Double) -> TissueState { - surfaceInterval(.saturated(surfacePressure: originPressure), minutes: hoursAgo * 60, - surfacePressure: surfacePressure) - } - - /// Off-gassing at the surface between two dives (on air). - public static func surfaceInterval(_ tissues: TissueState, minutes: Double, - surfacePressure: Double) -> TissueState { - var t = tissues - t.stay(atPressure: surfacePressure, gas: .air, minutes: minutes) - return t - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/DiveRecorder.swift b/Packages/RemoraDeco/Sources/RemoraDeco/DiveRecorder.swift @@ -1,70 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Records a dive in progress: feeds the computer and keeps the profile for the logbook. -public struct DiveRecorder: Sendable { - public private(set) var computer: DiveComputer - public let start: Date - public let surfaceIntervalBefore: Double? - /// Minimum gap between two profile points (s). Alarms are logged at every sample. - public var sampleInterval: Double = 2 - - private var t0: Double? - private var samples: [DiveSample] = [] - private var events: [DiveEvent] = [] - private var activeWarnings = Set<DiveComputer.Warning>() - private var lastLogged: [DiveComputer.Warning: Double] = [:] - /// An alarm that flickers around its threshold is logged only once per period (s). - public var eventRepeatInterval: Double = 30 - private var latest: DiveSample? - - /// Starts a dive. Tissues come from the logbook (repetitive dive) when it holds a recent one. - public init(configuration: DiveComputer.Configuration, surfacePressure: Double, - start: Date, logbook: Logbook? = nil) { - let previous = logbook?.tissues(at: start, surfacePressure: surfacePressure) - self.computer = DiveComputer(configuration: configuration, surfacePressure: surfacePressure, - tissues: previous?.tissues) - self.start = start - self.surfaceIntervalBefore = previous?.interval - } - - /// `time`: monotonic clock in seconds; `pressure`: absolute bar; `temperature`: °C. - @discardableResult - public mutating func record(time: Double, pressure: Double, temperature: Double? = nil) -> DiveComputer.Status { - computer.update(time: time, pressure: pressure) - let status = computer.status - if t0 == nil { t0 = time } - let elapsed = time - (t0 ?? time) - - for w in status.warnings.subtracting(activeWarnings) { - if let before = lastLogged[w], elapsed - before < eventRepeatInterval { continue } - lastLogged[w] = elapsed - events.append(DiveEvent(time: elapsed, warning: w)) - } - activeWarnings = status.warnings - - let stop = status.plan.stops.first - let sample = DiveSample(time: elapsed, depth: status.depth, temperature: temperature, - ceiling: status.ceilingDepth, - noDecompressionLimit: status.plan.noDecompressionLimit, - stopDepth: stop?.depth, stopMinutes: stop?.minutes) - latest = sample - if samples.isEmpty || elapsed - samples[samples.count - 1].time >= sampleInterval { - samples.append(sample) - } - return status - } - - /// Ends the dive and produces the logbook entry (number assigned by `Logbook.add`). - public func finish() -> DiveLog { - let c = computer.configuration - // The last sample received always closes the profile (back at the surface). - var samples = samples - if let latest, latest.time > (samples.last?.time ?? -1) { samples.append(latest) } - return DiveLog(id: UUID(), source: .remora, computerModel: "Open Rémora", number: 0, start: start, surfacePressure: computer.scale.surfacePressure, - surfaceIntervalBefore: surfaceIntervalBefore, gas: c.gas, - gradientFactors: c.deco.gradientFactors, water: c.water, - samples: samples, events: events.sorted { $0.time < $1.time }, - tissuesAfter: computer.tissues) - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/Logbook.swift b/Packages/RemoraDeco/Sources/RemoraDeco/Logbook.swift @@ -1,113 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// One recorded profile point (for the chart and the export). -public struct DiveSample: Sendable, Hashable, Codable { - public let time: Double // s since the start of the dive - public let depth: Double // m - public let temperature: Double? // °C (water) - public let ceiling: Double // m (0 = no ceiling) - public let noDecompressionLimit: Double? // min; nil = unlimited; 0 = in decompression - public let stopDepth: Double? // next mandatory stop, m - public let stopMinutes: Int? -} - -/// Alarm or warning raised during the dive. -public struct DiveEvent: Sendable, Hashable, Codable { - public let time: Double // s - public let warning: DiveComputer.Warning -} - -/// One dive of the logbook. -public struct DiveLog: Sendable, Hashable, Codable, Identifiable { - /// Where the dive comes from: recorded by Open Rémora, imported from a Subsurface logbook, - /// or simulated (demo: never counted in tissue loading or waiting times). - public enum Source: String, Sendable, Hashable, Codable { case remora, subsurface, simulation } - - public var id: UUID - public var source: Source = .remora - /// Computer that recorded the dive (imported dives: model as noted by Subsurface). - public var computerModel: String? - public var number: Int // number in the logbook (1, 2, …) - public let start: Date - public let surfacePressure: Double // bar - public let surfaceIntervalBefore: Double? // min; nil = first dive (saturated tissues) - public let gas: Gas - public let gradientFactors: GradientFactors? // nil: imported dive - public let water: Water - public let samples: [DiveSample] - public let events: [DiveEvent] - public let tissuesAfter: TissueState? // nil: imported dive - // Entered afterwards in the logbook - public var site: String? - public var notes: String? - public var latitude: Double? - public var longitude: Double? - - public var duration: Double { samples.last?.time ?? 0 } // s - public var maxDepth: Double { samples.map(\.depth).max() ?? 0 } - public var minTemperature: Double? { samples.compactMap(\.temperature).min() } - public var hadDecompression: Bool { samples.contains { $0.stopDepth != nil } } - /// Recorded violations: ceiling broken, ascent too fast, critical ppO2. - public var violations: [DiveEvent] { - events.filter { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains($0.warning) } - } - public var end: Date { start.addingTimeInterval(duration) } - - /// Time-weighted average depth. - public var averageDepth: Double { - guard samples.count > 1, duration > 0 else { return samples.first?.depth ?? 0 } - var area = 0.0 - for (a, b) in zip(samples, samples.dropFirst()) { area += (a.depth + b.depth) / 2 * (b.time - a.time) } - return area / duration - } -} - -/// The logbook: dives in order, and the tissue state for the next dive. -public struct Logbook: Sendable, Hashable, Codable { - public private(set) var dives: [DiveLog] = [] - - public init() {} - - /// Real dives (demo simulations are excluded from the computations). - public var realDives: [DiveLog] { dives.filter { $0.source != .simulation } } - - public mutating func add(_ dive: DiveLog) { - var d = dive - d.number = (dives.map(\.number).max() ?? 0) + 1 - dives.append(d) - dives.sort { $0.start < $1.start } - } - - /// Adds imported dives, keeping their number; skips those already present - /// (same start within one minute). Returns the number of dives added. - @discardableResult - public mutating func merge(_ imported: [DiveLog]) -> Int { - var added = 0 - for d in imported where !dives.contains(where: { abs($0.start.timeIntervalSince(d.start)) < 60 }) { - dives.append(d) - added += 1 - } - dives.sort { $0.start < $1.start } - return added - } - - public mutating func update(_ dive: DiveLog) { - guard let i = dives.firstIndex(where: { $0.id == dive.id }) else { return } - dives[i] = dive - } - - public mutating func remove(id: UUID) { dives.removeAll { $0.id == id } } - - /// Tissues at `date`, from the last dive and the current surface pressure. - /// `nil` when there is no recent dive (more than 72 h): the diver is considered saturated at the surface. - public func tissues(at date: Date, surfacePressure: Double) -> (tissues: TissueState, interval: Double)? { - // Known limitation: a more recent imported dive (without tissues) is not taken into account. - guard let last = realDives.last(where: { $0.tissuesAfter != nil }), let after = last.tissuesAfter - else { return nil } - let minutes = date.timeIntervalSince(last.end) / 60 - guard minutes >= 0, minutes < 72 * 60 else { return nil } - return (DiveComputer.surfaceInterval(after, minutes: minutes, - surfacePressure: surfacePressure), minutes) - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/Physics.swift b/Packages/RemoraDeco/Sources/RemoraDeco/Physics.swift @@ -1,76 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Engine units: pressures in bar (absolute), depths in metres, durations in minutes. -/// The watch provides the ambient pressure directly: depth is only a display value. -public enum Water: String, Sendable, Hashable, Codable, CaseIterable { - case fresh // 1000 kg/m³ - case en13319 // 1020 kg/m³, dive computer convention (EN 13319) - case salt // 1025 kg/m³ - - public var density: Double { - switch self { - case .fresh: 1000 - case .en13319: 1020 - case .salt: 1025 - } - } - - /// Pressure added per metre of water, in bar. - public var barPerMetre: Double { density * 9.80665 / 100_000 } -} - -/// Water vapour pressure in the lungs (Bühlmann value), in bar. -public let waterVapourPressure = 0.0627 - -/// Standard pressure at sea level, in bar. -public let standardSurfacePressure = 1.01325 - -/// Depth ↔ pressure conversion for a given surface pressure and water type. -public struct DepthScale: Sendable, Hashable { - public var surfacePressure: Double - public var water: Water - - public init(surfacePressure: Double = standardSurfacePressure, water: Water = .en13319) { - precondition(surfacePressure > 0.5 && surfacePressure < 1.2, "implausible surface pressure") - self.surfacePressure = surfacePressure - self.water = water - } - - public func pressure(atDepth depth: Double) -> Double { - surfacePressure + max(0, depth) * water.barPerMetre - } - - public func depth(atPressure pressure: Double) -> Double { - max(0, (pressure - surfacePressure) / water.barPerMetre) - } -} - -/// Breathing gas. Helium is not supported (recreational diving on air or nitrox, 40 m at most). -public struct Gas: Sendable, Hashable, Codable, CustomStringConvertible { - public let o2: Double - public var n2: Double { 1 - o2 } - - public init(o2: Double) { - precondition(o2 >= 0.16 && o2 <= 1.0, "oxygen fraction out of range") - self.o2 = o2 - } - - public static let air = Gas(o2: 0.21) - public static func nitrox(_ percent: Int) -> Gas { Gas(o2: Double(percent) / 100) } - - public var description: String { o2 == 0.21 ? "Air" : "EAN\(Int((o2 * 100).rounded()))" } - - /// Partial pressure of oxygen at an ambient pressure. - public func ppO2(atPressure pressure: Double) -> Double { pressure * o2 } - - /// Maximum operating depth for a ppO2 limit. - public func maximumOperatingDepth(ppO2Limit: Double, scale: DepthScale) -> Double { - scale.depth(atPressure: ppO2Limit / o2) - } - - /// Inspired partial pressure of nitrogen (in the alveoli). - func inspiredN2(atPressure pressure: Double) -> Double { - max(0, pressure - waterVapourPressure) * n2 - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/SubsurfaceImport.swift b/Packages/RemoraDeco/Sources/RemoraDeco/SubsurfaceImport.swift @@ -1,144 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -#if canImport(FoundationXML) -import FoundationXML -#endif - -/// Reads a Subsurface logbook (XML file, `.ssrf` or `.xml`) to review it in Open Rémora. -/// Only the first dive computer of each dive is read. Imported dives have neither tissues nor GF. -public enum SubsurfaceImport { - public enum Failure: Error { case notSubsurface, malformed(String) } - - public static func dives(from data: Data) throws -> [DiveLog] { - let delegate = Reader() - let parser = XMLParser(data: data) - parser.delegate = delegate - guard parser.parse() else { - throw Failure.malformed(parser.parserError?.localizedDescription ?? "unreadable XML") - } - guard delegate.sawDivelog else { throw Failure.notSubsurface } - return delegate.dives.sorted { $0.start < $1.start } - } - - /// "12.3 m", "21.0 C", "1.013 bar", "32.0%" → number. - static func number(_ s: String?) -> Double? { - guard let s else { return nil } - let head = s.prefix { "0123456789.-".contains($0) } - return Double(head) - } - - /// "45:30 min", "1:02:03", "30" → seconds. - static func seconds(_ s: String?) -> Double? { - guard let s else { return nil } - let head = s.prefix { "0123456789:".contains($0) } - let parts = head.split(separator: ":").compactMap { Double($0) } - guard !parts.isEmpty else { return nil } - if parts.count == 1 { return s.contains("min") ? parts[0] * 60 : parts[0] } - return parts.reduce(0) { $0 * 60 + $1 } - } - - private final class Reader: NSObject, XMLParserDelegate { - var sawDivelog = false - var dives: [DiveLog] = [] - private var sites: [String: (name: String, lat: Double?, lon: Double?)] = [:] - - private var inDive = false - private var computerIndex = 0 - private var attrs: [String: String] = [:] - private var samples: [DiveSample] = [] - private var model: String? - private var o2: Double? - private var surface: Double? - private var salinity: Double? - private var notes: String? - private var location: String? - private var text = "" - private var lastTemp: Double? - - func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, - qualifiedName: String?, attributes a: [String: String] = [:]) { - text = "" - switch name { - case "divelog": sawDivelog = true - case "site": - if let uuid = a["uuid"]?.trimmingCharacters(in: .whitespaces) { - let gps = (a["gps"] ?? "").split(separator: " ").compactMap { Double($0) } - sites[uuid] = (a["name"] ?? "", gps.count == 2 ? gps[0] : nil, gps.count == 2 ? gps[1] : nil) - } - case "dive": - inDive = true; attrs = a; samples = []; computerIndex = 0 - model = nil; o2 = nil; surface = nil; salinity = nil; notes = nil; location = nil; lastTemp = nil - case "divecomputer" where inDive: - computerIndex += 1 - if computerIndex == 1 { model = a["model"] } - case "cylinder" where inDive && o2 == nil: - o2 = SubsurfaceImport.number(a["o2"]).map { $0 / 100 } ?? 0.21 - case "surface" where inDive && computerIndex <= 1: - surface = SubsurfaceImport.number(a["pressure"]) - case "water" where inDive && computerIndex <= 1: - salinity = SubsurfaceImport.number(a["salinity"]) - case "temperature" where inDive && computerIndex <= 1 && lastTemp == nil: - break - case "sample" where inDive && computerIndex == 1: - guard let t = SubsurfaceImport.seconds(a["time"]), - let d = SubsurfaceImport.number(a["depth"]) else { break } - if let temp = SubsurfaceImport.number(a["temp"]) { lastTemp = temp } - let stopDepth = SubsurfaceImport.number(a["stopdepth"]) - let stopTime = SubsurfaceImport.seconds(a["stoptime"]) - let inDeco = (stopDepth ?? 0) > 0 || a["in_deco"] == "1" - samples.append(DiveSample( - time: t, depth: d, temperature: lastTemp, ceiling: inDeco ? (stopDepth ?? 0) : 0, - noDecompressionLimit: inDeco ? 0 : SubsurfaceImport.seconds(a["ndl"]).map { $0 / 60 }, - stopDepth: inDeco ? stopDepth : nil, - stopMinutes: inDeco ? stopTime.map { Int(($0 / 60).rounded(.up)) } : nil)) - default: break - } - } - - func parser(_ parser: XMLParser, foundCharacters string: String) { text += string } - - func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, - qualifiedName: String?) { - let value = text.trimmingCharacters(in: .whitespacesAndNewlines) - switch name { - case "notes" where inDive: notes = value.isEmpty ? nil : value - case "location" where inDive: location = value.isEmpty ? nil : value - case "dive": finishDive(); inDive = false - default: break - } - text = "" - } - - private func finishDive() { - guard let date = attrs["date"] else { return } - let f = DateFormatter() - f.locale = Locale(identifier: "en_US_POSIX") - f.timeZone = TimeZone(secondsFromGMT: 0) // Subsurface stores local time, without a time zone - f.dateFormat = "yyyy-MM-dd HH:mm:ss" - guard let start = f.date(from: "\(date) \(attrs["time"] ?? "00:00:00")") else { return } - - // No profile (dive entered by hand): two points are enough for the duration. - if samples.isEmpty, let duration = SubsurfaceImport.seconds(attrs["duration"]) { - samples = [DiveSample(time: 0, depth: 0, temperature: nil, ceiling: 0, noDecompressionLimit: nil, - stopDepth: nil, stopMinutes: nil), - DiveSample(time: duration, depth: 0, temperature: nil, ceiling: 0, - noDecompressionLimit: nil, stopDepth: nil, stopMinutes: nil)] - } - let site = attrs["divesiteid"].flatMap { sites[$0.trimmingCharacters(in: .whitespaces)] } - let water: Water = switch salinity ?? 1020 { - case ..<1010: .fresh - case 1023...: .salt - default: .en13319 - } - let fraction = min(1, max(0.16, o2 ?? 0.21)) - dives.append(DiveLog( - id: UUID(), source: .subsurface, computerModel: model, - number: Int(attrs["number"] ?? "") ?? 0, start: start, - surfacePressure: surface ?? standardSurfacePressure, surfaceIntervalBefore: nil, - gas: Gas(o2: fraction), gradientFactors: nil, water: water, - samples: samples, events: [], tissuesAfter: nil, - site: site?.name.isEmpty == false ? site?.name : location, notes: notes, - latitude: site?.lat, longitude: site?.lon)) - } - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift b/Packages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift @@ -1,45 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// After the dive: when it is possible to go to altitude or to fly. -public enum SurfaceAdvice { - /// Cabin pressure of an airliner (≈ 2400 m), bar. - public static let cabinPressure = 0.75 - - /// Minutes before the tissues tolerate the `target` pressure (high gradient factor), - /// while staying at `surfacePressure`. 0 = right away; capped at 72 h. - public static func minutesUntilTolerated(_ target: Double, tissues: TissueState, - surfacePressure: Double, gfHigh: Double) -> Double { - var t = tissues - var minutes = 0.0 - while t.ceiling(gradientFactor: gfHigh) > target, minutes < 72 * 60 { - t.stay(atPressure: surfacePressure, gas: .air, minutes: 5) - minutes += 5 - } - return minutes - } - - /// No-fly time: the longer of the model and the DAN rule - /// (12 h after a single no-stop dive, 18 h after several in the day, 24 h after decompression stops). - public static func noFlyHours(logbook: Logbook, at date: Date, surfacePressure: Double) -> Double { - guard let last = logbook.realDives.last, - let state = logbook.tissues(at: date, surfacePressure: surfacePressure) else { return 0 } - let model = minutesUntilTolerated(cabinPressure, tissues: state.tissues, - surfacePressure: surfacePressure, - gfHigh: (last.gradientFactors ?? .conservative).high) / 60 - let sameDay = logbook.realDives.filter { last.end.timeIntervalSince($0.end) < 24 * 3600 } - let rule: Double = sameDay.contains(where: \.hadDecompression) ? 24 : (sameDay.count > 1 ? 18 : 12) - let sinceEnd = date.timeIntervalSince(last.end) / 3600 - return max(0, max(model, rule - sinceEnd)) - } - - /// Hours before being able to go up to the given altitude (pass, mountain road), according to the model. - public static func hoursBeforeAltitude(_ metres: Double, logbook: Logbook, at date: Date, - surfacePressure: Double) -> Double { - guard let last = logbook.realDives.last, - let state = logbook.tissues(at: date, surfacePressure: surfacePressure) else { return 0 } - let target = standardSurfacePressure * pow(1 - 2.25577e-5 * metres, 5.25588) - return minutesUntilTolerated(target, tissues: state.tissues, surfacePressure: surfacePressure, - gfHigh: (last.gradientFactors ?? .conservative).high) / 60 - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/Tissues.swift b/Packages/RemoraDeco/Sources/RemoraDeco/Tissues.swift @@ -1,132 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// One compartment of the Bühlmann model: half-time (min) and coefficients a (bar) and b. -public struct Compartment: Sendable, Hashable { - public let halfTime: Double - public let a: Double - public let b: Double - - var k: Double { log(2) / halfTime } -} - -/// Bühlmann ZHL-16C, nitrogen (compartment 1b for the first one). -public enum ZHL16C { - public static let nitrogen: [Compartment] = [ - Compartment(halfTime: 5.0, a: 1.1696, b: 0.5578), - Compartment(halfTime: 8.0, a: 1.0000, b: 0.6514), - Compartment(halfTime: 12.5, a: 0.8618, b: 0.7222), - Compartment(halfTime: 18.5, a: 0.7562, b: 0.7825), - Compartment(halfTime: 27.0, a: 0.6200, b: 0.8126), - Compartment(halfTime: 38.3, a: 0.5043, b: 0.8434), - Compartment(halfTime: 54.3, a: 0.4410, b: 0.8693), - Compartment(halfTime: 77.0, a: 0.4000, b: 0.8910), - Compartment(halfTime: 109.0, a: 0.3750, b: 0.9092), - Compartment(halfTime: 146.0, a: 0.3500, b: 0.9222), - Compartment(halfTime: 187.0, a: 0.3295, b: 0.9319), - Compartment(halfTime: 239.0, a: 0.3065, b: 0.9403), - Compartment(halfTime: 305.0, a: 0.2835, b: 0.9477), - Compartment(halfTime: 390.0, a: 0.2610, b: 0.9544), - Compartment(halfTime: 498.0, a: 0.2480, b: 0.9602), - Compartment(halfTime: 635.0, a: 0.2327, b: 0.9653), - ] -} - -/// Gradient factors (Baker): `low` sets the first stop, `high` the surfacing. -public struct GradientFactors: Sendable, Hashable, Codable, CustomStringConvertible { - public let low: Double - public let high: Double - - public init(low: Double, high: Double) { - precondition(low > 0 && low <= high && high <= 1, "inconsistent gradient factors") - self.low = low - self.high = high - } - - /// Conservative default setting of Open Rémora (secondary computer). - public static let conservative = GradientFactors(low: 0.30, high: 0.70) - public static let pureBuhlmann = GradientFactors(low: 1, high: 1) - - public var description: String { "GF \(Int((low * 100).rounded()))/\(Int((high * 100).rounded()))" } -} - -/// Nitrogen loading of the 16 compartments, in bar. -public struct TissueState: Sendable, Hashable { - public private(set) var nitrogen: [Double] - let compartments: [Compartment] - - /// Diver saturated at the surface, on air. - public static func saturated(surfacePressure: Double = standardSurfacePressure) -> TissueState { - let p = Gas.air.inspiredN2(atPressure: surfacePressure) - return TissueState(nitrogen: Array(repeating: p, count: ZHL16C.nitrogen.count), - compartments: ZHL16C.nitrogen) - } - - /// Stay at constant pressure (Haldane equation). - public mutating func stay(atPressure pressure: Double, gas: Gas, minutes: Double) { - guard minutes > 0 else { return } - let pi = gas.inspiredN2(atPressure: pressure) - for i in nitrogen.indices { - let k = compartments[i].k - nitrogen[i] = pi + (nitrogen[i] - pi) * exp(-k * minutes) - } - } - - /// Linear pressure change (Schreiner equation): exact between two samples. - public mutating func change(from start: Double, to end: Double, gas: Gas, minutes: Double) { - guard minutes > 0 else { return } - let pi0 = gas.inspiredN2(atPressure: start) - let rate = (gas.inspiredN2(atPressure: end) - pi0) / minutes - for i in nitrogen.indices { - let k = compartments[i].k - let p0 = nitrogen[i] - nitrogen[i] = pi0 + rate * (minutes - 1 / k) - (pi0 - p0 - rate / k) * exp(-k * minutes) - } - } - - /// Tolerated ambient pressure (ceiling) with a given gradient factor, in bar. - public func ceiling(gradientFactor gf: Double) -> Double { - var worst = 0.0 - for (p, c) in zip(nitrogen, compartments) { - let tolerated = (p - c.a * gf) / (gf / c.b - gf + 1) - worst = max(worst, tolerated) - } - return worst - } - - /// Remaining no-stop time at constant pressure, in minutes (`nil` = unlimited). - /// Checks that a direct ascent would stay under the `gfHigh` factor at the surface. - public func noDecompressionLimit(atPressure pressure: Double, gas: Gas, - surfacePressure: Double, gfHigh gf: Double) -> Double? { - let pi = gas.inspiredN2(atPressure: pressure) - var limit = Double.infinity - for (p0, c) in zip(nitrogen, compartments) { - let maximum = surfacePressure * (gf / c.b - gf + 1) + c.a * gf - if p0 >= maximum { return 0 } - guard pi > maximum else { continue } - let t = log((pi - p0) / (pi - maximum)) / c.k - limit = min(limit, t) - } - return limit.isFinite ? limit : nil - } -} - -/// Tissues saved with the dive (repetitive dives, no-fly time). -extension TissueState: Codable { - enum CodingKeys: String, CodingKey { case nitrogen } - - public init(from decoder: Decoder) throws { - let values = try decoder.container(keyedBy: CodingKeys.self) - let n2 = try values.decode([Double].self, forKey: .nitrogen) - guard n2.count == ZHL16C.nitrogen.count else { - throw DecodingError.dataCorruptedError(forKey: .nitrogen, in: values, - debugDescription: "16 compartments expected") - } - self.init(nitrogen: n2, compartments: ZHL16C.nitrogen) - } - - public func encode(to encoder: Encoder) throws { - var values = encoder.container(keyedBy: CodingKeys.self) - try values.encode(nitrogen, forKey: .nitrogen) - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/UDDF.swift b/Packages/RemoraDeco/Sources/RemoraDeco/UDDF.swift @@ -1,81 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Logbook export in UDDF 3.2 format (import into Subsurface, MacDive, etc.). SI units: m, s, K, Pa. -public enum UDDF { - public static func export(_ dives: [DiveLog], generatorVersion: String = "0.1") -> String { - let iso = ISO8601DateFormatter() - var mixes: [Gas] = [] - for d in dives where !mixes.contains(d.gas) { mixes.append(d.gas) } - func mixID(_ g: Gas) -> String { "mix\(mixes.firstIndex(of: g)! + 1)" } - func n(_ v: Double, _ digits: Int = 2) -> String { String(format: "%.\(digits)f", v) } - func kelvin(_ c: Double) -> String { n(c + 273.15) } - func esc(_ s: String) -> String { - s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;") - .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;") - } - - var x = """ - <?xml version="1.0" encoding="UTF-8"?> - <uddf xmlns="http://www.streit.cc/uddf/3.2/" version="3.2.3"> - <generator> - <name>Open Rémora</name> - <type>divecomputer</type> - <version>\(generatorVersion)</version> - </generator> - <gasdefinitions> - - """ - for g in mixes { - x += """ - <mix id="\(mixID(g))"><name>\(g)</name><o2>\(n(g.o2, 3))</o2><n2>\(n(g.n2, 3))</n2><he>0.000</he></mix> - - """ - } - x += " </gasdefinitions>\n <profiledata>\n <repetitiongroup id=\"rg1\">\n" - for d in dives { - x += " <dive id=\"dive\(d.number)\">\n <informationbeforedive>\n" - x += " <divenumber>\(d.number)</divenumber>\n" - x += " <datetime>\(iso.string(from: d.start))</datetime>\n" - x += " <atmosphericpressure>\(n(d.surfacePressure * 100_000, 0))</atmosphericpressure>\n" - if let si = d.surfaceIntervalBefore { - x += " <surfaceintervalbeforedive><passedtime>\(n(si * 60, 0))</passedtime></surfaceintervalbeforedive>\n" - } else { - x += " <surfaceintervalbeforedive><infinity/></surfaceintervalbeforedive>\n" - } - x += " </informationbeforedive>\n <samples>\n" - for (i, s) in d.samples.enumerated() { - x += " <waypoint><divetime>\(n(s.time, 0))</divetime><depth>\(n(s.depth))</depth>" - if let t = s.temperature { x += "<temperature>\(kelvin(t))</temperature>" } - if i == 0 { x += "<switchmix ref=\"\(mixID(d.gas))\"/>" } - if let sd = s.stopDepth, let sm = s.stopMinutes { - x += "<decostop kind=\"mandatory\" decodepth=\"\(n(sd, 1))\" duration=\"\(sm * 60)\"/>" - } else if let ndl = s.noDecompressionLimit { - x += "<nodecotime>\(n(min(ndl, 999) * 60, 0))</nodecotime>" - } - for e in d.events where e.time == s.time { x += "<alarm>\(alarm(e.warning))</alarm>" } - x += "</waypoint>\n" - } - x += " </samples>\n <informationafterdive>\n" - x += " <greatestdepth>\(n(d.maxDepth))</greatestdepth>\n" - x += " <averagedepth>\(n(d.averageDepth))</averagedepth>\n" - x += " <diveduration>\(n(d.duration, 0))</diveduration>\n" - if let t = d.minTemperature { x += " <lowesttemperature>\(kelvin(t))</lowesttemperature>\n" } - if let notes = d.notes ?? d.site { x += " <notes><para>\(esc(notes))</para></notes>\n" } - x += " </informationafterdive>\n </dive>\n" - } - x += " </repetitiongroup>\n </profiledata>\n</uddf>\n" - return x - } - - static func alarm(_ w: DiveComputer.Warning) -> String { - switch w { - case .ascentFast, .ascentTooFast: "ascent" - case .ceilingViolated: "deco" - case .ppO2High, .ppO2Critical: "error" - case .missedSafetyStop: "deco" - case .depthLimit: "depth" - case .lowNoDecompression: "deco" - } - } -} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/UserSettings.swift b/Packages/RemoraDeco/Sources/RemoraDeco/UserSettings.swift @@ -1,110 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation - -/// Diver settings, as the app saves and displays them. -/// Settings: O2 percentage and water type. Advanced settings: conservatism (including custom gradient -/// factors) and maximum ppO2. Altitude is not a setting: the watch measures the surface pressure. -public struct UserSettings: Sendable, Hashable, Codable { - /// Conservatism levels offered on the main screen (values specific to Open Rémora). - public enum Conservatism: String, Sendable, Hashable, Codable, CaseIterable { - case high // GF 30/70, default - case medium // GF 40/80 - case low // GF 50/85 - case custom // gradient factors entered by the diver - - public var gradientFactors: GradientFactors? { - switch self { - case .high: GradientFactors(low: 0.30, high: 0.70) - case .medium: GradientFactors(low: 0.40, high: 0.80) - case .low: GradientFactors(low: 0.50, high: 0.85) - case .custom: nil - } - } - } - - /// Bounds of the settings (the interface offers nothing outside them). - public enum Limits { - public static let oxygenPercent = 21...40 // air to EAN40: a single gas, 40 m at most - public static let gfLowPercent = 10...100 - public static let gfHighPercent = 50...100 - public static let ppO2Max = 1.2...1.6 - /// NDL alarm: thresholds offered, in minutes (0 = off). - public static let ndlAlarmMinutes = [0, 3, 5, 10, 15] - } - - // Settings - public var oxygenPercent: Int = 21 - public var water: Water = .en13319 - /// Alarm when the NDL (remaining no-stop time) drops below this number of minutes; 0 = off. - public var ndlAlarmMinutes: Int = 5 - - // Advanced settings - public var conservatism: Conservatism = .high - /// Custom gradient factors (in %), used when `conservatism == .custom`. - public var customGFLowPercent: Int = 30 - public var customGFHighPercent: Int = 70 - public var ppO2Max: Double = 1.4 - - public init() {} - - /// Lenient decoding: a missing setting (saved by an older version, or sent by a watch that is not - /// up to date yet) takes its default value instead of making the whole decoding fail. - public init(from decoder: Decoder) throws { - let v = try decoder.container(keyedBy: CodingKeys.self) - let d = UserSettings() - oxygenPercent = try v.decodeIfPresent(Int.self, forKey: .oxygenPercent) ?? d.oxygenPercent - water = try v.decodeIfPresent(Water.self, forKey: .water) ?? d.water - ndlAlarmMinutes = try v.decodeIfPresent(Int.self, forKey: .ndlAlarmMinutes) ?? d.ndlAlarmMinutes - conservatism = try v.decodeIfPresent(Conservatism.self, forKey: .conservatism) ?? d.conservatism - customGFLowPercent = try v.decodeIfPresent(Int.self, forKey: .customGFLowPercent) ?? d.customGFLowPercent - customGFHighPercent = try v.decodeIfPresent(Int.self, forKey: .customGFHighPercent) ?? d.customGFHighPercent - ppO2Max = try v.decodeIfPresent(Double.self, forKey: .ppO2Max) ?? d.ppO2Max - } - - public enum Problem: Error, Hashable, Sendable { - case oxygenOutOfRange - case gfLowOutOfRange, gfHighOutOfRange, gfLowAboveHigh - case ppO2OutOfRange - case ndlAlarmOutOfRange - } - - /// What prevents the settings from being applied (empty = valid). - public var problems: [Problem] { - var p: [Problem] = [] - if !Limits.oxygenPercent.contains(oxygenPercent) { p.append(.oxygenOutOfRange) } - if conservatism == .custom { - if !Limits.gfLowPercent.contains(customGFLowPercent) { p.append(.gfLowOutOfRange) } - if !Limits.gfHighPercent.contains(customGFHighPercent) { p.append(.gfHighOutOfRange) } - if customGFLowPercent > customGFHighPercent { p.append(.gfLowAboveHigh) } - } - if !Limits.ppO2Max.contains(ppO2Max) { p.append(.ppO2OutOfRange) } - if !(0...30).contains(ndlAlarmMinutes) { p.append(.ndlAlarmOutOfRange) } - return p - } - - public var gas: Gas { Gas(o2: Double(oxygenPercent) / 100) } - - public var gradientFactors: GradientFactors { - conservatism.gradientFactors - ?? GradientFactors(low: Double(customGFLowPercent) / 100, high: Double(customGFHighPercent) / 100) - } - - /// Maximum operating depth of the chosen gas (shown next to the percentage). - public func maximumOperatingDepth(surfacePressure: Double = standardSurfacePressure) -> Double { - gas.maximumOperatingDepth(ppO2Limit: ppO2Max, - scale: DepthScale(surfacePressure: surfacePressure, water: water)) - } - - /// Computer configuration; refused when the settings are not valid. - public func configuration() throws -> DiveComputer.Configuration { - if let first = problems.first { throw first } - var c = DiveComputer.Configuration() - c.gas = gas - c.water = water - c.deco.gradientFactors = gradientFactors - c.ppO2Warning = ppO2Max - c.ppO2Alarm = max(1.6, ppO2Max) - c.lowNoDecompression = Double(ndlAlarmMinutes) // 0: never below the threshold, alarm off - return c - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/AltitudeTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/AltitudeTests.swift @@ -1,57 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -/// Surface pressure at a given altitude (standard atmosphere). -func pressure(atAltitude metres: Double) -> Double { - standardSurfacePressure * pow(1 - 2.25577e-5 * metres, 5.25588) -} - -@Suite("Altitude") -struct AltitudeTests { - let lake = pressure(atAltitude: 2000) // ≈ 0.795 bar - - func ndl(surface: Double, tissues: TissueState, depth: Double = 18) -> Double { - let scale = DepthScale(surfacePressure: surface, water: .fresh) - return tissues.noDecompressionLimit(atPressure: scale.pressure(atDepth: depth), gas: .air, - surfacePressure: surface, gfHigh: 0.7) ?? .infinity - } - - @Test func depthIsMeasuredFromLocalSurface() { - let scale = DepthScale(surfacePressure: lake, water: .fresh) - #expect(scale.depth(atPressure: lake) == 0) - #expect(abs(scale.depth(atPressure: lake + 1) - 10.2) < 0.05) - } - - @Test func altitudeShortensNoDecoLimit() { - let sea = ndl(surface: standardSurfacePressure, tissues: .saturated()) - let acclimatised = ndl(surface: lake, tissues: .saturated(surfacePressure: lake)) - #expect(acclimatised < sea) - } - - @Test func freshArrivalIsWorseThanAcclimatised() { - let acclimatised = ndl(surface: lake, tissues: .saturated(surfacePressure: lake)) - let after2h = ndl(surface: lake, tissues: DiveComputer.arrival(to: lake, hoursAgo: 2)) - let after15min = ndl(surface: lake, tissues: DiveComputer.arrival(to: lake, hoursAgo: 0.25)) - let deep15 = ndl(surface: lake, tissues: DiveComputer.arrival(to: lake, hoursAgo: 0.25), depth: 30) - let deep48 = ndl(surface: lake, tissues: DiveComputer.arrival(to: lake, hoursAgo: 48), depth: 30) - print("15 min = \(after15min); 30 m: 15 min = \(deep15), 48 h = \(deep48)") - let after48h = ndl(surface: lake, tissues: DiveComputer.arrival(to: lake, hoursAgo: 48)) - print("NDL 18 m, lake at 2000 m, GF 30/70: arrived 2 h ago = \(after2h), 48 h = \(after48h), acclimatised = \(acclimatised)") - #expect(after15min < after48h) // small effect: ~0.4 min at 18 m - #expect(after2h <= after48h) - #expect(abs(after48h - acclimatised) < 1) - } - - @Test func decoStopsAreAtLocalDepths() { - var c = DiveComputer.Configuration(); c.water = .fresh - let scale = DepthScale(surfacePressure: lake, water: .fresh) - var t = TissueState.saturated(surfacePressure: lake) - t.stay(atPressure: scale.pressure(atDepth: 30), gas: .air, minutes: 25) - let plan = AscentPlanner.plan(tissues: t, pressure: scale.pressure(atDepth: 30), gas: .air, - scale: scale, settings: c.deco) - #expect(plan.inDecompression) - #expect(plan.stops.last?.depth == 3) - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift @@ -1,369 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -let scale = DepthScale(surfacePressure: standardSurfacePressure, water: .salt) - -/// Diver saturated at the surface, dropped instantly to `depth`, then staying there for `minutes`. -func tissues(after minutes: Double, at depth: Double, gas: Gas = .air) -> TissueState { - var t = TissueState.saturated(surfacePressure: scale.surfacePressure) - t.stay(atPressure: scale.pressure(atDepth: depth), gas: gas, minutes: minutes) - return t -} - -func ndl(at depth: Double, gf: GradientFactors, gas: Gas = .air) -> Double? { - TissueState.saturated(surfacePressure: scale.surfacePressure) - .noDecompressionLimit(atPressure: scale.pressure(atDepth: depth), gas: gas, - surfacePressure: scale.surfacePressure, gfHigh: gf.high) -} - -@Suite("Physics") -struct PhysicsTests { - @Test func depthRoundTrip() { - let p = scale.pressure(atDepth: 30) - #expect(abs(scale.depth(atPressure: p) - 30) < 1e-9) - #expect(abs(p - (1.01325 + 30 * 0.10052)) < 0.001) - } - - @Test func maximumOperatingDepth() { - #expect(abs(Gas.air.maximumOperatingDepth(ppO2Limit: 1.4, scale: scale) - 56.2) < 0.1) - #expect(abs(Gas.nitrox(32).maximumOperatingDepth(ppO2Limit: 1.4, scale: scale) - 33.4) < 0.3) - } -} - -@Suite("Tissues") -struct TissueTests { - @Test func surfaceSaturationHasNoCeiling() { - let t = TissueState.saturated(surfacePressure: scale.surfacePressure) - #expect(t.ceiling(gradientFactor: 1) < scale.surfacePressure) - #expect(t.ceiling(gradientFactor: 0.3) < scale.surfacePressure) - #expect(ndl(at: 0, gf: .conservative) == nil) - #expect(ndl(at: 3, gf: .conservative) == nil) - #expect(ndl(at: 6, gf: .conservative)! > 24 * 60) // finite but out of reach (shown as ">99") - } - - @Test func schreinerMatchesFineConstantSteps() { - let start = scale.pressure(atDepth: 0), end = scale.pressure(atDepth: 30) - var exact = TissueState.saturated(), stepped = TissueState.saturated() - exact.change(from: start, to: end, gas: .air, minutes: 2) - let n = 4000 - for i in 0..<n { - let mid = start + (end - start) * (Double(i) + 0.5) / Double(n) - stepped.stay(atPressure: mid, gas: .air, minutes: 2 / Double(n)) - } - for (a, b) in zip(exact.nitrogen, stepped.nitrogen) { #expect(abs(a - b) < 1e-5) } - } - - @Test func schreinerAtConstantPressureIsHaldane() { - let p = scale.pressure(atDepth: 20) - var a = TissueState.saturated(), b = TissueState.saturated() - a.change(from: p, to: p, gas: .air, minutes: 17) - b.stay(atPressure: p, gas: .air, minutes: 17) - for (x, y) in zip(a.nitrogen, b.nitrogen) { #expect(abs(x - y) < 1e-12) } - } - - @Test func surfaceIntervalOffgasses() { - let loaded = tissues(after: 30, at: 25) - let rested = DiveComputer.surfaceInterval(loaded, minutes: 60, surfacePressure: scale.surfacePressure) - for (a, b) in zip(loaded.nitrogen, rested.nitrogen) { #expect(b < a) } - } -} - -@Suite("No-decompression limit") -struct NoDecoTests { - @Test func decreasesWithDepth() throws { - var previous = Double.infinity - for depth in [12.0, 18, 24, 30, 40] { - let v = try #require(ndl(at: depth, gf: .conservative)) - #expect(v < previous) - previous = v - } - } - - @Test func conservativeIsShorterThanPureBuhlmann() throws { - let strict = try #require(ndl(at: 30, gf: .conservative)) - let pure = try #require(ndl(at: 30, gf: .pureBuhlmann)) - #expect(strict < pure) - } - - @Test func nitroxExtendsLimit() throws { - let air = try #require(ndl(at: 30, gf: .conservative)) - let ean32 = try #require(ndl(at: 30, gf: .conservative, gas: .nitrox(32))) - #expect(ean32 > air) - } - - /// Orders of magnitude only: fine validation will be done against Subsurface. - @Test func plausibleValues() throws { - let pure30 = try #require(ndl(at: 30, gf: .pureBuhlmann)) - let pure18 = try #require(ndl(at: 18, gf: .pureBuhlmann)) - print("NDL air, GF 100/100: 18 m = \(pure18) min, 30 m = \(pure30) min") - print("NDL air, GF 30/70: 18 m = \(ndl(at: 18, gf: .conservative)!) min, 30 m = \(ndl(at: 30, gf: .conservative)!) min") - #expect((10...25).contains(pure30)) - #expect((40...70).contains(pure18)) - } - - @Test func limitReachedMeansSurfaceCeiling() throws { - let gf = GradientFactors.conservative - let limit = try #require(ndl(at: 30, gf: gf)) - let t = tissues(after: limit, at: 30) - #expect(abs(t.ceiling(gradientFactor: gf.high) - scale.surfacePressure) < 0.002) - } -} - -@Suite("Decompression stops") -struct DecoPlanTests { - func plan(minutes: Double, depth: Double, settings: DecoSettings = DecoSettings()) -> AscentPlan { - AscentPlanner.plan(tissues: tissues(after: minutes, at: depth), - pressure: scale.pressure(atDepth: depth), gas: .air, - scale: scale, settings: settings) - } - - @Test func noStopsInsideLimit() { - let p = plan(minutes: 5, depth: 18) - #expect(!p.inDecompression) - #expect(p.noDecompressionLimit ?? .infinity > 0) - #expect(abs(p.timeToSurface - 2) < 1e-9) // 18 m at 9 m/min - } - - @Test func decoDiveHasOrderedStops() throws { - let p = plan(minutes: 25, depth: 40) - print("40 m, 25 min, air, GF 30/70:", p.stops.map { "\(Int($0.depth)) m \($0.minutes) min" }, "TTS", p.timeToSurface) - #expect(p.inDecompression) - #expect(p.noDecompressionLimit == 0) - let depths = p.stops.map(\.depth) - #expect(depths == depths.sorted(by: >)) - #expect(depths.allSatisfy { $0.truncatingRemainder(dividingBy: 3) == 0 && $0 >= 3 }) - let first = try #require(depths.first) - #expect((6...24).contains(first)) - #expect(p.gradientAnchorDepth == first) - #expect(p.timeToSurface > 40 / 9) - } - - @Test func followingThePlanAllowsSurfacing() throws { - let settings = DecoSettings() - let p = plan(minutes: 25, depth: 40, settings: settings) - var t = tissues(after: 25, at: 40) - var depth = 40.0 - for stop in p.stops { - t.change(from: scale.pressure(atDepth: depth), to: scale.pressure(atDepth: stop.depth), - gas: .air, minutes: (depth - stop.depth) / settings.ascentRate) - t.stay(atPressure: scale.pressure(atDepth: stop.depth), gas: .air, minutes: Double(stop.minutes)) - depth = stop.depth - } - t.change(from: scale.pressure(atDepth: depth), to: scale.surfacePressure, gas: .air, - minutes: depth / settings.ascentRate) - #expect(t.ceiling(gradientFactor: settings.gradientFactors.high) <= scale.surfacePressure + 1e-6) - } - - @Test func moreConservativeMeansLongerDeco() { - var pure = DecoSettings(); pure.gradientFactors = .pureBuhlmann - let strict = plan(minutes: 25, depth: 40) - let loose = plan(minutes: 25, depth: 40, settings: pure) - #expect(strict.timeToSurface > loose.timeToSurface) - } -} - -@Suite("Dive computer") -struct DiveComputerTests { - /// Profile sampled at 1 Hz: (target depth, rate in m/min or bottom time). - func run(_ computer: inout DiveComputer, from depth: inout Double, to target: Double, - rate: Double, time: inout Double) { - while abs(depth - target) > 1e-9 { - let step = rate / 60 - depth = depth < target ? min(target, depth + step) : max(target, depth - step) - time += 1 - computer.update(time: time, pressure: scale.pressure(atDepth: depth)) - } - } - - func hold(_ computer: inout DiveComputer, at depth: Double, seconds: Int, time: inout Double) { - for _ in 0..<seconds { - time += 1 - computer.update(time: time, pressure: scale.pressure(atDepth: depth)) - } - } - - func makeComputer() -> DiveComputer { - var config = DiveComputer.Configuration() - config.water = .salt - return DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) - } - - @Test func recreationalDive() { - var c = makeComputer() - var t = 0.0, d = 0.0 - c.update(time: 0, pressure: scale.surfacePressure) - run(&c, from: &d, to: 18, rate: 18, time: &t) - hold(&c, at: 18, seconds: 20 * 60, time: &t) - let s = c.status - #expect(abs(s.depth - 18) < 1e-6) - #expect(abs(s.maxDepth - 18) < 1e-6) - #expect(!s.plan.inDecompression) - #expect(s.plan.noDecompressionLimit ?? .infinity > 0) - #expect(s.safetyStopRecommended) - #expect(s.warnings.isEmpty) - #expect(abs(s.elapsed - 21) < 0.02) - } - - @Test func fastAscentIsFlagged() { - var c = makeComputer() - var t = 0.0, d = 0.0 - c.update(time: 0, pressure: scale.surfacePressure) - run(&c, from: &d, to: 20, rate: 18, time: &t) - run(&c, from: &d, to: 14, rate: 18, time: &t) - #expect(c.status.warnings.contains(.ascentTooFast)) - run(&c, from: &d, to: 8, rate: 6, time: &t) - #expect(c.status.warnings.isDisjoint(with: [.ascentFast, .ascentTooFast])) - } - - @Test func decoAnchorsGradientAndFlagsCeiling() throws { - var c = makeComputer() - var t = 0.0, d = 0.0 - c.update(time: 0, pressure: scale.surfacePressure) - run(&c, from: &d, to: 40, rate: 18, time: &t) - hold(&c, at: 40, seconds: 25 * 60, time: &t) - let s = c.status - #expect(s.plan.inDecompression) - let anchor = try #require(c.gradientAnchorDepth) - #expect(anchor == s.plan.stops.first?.depth) - #expect(s.ceilingDepth > 0) - // Direct ascent above the ceiling: alarm. - run(&c, from: &d, to: 0.5, rate: 9, time: &t) - #expect(c.status.warnings.contains(.ceilingViolated)) - } - - @Test func highPpO2() { - var config = DiveComputer.Configuration() - config.gas = .nitrox(36) - config.water = .salt - var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) - c.update(time: 0, pressure: scale.pressure(atDepth: 33)) - #expect(c.status.warnings.contains(.ppO2High)) - c.update(time: 1, pressure: scale.pressure(atDepth: 36)) - #expect(c.status.warnings.contains(.ppO2Critical)) - } -} - -@Suite("Dive screen") -struct DiveScreenEngineTests { - func computer() -> DiveComputer { - var config = DiveComputer.Configuration() - config.water = .salt - return DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) - } - - /// 1 Hz profile: (target depth, rate in m/min, seconds held there). - func run(_ c: inout DiveComputer, _ legs: [(Double, Double, Int)]) { - var t = 0.0, d = 0.0 - c.update(time: 0, pressure: scale.surfacePressure) - for (target, rate, hold) in legs { - while abs(d - target) > 1e-9 { - d = d < target ? min(target, d + rate / 60) : max(target, d - rate / 60) - t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) - } - for _ in 0..<hold { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) } - } - } - - @Test func firstStopHasSecondsCountdown() throws { - let p = AscentPlanner.plan(tissues: tissues(after: 25, at: 40), pressure: scale.pressure(atDepth: 40), - gas: .air, scale: scale, settings: DecoSettings()) - let first = try #require(p.stops.first) - let seconds = try #require(first.seconds) - #expect(seconds % 10 == 0) - #expect(seconds <= first.minutes * 60) // the countdown never exceeds the displayed minute - #expect(seconds > (first.minutes - 1) * 60) - #expect(p.stops.dropFirst().allSatisfy { $0.seconds == nil }) - } - - @Test func safetyStopCountsDownThenDone() { - var c = computer() - run(&c, [(18, 18, 600), (5, 9, 90)]) - guard case .running(let remaining) = c.safetyStop else { Issue.record("expected running: \(c.safetyStop)"); return } - #expect(abs(remaining - 90) < 15) - var d = c - let t0 = 18.0 / 18 * 60 + 600 + 13.0 / 9 * 60 + 90 - for i in 1...120 { d.update(time: t0 + Double(i), pressure: scale.pressure(atDepth: 5)) } - #expect(d.safetyStop == .done) - } - - @Test func skippingSafetyStopIsFlagged() { - var c = computer() - run(&c, [(18, 18, 600), (0, 9, 5)]) - #expect(c.safetyStop == .missed) - #expect(c.status.warnings.contains(.missedSafetyStop)) - } - - @Test func shallowDiveNeedsNoSafetyStop() { - var c = computer() - run(&c, [(8, 18, 600), (0, 9, 5)]) - #expect(c.safetyStop == .notRequired) - #expect(!c.status.warnings.contains(.missedSafetyStop)) - } - - @Test func depthLimitAndLowNoDecoWarnings() { - var c = computer() - run(&c, [(38.5, 18, 5)]) - #expect(c.status.warnings.contains(.depthLimit)) - var l = computer() - run(&l, [(30, 18, 360)]) - let ndl = l.status.plan.noDecompressionLimit ?? 99 - #expect(ndl < 5) - #expect(l.status.warnings.contains(.lowNoDecompression)) - } -} - -@Suite("0.2 review") -struct ReviewTests { - @Test func aboveRequiredStopIsAViolation() { - var config = DiveComputer.Configuration(); config.water = .salt - var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) - var t = 0.0, d = 0.0 - c.update(time: 0, pressure: scale.surfacePressure) - while d < 40 { d = min(40, d + 0.3); t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) } - for _ in 0..<(25 * 60) { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: d)) } - // Continuous ascent at 9 m/min, skipping the stops (the first ones clear on the way up, not the last). - var flagged = false - while d > 1 { - d -= 0.15; t += 1 - c.update(time: t, pressure: scale.pressure(atDepth: d)) - let status = c.status - if let stop = status.plan.stops.first, d < stop.depth - 0.6 { - #expect(status.warnings.contains(.ceilingViolated)) - flagged = true - } - } - #expect(flagged) - } - - @Test func missedSafetyStopCanBeRedone() { - var config = DiveComputer.Configuration(); config.water = .salt - var c = DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) - var t = 0.0 - func at(_ depth: Double, _ seconds: Int) { for _ in 0..<seconds { t += 1; c.update(time: t, pressure: scale.pressure(atDepth: depth)) } } - c.update(time: 0, pressure: scale.surfacePressure) - at(15, 300); at(0.2, 5) - #expect(c.safetyStop == .missed) - at(12, 60) - #expect(c.safetyStop == .pending) - at(5, 181) - #expect(c.safetyStop == .done) - #expect(!c.status.warnings.contains(.missedSafetyStop)) - } - - @Test func oscillatingAlarmIsLoggedOncePerPeriod() { - var config = DiveComputer.Configuration(); config.water = .salt - var r = DiveRecorder(configuration: config, surfacePressure: scale.surfacePressure, - start: Date(timeIntervalSince1970: 1_800_000_000)) - var t = 0.0 - r.record(time: 0, pressure: scale.surfacePressure) - // Around 38 m: above then below the depth limit, every 2 s for 40 s. - for i in 0..<20 { - t += 2 - r.record(time: t, pressure: scale.pressure(atDepth: i % 2 == 0 ? 38.2 : 37.8)) - } - let count = r.finish().events.filter { $0.warning == .depthLimit }.count - #expect(count == 2) // at t=2 s, then once 30 s have passed - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/LogbookTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/LogbookTests.swift @@ -1,108 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -/// Dive simulated at 1 Hz: descent at 18 m/min, bottom time, ascent at 9 m/min, safety stop. -func simulateDive(depth: Double, bottomMinutes: Int, start: Date, logbook: Logbook, - config: DiveComputer.Configuration = DiveComputer.Configuration()) -> DiveLog { - let scale = DepthScale(water: config.water) - var r = DiveRecorder(configuration: config, surfacePressure: scale.surfacePressure, - start: start, logbook: logbook) - var t = 0.0, d = 0.0 - func tick() { t += 1; r.record(time: t, pressure: scale.pressure(atDepth: d), temperature: 18 - d / 4) } - r.record(time: 0, pressure: scale.surfacePressure, temperature: 20) - while d < depth { d = min(depth, d + 18.0 / 60); tick() } - for _ in 0..<(bottomMinutes * 60) { tick() } - while d > 5 { d = max(5, d - 9.0 / 60); tick() } - for _ in 0..<180 { tick() } - while d > 0 { d = max(0, d - 9.0 / 60); tick() } - return r.finish() -} - -@Suite("Logbook") -struct LogbookTests { - let start = Date(timeIntervalSince1970: 1_800_000_000) - - @Test func recordsProfileForTheGraph() throws { - let dive = simulateDive(depth: 18, bottomMinutes: 20, start: start, logbook: Logbook()) - #expect(abs(dive.maxDepth - 18) < 1e-6) - #expect(dive.samples.first?.time == 0) - #expect(dive.samples.last?.depth == 0) - // One sample every 2 s: a 26 min dive → ~780 samples - #expect((770...790).contains(dive.samples.count)) - #expect(zip(dive.samples, dive.samples.dropFirst()).allSatisfy { $1.time > $0.time }) - #expect(abs(dive.duration / 60 - 26.0) < 0.1) - #expect((14...18).contains(dive.averageDepth)) - #expect(dive.minTemperature == 13.5) - #expect(!dive.hadDecompression) - #expect(dive.events.isEmpty) - #expect(dive.violations.isEmpty) - #expect(dive.surfaceIntervalBefore == nil) - } - - @Test func repetitiveDiveInheritsTissues() throws { - var book = Logbook() - let first = simulateDive(depth: 25, bottomMinutes: 20, start: start, logbook: book) - book.add(first) - let second = simulateDive(depth: 18, bottomMinutes: 10, - start: first.end.addingTimeInterval(60 * 60), logbook: book) - book.add(second) - #expect(book.dives.map(\.number) == [1, 2]) - #expect(abs((book.dives[1].surfaceIntervalBefore ?? 0) - 60) < 0.1) - // Shorter no-decompression limit than the same dive done first - let fresh = simulateDive(depth: 18, bottomMinutes: 10, start: start, logbook: Logbook()) - let ndlRepeat = try #require(second.samples.first { abs($0.depth - 18) < 1e-6 }?.noDecompressionLimit) - let ndlFresh = try #require(fresh.samples.first { abs($0.depth - 18) < 1e-6 }?.noDecompressionLimit) - #expect(ndlRepeat < ndlFresh) - } - - @Test func decoDiveIsMarkedAndAlarmsLogged() { - let dive = simulateDive(depth: 40, bottomMinutes: 20, start: start, logbook: Logbook()) - #expect(dive.hadDecompression) - // The simulation ascends without doing the stops: ceiling violated, logged in the events. - #expect(dive.violations.contains { $0.warning == .ceilingViolated }) - } - - @Test func logbookRoundTripsThroughJSON() throws { - var book = Logbook() - var dive = simulateDive(depth: 12, bottomMinutes: 5, start: start, logbook: book) - dive.site = "Lac Memphrémagog" - book.add(dive) - let data = try JSONEncoder().encode(book) - let back = try JSONDecoder().decode(Logbook.self, from: data) - #expect(back == book) - } - - @Test func noFlyFollowsDANRuleAndModel() { - var book = Logbook() - let single = simulateDive(depth: 18, bottomMinutes: 20, start: start, logbook: book) - book.add(single) - let rightAfter = SurfaceAdvice.noFlyHours(logbook: book, at: single.end, surfacePressure: standardSurfacePressure) - #expect(abs(rightAfter - 12) < 0.01) - var decoBook = Logbook() - decoBook.add(simulateDive(depth: 40, bottomMinutes: 20, start: start, logbook: decoBook)) - let afterDeco = SurfaceAdvice.noFlyHours(logbook: decoBook, at: decoBook.dives[0].end, - surfacePressure: standardSurfacePressure) - #expect(afterDeco >= 24) - let mountain = SurfaceAdvice.hoursBeforeAltitude(2500, logbook: decoBook, at: decoBook.dives[0].end, - surfacePressure: standardSurfacePressure) - print("After 40 m × 20 min: flying in \(afterDeco) h, 2500 m pass in \(mountain) h") - #expect(mountain > 0) - } - - @Test func uddfExport() { - var book = Logbook() - var dive = simulateDive(depth: 18, bottomMinutes: 10, start: start, logbook: book) - dive.notes = "Épave <test> & essai" - book.add(dive) - let xml = UDDF.export(book.dives) - #expect(xml.contains("<uddf xmlns=\"http://www.streit.cc/uddf/3.2/\"")) - #expect(xml.contains("<mix id=\"mix1\"><name>Air</name><o2>0.210</o2>")) - #expect(xml.contains("<greatestdepth>18.00</greatestdepth>")) - #expect(xml.contains("Épave &lt;test&gt; &amp; essai")) - #expect(xml.components(separatedBy: "<waypoint>").count - 1 == book.dives[0].samples.count) - // Well-formed XML - #expect((try? XMLDocument(xmlString: xml)) != nil) - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/SampleDiveExportTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/SampleDiveExportTests.swift @@ -1,30 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -/// Builds a test dive in the shared-folder format (JSON + UDDF), to exercise the Sub Rascasse import. -/// Runs only when SAMPLE_DIVE_DIR (output folder) is set. The profile is computed, but `source = remora` so it -/// gets past the simulation filter: the site and notes say clearly that it is a test, to be deleted. -@Suite("Sample dive") -struct SampleDiveExportTests { - static let dir = ProcessInfo.processInfo.environment["SAMPLE_DIVE_DIR"] - - @Test(.enabled(if: dir != nil)) - func writeSampleDive() throws { - let start = ISO8601DateFormatter().date(from: "2026-11-13T15:00:00Z")! - var dive = simulateDive(depth: 18, bottomMinutes: 25, start: start, logbook: Logbook()) - dive.site = "Open Rémora test" - dive.notes = "Test dive generated by the Open Rémora engine to exercise the import (computed profile, not a real dive). Delete it." - dive.number = 1 - #expect(dive.source == .remora) - - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - encoder.outputFormatting = [.sortedKeys] - let base = URL(fileURLWithPath: Self.dir!).appendingPathComponent(dive.id.uuidString) - try encoder.encode(dive).write(to: base.appendingPathExtension("json")) - try UDDF.export([dive]).write(to: base.appendingPathExtension("uddf"), atomically: true, encoding: .utf8) - print("WROTE \(base.path).json and .uddf: \(dive.samples.count) samples, \(dive.maxDepth) m, \(Int(dive.duration / 60)) min") - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/SettingsTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/SettingsTests.swift @@ -1,94 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -@Suite("Settings") -struct SettingsTests { - @Test func defaultsAreAirAndConservative() throws { - let c = try UserSettings().configuration() - #expect(c.gas == .air) - #expect(c.deco.gradientFactors == GradientFactors(low: 0.30, high: 0.70)) - #expect(c.ppO2Warning == 1.4) - } - - @Test func nitroxPercentSetsGasAndMOD() throws { - var s = UserSettings() - s.oxygenPercent = 32 - s.water = .salt - #expect(try s.configuration().gas == .nitrox(32)) - #expect(abs(s.maximumOperatingDepth() - 33.4) < 0.3) - } - - @Test func customGradientFactorsFromAdvancedSettings() throws { - var s = UserSettings() - s.conservatism = .custom - s.customGFLowPercent = 45 - s.customGFHighPercent = 90 - #expect(try s.configuration().deco.gradientFactors == GradientFactors(low: 0.45, high: 0.90)) - s.conservatism = .medium // the advanced values are kept but no longer apply - #expect(try s.configuration().deco.gradientFactors == GradientFactors(low: 0.40, high: 0.80)) - } - - @Test func invalidSettingsAreRefused() { - var s = UserSettings() - s.oxygenPercent = 50 - s.conservatism = .custom - s.customGFLowPercent = 80 - s.customGFHighPercent = 60 - s.ppO2Max = 1.8 - #expect(Set(s.problems) == [.oxygenOutOfRange, .gfLowAboveHigh, .ppO2OutOfRange]) - #expect(throws: UserSettings.Problem.self) { try s.configuration() } - } - - @Test func roundTripsThroughJSON() throws { - var s = UserSettings() - s.oxygenPercent = 36 - s.conservatism = .custom - s.customGFLowPercent = 35 - let data = try JSONEncoder().encode(s) - #expect(try JSONDecoder().decode(UserSettings.self, from: data) == s) - } - - @Test func nitroxShortensDecoAtSameProfile() throws { - func tts(_ o2: Int) throws -> Double { - var s = UserSettings(); s.oxygenPercent = o2 - let c = try s.configuration() - let scale = DepthScale(water: c.water) - var t = TissueState.saturated() - t.stay(atPressure: scale.pressure(atDepth: 28), gas: c.gas, minutes: 40) - return AscentPlanner.plan(tissues: t, pressure: scale.pressure(atDepth: 28), gas: c.gas, - scale: scale, settings: c.deco).timeToSurface - } - #expect(try tts(32) < tts(21)) - } - - @Test func ndlAlarmIsAdjustableAndCanBeOff() throws { - var s = UserSettings() - #expect(try s.configuration().lowNoDecompression == 5) - s.ndlAlarmMinutes = 10 - #expect(try s.configuration().lowNoDecompression == 10) - - func warns(_ minutes: Int) throws -> Bool { - var u = UserSettings(); u.ndlAlarmMinutes = minutes; u.water = .salt - var c = DiveComputer(configuration: try u.configuration(), surfacePressure: standardSurfacePressure) - let scale = c.scale - c.update(time: 0, pressure: scale.surfacePressure) - for t in 1...300 { c.update(time: Double(t), pressure: scale.pressure(atDepth: 30)) } // NDL ≈ 4 min - return c.status.warnings.contains(.lowNoDecompression) - } - #expect(try warns(5)) - #expect(try !warns(3)) - #expect(try !warns(0)) - } - - @Test func olderSavedSettingsStillLoad() throws { - // Settings saved by 0.2 (without the NDL alarm): they must not be lost. - let old = #"{"oxygenPercent":32,"water":"salt","conservatism":"medium","customGFLowPercent":30,"customGFHighPercent":70,"ppO2Max":1.4}"# - let s = try JSONDecoder().decode(UserSettings.self, from: Data(old.utf8)) - #expect(s.oxygenPercent == 32) - #expect(s.water == .salt) - #expect(s.conservatism == .medium) - #expect(s.ndlAlarmMinutes == 5) - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/ShearwaterComparisonTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/ShearwaterComparisonTests.swift @@ -1,140 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -/// Compares the engine with a certified dive computer: replays Shearwater dives (same algorithm, same GF) -/// and checks the no-decompression time and the stops against what the computer displayed. -/// Personal data kept out of the repository: `tools/shearwater_decode.py` produces the JSON, path in SHEARWATER_JSON. -struct ShearwaterDive: Decodable { - struct Sample: Decodable { - let depth: Double - let stop_depth: Int - let tts: Int - let o2: Int - let ndl_or_stop: Int - let ceiling: Int - } - let number: String? - let site: String? - let date: String - let gf_low: Int - let gf_high: Int - let surface_mbar: Int - let sample_ms: Int - let samples: [Sample] -} - -@Suite("Shearwater comparison") -struct ShearwaterComparisonTests { - static let path = ProcessInfo.processInfo.environment["SHEARWATER_JSON"] - - @Test(.enabled(if: path != nil)) - func replayAgainstShearwater() throws { - let dives = try JSONDecoder().decode([ShearwaterDive].self, - from: Data(contentsOf: URL(fileURLWithPath: Self.path!))) - let dates = DateFormatter() - dates.locale = Locale(identifier: "en_US_POSIX") - dates.timeZone = TimeZone(secondsFromGMT: 0) - dates.dateFormat = "yyyy-MM-dd HH:mm:ss" - - var previous: (end: Date, tissues: TissueState)? - var allNDL: [Double] = [] - var zeroEarly = 0, liberal = 0 - var shortNDL: [Double] = [] // when the Shearwater shows 30 min or less: where it matters - for dive in dives { - let start = try #require(dates.date(from: dive.date)) - let surface = Double(dive.surface_mbar) / 1000 - let step = Double(dive.sample_ms) / 1000 - - var config = DiveComputer.Configuration() - config.gas = Gas(o2: Double(dive.samples[0].o2) / 100) - config.water = .en13319 - config.deco.gradientFactors = GradientFactors(low: Double(dive.gf_low) / 100, high: Double(dive.gf_high) / 100) - config.deco.ascentRate = 10 - - var tissues: TissueState? - var interval: Double? - if let p = previous, start.timeIntervalSince(p.end) < 48 * 3600 { - interval = start.timeIntervalSince(p.end) / 60 - tissues = DiveComputer.surfaceInterval(p.tissues, minutes: interval!, surfacePressure: surface) - } - var computer = DiveComputer(configuration: config, surfacePressure: surface, tissues: tissues) - computer.update(time: 0, pressure: surface) - - var ndlDiffs: [Double] = [] - var stopRows: [String] = [] - var firstDeco: String? - var decoStats = (both: 0, sameDepth: 0, minuteDiffs: [Double](), ttsDiffs: [Double](), onlyTheirs: 0, onlyOurs: 0) - var enter: (theirs: Double?, ours: Double?) = (nil, nil) - var leave: (theirs: Double?, ours: Double?) = (nil, nil) - for (i, s) in dive.samples.enumerated() { - computer.update(time: Double(i + 1) * step, pressure: computer.scale.pressure(atDepth: s.depth)) - let plan = computer.status.plan - if s.stop_depth == 0, s.ndl_or_stop > 0, s.ndl_or_stop < 99, s.depth > 9, !plan.inDecompression { - let diff = floor(plan.noDecompressionLimit ?? 99) - Double(s.ndl_or_stop) - ndlDiffs.append(diff) - if s.ndl_or_stop <= 30 { shortNDL.append(diff) } - if s.ndl_or_stop >= 5, (plan.noDecompressionLimit ?? 99) < 1 { zeroEarly += 1 } - if s.ndl_or_stop <= 30, diff >= 5 { liberal += 1 } - if s.ndl_or_stop <= 30, abs(diff) >= 5, i % 6 == 0 { - print(" diff t=\(Int(Double(i + 1) * step / 60))' \(s.depth) m: Shearwater \(s.ndl_or_stop) min, Rémora \(Int(plan.noDecompressionLimit ?? 99)) min") - } - } - let minute = Double(i + 1) * step / 60 - if s.stop_depth > 0 { if enter.theirs == nil { enter.theirs = minute }; leave.theirs = minute } - if plan.inDecompression { if enter.ours == nil { enter.ours = minute }; leave.ours = minute } - if s.stop_depth > 0, let stop = plan.stops.first { - decoStats.both += 1 - if Int(stop.depth) == s.stop_depth { - decoStats.sameDepth += 1 - decoStats.minuteDiffs.append(Double(stop.minutes - s.ndl_or_stop)) - } - decoStats.ttsDiffs.append(plan.timeToSurface.rounded(.up) - Double(s.tts)) - } else if s.stop_depth > 0 { decoStats.onlyTheirs += 1 } else if plan.inDecompression { decoStats.onlyOurs += 1 } - if s.stop_depth > 0 || plan.inDecompression { - let ours = plan.stops.first.map { "\(Int($0.depth)) m \($0.minutes) min, surface \(Int(plan.timeToSurface.rounded(.up)))" } ?? "none" - let theirs = s.stop_depth > 0 ? "\(s.stop_depth) m \(s.ndl_or_stop) min, surface \(s.tts)" : "none" - if firstDeco == nil { firstDeco = "t=\(Int(Double(i + 1) * step / 60)) min" } - if i % 12 == 0 { stopRows.append(" t=\(Int(Double(i + 1) * step / 60))' \(s.depth) m | Shearwater \(theirs) | Rémora \(ours)") } - } - } - allNDL.append(contentsOf: ndlDiffs) - let mean = ndlDiffs.isEmpty ? 0 : ndlDiffs.reduce(0, +) / Double(ndlDiffs.count) - let worst = ndlDiffs.map { abs($0) }.max() ?? 0 - print("Dive \(dive.number ?? "?") \(dive.site ?? "") GF \(dive.gf_low)/\(dive.gf_high) O2 \(dive.samples[0].o2)%" - + (interval.map { " (interval \(Int($0)) min)" } ?? "") - + String(format: ": no-deco, %d samples, mean diff %+.1f min, worst %.0f min", ndlDiffs.count, mean, worst)) - if enter.theirs != nil || enter.ours != nil { - func f(_ v: Double?) -> String { v.map { String(format: "%.1f", $0) } ?? "never" } - let m = decoStats.minuteDiffs - let t = decoStats.ttsDiffs - print(" DECO: entered Shearwater \(f(enter.theirs)) min, Rémora \(f(enter.ours)) min; left \(f(leave.theirs)) / \(f(leave.ours)) min") - print(String(format: " DECO: %d samples in common, same depth %d, stop time %+.2f min on average (worst %+.0f), surface %+.1f min; Shearwater only %d samples, Rémora only %d samples", - decoStats.both, decoStats.sameDepth, m.isEmpty ? 0 : m.reduce(0, +) / Double(m.count), - m.max(by: { abs($0) < abs($1) }) ?? 0, t.isEmpty ? 0 : t.reduce(0, +) / Double(t.count), - decoStats.onlyTheirs, decoStats.onlyOurs)) - } - - let duration = Double(dive.samples.count) * step - previous = (start.addingTimeInterval(duration), computer.tissues) - } - let mean = allNDL.reduce(0, +) / Double(max(1, allNDL.count)) - let meanAbs = allNDL.map { abs($0) }.reduce(0, +) / Double(max(1, allNDL.count)) - print(String(format: "TOTAL no-deco: %d samples, mean diff %+.2f min, mean absolute diff %.2f min", allNDL.count, mean, meanAbs)) - let shortMean = shortNDL.reduce(0, +) / Double(max(1, shortNDL.count)) - let shortAbs = shortNDL.map { abs($0) }.reduce(0, +) / Double(max(1, shortNDL.count)) - let within2 = Double(shortNDL.filter { abs($0) <= 2 }.count) / Double(max(1, shortNDL.count)) * 100 - print(String(format: "SHORT (Shearwater ≤ 30 min): %d samples, mean diff %+.2f min, mean absolute %.2f min, worst %.0f min, %.0f%% within 2 min", - shortNDL.count, shortMean, shortAbs, shortNDL.map { abs($0) }.max() ?? 0, within2)) - // Result of 2026-11-13 (10 dives from a Petrel 3): stops identical to within one minute. - // No-decompression time, when the Shearwater shows 30 min or less, depending on the ascent off-gassing credit: - // no credit : -1.8 min on average, 77% within 2 min, 44 samples at zero too early; - // credit at 30 m/min : -0.3 min, 88% within 2 min, 7 samples at zero too early ← chosen (noStopAscentRate); - // credit at 18 m/min : +0.6 min (less conservative than the Shearwater): rejected. - #expect(meanAbs < 3) - #expect(shortAbs < 2) - #expect(shortMean < 0, "the engine must stay on the conservative side of the Shearwater") - #expect(zeroEarly < 15) - } -} diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/SubsurfaceImportTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/SubsurfaceImportTests.swift @@ -1,93 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import Testing -@testable import RemoraDeco - -let sampleLog = """ -<divelog program='subsurface' version='3'> -<settings> -<divecomputerid model='Shearwater Perdix' deviceid='1234'/> -</settings> -<divesites> -<site uuid='4c2e7d10' name='Carrière Morrison' gps='45.628300 -75.923900'> -</site> -</divesites> -<dives> -<trip date='2026-07-12' time='10:15:00' location='Wakefield'> -<dive number='41' divesiteid='4c2e7d10' date='2026-07-12' time='10:15:00' duration='38:20 min'> - <notes>Visibilité 8 m &amp; thermocline à 9 m</notes> - <cylinder size='11.1 l' workpressure='207.0 bar' description='AL80' o2='32.0%' start='200.0 bar' end='70.0 bar'/> - <divecomputer model='Shearwater Perdix' deviceid='1234' diveid='abcd'> - <depth max='24.3 m' mean='14.1 m' /> - <temperature water='9.0 C' /> - <surface pressure='0.998 bar' /> - <water salinity='1000 g/l' /> - <sample time='0:10 min' depth='1.5 m' temp='21.0 C' ndl='99:00 min' /> - <sample time='2:00 min' depth='24.3 m' temp='9.0 C' ndl='18:00 min' /> - <sample time='25:00 min' depth='24.3 m' in_deco='1' stoptime='2:00 min' stopdepth='3.0 m' /> - <sample time='33:00 min' depth='3.0 m' in_deco='0' ndl='99:00 min' /> - <sample time='38:20 min' depth='0.0 m' /> - </divecomputer> - <divecomputer model='Second ordinateur'> - <sample time='0:10 min' depth='99.0 m' /> - </divecomputer> -</dive> -</trip> -<dive number='40' date='2026-06-01' time='14:00:00' duration='45:00 min'> - <location>Lac</location> -</dive> -</dives> -</divelog> -""" - -@Suite("Subsurface import") -struct SubsurfaceImportTests { - @Test func parsesDivesSitesAndProfile() throws { - let dives = try SubsurfaceImport.dives(from: Data(sampleLog.utf8)) - #expect(dives.map(\.number) == [40, 41]) - let d = dives[1] - #expect(d.source == .subsurface) - #expect(d.computerModel == "Shearwater Perdix") - #expect(d.site == "Carrière Morrison") - #expect(d.latitude == 45.6283) - #expect(d.notes == "Visibilité 8 m & thermocline à 9 m") - #expect(d.gas == .nitrox(32)) - #expect(d.water == .fresh) - #expect(d.surfacePressure == 0.998) - #expect(d.samples.count == 5) // first dive computer only - #expect(d.maxDepth == 24.3) - #expect(d.duration == 38 * 60 + 20) - #expect(d.minTemperature == 9) - #expect(d.samples[2].temperature == 9) // temperature carries forward - #expect(d.hadDecompression) - #expect(d.samples[2].stopDepth == 3 && d.samples[2].stopMinutes == 2) - #expect(d.samples[3].stopDepth == nil) - #expect(d.tissuesAfter == nil) - } - - @Test func diveWithoutProfileKeepsDuration() throws { - let d = try SubsurfaceImport.dives(from: Data(sampleLog.utf8))[0] - #expect(d.duration == 45 * 60) - #expect(d.site == "Lac") - } - - @Test func mergeIsIdempotentAndKeepsNumbers() throws { - let dives = try SubsurfaceImport.dives(from: Data(sampleLog.utf8)) - var book = Logbook() - #expect(book.merge(dives) == 2) - #expect(book.merge(try SubsurfaceImport.dives(from: Data(sampleLog.utf8))) == 0) - let mine = simulateDive(depth: 12, bottomMinutes: 5, - start: Date(timeIntervalSince1970: 1_800_000_000), logbook: book) - book.add(mine) - #expect(book.dives.map(\.number) == [40, 41, 42]) - // Tissues come from the last Open Rémora dive, not from the imported ones. - #expect(book.tissues(at: book.dives[2].end.addingTimeInterval(600), - surfacePressure: standardSurfacePressure) != nil) - } - - @Test func rejectsOtherXML() { - #expect(throws: SubsurfaceImport.Failure.self) { - try SubsurfaceImport.dives(from: Data("<uddf></uddf>".utf8)) - } - } -} diff --git a/README.md b/README.md @@ -27,18 +27,21 @@ The depth sensor entitlement granted by default stops at about 6 m; the 40 m ent ## Layout -- `Packages/RemoraDeco`: the decompression engine, logbook model, UDDF export and Subsurface import. Pure Swift, - no user interface, tested on its own. -- `OpenRemoraWatch`: the watch app (sensor, dive session, screens, logbook, settings). +- RemoraKit, a separate repository checked out next to this one (`../remora-kit`), shared with other apps: + `RemoraDeco` (decompression engine, logbook model, UDDF export, Subsurface import, and the dive logic: start + on submersion, depth held when the reading is missing, alarms, end at the surface) and `RemoraUI` (formatting, + wording, alarm styling, settings screens, dive read-outs, terms). +- `OpenRemoraWatch`: the watch app (sensor, haptics, workout and dive session, Action button, screens, logbook). - `OpenRemora`: the iPhone companion app. `OpenRemoraWidgets`: its Live Activity. -- `Shared`: sources compiled into several targets (formatting, sync contract, terms). +- `Shared`: sources compiled into several targets (sync contract with the iPhone and Sub Rascasse, Live Activity). - `docs/DESIGN.md` (design notes), `docs/SHARING.md` (contract with Sub Rascasse), `docs/VALIDATION.md` (validation of the engine against a Shearwater Petrel 3). - `tools`: icon generator and scripts used for the Shearwater comparison. English is the source language. The French translation is in the String Catalogs (`OpenRemora/Localizable.xcstrings`, `OpenRemoraWatch/Localizable.xcstrings`, -`OpenRemoraWidgets/Localizable.xcstrings`, `OpenRemoraWatch/InfoPlist.xcstrings`). +`OpenRemoraWidgets/Localizable.xcstrings`, `OpenRemoraWatch/InfoPlist.xcstrings`); the texts that come from +RemoraUI are in that package's own catalog. Some names stay in French on purpose because they are stored data or a contract with other apps: the files `carnet.json` and `reglages.json` on the watch, `plongees.json` and `reglages-montre.json` on the iPhone, and the @@ -46,21 +49,27 @@ shared folder `OpenRemora/Plongees/` of the app group `group.org.schurger.dive`. ## Build and test -Requirements: Xcode 16 or later (Swift 6) and [XcodeGen](https://github.com/yonaskolb/XcodeGen). +Requirements: Xcode 16 or later (Swift 6), [XcodeGen](https://github.com/yonaskolb/XcodeGen), and the RemoraKit +repository checked out as a sibling directory named `remora-kit`: + + some-directory/ + open-remora/ (this repository) + remora-kit/ (RemoraKit) On a Mac: - cd Packages/RemoraDeco && swift test # decompression engine, 51 tests - xcodegen # generates OpenRemora.xcodeproj from project.yml + cd ../remora-kit && swift test # engine, dive logic and formatting tests + cd ../open-remora && xcodegen # generates OpenRemora.xcodeproj from project.yml open OpenRemora.xcodeproj `project.yml` is the source of truth; the `.xcodeproj` is not versioned. The Makefile assumes the author's setup: the sources are edited on a Linux host and synced with `rsync` to a Mac -reachable over SSH as `chunga`, which runs Swift and Xcode. Set `CHUNGA` (the SSH host) and `REMOTE` (the directory -on the Mac) to adapt it: +reachable over SSH as `chunga`, which runs Swift and Xcode. Every target syncs both this repository and RemoraKit +(`KIT`, `../remora-kit` by default) so that they are siblings on the Mac too. Set `CHUNGA` (the SSH host), `REMOTE` +(the directory on the Mac) and, if needed, `KIT` and `REMOTE_KIT` to adapt it: - make test-deco # swift test in Packages/RemoraDeco + make test-deco # swift test in RemoraKit make build-watch # watch app, watchOS simulator, unsigned make build-phone # iPhone app with its widget and the watch app, iOS simulator, unsigned make build-watch CHUNGA=my-mac REMOTE=src/open-remora @@ -70,7 +79,7 @@ setup. Launch arguments used for screenshots and dry runs: `-demo` (demo logbook, simulated compass), `-simulate` (accelerated demo dive; with `-deep`, `-slow`), `-ready`, `-showDive`, `-showProfile`, `-page2`, `-page3`, -`-testAlarm`, `-acceptTerms`, and `-liveActivity` on the iPhone. +`-testAlarm`, `-showSettings`, `-showAdvancedSettings`, `-acceptTerms`, and `-liveActivity` on the iPhone. ## License diff --git a/Shared/DemoProfile.swift b/Shared/DemoProfile.swift @@ -1,44 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import Foundation -import RemoraDeco - -/// Simulated profiles: dry demo and screenshots. -struct DemoProfile { - /// Segments: target depth (m), rate to get there (m/min), then time spent there (s). - var segments: [(depth: Double, rate: Double, hold: Double)] - - static let shallow = DemoProfile(segments: [(8, 15, 600), (5, 6, 180), (0, 8, 0)]) - static let reef = DemoProfile(segments: [(22, 18, 720), (12, 16, 300), (5, 8, 180), (0, 8, 0)]) - static let deep = DemoProfile(segments: [(38, 20, 780), (15, 9, 120), (6, 9, 300), (0, 9, 0)]) - - /// Depth at every second, including the return to the surface. - var depths: [Double] { - var out: [Double] = [0] - var d = 0.0 - for s in segments { - while abs(d - s.depth) > 1e-9 { - let step = s.rate / 60 - d = d < s.depth ? min(s.depth, d + step) : max(s.depth, d - step) - out.append(d) - } - out.append(contentsOf: Array(repeating: d, count: Int(s.hold))) - } - return out - } - - static func temperature(atDepth depth: Double) -> Double { 21 - min(depth, 30) * 0.4 } - - /// Records the whole profile at once (demo logbook). - @MainActor - func record(start: Date, settings: UserSettings, logbook: Logbook) -> DiveLog { - let configuration = (try? settings.configuration()) ?? DiveComputer.Configuration() - var recorder = DiveRecorder(configuration: configuration, surfacePressure: standardSurfacePressure, - start: start, logbook: logbook) - let scale = recorder.computer.scale - for (t, d) in depths.enumerated() { - recorder.record(time: Double(t), pressure: scale.pressure(atDepth: d), - temperature: Self.temperature(atDepth: d)) - } - return recorder.finish() - } -} diff --git a/Shared/Format.swift b/Shared/Format.swift @@ -1,91 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import SwiftUI -import RemoraDeco - -enum Format { - /// Language the app runs in. The French interface keeps the decimal comma and the date style it always had. - static let isFrench = Bundle.main.preferredLocalizations.first?.hasPrefix("fr") ?? false - private static let locale: Locale = { - if isFrench { return Locale(identifier: "fr_CA") } - return Locale.current.language.languageCode == .english ? Locale.current : Locale(identifier: "en_US") - }() - - /// Fixed number of decimals, with the decimal separator of the interface language. - static func decimal(_ value: Double, digits: Int) -> String { - let s = String(format: "%.\(digits)f", value) - return isFrench ? s.replacingOccurrences(of: ".", with: ",") : s - } - - static func depth(_ metres: Double) -> String { decimal(metres, digits: 1) } - - /// Seconds → "12:34" (or "1:02:03"). - static func clock(_ seconds: Double) -> String { - let s = Int(seconds.rounded()) - return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60) - : String(format: "%d:%02d", s / 60, s % 60) - } - - static func minutes(_ seconds: Double) -> String { "\(Int((seconds / 60).rounded())) min" } - - /// Waiting time in hours → "3 h 05" (or "45 min"). - static func hours(_ h: Double) -> String { - let total = Int((h * 60).rounded(.up)) - return total >= 60 ? "\(total / 60) h \(String(format: "%02d", total % 60))" : "\(total) min" - } - - static func percent(_ value: Int) -> String { String(localized: "\(value)%") } - - static func ndl(_ minutes: Double?) -> String { - guard let minutes else { return ">99" } - return minutes > 99 ? ">99" : "\(Int(minutes))" - } - - static func day(_ date: Date) -> String { - date.formatted(.dateTime.day().month(.abbreviated).year().locale(locale)) - } - - static func dayTime(_ date: Date) -> String { - date.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(locale)) - } -} - -extension DiveComputer.Warning { - var label: String { - switch self { - case .ascentFast: String(localized: "Fast ascent") - case .ascentTooFast: String(localized: "Ascent too fast") - case .ceilingViolated: String(localized: "Ceiling broken") - case .ppO2High: String(localized: "High ppO2") - case .ppO2Critical: String(localized: "Critical ppO2") - case .missedSafetyStop: String(localized: "Safety stop missed") - case .depthLimit: String(localized: "Depth limit") - case .lowNoDecompression: String(localized: "Low NDL") - } - } - - var isViolation: Bool { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains(self) } - var color: Color { isViolation ? .red : .orange } - /// Most serious first. - var rank: Int { isViolation ? 0 : 1 } -} - -extension Water { - var label: String { - switch self { - case .fresh: String(localized: "Fresh") - case .en13319: String(localized: "Standard (EN 13319)") - case .salt: String(localized: "Salt") - } - } -} - -extension UserSettings.Conservatism { - var label: String { - switch self { - case .high: String(localized: "High (GF 30/70)") - case .medium: String(localized: "Medium (GF 40/80)") - case .low: String(localized: "Low (GF 50/85)") - case .custom: String(localized: "Custom") - } - } -} diff --git a/Shared/PhoneSync.swift b/Shared/PhoneSync.swift @@ -1,6 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only import Foundation import RemoraDeco +import RemoraUI /// What the watch sends to the iPhone (WatchConnectivity). The watch is the only source: /// the iPhone shows the settings and stores the dives, it sends nothing back. @@ -34,21 +35,12 @@ enum SharedFolder { static let outboxPath = "OpenRemora/Plongees" } -/// Warning to accept at first launch, on the watch as on the iPhone. +/// Warning to accept at first launch, on the watch as on the iPhone (text and view come from RemoraUI). /// Changing `version` makes the user accept it again. -enum Terms { - static let version = 1 - static let acceptedKey = "termsAcceptedVersion" - - static let title = String(localized: "Before you dive") - static let points = [ - String(localized: "Open Rémora is not a certified dive computer."), - String(localized: "Always dive with a primary dive computer, and follow it when the two disagree."), - String(localized: "No computation guarantees the absence of decompression sickness."), - String(localized: "The watch can fail or measure wrongly during the dive."), - String(localized: "Dive within the limits of your training. You are responsible for your settings and your gas."), - ] - static let accept = String(localized: "I understand and accept") +enum AppTerms { static let link = URL(string: "https://agora.schurger.org/open-remora/")! static let privacy = URL(string: "https://agora.schurger.org/open-remora/confidentialite/")! + static let terms = Terms(version: 1, acceptedKey: "termsAcceptedVersion", appName: "Open Rémora", + devicePoint: String(localized: "The watch can fail or measure wrongly during the dive."), + link: link) } diff --git a/Shared/TermsView.swift b/Shared/TermsView.swift @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -import SwiftUI - -/// Warning to accept at first launch (and after a change of `Terms.version`). -struct TermsView: View { - let onAccept: () -> Void - - var body: some View { - ScrollView { - VStack(alignment: .leading, spacing: 10) { - Label(Terms.title, systemImage: "exclamationmark.triangle.fill") - .font(.headline) - .foregroundStyle(.orange) - ForEach(Terms.points, id: \.self) { point in - HStack(alignment: .firstTextBaseline, spacing: 6) { - Text("•") - Text(point).fixedSize(horizontal: false, vertical: true) - } - .font(.footnote) - } - Link("Terms of use", destination: Terms.link) - .font(.footnote) - Button(Terms.accept, action: onAccept) - .buttonStyle(.borderedProminent) - .tint(.orange) - .padding(.top, 4) - } - .padding() - } - } -} - -extension View { - /// Shows `TermsView` until the current version has been accepted. - func requiresTerms() -> some View { modifier(TermsGate()) } -} - -private struct TermsGate: ViewModifier { - @AppStorage(Terms.acceptedKey) private var accepted = 0 - - func body(content: Content) -> some View { - if accepted >= Terms.version || CommandLine.arguments.contains("-acceptTerms") { - content - } else { - TermsView { accepted = Terms.version } - } - } -} diff --git a/docs/DESIGN.md b/docs/DESIGN.md @@ -14,7 +14,7 @@ possibly a merge at the surface (profile from the watch + timestamped photos fro - References: <https://developer.apple.com/documentation/coremotion/accessing-submersion-data>, existing apps Oceanic+, Mares, DiveCore. -## Engine (`Packages/RemoraDeco`, pure Swift, tested on chunga with `make test-deco`) +## Engine (`RemoraDeco` in the RemoraKit repository, pure Swift, tested on chunga with `make test-deco`) - Bühlmann ZHL-16C, nitrogen only (air and nitrox; no helium: 40 m at most), Baker gradient factors, **GF 30/70 by default**. Haldane equation (constant depth) and Schreiner equation (between diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md @@ -6,7 +6,7 @@ full *Submerged Depth and Pressure* entitlement (40 m). The design notes are in ## Summary Open Rémora is a **backup** dive computer for Apple Watch Ultra. Its decompression engine -(Swift package `RemoraDeco`) implements Bühlmann ZHL-16C with gradient factors, the same +(`RemoraDeco`, in the RemoraKit repository) implements Bühlmann ZHL-16C with gradient factors, the same algorithm family as Shearwater dive computers. We replayed ten real dives logged by a **Shearwater Petrel 3** through the engine, with the same gradient factors, gas and surface pressure, and compared what the engine would have displayed to what the Petrel displayed, diff --git a/project.yml b/project.yml @@ -7,9 +7,10 @@ options: deploymentTarget: iOS: "17.0" watchOS: "11.0" +# RemoraKit (engine, dive logic, shared interface) is a separate repository, checked out next to this one. packages: - RemoraDeco: - path: Packages/RemoraDeco + RemoraKit: + path: ../remora-kit settings: base: DEVELOPMENT_TEAM: CM5RQKJH56 @@ -30,7 +31,10 @@ targets: - target: OpenRemoraWatch - target: OpenRemoraWidgets embed: true - - package: RemoraDeco + - package: RemoraKit + product: RemoraDeco + - package: RemoraKit + product: RemoraUI settings: base: PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openremora @@ -88,7 +92,10 @@ targets: - path: OpenRemoraWatch - path: Shared dependencies: - - package: RemoraDeco + - package: RemoraKit + product: RemoraDeco + - package: RemoraKit + product: RemoraUI settings: base: PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openremora.watchkitapp