DiveSession.swift (6163B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 // The optional dive computer. The dive logic itself (start on submersion, decompression, alarms, depth held 3 // when the reading is missing, end at the surface) is `DiveMonitor` from RemoraKit, shared with Open Rémora; 4 // this adapter feeds it from the housing's pressure sensor and holds what belongs to this app: the on/off 5 // setting, the terms to accept, and the basic dive information shown even when the computer is off. 6 // 7 // Off (the default): the monitor receives nothing, nothing is recorded or shared. 8 import Foundation 9 import Observation 10 import RemoraDeco 11 import RemoraUI 12 13 @MainActor @Observable 14 final class DiveSession { 15 /// Name written in the recorded dives and in the UDDF files. 16 static let computerName = "Open Mérou" 17 /// Depth of the "depth limit" warning (m): the engine is made for recreational dives to 40 m at most. 18 static let depthLimit = 40.0 19 /// UserDefaults keys. 20 static let enabledKey = "diveComputer" 21 22 /// Warning to accept before the dive computer can be turned on. Changing `version` asks again. 23 static let terms = Terms( 24 version: 1, acceptedKey: "termsAcceptedVersion", appName: computerName, 25 devicePoint: String(localized: "The depth comes from the housing's sensor, read through a reverse-engineered protocol. An iPhone that films can overheat and iOS can stop the app: the computation is then lost."), 26 link: URL(string: "https://agora.schurger.org/open-merou/")!) 27 28 let store: DiveStore 29 let monitor: DiveMonitor 30 private let defaults: UserDefaults 31 private let now: () -> Date 32 private(set) var source = HousingDepthSource() 33 /// The setting. The computer only runs once the terms are accepted (`isActive`). 34 var enabled: Bool { didSet { defaults.set(enabled, forKey: Self.enabledKey) } } 35 private(set) var acceptedTermsVersion: Int 36 /// Sound, flash and screen wake-up are the app's business. 37 @ObservationIgnored var onCue: ((DiveCue) -> Void)? 38 /// A dive ended; `saved` is nil when nothing was kept, `simulation` true for the simulated housing. 39 @ObservationIgnored var onDiveEnded: ((_ saved: DiveLog?, _ simulation: Bool) -> Void)? 40 41 init(store: DiveStore = DiveStore(), defaults: UserDefaults = .standard, now: @escaping () -> Date = { Date() }) { 42 self.store = store 43 self.defaults = defaults 44 self.now = now 45 enabled = defaults.bool(forKey: Self.enabledKey) 46 acceptedTermsVersion = defaults.integer(forKey: Self.terms.acceptedKey) 47 var cue: ((DiveCue) -> Void)? 48 monitor = DiveMonitor(store: store, feedback: { cue?($0) }, now: now) 49 monitor.computerModel = Self.computerName 50 monitor.configure = { $0.depthLimit = Self.depthLimit } 51 cue = { [weak self] in self?.onCue?($0) } 52 monitor.onDiveEnded = { [weak self] saved, _ in 53 guard let self else { return } 54 self.monitor.finishedDive = nil 55 self.onDiveEnded?(saved, self.store.simulated) 56 } 57 } 58 59 var termsAccepted: Bool { 60 acceptedTermsVersion >= Self.terms.version || CommandLine.arguments.contains("-acceptTerms") 61 } 62 63 /// The dive computer runs: turned on, and terms accepted. 64 var isActive: Bool { enabled && termsAccepted } 65 66 /// The diver accepted the terms: the computer is turned on. 67 func acceptTerms() { 68 acceptedTermsVersion = Self.terms.version 69 defaults.set(acceptedTermsVersion, forKey: Self.terms.acceptedKey) 70 enabled = true 71 } 72 73 // MARK: Basic dive information (computer on or off) 74 75 /// Depth to display (m): the computer's during a dive it follows, otherwise the estimate of the source. 76 var depth: Double? { isActive && monitor.isDiving ? monitor.status?.depth : source.depth } 77 /// Start of the current dive (nil at the surface), from the source: an estimate. 78 var diveStart: Date? { source.diveStart } 79 /// The dive computer is on and following a dive. 80 var isComputing: Bool { isActive && monitor.isDiving } 81 /// The pressure sensor reports values that cannot be a pressure: no depth, no dive computer. 82 var sensorImplausible: Bool { source.implausible } 83 84 // MARK: Depth source 85 86 /// One sample of the housing's external pressure (Pa). `time`: clock of the source, in seconds. 87 func pressure(pa: Double, time: Double, simulated: Bool) { 88 let wasUnder = source.diveStart != nil 89 let reading = source.pressure(pa, time: time, now: now()) 90 if (source.diveStart != nil) != wasUnder { 91 DevLog.shared.event(wasUnder ? String(localized: "dive end (estimated)") : String(localized: "dive start (estimated)")) 92 } 93 guard isActive, let reading else { return } 94 store.simulated = simulated 95 monitor.receive(reading) 96 } 97 98 /// The Bluetooth link to the housing was lost: underwater, the depth becomes unknown at once. 99 func linkLost() { 100 guard isActive, let reading = source.linkLost(time: now().timeIntervalSinceReferenceDate) else { return } 101 monitor.receive(reading) 102 } 103 104 /// A new housing session starts (reconnection asked by the user, simulation started or stopped): 105 /// the surface pressure is measured afresh. A dive in progress is ended. 106 func reset() { 107 if monitor.isDiving { monitor.end() } 108 source = HousingDepthSource() 109 } 110 111 // MARK: Photo and video metadata 112 113 /// Basic dive information for the metadata of a shot (plain English, not localized: it is data). 114 /// Nil at the surface. The temperature is the one inside the housing, and says so. 115 func shotComment(housingTemperature: Double?) -> String? { 116 guard let start = source.diveStart, let depth else { return nil } 117 let seconds = max(0, Int(now().timeIntervalSince(start))) 118 var text = String(format: "Open Mérou: depth %.1f m%@, dive time %d:%02d", depth, 119 isComputing ? "" : " (estimated)", seconds / 60, seconds % 60) 120 if let housingTemperature { text += String(format: ", temperature inside the housing %.1f °C", housingTemperature) } 121 return text 122 } 123 }