commit d78e55219bb607d207b8178f2e9a6b406a189535
parent 4c94179f65ce4cf2956e8376dbeb69cb41b223bd
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 13:55:31 -0500
Dive log: profile recording, alarms and violations, repetitive dives, time to fly or to altitude, UDDF export
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYGcjJYQu2t1EUEKgbs
Diffstat:
7 files changed, 398 insertions(+), 1 deletion(-)
diff --git a/Sources/RemoraDeco/DiveComputer.swift b/Sources/RemoraDeco/DiveComputer.swift
@@ -11,7 +11,7 @@ public struct DiveComputer: Sendable {
public init() {}
}
- public enum Warning: Sendable, Hashable {
+ public enum Warning: String, Sendable, Hashable, Codable, CaseIterable {
case ascentFast, ascentTooFast
case ceilingViolated
case ppO2High, ppO2Critical
diff --git a/Sources/RemoraDeco/DiveRecorder.swift b/Sources/RemoraDeco/DiveRecorder.swift
@@ -0,0 +1,62 @@
+import Foundation
+
+/// Enregistre une plongée en cours : alimente l'ordinateur et garde le profil pour le carnet.
+public struct DiveRecorder: Sendable {
+ public private(set) var computer: DiveComputer
+ public let start: Date
+ public let surfaceIntervalBefore: Double?
+ /// Écart minimal entre deux points du profil (s). Les alarmes sont notées à chaque échantillon.
+ 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 latest: DiveSample?
+
+ /// Démarre une plongée. Les tissus viennent du carnet (plongée successive) s'il y en a une récente.
+ 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` : horloge monotone en secondes ; `pressure` : bar absolus ; `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) { 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
+ }
+
+ /// Termine la plongée et produit l'entrée du carnet (numéro attribué par `Logbook.add`).
+ public func finish() -> DiveLog {
+ let c = computer.configuration
+ // Le dernier échantillon reçu termine toujours le profil (retour en surface).
+ var samples = samples
+ if let latest, latest.time > (samples.last?.time ?? -1) { samples.append(latest) }
+ return DiveLog(id: UUID(), 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/Sources/RemoraDeco/Logbook.swift b/Sources/RemoraDeco/Logbook.swift
@@ -0,0 +1,86 @@
+import Foundation
+
+/// Un point du profil enregistré (pour le graphe et l'export).
+public struct DiveSample: Sendable, Hashable, Codable {
+ public let time: Double // s depuis le début de la plongée
+ public let depth: Double // m
+ public let temperature: Double? // °C (eau)
+ public let ceiling: Double // m (0 = pas de plafond)
+ public let noDecompressionLimit: Double? // min ; nil = illimité ; 0 = en décompression
+ public let stopDepth: Double? // prochain palier obligatoire, m
+ public let stopMinutes: Int?
+}
+
+/// Alarme ou avertissement apparu pendant la plongée.
+public struct DiveEvent: Sendable, Hashable, Codable {
+ public let time: Double // s
+ public let warning: DiveComputer.Warning
+}
+
+/// Une plongée du carnet.
+public struct DiveLog: Sendable, Hashable, Codable, Identifiable {
+ public var id: UUID
+ public var number: Int // numéro dans le carnet (1, 2, …)
+ public let start: Date
+ public let surfacePressure: Double // bar
+ public let surfaceIntervalBefore: Double? // min ; nil = première plongée (tissus saturés)
+ public let gas: Gas
+ public let gradientFactors: GradientFactors
+ public let water: Water
+ public let samples: [DiveSample]
+ public let events: [DiveEvent]
+ public let tissuesAfter: TissueState
+ // Saisi après coup dans le carnet
+ 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 } }
+ /// Violations enregistrées : plafond franchi, remontée trop rapide, ppO2 critique.
+ public var violations: [DiveEvent] {
+ events.filter { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains($0.warning) }
+ }
+ public var end: Date { start.addingTimeInterval(duration) }
+
+ /// Profondeur moyenne pondérée par le temps.
+ 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
+ }
+}
+
+/// Le carnet : plongées dans l'ordre, et état des tissus pour la plongée suivante.
+public struct Logbook: Sendable, Hashable, Codable {
+ public private(set) var dives: [DiveLog] = []
+
+ public init() {}
+
+ public mutating func add(_ dive: DiveLog) {
+ var d = dive
+ d.number = (dives.last?.number ?? 0) + 1
+ dives.append(d)
+ }
+
+ 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 } }
+
+ /// Tissus au moment `date`, d'après la dernière plongée et la pression de surface actuelle.
+ /// `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)? {
+ guard let last = dives.last else { return nil }
+ let minutes = date.timeIntervalSince(last.end) / 60
+ guard minutes >= 0, minutes < 72 * 60 else { return nil }
+ return (DiveComputer.surfaceInterval(last.tissuesAfter, minutes: minutes,
+ surfacePressure: surfacePressure), minutes)
+ }
+}
diff --git a/Sources/RemoraDeco/SurfaceAdvice.swift b/Sources/RemoraDeco/SurfaceAdvice.swift
@@ -0,0 +1,44 @@
+import Foundation
+
+/// Après la plongée : quand peut-on monter en altitude ou prendre l'avion.
+public enum SurfaceAdvice {
+ /// Pression de cabine d'un avion de ligne (≈ 2400 m), bar.
+ public static let cabinPressure = 0.75
+
+ /// Minutes avant que les tissus tolèrent la pression `target` (facteur de gradient haut),
+ /// en restant à `surfacePressure`. 0 = tout de suite ; plafonné à 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
+ }
+
+ /// 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,
+ let state = logbook.tissues(at: date, surfacePressure: surfacePressure) else { return 0 }
+ let model = minutesUntilTolerated(cabinPressure, tissues: state.tissues,
+ surfacePressure: surfacePressure,
+ gfHigh: last.gradientFactors.high) / 60
+ let sameDay = logbook.dives.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))
+ }
+
+ /// 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,
+ 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.high) / 60
+ }
+}
diff --git a/Sources/RemoraDeco/Tissues.swift b/Sources/RemoraDeco/Tissues.swift
@@ -109,3 +109,23 @@ public struct TissueState: Sendable, Hashable {
return limit.isFinite ? limit : nil
}
}
+
+/// Enregistrement des tissus avec la plongée (plongées successives, temps avant l'avion).
+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 compartiments attendus")
+ }
+ 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/Sources/RemoraDeco/UDDF.swift b/Sources/RemoraDeco/UDDF.swift
@@ -0,0 +1,78 @@
+import Foundation
+
+/// Export du carnet au format UDDF 3.2 (import dans Subsurface, MacDive, etc.). Unités SI : 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: "&").replacingOccurrences(of: "<", with: "<")
+ .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
+ }
+
+ 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"
+ }
+ }
+}
diff --git a/Tests/RemoraDecoTests/LogbookTests.swift b/Tests/RemoraDecoTests/LogbookTests.swift
@@ -0,0 +1,107 @@
+import Foundation
+import Testing
+@testable import RemoraDeco
+
+/// Plongée simulée à 1 Hz : descente à 18 m/min, fond, remontée à 9 m/min, palier de sécurité.
+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("Carnet")
+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)
+ // Un point toutes les 2 s : 26 min de plongée → ~780 points
+ #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)
+ // Plus court sans palier que la même plongée faite en premier
+ 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)
+ // La simulation remonte sans faire les paliers : plafond violé, noté dans les événements.
+ #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("Après 40 m × 20 min : avion dans \(afterDeco) h, col à 2500 m dans \(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 <test> & essai"))
+ #expect(xml.components(separatedBy: "<waypoint>").count - 1 == book.dives[0].samples.count)
+ // XML bien formé
+ #expect((try? XMLDocument(xmlString: xml)) != nil)
+ }
+}