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 7bbcc9c1564698ad5d2fb62a98cea5801d8ffa46
parent 2173e3814c9859eff87ad15f9f97acfe623a6ab2
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 14:19:17 -0500

Watch app: dive screen, logbook, profile review with the crown, settings, demo dive

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

Diffstat:
M.gitignore | 1+
MMakefile | 9+++++++++
AOpenRemoraWatch/DemoProfile.swift | 43+++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/DiveDetailView.swift | 169+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/DiveSession.swift | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/DiveView.swift | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/Format.swift | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/LogStore.swift | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/OpenRemoraApp.swift | 23+++++++++++++++++++++++
AOpenRemoraWatch/RootView.swift | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/SettingsView.swift | 63+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AOpenRemoraWatch/SubmersionSource.swift | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
MPackages/RemoraDeco/Sources/RemoraDeco/Logbook.swift | 10+++++++---
MPackages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift | 6+++---
Aproject.yml | 48++++++++++++++++++++++++++++++++++++++++++++++++
15 files changed, 860 insertions(+), 6 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -2,3 +2,4 @@ build/ .build/ .swiftpm/ +OpenRemoraWatch/Info.plist diff --git a/Makefile b/Makefile @@ -10,3 +10,12 @@ sync: # Moteur de décompression seul (paquet Swift, sans interface) test-deco: sync ssh $(CHUNGA) 'cd $(REMOTE)/Packages/RemoraDeco && swift test 2>&1' + +WATCH_DEST ?= generic/platform=watchOS Simulator + +.PHONY: project build-watch +project: sync + ssh $(CHUNGA) 'cd $(REMOTE) && xcodegen -q' + +build-watch: project + ssh $(CHUNGA) 'cd $(REMOTE) && xcodebuild -quiet -scheme OpenRemoraWatch -destination "$(WATCH_DEST)" -derivedDataPath build CODE_SIGNING_ALLOWED=NO build' diff --git a/OpenRemoraWatch/DemoProfile.swift b/OpenRemoraWatch/DemoProfile.swift @@ -0,0 +1,43 @@ +import Foundation +import RemoraDeco + +/// Profils simulés : démonstration à sec et captures d'écran. +struct DemoProfile { + /// Segments : profondeur visée (m), vitesse pour y aller (m/min), puis durée sur place (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)]) + + /// Profondeur à chaque seconde, retour en surface compris. + 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 } + + /// Enregistre le profil d'un coup (carnet de démonstration). + @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/OpenRemoraWatch/DiveDetailView.swift b/OpenRemoraWatch/DiveDetailView.swift @@ -0,0 +1,169 @@ +import SwiftUI +import Charts +import RemoraDeco + +/// Résumé d'une plongée : le profil en premier, on le touche pour le parcourir à la couronne. +struct DiveDetailView: View { + let dive: DiveLog + + var body: some View { + List { + Section { + NavigationLink { ProfileView(dive: dive) } label: { + VStack(alignment: .leading, spacing: 4) { + ProfileChart(dive: dive, cursor: nil).frame(height: 70) + Text("Toucher pour parcourir le profil").font(.caption2).foregroundStyle(.secondary) + } + } + } + + Section { + row("Profondeur max", "\(Format.depth(dive.maxDepth)) m") + row("Durée", Format.clock(dive.duration)) + row("Profondeur moyenne", "\(Format.depth(dive.averageDepth)) m") + if let t = dive.minTemperature { row("Eau au plus froid", "\(Int(t.rounded())) °C") } + row("Mélange", dive.gas.description) + row("Paliers obligatoires", dive.hadDecompression ? "Oui" : "Non") + if let si = dive.surfaceIntervalBefore { row("Intervalle de surface", Format.clock(si * 60)) } + } + + Section(dive.events.isEmpty ? "Aucune alarme" : "Alarmes") { + ForEach(Array(dive.events.enumerated()), id: \.offset) { _, event in + HStack { + Image(systemName: event.warning.isViolation ? "exclamationmark.triangle.fill" : "exclamationmark.circle") + .foregroundStyle(event.warning.color) + Text(event.warning.label).font(.footnote) + Spacer() + Text(Format.clock(event.time)).font(.footnote).foregroundStyle(.secondary).monospacedDigit() + } + } + } + + Section { + row("Début", Format.dayTime(dive.start)) + if let site = dive.site { row("Site", site) } + if let gf = dive.gradientFactors { row("Prudence", gf.description) } + row("Eau", dive.water.label) + if let model = dive.computerModel { row("Ordinateur", model) } + } + } + .navigationTitle("Plongée \(dive.number)") + } + + private func row(_ title: String, _ value: String) -> some View { + VStack(alignment: .leading, spacing: 0) { + Text(title).font(.caption2).foregroundStyle(.secondary) + Text(value).font(.body) + } + } +} + +/// Profil en plein écran : la couronne déplace le curseur le long de la plongée. +struct ProfileView: View { + let dive: DiveLog + @State private var position = 0.0 + @FocusState private var focused: Bool + + var body: some View { + let sample = dive.samples.isEmpty ? nil : dive.samples[min(dive.samples.count - 1, Int(position.rounded()))] + VStack(alignment: .leading, spacing: 2) { + if let sample { + HStack(alignment: .firstTextBaseline) { + Text("\(Format.depth(sample.depth)) m").font(.system(size: 22, weight: .semibold, design: .rounded)) + Spacer() + Text(Format.clock(sample.time)).font(.system(size: 17, design: .rounded)).foregroundStyle(.secondary) + } + .monospacedDigit() + Text(detail(sample)).font(.caption2).foregroundStyle(detailColor(sample)).lineLimit(1) + } + ProfileChart(dive: dive, cursor: sample) + } + .padding(.horizontal, 4) + .focusable() + .focused($focused) + .digitalCrownRotation($position, from: 0, through: Double(max(1, dive.samples.count - 1)), + by: 1, sensitivity: .high, isContinuous: false, isHapticFeedbackEnabled: false) + .onAppear { + focused = true + // Ouvrir sur le point le plus profond. + if let deepest = dive.samples.indices.max(by: { dive.samples[$0].depth < dive.samples[$1].depth }) { + position = Double(deepest) + } + } + .navigationTitle("Profil") + } + + private func event(at sample: DiveSample) -> DiveEvent? { + dive.events.last { abs($0.time - sample.time) <= 5 } + } + + private func detail(_ s: DiveSample) -> String { + if let e = event(at: s) { return e.warning.label } + var parts: [String] = [] + if let t = s.temperature { parts.append("\(Int(t.rounded())) °C") } + if let stop = s.stopDepth, let minutes = s.stopMinutes { + parts.append("palier \(Int(stop)) m · \(minutes) min") + } else if dive.source != .subsurface || s.noDecompressionLimit != nil { + parts.append("sans palier \(Format.ndl(s.noDecompressionLimit)) min") + } + return parts.joined(separator: " · ") + } + + private func detailColor(_ s: DiveSample) -> Color { + if let e = event(at: s) { return e.warning.color } + return s.stopDepth != nil ? .orange : .secondary + } +} + +/// Le graphe : profondeur (vers le bas), plafond de décompression, alarmes. +struct ProfileChart: View { + let dive: DiveLog + let cursor: DiveSample? + + /// Au plus ~150 points pour le tracé. + private var points: [DiveSample] { + let step = max(1, dive.samples.count / 150) + var out = stride(from: 0, to: dive.samples.count, by: step).map { dive.samples[$0] } + if let last = dive.samples.last, out.last != last { out.append(last) } + return out + } + + private func depth(at time: Double) -> Double { + dive.samples.min { abs($0.time - time) < abs($1.time - time) }?.depth ?? 0 + } + + var body: some View { + Chart { + ForEach(points, id: \.time) { s in + AreaMark(x: .value("Temps", s.time / 60), y: .value("Profondeur", s.depth)) + .foregroundStyle(.linearGradient(colors: [.cyan.opacity(0.25), .blue.opacity(0.6)], + startPoint: .top, endPoint: .bottom)) + LineMark(x: .value("Temps", s.time / 60), y: .value("Profondeur", s.depth), + series: .value("Série", "profondeur")) + .foregroundStyle(.cyan) + .lineStyle(StrokeStyle(lineWidth: 1.5)) + } + if dive.hadDecompression { + ForEach(points, id: \.time) { s in + LineMark(x: .value("Temps", s.time / 60), y: .value("Plafond", s.ceiling), + series: .value("Série", "plafond")) + .foregroundStyle(.orange) + .lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 2])) + } + } + ForEach(Array(dive.events.enumerated()), id: \.offset) { _, e in + PointMark(x: .value("Temps", e.time / 60), y: .value("Profondeur", depth(at: e.time))) + .foregroundStyle(e.warning.color) + .symbolSize(30) + } + if let cursor { + RuleMark(x: .value("Temps", cursor.time / 60)).foregroundStyle(.white.opacity(0.7)) + PointMark(x: .value("Temps", cursor.time / 60), y: .value("Profondeur", cursor.depth)) + .foregroundStyle(.white) + } + } + .chartYScale(domain: .automatic(includesZero: true, reversed: true)) + .chartXAxis { AxisMarks(values: .automatic(desiredCount: 3)) { AxisValueLabel().font(.system(size: 9)) } } + .chartYAxis { AxisMarks(values: .automatic(desiredCount: 3)) { AxisGridLine(); AxisValueLabel().font(.system(size: 9)) } } + } +} diff --git a/OpenRemoraWatch/DiveSession.swift b/OpenRemoraWatch/DiveSession.swift @@ -0,0 +1,118 @@ +import Foundation +import Observation +import WatchKit +import RemoraDeco + +/// La plongée en cours : reçoit les mesures (capteur ou simulation), tient l'ordinateur et les alarmes. +@MainActor @Observable +final class DiveSession { + private(set) var isDiving = false + private(set) var isSimulation = false + private(set) var status: DiveComputer.Status? + private(set) var temperature: Double? + private(set) var sensorMessage: String? + /// Plongée qui vient de se terminer : l'écran d'accueil ouvre son résumé. + var finishedDive: DiveLog? + + private let store: LogStore + private var recorder: DiveRecorder? + private var surfacedAt: Double? + private var wentUnder = false + private var warnings = Set<DiveComputer.Warning>() + private var sensor: SubmersionSource? + private var simulation: Task<Void, Never>? + + init(store: LogStore) { + self.store = store + } + + var sensorAvailable: Bool { SubmersionSource.isAvailable } + + /// Écoute le capteur : la plongée démarre seule à l'immersion. + 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): + guard !isSimulation else { return } + if !isDiving { + guard let absolute, absolute > surface + 0.03 else { return } // ≈ 30 cm d'eau + start(surfacePressure: surface, simulation: false) + } + ingest(time: time, pressure: absolute ?? surface) + } + } + + 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 + surfacedAt = nil + wentUnder = false + warnings = [] + 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 + + let fresh = s.warnings.subtracting(warnings) + warnings = s.warnings + if !fresh.isEmpty { + let serious = !fresh.isDisjoint(with: [.ceilingViolated, .ascentTooFast, .ppO2Critical]) + WKInterfaceDevice.current().play(serious ? .failure : .notification) + } + + // Fin automatique : une minute en surface après être descendu sous 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 + } + } + + /// Termine la plongée et l'ajoute au carnet (rien n'est gardé si on n'est jamais descendu). + func end() { + simulation?.cancel() + simulation = nil + guard let r = recorder else { return } + recorder = nil + isDiving = false + guard wentUnder else { return } + var dive = r.finish() + if isSimulation { + dive.source = .simulation + dive.site = "Démonstration" + } + finishedDive = store.add(dive) + WKInterfaceDevice.current().play(.success) + } + + /// Plongée de démonstration à sec, accélérée. + func startSimulation(_ profile: DemoProfile = .reef, speed: Double = 30) { + guard !isDiving 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)) + } + } + } +} diff --git a/OpenRemoraWatch/DiveView.swift b/OpenRemoraWatch/DiveView.swift @@ -0,0 +1,105 @@ +import SwiftUI +import RemoraDeco + +/// Écran de plongée : profondeur en grand, puis ce qu'il faut faire. +struct DiveView: View { + @Environment(DiveSession.self) private var session + + var body: some View { + let s = session.status + VStack(spacing: 2) { + HStack { + Text(Format.clock((s?.elapsed ?? 0) * 60)) + Spacer() + if let t = session.temperature { Text("\(Int(t.rounded())) °C") } + } + .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) + } + + 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) } + } + .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() } + } + } + .overlay(alignment: .top) { + if let message = session.sensorMessage { + Text(message).font(.caption2).padding(3).background(.orange, in: Capsule()) + } + } + } + + @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) + } + 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) + } + if s.safetyStopRecommended, s.depth < 7 { + Text("Palier de sécurité 3 min à 5 m").font(.caption2).foregroundStyle(.cyan) + } + } + } + + 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 + } +} + +/// Vitesse de remontée : flèches qui se remplissent, rouge au-delà de 12 m/min. +struct AscentGauge: View { + let rate: Double + + 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)) + } + } + .accessibilityLabel("Remontée \(Int(max(0, rate))) mètres par minute") + } + + private var color: Color { rate > 12 ? .red : rate > 10 ? .orange : .green } +} diff --git a/OpenRemoraWatch/Format.swift b/OpenRemoraWatch/Format.swift @@ -0,0 +1,67 @@ +import SwiftUI +import RemoraDeco + +enum Format { + static func depth(_ metres: Double) -> String { String(format: "%.1f", metres).replacingOccurrences(of: ".", with: ",") } + + /// Secondes → « 12:34 » (ou « 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" } + + 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(identifier: "fr_CA"))) + } + + static func dayTime(_ date: Date) -> String { + date.formatted(.dateTime.day().month(.abbreviated).hour().minute().locale(Locale(identifier: "fr_CA"))) + } +} + +extension DiveComputer.Warning { + var label: String { + switch self { + case .ascentFast: "Remontée rapide" + case .ascentTooFast: "Remontée trop rapide" + case .ceilingViolated: "Plafond franchi" + case .ppO2High: "ppO2 élevée" + case .ppO2Critical: "ppO2 critique" + case .missedSafetyStop: "Palier de sécurité sauté" + } + } + + var isViolation: Bool { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains(self) } + var color: Color { isViolation ? .red : .orange } + /// La plus grave d'abord. + var rank: Int { isViolation ? 0 : 1 } +} + +extension Water { + var label: String { + switch self { + case .fresh: "Douce" + case .en13319: "Standard (EN 13319)" + case .salt: "Salée" + } + } +} + +extension UserSettings.Conservatism { + var label: String { + switch self { + case .high: "Élevée (GF 30/70)" + case .medium: "Moyenne (GF 40/80)" + case .low: "Faible (GF 50/85)" + case .custom: "Personnalisée" + } + } +} diff --git a/OpenRemoraWatch/LogStore.swift b/OpenRemoraWatch/LogStore.swift @@ -0,0 +1,60 @@ +import Foundation +import Observation +import RemoraDeco + +/// Carnet et réglages, enregistrés en JSON sur la montre. +@MainActor @Observable +final class LogStore { + private(set) var logbook = Logbook() + var settings = UserSettings() + + private let folder: URL + private var logbookURL: URL { folder.appendingPathComponent("carnet.json") } + private var settingsURL: URL { folder.appendingPathComponent("reglages.json") } + + init() { + folder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + if let data = try? Data(contentsOf: logbookURL), + let book = try? JSONDecoder().decode(Logbook.self, from: data) { logbook = book } + if let data = try? Data(contentsOf: settingsURL), + let saved = try? JSONDecoder().decode(UserSettings.self, from: data) { settings = saved } + } + + /// Plongées les plus récentes d'abord. + var dives: [DiveLog] { logbook.dives.reversed() } + + func add(_ dive: DiveLog) -> DiveLog { + logbook.add(dive) + saveLogbook() + return logbook.dives.first { $0.id == dive.id } ?? dive + } + + func remove(_ dive: DiveLog) { + logbook.remove(id: dive.id) + saveLogbook() + } + + func saveSettings() { + guard settings.problems.isEmpty, let data = try? JSONEncoder().encode(settings) else { return } + try? data.write(to: settingsURL, options: .atomic) + } + + private func saveLogbook() { + guard let data = try? JSONEncoder().encode(logbook) else { return } + try? data.write(to: logbookURL, options: .atomic) + } + + /// Carnet de démonstration (argument `-demo`) : trois plongées simulées si le carnet est vide. + func seedDemo() { + guard logbook.dives.isEmpty else { return } + let day = 86_400.0 + for (i, profile) in [DemoProfile.shallow, .reef, .deep].enumerated() { + let start = Date().addingTimeInterval(-day * Double(3 - i) * 2) + var dive = profile.record(start: start, settings: settings, logbook: Logbook()) + dive.source = .simulation + dive.site = "Démonstration" + logbook.add(dive) + } + } +} diff --git a/OpenRemoraWatch/OpenRemoraApp.swift b/OpenRemoraWatch/OpenRemoraApp.swift @@ -0,0 +1,23 @@ +import SwiftUI +import RemoraDeco + +@main +struct OpenRemoraApp: App { + @State private var store: LogStore + @State private var session: DiveSession + + init() { + let store = LogStore() + if CommandLine.arguments.contains("-demo") { store.seedDemo() } + _store = State(initialValue: store) + _session = State(initialValue: DiveSession(store: store)) + } + + var body: some Scene { + WindowGroup { + RootView() + .environment(store) + .environment(session) + } + } +} diff --git a/OpenRemoraWatch/RootView.swift b/OpenRemoraWatch/RootView.swift @@ -0,0 +1,90 @@ +import SwiftUI +import RemoraDeco + +struct RootView: View { + @Environment(LogStore.self) private var store + @Environment(DiveSession.self) private var session + @State private var path: [DiveLog] = [] + + var body: some View { + @Bindable var session = session + NavigationStack(path: $path) { + List { + Section("Carnet") { + if store.dives.isEmpty { + Text("Aucune plongée").foregroundStyle(.secondary) + } + ForEach(store.dives) { dive in + NavigationLink(value: dive) { DiveRow(dive: dive) } + } + .onDelete { offsets in + let dives = store.dives + for i in offsets { store.remove(dives[i]) } + } + } + + Section { + if session.sensorAvailable { + Label("Entrez dans l'eau : la plongée démarre seule", systemImage: "water.waves") + .font(.footnote) + } else { + Label("Pas de capteur de profondeur sur cette montre", systemImage: "exclamationmark.triangle") + .font(.footnote) + .foregroundStyle(.orange) + } + Text("\(store.settings.gas.description) · \(store.settings.gradientFactors.description)") + .font(.footnote) + .foregroundStyle(.secondary) + } + + Section { + NavigationLink { SettingsView() } label: { Label("Réglages", systemImage: "gearshape") } + Button { session.startSimulation() } label: { + Label("Plongée de démonstration", systemImage: "play.circle") + } + } footer: { + Text("Ordinateur secondaire, non certifié. À utiliser avec un ordinateur de plongée principal.") + } + } + .navigationTitle("Open Rémora") + .navigationDestination(for: DiveLog.self) { dive in + if CommandLine.arguments.contains("-showProfile") { ProfileView(dive: dive) } + else { DiveDetailView(dive: dive) } + } + } + .fullScreenCover(isPresented: .constant(session.isDiving)) { DiveView() } + .onChange(of: session.finishedDive) { _, dive in + guard let dive else { return } + path = [dive] + session.finishedDive = nil + } + .task { + session.listen() + if CommandLine.arguments.contains(where: { $0 == "-showDive" || $0 == "-showProfile" }), let dive = store.dives.first { path = [dive] } + if CommandLine.arguments.contains("-simulate") { session.startSimulation() } + } + } +} + +/// Une ligne du carnet : l'essentiel d'un coup d'œil. +struct DiveRow: View { + let dive: DiveLog + + var body: some View { + HStack(alignment: .firstTextBaseline) { + VStack(alignment: .leading, spacing: 2) { + Text("\(Format.depth(dive.maxDepth)) m · \(Format.minutes(dive.duration))") + .font(.headline) + Text("Nº \(dive.number) · \(Format.day(dive.start))") + .font(.caption2) + .foregroundStyle(.secondary) + } + Spacer() + if !dive.violations.isEmpty { + Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.red) + } else if dive.hadDecompression { + Text("PALIERS").font(.system(size: 9, weight: .bold)).foregroundStyle(.orange) + } + } + } +} diff --git a/OpenRemoraWatch/SettingsView.swift b/OpenRemoraWatch/SettingsView.swift @@ -0,0 +1,63 @@ +import SwiftUI +import RemoraDeco + +struct SettingsView: View { + @Environment(LogStore.self) private var store + + var body: some View { + @Bindable var store = store + List { + Section { + Picker("Oxygène", selection: $store.settings.oxygenPercent) { + ForEach(Array(UserSettings.Limits.oxygenPercent), id: \.self) { p in + Text(p == 21 ? "21 % (air)" : "\(p) %").tag(p) + } + } + Picker("Eau", selection: $store.settings.water) { + ForEach(Water.allCases, id: \.self) { Text($0.label).tag($0) } + } + } footer: { + Text("Profondeur maximale du mélange : \(Format.depth(store.settings.maximumOperatingDepth())) m") + } + + Section { + NavigationLink("Réglages avancés") { AdvancedSettingsView() } + } footer: { + Text("L'altitude est mesurée par la montre : rien à régler.") + } + } + .navigationTitle("Réglages") + .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("Prudence") { + Picker("Prudence", selection: $store.settings.conservatism) { + ForEach(UserSettings.Conservatism.allCases, id: \.self) { Text($0.label).tag($0) } + } + if store.settings.conservatism == .custom { + Stepper("GF bas \(store.settings.customGFLowPercent) %", + value: $store.settings.customGFLowPercent, + in: UserSettings.Limits.gfLowPercent.lowerBound...store.settings.customGFHighPercent, step: 5) + Stepper("GF haut \(store.settings.customGFHighPercent) %", + value: $store.settings.customGFHighPercent, + in: max(UserSettings.Limits.gfHighPercent.lowerBound, store.settings.customGFLowPercent)...100, step: 5) + } + } + Section("Oxygène") { + Picker("ppO2 maximale", selection: $store.settings.ppO2Max) { + ForEach([1.2, 1.3, 1.4, 1.5, 1.6], id: \.self) { v in + Text(String(format: "%.1f bar", v).replacingOccurrences(of: ".", with: ",")).tag(v) + } + } + } + } + .navigationTitle("Avancés") + } +} diff --git a/OpenRemoraWatch/SubmersionSource.swift b/OpenRemoraWatch/SubmersionSource.swift @@ -0,0 +1,54 @@ +import Foundation +@preconcurrency import CoreMotion + +/// Capteur de profondeur de l'Apple Watch Ultra (Core Motion). +/// Avec l'autorisation « profondeur faible », les mesures s'arrêtent vers 6 m. +final class SubmersionSource: NSObject, CMWaterSubmersionManagerDelegate, @unchecked Sendable { + enum Reading: Sendable { + /// `time` en secondes, pressions en bar ; `absolute` est nil hors de l'eau. + case pressure(time: Double, surface: Double, absolute: Double?) + case temperature(Double) + case message(String?) + } + + static var isAvailable: Bool { CMWaterSubmersionManager.waterSubmersionAvailable } + + private let manager = CMWaterSubmersionManager() + private let handler: @MainActor (Reading) -> Void + + init(handler: @escaping @MainActor (Reading) -> Void) { + self.handler = handler + super.init() + manager.delegate = self + } + + private func send(_ reading: Reading) { + let handler = handler + Task { @MainActor in handler(reading) } + } + + func manager(_ manager: CMWaterSubmersionManager, didUpdate event: CMWaterSubmersionEvent) {} + + func manager(_ manager: CMWaterSubmersionManager, didUpdate measurement: CMWaterSubmersionMeasurement) { + let surface = measurement.surfacePressure.converted(to: .bars).value + var absolute = measurement.pressure?.converted(to: .bars).value + // Garde-fou : si la pression fournie est relative à la surface, la ramener en absolu. + // À confirmer au premier essai en piscine. + if let p = absolute, p < surface * 0.8 { absolute = p + surface } + send(.pressure(time: measurement.date.timeIntervalSinceReferenceDate, surface: surface, absolute: absolute)) + switch measurement.submersionState { + case .approachingMaxDepth: send(.message("Limite du capteur proche")) + case .pastMaxDepth: send(.message("Au-delà de la limite du capteur")) + case .sensorDepthError: send(.message("Erreur du capteur de profondeur")) + default: send(.message(nil)) + } + } + + func manager(_ manager: CMWaterSubmersionManager, didUpdate measurement: CMWaterTemperature) { + send(.temperature(measurement.temperature.converted(to: .celsius).value)) + } + + func manager(_ manager: CMWaterSubmersionManager, errorOccurred error: any Error) { + send(.message("Capteur : \(error.localizedDescription)")) + } +} diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/Logbook.swift b/Packages/RemoraDeco/Sources/RemoraDeco/Logbook.swift @@ -19,8 +19,9 @@ public struct DiveEvent: Sendable, Hashable, Codable { /// Une plongée du carnet. public struct DiveLog: Sendable, Hashable, Codable, Identifiable { - /// D'où vient la plongée : enregistrée par Open Rémora, ou importée d'un carnet Subsurface. - public enum Source: String, Sendable, Hashable, Codable { case remora, subsurface } + /// D'où vient la plongée : enregistrée par Open Rémora, importée d'un carnet Subsurface, + /// ou simulée (démonstration : jamais comptée dans la saturation ni les délais). + public enum Source: String, Sendable, Hashable, Codable { case remora, subsurface, simulation } public var id: UUID public var source: Source = .remora @@ -67,6 +68,9 @@ public struct Logbook: Sendable, Hashable, Codable { public init() {} + /// Plongées réelles (les simulations de démonstration sont exclues des calculs). + 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 @@ -98,7 +102,7 @@ public struct Logbook: Sendable, Hashable, Codable { /// `nil` si aucune plongée récente (plus de 72 h) : le plongeur est considéré saturé en surface. public func tissues(at date: Date, surfacePressure: Double) -> (tissues: TissueState, interval: Double)? { // Limite connue : une plongée importée (sans tissus) plus récente n'est pas prise en compte. - guard let last = dives.last(where: { $0.tissuesAfter != nil }), let after = last.tissuesAfter + 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 } diff --git a/Packages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift b/Packages/RemoraDeco/Sources/RemoraDeco/SurfaceAdvice.swift @@ -21,12 +21,12 @@ public enum SurfaceAdvice { /// Délai avant l'avion : le plus long du modèle et de la règle de DAN /// (12 h après une plongée sans palier, 18 h après plusieurs dans la journée, 24 h après des paliers). public static func noFlyHours(logbook: Logbook, at date: Date, surfacePressure: Double) -> Double { - guard let last = logbook.dives.last, + 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.dives.filter { last.end.timeIntervalSince($0.end) < 24 * 3600 } + 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)) @@ -35,7 +35,7 @@ public enum SurfaceAdvice { /// Heures avant de pouvoir monter à l'altitude donnée (col, route de montagne), selon le modèle. public static func hoursBeforeAltitude(_ metres: Double, logbook: Logbook, at date: Date, surfacePressure: Double) -> Double { - guard let last = logbook.dives.last, + 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, diff --git a/project.yml b/project.yml @@ -0,0 +1,48 @@ +# Projet Xcode généré par XcodeGen (`xcodegen` sur chunga) : modifier ce fichier, pas le .xcodeproj. +name: OpenRemora +options: + bundleIdPrefix: org.schurger + developmentLanguage: fr + deploymentTarget: + watchOS: "11.0" +packages: + RemoraDeco: + path: Packages/RemoraDeco +settings: + base: + DEVELOPMENT_TEAM: CM5RQKJH56 + CODE_SIGN_STYLE: Automatic + MARKETING_VERSION: "0.1" + CURRENT_PROJECT_VERSION: "1" + SWIFT_VERSION: "6.0" +targets: + OpenRemoraWatch: + type: application + platform: watchOS + sources: + - path: OpenRemoraWatch + dependencies: + - package: RemoraDeco + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: org.schurger.openremora.watchkitapp + PRODUCT_NAME: OpenRemora + info: + path: OpenRemoraWatch/Info.plist + properties: + CFBundleDisplayName: Open Rémora + WKApplication: true + # Tant que l'app iPhone n'existe pas ; deviendra WKCompanionAppBundleIdentifier. + WKWatchOnly: true + WKBackgroundModes: [underwater-depth] + NSMotionUsageDescription: Open Rémora lit la profondeur et la température de l'eau pendant la plongée. + entitlements: + path: OpenRemoraWatch/OpenRemoraWatch.entitlements + properties: + # 6 m : libre. 40 m (submerged-depth-and-pressure) : sur demande à Apple. + com.apple.developer.submerged-shallow-depth-and-pressure: true +schemes: + OpenRemoraWatch: + build: + targets: + OpenRemoraWatch: all