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 7031b76ef679f351534c51c417b8d5fcd49daf50
parent 7ef9a9cc9083f40cecad3aae75b05888ce163309
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 23:53:50 -0500

Three-page dive screen (crown): ascent rate scale, countdown for stops and the safety stop, details, compass with heading; reduced display with the wrist down; depth limit, short no-stop time and missed safety stop alarms; compass from the home screen

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

Diffstat:
AOpenRemoraWatch/Compass.swift | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MOpenRemoraWatch/DiveSession.swift | 10++++++++++
MOpenRemoraWatch/DiveView.swift | 249+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
MOpenRemoraWatch/OpenRemoraApp.swift | 2++
MOpenRemoraWatch/RootView.swift | 6+++++-
MPackages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift | 22+++++++++++++++++++++-
MPackages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift | 48+++++++++++++++++++++++++++++++++++++++++++++++-
MPackages/RemoraDeco/Sources/RemoraDeco/UDDF.swift | 2++
MPackages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MShared/Format.swift | 2++
10 files changed, 533 insertions(+), 59 deletions(-)

diff --git a/OpenRemoraWatch/Compass.swift b/OpenRemoraWatch/Compass.swift @@ -0,0 +1,182 @@ +import Foundation +import Observation +@preconcurrency import CoreLocation +import SwiftUI + +/// Boussole de la montre (magnétomètre, cap magnétique) et cap à suivre. +@MainActor @Observable +final class Compass: NSObject, CLLocationManagerDelegate { + /// Cap magnétique en degrés (0 = nord), nil tant que la montre n'en donne pas. + private(set) var heading: Double? + /// Précision annoncée par la montre, en degrés (négative = calibrage nécessaire). + private(set) var accuracy: Double? + /// Cap à suivre, posé par le plongeur. + var bearing: Double? + + private let manager = CLLocationManager() + private var users = 0 + + static var isAvailable: Bool { CLLocationManager.headingAvailable() || isDemo } + /// Captures d'écran (`-demo`) : cap fixe simulé, le simulateur n'a pas de boussole. + static let isDemo = CommandLine.arguments.contains("-demo") + + override init() { + super.init() + manager.delegate = self + manager.headingFilter = 1 + if Self.isDemo { + heading = 237 + accuracy = 5 + bearing = 250 + } + } + + /// Plusieurs vues peuvent la demander : elle tourne tant qu'au moins une est affichée. + func start() { + users += 1 + if users == 1, Self.isAvailable { manager.startUpdatingHeading() } + } + + func stop() { + users = max(0, users - 1) + if users == 0 { manager.stopUpdatingHeading() } + } + + func setBearing() { bearing = heading } + func clearBearing() { bearing = nil } + + /// Écart signé vers le cap (négatif = tourner à gauche), en degrés. + var offset: Double? { + guard let heading, let bearing else { return nil } + var d = (bearing - heading).truncatingRemainder(dividingBy: 360) + if d > 180 { d -= 360 } + if d < -180 { d += 360 } + return d + } + + static func cardinal(_ degrees: Double) -> String { + let names = ["N", "NE", "E", "SE", "S", "SO", "O", "NO"] + return names[Int(((degrees + 22.5).truncatingRemainder(dividingBy: 360)) / 45) % 8] + } + + nonisolated func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { + let value = newHeading.magneticHeading + let accuracy = newHeading.headingAccuracy + Task { @MainActor in + self.heading = value + self.accuracy = accuracy + } + } + + nonisolated func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool { true } +} + +/// Rose des vents qui tourne avec la montre ; repère fixe en haut ; cap posé en orange. +struct CompassView: View { + @Environment(Compass.self) private var compass + var compact = false + + var body: some View { + VStack(spacing: 2) { + if !Compass.isAvailable { + Label("Pas de boussole sur cette montre", systemImage: "location.slash").font(.footnote) + } else if let heading = compass.heading { + ZStack { + Dial(bearing: compass.bearing).rotationEffect(.degrees(-heading)) + // Repère fixe : la direction de la montre. + Triangle().fill(.red).frame(width: 12, height: 10).offset(y: compact ? -52 : -66) + VStack(spacing: 0) { + Text("\(Int(heading.rounded()) % 360)°") + .font(.system(size: compact ? 26 : 32, weight: .semibold, design: .rounded)) + .monospacedDigit() + Text(Compass.cardinal(heading)).font(.footnote).foregroundStyle(.secondary) + } + } + .frame(width: compact ? 120 : 150, height: compact ? 120 : 150) + if let offset = compass.offset, let bearing = compass.bearing { + HStack(spacing: 4) { + Image(systemName: abs(offset) < 5 ? "checkmark" : (offset < 0 ? "arrow.left" : "arrow.right")) + Text("cap \(Int(bearing.rounded()) % 360)° · \(Int(abs(offset).rounded()))°") + } + .font(.footnote.bold()) + .foregroundStyle(abs(offset) < 5 ? .green : .orange) + } + if let accuracy = compass.accuracy, accuracy < 0 || accuracy > 20 { + Text("Précision faible : faites un 8 avec le poignet").font(.caption2).foregroundStyle(.orange) + } + } else { + ProgressView() + Text("Boussole…").font(.footnote).foregroundStyle(.secondary) + } + } + .onAppear { compass.start() } + .onDisappear { compass.stop() } + } +} + +private struct Dial: View { + let bearing: Double? + + var body: some View { + Canvas { context, size in + let c = CGPoint(x: size.width / 2, y: size.height / 2) + let r = min(size.width, size.height) / 2 - 2 + for i in stride(from: 0, to: 360, by: 10) { + let a = Angle.degrees(Double(i) - 90).radians + let long = i % 90 == 0, mid = i % 30 == 0 + let inner = r - (long ? 12 : mid ? 8 : 4) + var tick = Path() + tick.move(to: CGPoint(x: c.x + inner * cos(a), y: c.y + inner * sin(a))) + tick.addLine(to: CGPoint(x: c.x + r * cos(a), y: c.y + r * sin(a))) + context.stroke(tick, with: .color(i == 0 ? .red : .gray), lineWidth: long ? 2.5 : 1) + } + for (label, deg) in [("N", 0.0), ("E", 90.0), ("S", 180.0), ("O", 270.0)] { + let a = Angle.degrees(deg - 90).radians + let p = CGPoint(x: c.x + (r - 22) * cos(a), y: c.y + (r - 22) * sin(a)) + context.draw(Text(label).font(.system(size: 11, weight: .bold)).foregroundColor(label == "N" ? .red : .white), at: p) + } + if let bearing { + let a = Angle.degrees(bearing - 90).radians + let p = CGPoint(x: c.x + (r + 1) * cos(a), y: c.y + (r + 1) * sin(a)) + context.fill(Path(ellipseIn: CGRect(x: p.x - 5, y: p.y - 5, width: 10, height: 10)), with: .color(.orange)) + } + } + } +} + +private struct Triangle: Shape { + func path(in rect: CGRect) -> Path { + Path { p in + p.move(to: CGPoint(x: rect.midX, y: rect.maxY)) + p.addLine(to: CGPoint(x: rect.minX, y: rect.minY)) + p.addLine(to: CGPoint(x: rect.maxX, y: rect.minY)) + p.closeSubpath() + } + } +} + +/// Boussole seule, depuis l'accueil (à terre ou en surface, l'écran tactile marche : on pose le cap au toucher). +struct CompassScreen: View { + @Environment(Compass.self) private var compass + + var body: some View { + ScrollView { + VStack(spacing: 6) { + CompassView() + if compass.heading != nil { + if compass.bearing == nil { + Button("Fixer le cap") { compass.setBearing() }.tint(.orange) + } else { + HStack { + Button("Nouveau cap") { compass.setBearing() }.tint(.orange) + Button("Effacer") { compass.clearBearing() } + } + } + } + Text("Le cap posé ici reste affiché pendant la plongée (page boussole, deux crans de couronne).") + .font(.caption2).foregroundStyle(.secondary).multilineTextAlignment(.center) + } + } + .navigationTitle("Boussole") + } +} diff --git a/OpenRemoraWatch/DiveSession.swift b/OpenRemoraWatch/DiveSession.swift @@ -21,6 +21,7 @@ final class DiveSession { private var surfacedAt: Double? private var wentUnder = false private var warnings = Set<DiveComputer.Warning>() + private var safetyStop = DiveComputer.SafetyStop.notRequired private var sensor: SubmersionSource? private var simulation: Task<Void, Never>? let workout = DiveWorkout() @@ -85,6 +86,7 @@ final class DiveSession { surfacedAt = nil wentUnder = false warnings = [] + safetyStop = .notRequired status = nil } @@ -94,6 +96,14 @@ final class DiveSession { recorder = r status = s + // Palier de sécurité : une vibration au début et à la fin du compte à rebours. + 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 + let fresh = s.warnings.subtracting(warnings) warnings = s.warnings if !fresh.isEmpty { diff --git a/OpenRemoraWatch/DiveView.swift b/OpenRemoraWatch/DiveView.swift @@ -1,12 +1,60 @@ import SwiftUI import RemoraDeco -/// Écran de plongée : profondeur en grand, puis ce qu'il faut faire. +/// Écran de plongée. Sous l'eau l'écran tactile est verrouillé : on passe d'une page à l'autre à la couronne. +/// Page 1 : profondeur, vitesse de remontée, sans palier ou palier ; page 2 : détails ; page 3 : boussole. +/// Poignet baissé (luminosité réduite) : seulement la profondeur et le sans palier ou palier, en très gros. struct DiveView: View { @Environment(DiveSession.self) private var session + @Environment(\.isLuminanceReduced) private var dimmed + @State private var page = 0 var body: some View { let s = session.status + Group { + if dimmed { + DimmedDivePage(status: s) + } else { + TabView(selection: $page) { + MainDivePage(status: s).tag(0) + DetailsDivePage(status: s).tag(1) + CompassView(compact: true).tag(2) + } + .tabViewStyle(.verticalPage) + } + } + .background(alarmColor(s).opacity(dimmed ? 0 : 0.35)) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Fin", role: .destructive) { session.end() } + } + } + .overlay(alignment: .top) { + if let message = session.sensorMessage { + Text(message).font(.caption2).padding(3).background(.orange, in: Capsule()) + } + } + .task { + if CommandLine.arguments.contains("-page2") { page = 1 } + if CommandLine.arguments.contains("-page3") { page = 2 } + } + } + + private func alarmColor(_ s: DiveComputer.Status?) -> Color { + guard let s else { return .clear } + if s.warnings.contains(where: \.isViolation) { return .red } + return s.warnings.isEmpty ? .clear : .orange + } +} + +// MARK: - Page 1 + +private struct MainDivePage: View { + @Environment(DiveSession.self) private var session + let status: DiveComputer.Status? + + var body: some View { + let s = status VStack(spacing: 2) { HStack { Text(Format.clock((s?.elapsed ?? 0) * 60)) @@ -16,90 +64,179 @@ struct DiveView: View { .font(.system(size: 15, weight: .medium, design: .rounded)) .foregroundStyle(.secondary) - HStack(alignment: .firstTextBaseline, spacing: 2) { - Text(Format.depth(s?.depth ?? 0)) - .font(.system(size: 58, weight: .semibold, design: .rounded)) - .monospacedDigit() - .minimumScaleFactor(0.6) - Text("m").font(.title3).foregroundStyle(.secondary) + HStack(alignment: .center, spacing: 6) { + AscentScale(rate: s?.ascentRate ?? 0) + VStack(spacing: 2) { + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(Format.depth(s?.depth ?? 0)) + .font(.system(size: 56, weight: .semibold, design: .rounded)) + .monospacedDigit() + .minimumScaleFactor(0.6) + Text("m").font(.title3).foregroundStyle(.secondary) + } + if let s { Instruction(status: s) } + } + .frame(maxWidth: .infinity) } - if let s { instruction(s) } - Spacer(minLength: 0) HStack { Text("max \(Format.depth(s?.maxDepth ?? 0)) m") Spacer() - if let s { AscentGauge(rate: s.ascentRate) } + Text("\(Int(max(0, s?.ascentRate ?? 0).rounded())) m/min ↑") } .font(.system(size: 13, design: .rounded)) .foregroundStyle(.secondary) } .padding(.horizontal, 6) - .background(alarmColor(s).opacity(0.35)) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Fin", role: .destructive) { session.end() } + } +} + +/// Ce qu'il faut faire maintenant : alarme, palier (compte à rebours), palier de sécurité, ou sans palier. +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.color) + .minimumScaleFactor(0.6) + .lineLimit(1) } - } - .overlay(alignment: .top) { - if let message = session.sensorMessage { - Text(message).font(.caption2).padding(3).background(.orange, in: Capsule()) + if let stop = s.plan.stops.first { + HStack(alignment: .firstTextBaseline, spacing: 4) { + Text("PALIER \(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 dans \(Int(s.plan.timeToSurface.rounded(.up))) min") + .font(.caption2).foregroundStyle(.secondary) + } else if case .running(let remaining) = s.safetyStop { + Text("PALIER DE SÉCURITÉ").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 { + HStack(alignment: .firstTextBaseline, spacing: 4) { + Text("sans palier").font(.caption).foregroundStyle(.secondary) + Text(Format.ndl(s.plan.noDecompressionLimit)) + .font(.system(size: 24, weight: .semibold, design: .rounded)) + .foregroundStyle((s.plan.noDecompressionLimit ?? 99) < 5 ? .orange : .green) + Text("min").font(.caption).foregroundStyle(.secondary) + } + switch s.safetyStop { + case .pending where s.depth < 9: + Text("Palier de sécurité 3 min à 5 m").font(.caption2).foregroundStyle(.cyan) + case .done: + Text("Palier de sécurité fait ✓").font(.caption2).foregroundStyle(.green) + default: + EmptyView() + } } } } +} - @ViewBuilder - private func instruction(_ s: DiveComputer.Status) -> some View { - if let warning = s.warnings.sorted(by: { $0.rank < $1.rank }).first { - Text(warning.label.uppercased()) - .font(.system(size: 15, weight: .bold, design: .rounded)) - .foregroundStyle(warning.color) - .minimumScaleFactor(0.7) - .lineLimit(1) +/// Échelle verticale de vitesse de remontée : 5 segments (3, 6, 9, 10, 12 m/min) qui se remplissent du bas ; +/// vert, jaune au-delà de 10 m/min, rouge au-delà de 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) + } } - if let stop = s.plan.stops.first { - Text("PALIER \(Int(stop.depth)) m · \(stop.minutes) min") - .font(.system(size: 19, weight: .bold, design: .rounded)) - .foregroundStyle(.orange) - Text("surface dans \(Int(s.plan.timeToSurface.rounded(.up))) min") - .font(.caption2).foregroundStyle(.secondary) - } else { - HStack(alignment: .firstTextBaseline, spacing: 4) { - Text("sans palier").font(.caption).foregroundStyle(.secondary) - Text(Format.ndl(s.plan.noDecompressionLimit)) - .font(.system(size: 24, weight: .semibold, design: .rounded)) - .foregroundStyle(.green) - Text("min").font(.caption).foregroundStyle(.secondary) + .accessibilityLabel("Remontée \(Int(max(0, rate))) mètres par minute") + } + + private var color: Color { rate > 12 ? .red : rate > 10 ? .yellow : .green } +} + +// MARK: - Page 2 + +private struct DetailsDivePage: View { + @Environment(DiveSession.self) private var session + @Environment(LogStore.self) private var store + let status: DiveComputer.Status? + + var body: some View { + let s = status + Grid(horizontalSpacing: 10, verticalSpacing: 8) { + GridRow { + cell("Max", "\(Format.depth(s?.maxDepth ?? 0)) m") + cell("Surface", "\(Int((s?.plan.timeToSurface ?? 0).rounded(.up))) min") + } + GridRow { + cell("ppO2", String(format: "%.2f", s?.ppO2 ?? 0).replacingOccurrences(of: ".", with: ","), + color: (s?.ppO2 ?? 0) > store.settings.ppO2Max ? .orange : .primary) + cell("Mélange", store.settings.gas.description) } - if s.safetyStopRecommended, s.depth < 7 { - Text("Palier de sécurité 3 min à 5 m").font(.caption2).foregroundStyle(.cyan) + GridRow { + cell("Heure", Date().formatted(date: .omitted, time: .shortened)) + if let level = session.batteryLevel { + cell("Batterie", "\(Int((level * 100).rounded())) %", color: level < 0.3 ? .red : .primary) + } else { + cell("Prudence", store.settings.gradientFactors.description) + } } } + .padding(.horizontal, 6) } - private func alarmColor(_ s: DiveComputer.Status?) -> Color { - guard let s else { return .clear } - if s.warnings.contains(where: \.isViolation) { return .red } - return s.warnings.isEmpty ? .clear : .orange + private func cell(_ title: String, _ value: String, color: Color = .primary) -> some View { + VStack(spacing: 0) { + Text(title).font(.caption2).foregroundStyle(.secondary) + Text(value).font(.system(size: 20, weight: .semibold, design: .rounded)).monospacedDigit() + .foregroundStyle(color).minimumScaleFactor(0.6).lineLimit(1) + } + .frame(maxWidth: .infinity) } } -/// Vitesse de remontée : flèches qui se remplissent, rouge au-delà de 12 m/min. -struct AscentGauge: View { - let rate: Double +// MARK: - Poignet baissé + +private struct DimmedDivePage: View { + let status: DiveComputer.Status? var body: some View { - HStack(spacing: 1) { - ForEach(1...4, id: \.self) { i in - Image(systemName: "chevron.up") - .font(.system(size: 11, weight: .heavy)) - .foregroundStyle(rate >= Double(i) * 3 ? color : Color.gray.opacity(0.35)) + let s = status + VStack(spacing: 4) { + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(Format.depth(s?.depth ?? 0)) + .font(.system(size: 64, weight: .bold, design: .rounded)) + .monospacedDigit().minimumScaleFactor(0.6) + Text("m").font(.title3) + } + if let s { + if let stop = s.plan.stops.first { + Text("PALIER \(Int(stop.depth)) m · \(Format.clock(Double(stop.seconds ?? stop.minutes * 60)))") + .font(.system(size: 20, weight: .bold, design: .rounded)) + } else if case .running(let remaining) = s.safetyStop { + Text("SÉCURITÉ \(Format.clock(remaining))").font(.system(size: 20, weight: .bold, design: .rounded)) + } else { + Text("sans palier \(Format.ndl(s.plan.noDecompressionLimit)) min") + .font(.system(size: 20, weight: .bold, design: .rounded)) + } + if let warning = s.warnings.sorted(by: { $0.rank < $1.rank }).first { + Text(warning.label.uppercased()).font(.system(size: 15, weight: .heavy)).lineLimit(1) + .minimumScaleFactor(0.6) + } } } - .accessibilityLabel("Remontée \(Int(max(0, rate))) mètres par minute") + .foregroundStyle(.white) } - - private var color: Color { rate > 12 ? .red : rate > 10 ? .orange : .green } } diff --git a/OpenRemoraWatch/OpenRemoraApp.swift b/OpenRemoraWatch/OpenRemoraApp.swift @@ -5,6 +5,7 @@ import RemoraDeco struct OpenRemoraApp: App { @State private var store: LogStore @State private var session: DiveSession + @State private var compass = Compass() private let phone: PhoneLink init() { @@ -25,6 +26,7 @@ struct OpenRemoraApp: App { RootView() .requiresTerms() .environment(store) + .environment(compass) .environment(session) } } diff --git a/OpenRemoraWatch/RootView.swift b/OpenRemoraWatch/RootView.swift @@ -50,6 +50,7 @@ struct RootView: View { } Section { + NavigationLink { CompassScreen() } label: { Label("Boussole", systemImage: "location.north.line") } NavigationLink { SettingsView() } label: { Label("Réglages", systemImage: "gearshape") } Button { session.startSimulation() } label: { Label("Plongée de démonstration", systemImage: "play.circle") @@ -75,7 +76,10 @@ struct RootView: View { session.listen() if !CommandLine.arguments.contains("-demo") { await session.workout.requestAuthorization() } if CommandLine.arguments.contains(where: { $0 == "-showDive" || $0 == "-showProfile" }), let dive = store.dives.first { path = [dive] } - if CommandLine.arguments.contains("-simulate") { session.startSimulation() } + if CommandLine.arguments.contains("-simulate") { + session.startSimulation(CommandLine.arguments.contains("-deep") ? .deep : .reef, + speed: CommandLine.arguments.contains("-slow") ? 8 : 30) + } if CommandLine.arguments.contains("-ready") { session.getReady() } } } diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift b/Packages/RemoraDeco/Sources/RemoraDeco/AscentPlanner.swift @@ -19,6 +19,14 @@ public struct DecoSettings: Sendable, Hashable { public struct DecoStop: Sendable, Hashable { public let depth: Double // m public let minutes: Int + /// Durée du palier à 10 s près (affichage du compte à rebours ; seulement pour le premier palier). + 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 { @@ -121,12 +129,24 @@ public enum AscentPlanner { } // Palier à `depth` : l'ancre suit le premier (plus profond) palier, puis on attend minute par minute. if anchor.map({ depth > $0 }) ?? true { anchor = depth } + // Premier palier : durée à 10 s près, pour le compte à rebours (sur une copie : le plan garde + // ses minutes entières, plus prudentes). + 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)) + stops.append(DecoStop(depth: depth, minutes: waited, seconds: seconds)) tts += Double(waited) } diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift b/Packages/RemoraDeco/Sources/RemoraDeco/DiveComputer.swift @@ -8,6 +8,10 @@ public struct DiveComputer: Sendable { public var deco = DecoSettings() public var ppO2Warning: Double = 1.4 public var ppO2Alarm: Double = 1.6 + /// Profondeur d'alerte, avant la limite de 40 m de la montre. + public var depthLimit: Double = 38 + /// Alerte quand le temps sans palier passe sous cette valeur (min). + public var lowNoDecompression: Double = 5 public init() {} } @@ -16,6 +20,18 @@ public struct DiveComputer: Sendable { case ceilingViolated case ppO2High, ppO2Critical case missedSafetyStop + case depthLimit + case lowNoDecompression + } + + /// Palier de sécurité (3 min entre 3 et 6 m après être descendu sous 10 m, hors décompression). + public enum SafetyStop: Sendable, Hashable { + case notRequired + case pending + /// En cours : secondes restantes. + case running(remaining: Double) + case done + case missed } public struct Status: Sendable { @@ -27,6 +43,7 @@ public struct DiveComputer: Sendable { public let plan: AscentPlan public let ceilingDepth: Double // m (0 = pas de plafond) public let safetyStopRecommended: Bool + public let safetyStop: SafetyStop public let warnings: Set<Warning> } @@ -38,6 +55,8 @@ public struct DiveComputer: Sendable { private var start: Double? private var last: (time: Double, pressure: Double)? private var ascent = AscentRateMonitor() + private var safetyStopTime = 0.0 // s passées dans la zone du palier de sécurité + private var safetyStopState = SafetyStop.notRequired private var plan: AscentPlan? /// `surfacePressure` : mesurée par la montre juste avant l'immersion. @@ -51,6 +70,7 @@ public struct DiveComputer: Sendable { /// Nouvel échantillon : `time` en secondes (horloge monotone), `pressure` absolue en 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) @@ -67,8 +87,30 @@ public struct DiveComputer: Sendable { // L'ancre des facteurs de gradient suit le premier palier le plus profond et reste pour la plongée. if let anchor = newPlan.gradientAnchorDepth { gradientAnchorDepth = max(gradientAnchorDepth ?? 0, anchor) } plan = newPlan + updateSafetyStop(depth: depth, seconds: elapsedStep) + } + + /// Avance le palier de sécurité. Zone : de 3 à 6,5 m ; on repart de zéro si on redescend sous 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 } + if case .missed = safetyStopState { 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) @@ -87,13 +129,17 @@ public struct DiveComputer: Sendable { if ceiling > 0, depth < ceiling - 0.3 { 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, - warnings: warnings) + safetyStop: safetyStopState, warnings: warnings) } private func currentGF(depth: Double) -> Double { diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/UDDF.swift b/Packages/RemoraDeco/Sources/RemoraDeco/UDDF.swift @@ -73,6 +73,8 @@ public enum UDDF { case .ceilingViolated: "deco" case .ppO2High, .ppO2Critical: "error" case .missedSafetyStop: "deco" + case .depthLimit: "depth" + case .lowNoDecompression: "deco" } } } diff --git a/Packages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift b/Packages/RemoraDeco/Tests/RemoraDecoTests/DecoTests.swift @@ -243,3 +243,72 @@ struct DiveComputerTests { #expect(c.status.warnings.contains(.ppO2Critical)) } } + +@Suite("Écran de plongée") +struct DiveScreenEngineTests { + func computer() -> DiveComputer { + var config = DiveComputer.Configuration() + config.water = .salt + return DiveComputer(configuration: config, surfacePressure: scale.surfacePressure) + } + + /// Profil à 1 Hz : (profondeur cible, vitesse m/min, secondes sur place). + 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) // le compte à rebours ne dépasse pas la minute affichée + #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("attendu en cours : \(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)) + } +} diff --git a/Shared/Format.swift b/Shared/Format.swift @@ -36,6 +36,8 @@ extension DiveComputer.Warning { case .ppO2High: "ppO2 élevée" case .ppO2Critical: "ppO2 critique" case .missedSafetyStop: "Palier de sécurité sauté" + case .depthLimit: "Profondeur limite" + case .lowNoDecompression: "Moins de 5 min sans palier" } }