DiveTracker.swift (15131B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 4 /// What a depth source reports. The Apple Watch feeds these from its submersion sensor; another device 5 /// (a housing with a pressure sensor, a simulator) feeds the same values from whatever it has. 6 public enum DiveReading: Sendable, Hashable { 7 /// `time` in seconds on the clock of the source (only differences matter), pressures in bar. 8 /// `absolute` is the ambient pressure; nil when there is no measurement: out of the water, but also when 9 /// the sensor cannot measure underwater (beyond its limit, error, link lost). `submerged` tells them apart. 10 case pressure(time: Double, surface: Double, absolute: Double?, submerged: Bool) 11 /// Water temperature, °C. 12 case temperature(Double) 13 /// Text from the source to show on the dive screen (nil clears it). 14 case message(String?) 15 } 16 17 /// Feedback the dive logic asks for. The app turns each cue into a vibration, a sound or a flash. 18 public enum DiveCue: Sendable, Hashable, CaseIterable { 19 /// Underwater and the depth reading was just lost. 20 case depthLost 21 case safetyStopStarted 22 case safetyStopDone 23 /// Alarm in progress (violation or depth unknown): repeated every `alarmRepeat` seconds while it lasts. 24 case alarm 25 /// Warning: once when it appears, repeated every `warningRepeat` seconds while it lasts. 26 case warning 27 /// A dive was just saved in the logbook. 28 case diveSaved 29 } 30 31 extension DiveComputer.Warning { 32 /// Violations are alarms (the whole screen flashes); the other warnings only blink the value concerned. 33 public var isViolation: Bool { [.ceilingViolated, .ascentTooFast, .ppO2Critical].contains(self) } 34 /// Most serious first. 35 public var rank: Int { isViolation ? 0 : 1 } 36 } 37 38 /// The dive in progress, independent of any platform: starts the dive on submersion, feeds the computer and 39 /// the recorder, holds the depth when the reading is missing, decides when to give feedback, and ends the dive 40 /// after a minute at the surface. A value type with no clock and no timer of its own: the caller passes the 41 /// readings, the wall-clock time (`now`) and calls `tick` regularly; every call returns what happened. 42 /// `DiveMonitor` wraps it for an app. 43 public struct DiveTracker: Sendable { 44 public enum Event: Sendable, Hashable { 45 case diveStarted(simulation: Bool) 46 case cue(DiveCue) 47 /// The dive is over. No dive log when the diver never went below `underDepth`. 48 case diveEnded(DiveLog?, simulation: Bool) 49 } 50 51 public struct Tuning: Sendable, Hashable { 52 /// Pressure above the surface pressure that starts a dive (bar; 0.03 ≈ 30 cm of water). 53 public var startOverpressure = 0.03 54 /// The dive counts once the diver went below this depth (m)… 55 public var underDepth = 1.0 56 /// …and ends after `surfaceSeconds` above this depth (m). 57 public var surfaceDepth = 0.3 58 public var surfaceSeconds = 60.0 59 /// Silence of the source (s) after which `tick` moves time forward by itself. 60 public var silence = 5.0 61 /// Silent source: below this overpressure (bar; 0.15 ≈ 1.5 m) the diver is considered out of the water, 62 /// deeper the last known depth is held and flagged. 63 public var shallowOverpressure = 0.15 64 /// Repeat periods of the feedback (s, wall clock). 65 public var alarmRepeat = 2.0 66 public var warningRepeat = 15.0 67 /// A dive started by hand ends by itself when the diver has still not gone under after this long (s). 68 public var manualStartTimeout = 1800.0 69 public init() {} 70 } 71 72 public var tuning = Tuning() 73 /// Name of the computer written in the dives recorded (the app's name). 74 public var computerModel = "Open Rémora" 75 /// Forces the alarm state (screenshots and feedback tests). 76 public var forcedAlarm = false 77 78 public private(set) var isDiving = false 79 public private(set) var isSimulation = false 80 public private(set) var status: DiveComputer.Status? 81 public private(set) var temperature: Double? 82 public private(set) var sourceMessage: String? 83 /// Underwater without a depth reading (sensor limit exceeded, error, silence): the computer assumes the 84 /// diver stays at the last known depth, and the app must say so in large type. 85 public private(set) var depthUnknown = false 86 public private(set) var warnings = Set<DiveComputer.Warning>() 87 88 private var recorder: DiveRecorder? 89 private var surfacedAt: Double? 90 /// Dive started by hand, at the surface. 91 private var manualStart = false 92 /// Surface pressure of the last reading received out of a dive. 93 private var lastSurfacePressure: Double? 94 /// Started by hand before any reading: the surface pressure is taken from the first one. 95 private var surfaceAssumed = false 96 private var wentUnder = false 97 private var safetyStop = DiveComputer.SafetyStop.notRequired 98 private var lastReadingAt: Date? 99 private var lastPressure: Double? 100 private var surfacePressure = standardSurfacePressure 101 private var lastWarningCue: [DiveComputer.Warning: Date] = [:] 102 private var lastAlarmCue: Date? 103 104 public init() {} 105 106 /// Alarm in progress: a violation, or depth unknown. 107 public var isAlarming: Bool { depthUnknown || warnings.contains(where: \.isViolation) || forcedAlarm } 108 /// Warnings in progress (violations excluded). 109 public var activeWarnings: Set<DiveComputer.Warning> { warnings.filter { !$0.isViolation } } 110 /// Depth ↔ pressure conversion of the dive in progress. 111 public var scale: DepthScale? { recorder?.computer.scale } 112 113 /// A reading from the depth source. `configuration` and `logbook` are only evaluated when this reading 114 /// starts a dive (the logbook provides the tissues of a recent dive). 115 public mutating func handle(_ reading: DiveReading, now: Date, 116 configuration: @autoclosure () -> DiveComputer.Configuration, 117 logbook: @autoclosure () -> Logbook?) -> [Event] { 118 switch reading { 119 case .message(let text): 120 sourceMessage = text 121 return [] 122 case .temperature(let celsius): 123 temperature = celsius 124 return [] 125 case .pressure(let time, let surface, let absolute, let submerged): 126 // A simulated dive in progress ignores the real sensor. 127 guard !(isDiving && isSimulation) else { return [] } 128 var events: [Event] = [] 129 if !isDiving { 130 lastSurfacePressure = surface 131 guard let absolute, absolute > surface + tuning.startOverpressure else { return [] } 132 events += start(surfacePressure: surface, simulation: false, now: now, 133 configuration: configuration(), logbook: logbook()) 134 } 135 if surfaceAssumed, !wentUnder, let r = recorder { 136 // Started by hand before the sensor said anything: restart the computer on the real surface pressure. 137 recorder = DiveRecorder(configuration: configuration(), surfacePressure: surface, 138 start: r.start, logbook: logbook()) 139 surfacePressure = surface 140 } 141 surfaceAssumed = false 142 lastReadingAt = now 143 if let absolute { 144 depthUnknown = false 145 lastPressure = absolute 146 events += ingest(time: time, pressure: absolute, now: now) 147 } else if submerged, let held = lastPressure { 148 // Underwater without a reading: stay at the last known depth (tissues keep loading), 149 // never a false return to the surface. 150 events += signalDepthUnknown() 151 events += ingest(time: time, pressure: held, now: now) 152 } else { 153 depthUnknown = false 154 lastPressure = surface 155 events += ingest(time: time, pressure: surface, now: now) 156 } 157 return events 158 } 159 } 160 161 /// Watchdog, to be called every couple of seconds during a real dive: when the source has been silent for 162 /// more than `silence` seconds, time still moves forward. Near the surface the diver is considered out 163 /// (the dive ends after a minute); deeper, the last known depth is held and flagged. 164 public mutating func tick(now: Date) -> [Event] { 165 guard isDiving, !isSimulation, 166 let last = lastReadingAt, now.timeIntervalSince(last) > tuning.silence, 167 let held = lastPressure else { return [] } 168 let shallow = held < surfacePressure + tuning.shallowOverpressure 169 var events: [Event] = [] 170 if !shallow { events += signalDepthUnknown() } 171 events += ingest(time: now.timeIntervalSinceReferenceDate, 172 pressure: shallow ? surfacePressure : held, now: now) 173 return events 174 } 175 176 /// Starts a real dive by hand, at the surface (the diver asked for the dive screens before getting in). 177 /// The dive clock runs from now; `tick` moves it forward while the source is silent. 178 public mutating func startManually(now: Date, configuration: DiveComputer.Configuration, 179 logbook: Logbook?) -> [Event] { 180 guard !isDiving else { return [] } 181 let surface = lastSurfacePressure 182 var events = start(surfacePressure: surface ?? standardSurfacePressure, simulation: false, now: now, 183 configuration: configuration, logbook: logbook) 184 manualStart = true 185 surfaceAssumed = surface == nil 186 lastPressure = surfacePressure 187 events += ingest(time: now.timeIntervalSinceReferenceDate, pressure: surfacePressure, now: now) 188 return events 189 } 190 191 /// Marks the current point of the dive (kept in the dive log). Nil when no dive is in progress. 192 public mutating func mark(heading: Double? = nil) -> DiveMark? { 193 guard isDiving, var r = recorder else { return nil } 194 let mark = r.mark(heading: heading) 195 recorder = r 196 return mark 197 } 198 199 /// Number of points marked in the dive in progress. 200 public var markCount: Int { recorder?.marks.count ?? 0 } 201 202 /// Ends the dive now (it also ends by itself after a minute at the surface). 203 public mutating func end() -> [Event] { 204 depthUnknown = false 205 guard let r = recorder else { return [] } 206 recorder = nil 207 isDiving = false 208 guard wentUnder else { return [.diveEnded(nil, simulation: isSimulation)] } 209 var dive = r.finish() 210 if isSimulation { dive.source = .simulation } 211 return [.diveEnded(dive, simulation: isSimulation)] 212 } 213 214 /// Starts a simulated dive (dry demo); feed it with `simulate`. 215 public mutating func startSimulation(now: Date, configuration: DiveComputer.Configuration, 216 logbook: Logbook?) -> [Event] { 217 guard !isDiving else { return [] } 218 return start(surfacePressure: standardSurfacePressure, simulation: true, now: now, 219 configuration: configuration, logbook: logbook) 220 } 221 222 /// One step of a simulated dive: `time` in seconds since its start, `depth` in metres. 223 public mutating func simulate(time: Double, depth: Double, temperature: Double?, now: Date) -> [Event] { 224 guard isDiving, isSimulation, let scale else { return [] } 225 self.temperature = temperature 226 return ingest(time: time, pressure: scale.pressure(atDepth: depth), now: now) 227 } 228 229 private mutating func signalDepthUnknown() -> [Event] { 230 defer { depthUnknown = true } 231 return depthUnknown ? [] : [.cue(.depthLost)] 232 } 233 234 private mutating func start(surfacePressure: Double, simulation: Bool, now: Date, 235 configuration: DiveComputer.Configuration, logbook: Logbook?) -> [Event] { 236 recorder = DiveRecorder(configuration: configuration, surfacePressure: surfacePressure, 237 start: now, logbook: logbook, computerModel: computerModel) 238 isSimulation = simulation 239 isDiving = true 240 self.surfacePressure = surfacePressure 241 lastPressure = nil 242 lastReadingAt = now 243 depthUnknown = false 244 lastWarningCue = [:] 245 lastAlarmCue = nil 246 surfacedAt = nil 247 wentUnder = false 248 manualStart = false 249 surfaceAssumed = false 250 warnings = [] 251 safetyStop = .notRequired 252 status = nil 253 return [.diveStarted(simulation: simulation)] 254 } 255 256 private mutating func ingest(time: Double, pressure: Double, now: Date) -> [Event] { 257 guard var r = recorder else { return [] } 258 let s = r.record(time: time, pressure: pressure, temperature: temperature) 259 recorder = r 260 status = s 261 var events: [Event] = [] 262 263 // Safety stop: one cue at the start and at the end of the countdown. 264 switch (safetyStop, s.safetyStop) { 265 case (.pending, .running), (.notRequired, .running): events.append(.cue(.safetyStopStarted)) 266 case (.running, .done): events.append(.cue(.safetyStopDone)) 267 default: break 268 } 269 safetyStop = s.safetyStop 270 271 // Feedback (wall clock, not the dive clock). 272 // Alarm (violation, depth unknown): strong cue every `alarmRepeat` seconds for as long as it lasts. 273 // Warning: one cue when it appears, repeated every `warningRepeat` seconds for as long as it lasts. 274 warnings = s.warnings 275 if isAlarming { 276 if lastAlarmCue.map({ now.timeIntervalSince($0) >= tuning.alarmRepeat }) ?? true { 277 lastAlarmCue = now 278 events.append(.cue(.alarm)) 279 } 280 } else { 281 lastAlarmCue = nil 282 let due = s.warnings.filter { w in 283 lastWarningCue[w].map { now.timeIntervalSince($0) >= tuning.warningRepeat } ?? true 284 } 285 if !due.isEmpty { 286 for w in due { lastWarningCue[w] = now } 287 events.append(.cue(.warning)) 288 } 289 } 290 // A warning that went away and came back gives a cue again, but no more than once per period. 291 lastWarningCue = lastWarningCue.filter { 292 now.timeIntervalSince($0.value) < tuning.warningRepeat || s.warnings.contains($0.key) 293 } 294 295 // Automatic end: a minute at the surface after going below `underDepth`. 296 if s.depth > tuning.underDepth { wentUnder = true } 297 if s.depth < tuning.surfaceDepth { 298 if surfacedAt == nil { surfacedAt = time } 299 if wentUnder, let since = surfacedAt, time - since >= tuning.surfaceSeconds { events += end() } 300 } else { 301 surfacedAt = nil 302 } 303 // Started by hand and never went under: give up after a while. 304 if isDiving, manualStart, !wentUnder, s.elapsed * 60 >= tuning.manualStartTimeout { events += end() } 305 return events 306 } 307 }