DiveComputer.swift (8878B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 4 /// Dive computer: receives the pressure samples from the watch and keeps the state of the dive. 5 public struct DiveComputer: Sendable { 6 public struct Configuration: Sendable, Hashable { 7 public var gas: Gas = .air 8 public var water: Water = .en13319 9 public var deco = DecoSettings() 10 public var ppO2Warning: Double = 1.4 11 public var ppO2Alarm: Double = 1.6 12 /// Warning depth: 38 m by default, before the 40 m limit of the watch. An app with another depth 13 /// sensor sets its own (see `DiveMonitor.configure`). 14 public var depthLimit: Double = 38 15 /// Warning when the NDL (no-stop time) drops below this value (min); 0 = off. 16 public var lowNoDecompression: Double = 5 17 /// Window over which the ascent rate is smoothed (s). 5 s suits a 1 Hz sensor; a noisier or 18 /// irregular source may want a longer one. 19 public var ascentRateWindow: Double = 5 20 public init() {} 21 } 22 23 public enum Warning: String, Sendable, Hashable, Codable, CaseIterable { 24 case ascentFast, ascentTooFast 25 case ceilingViolated 26 case ppO2High, ppO2Critical 27 case missedSafetyStop 28 case depthLimit 29 case lowNoDecompression 30 } 31 32 /// Safety stop (3 min between 3 and 6 m after going below 10 m, outside decompression). 33 public enum SafetyStop: Sendable, Hashable { 34 case notRequired 35 case pending 36 /// Running: seconds remaining. 37 case running(remaining: Double) 38 case done 39 case missed 40 } 41 42 public struct Status: Sendable { 43 public let elapsed: Double // min 44 public let depth: Double // m 45 public let maxDepth: Double // m 46 public let ascentRate: Double // m/min 47 public let ppO2: Double 48 public let plan: AscentPlan 49 public let ceilingDepth: Double // m (0 = no ceiling) 50 public let safetyStopRecommended: Bool 51 public let safetyStop: SafetyStop 52 public let warnings: Set<Warning> 53 } 54 55 public let configuration: Configuration 56 public let scale: DepthScale 57 public private(set) var tissues: TissueState 58 public private(set) var maxDepth = 0.0 59 public private(set) var gradientAnchorDepth: Double? 60 private var start: Double? 61 private var last: (time: Double, pressure: Double)? 62 private var ascent = AscentRateMonitor() 63 private var safetyStopTime = 0.0 // s spent in the safety stop zone 64 private var safetyStopState = SafetyStop.notRequired 65 private var plan: AscentPlan? 66 67 /// `surfacePressure`: measured by the watch just before submersion. 68 /// `tissues`: state inherited from the previous dive (repetitive dives), otherwise saturated at the surface. 69 public init(configuration: Configuration = Configuration(), surfacePressure: Double, 70 tissues: TissueState? = nil) { 71 self.configuration = configuration 72 self.scale = DepthScale(surfacePressure: surfacePressure, water: configuration.water) 73 self.tissues = tissues ?? .saturated(surfacePressure: surfacePressure) 74 ascent.window = configuration.ascentRateWindow 75 } 76 77 /// New sample: `time` in seconds (monotonic clock), absolute `pressure` in bar. 78 public mutating func update(time: Double, pressure: Double) { 79 let elapsedStep = last.map { max(0, time - $0.time) } ?? 0 80 if let last, time > last.time { 81 tissues.change(from: last.pressure, to: pressure, gas: configuration.gas, 82 minutes: (time - last.time) / 60) 83 } 84 if start == nil { start = time } 85 last = (time, pressure) 86 let depth = scale.depth(atPressure: pressure) 87 maxDepth = max(maxDepth, depth) 88 ascent.add(time: time, depth: depth) 89 90 let newPlan = AscentPlanner.plan(tissues: tissues, pressure: pressure, gas: configuration.gas, 91 scale: scale, settings: configuration.deco, 92 anchorDepth: gradientAnchorDepth) 93 // The gradient factor anchor follows the deepest first stop and stays for the whole dive. 94 if let anchor = newPlan.gradientAnchorDepth { gradientAnchorDepth = max(gradientAnchorDepth ?? 0, anchor) } 95 plan = newPlan 96 updateSafetyStop(depth: depth, seconds: elapsedStep) 97 } 98 99 /// Advances the safety stop. Zone: 3 to 6.5 m; it restarts from zero when going back below 7 m. 100 private mutating func updateSafetyStop(depth: Double, seconds: Double) { 101 let deco = configuration.deco 102 guard maxDepth >= deco.safetyStopTriggerDepth else { return } 103 if case .done = safetyStopState { return } 104 // Missed, then back down: the stop is to be done again. 105 if case .missed = safetyStopState, depth <= deco.safetyStopDepth + 2 { return } 106 if plan?.inDecompression == true { safetyStopState = .pending; safetyStopTime = 0; return } 107 let required = deco.safetyStopMinutes * 60 108 if depth >= 3, depth <= deco.safetyStopDepth + 1.5 { 109 safetyStopTime += seconds 110 safetyStopState = safetyStopTime >= required ? .done : .running(remaining: required - safetyStopTime) 111 } else if depth > deco.safetyStopDepth + 2 { 112 safetyStopTime = 0 113 safetyStopState = .pending 114 } else if depth < 1 { 115 safetyStopState = .missed 116 } 117 } 118 119 public var safetyStop: SafetyStop { safetyStopState } 120 121 public var status: Status { 122 let pressure = last?.pressure ?? scale.surfacePressure 123 let depth = scale.depth(atPressure: pressure) 124 let plan = self.plan ?? AscentPlanner.plan(tissues: tissues, pressure: pressure, 125 gas: configuration.gas, scale: scale, 126 settings: configuration.deco) 127 let ceiling = scale.depth(atPressure: tissues.ceiling(gradientFactor: currentGF(depth: depth))) 128 let ppO2 = configuration.gas.ppO2(atPressure: pressure) 129 130 var warnings = Set<Warning>() 131 switch ascent.level { 132 case .fast: warnings.insert(.ascentFast) 133 case .tooFast: warnings.insert(.ascentTooFast) 134 case .normal: break 135 } 136 if ceiling > 0, depth < ceiling - 0.3 { warnings.insert(.ceilingViolated) } 137 // Above the required stop (stops come in 3 m steps, deeper than the continuous ceiling). 138 if let stop = plan.stops.first, depth < stop.depth - 0.6 { warnings.insert(.ceilingViolated) } 139 if ppO2 > configuration.ppO2Alarm { warnings.insert(.ppO2Critical) } 140 else if ppO2 > configuration.ppO2Warning { warnings.insert(.ppO2High) } 141 if depth >= configuration.depthLimit { warnings.insert(.depthLimit) } 142 if !plan.inDecompression, let ndl = plan.noDecompressionLimit, ndl < configuration.lowNoDecompression, 143 depth > configuration.deco.safetyStopDepth + 2 { warnings.insert(.lowNoDecompression) } 144 if case .missed = safetyStopState { warnings.insert(.missedSafetyStop) } 145 146 let elapsed = ((last?.time ?? 0) - (start ?? 0)) / 60 147 return Status(elapsed: elapsed, depth: depth, maxDepth: maxDepth, ascentRate: ascent.rate, 148 ppO2: ppO2, plan: plan, ceilingDepth: ceiling, 149 safetyStopRecommended: !plan.inDecompression 150 && maxDepth >= configuration.deco.safetyStopTriggerDepth, 151 safetyStop: safetyStopState, warnings: warnings) 152 } 153 154 private func currentGF(depth: Double) -> Double { 155 let gf = configuration.deco.gradientFactors 156 guard let anchor = gradientAnchorDepth, anchor > 0 else { return gf.high } 157 return gf.high - (gf.high - gf.low) * min(1, max(0, depth / anchor)) 158 } 159 160 /// Arrival at altitude: tissues saturated at the origin pressure (sea level by default), then 161 /// off-gassed for `hoursAgo` at the local pressure. Without this, a dive in a mountain lake on the 162 /// day of travel would be computed as if the diver lived there. 163 public static func arrival(from originPressure: Double = standardSurfacePressure, 164 to surfacePressure: Double, hoursAgo: Double) -> TissueState { 165 surfaceInterval(.saturated(surfacePressure: originPressure), minutes: hoursAgo * 60, 166 surfacePressure: surfacePressure) 167 } 168 169 /// Off-gassing at the surface between two dives (on air). 170 public static func surfaceInterval(_ tissues: TissueState, minutes: Double, 171 surfacePressure: Double) -> TissueState { 172 var t = tissues 173 t.stay(atPressure: surfacePressure, gas: .air, minutes: minutes) 174 return t 175 } 176 }