remora-kit

RemoraKit, shared dive computer engine (Buhlmann ZHL-16C + GF) and SwiftUI components for Open Remora and Open Merou
git clone https://git.schurger.org/remora-kit.git
Log | Files | Refs | README | LICENSE

DiveMonitor.swift (7396B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import Observation
      4 
      5 /// Where the dive logic reads the diver's settings and logbook, and saves a finished dive.
      6 @MainActor
      7 public protocol DiveLogStore: AnyObject {
      8     var settings: UserSettings { get }
      9     var logbook: Logbook { get }
     10     /// Adds the dive to the logbook and returns it as saved (with its number).
     11     func add(_ dive: DiveLog) -> DiveLog
     12 }
     13 
     14 /// The dive in progress for an app: an observable wrapper around `DiveTracker` that runs the watchdog and the
     15 /// demo dives, saves finished dives in the store and passes the feedback cues on.
     16 ///
     17 /// The app creates one, forwards the readings of its depth source to `receive`, and shows `status`,
     18 /// `warnings`, `depthUnknown`… What is specific to a platform (vibrations or sounds, keeping the app in the
     19 /// foreground, a workout session) stays in the app, driven by `feedback`, `onDiveStarted` and `onDiveEnded`.
     20 @MainActor @Observable
     21 public final class DiveMonitor {
     22     public private(set) var tracker = DiveTracker()
     23     /// Dive that just ended and was saved: the app opens its summary, then sets this back to nil.
     24     public var finishedDive: DiveLog?
     25     /// Site name given to demo dives.
     26     public var simulationSite: String?
     27     /// Position of the entry point, taken before the dive (GPS does not work underwater): written into the
     28     /// next real dive saved, then cleared.
     29     public var entryPosition: (latitude: Double, longitude: Double)?
     30     /// Called when a dive starts, before its first cue.
     31     public var onDiveStarted: ((_ simulation: Bool) -> Void)?
     32     /// Called when a dive ends; `saved` is nil when nothing was kept (the diver never went down).
     33     public var onDiveEnded: ((_ saved: DiveLog?, _ simulation: Bool) -> Void)?
     34     /// Last word of the app on the computer configuration, after the diver's settings: what depends on the
     35     /// device rather than on the diver (depth limit of its sensor, ascent rate window). Evaluated when a dive starts.
     36     public var configure: ((inout DiveComputer.Configuration) -> Void)?
     37 
     38     private let store: any DiveLogStore
     39     private let feedback: (DiveCue) -> Void
     40     private let now: () -> Date
     41     @ObservationIgnored private var simulation: Task<Void, Never>?
     42     @ObservationIgnored private var watchdog: Task<Void, Never>?
     43 
     44     public init(store: any DiveLogStore, feedback: @escaping (DiveCue) -> Void,
     45                 now: @escaping () -> Date = { Date() }) {
     46         self.store = store
     47         self.feedback = feedback
     48         self.now = now
     49     }
     50 
     51     public var isDiving: Bool { tracker.isDiving }
     52     public var isSimulation: Bool { tracker.isSimulation }
     53     public var status: DiveComputer.Status? { tracker.status }
     54     public var temperature: Double? { tracker.temperature }
     55     public var sourceMessage: String? { tracker.sourceMessage }
     56     public var depthUnknown: Bool { tracker.depthUnknown }
     57     public var warnings: Set<DiveComputer.Warning> { tracker.warnings }
     58     public var isAlarming: Bool { tracker.isAlarming }
     59     public var activeWarnings: Set<DiveComputer.Warning> { tracker.activeWarnings }
     60     public var forcedAlarm: Bool {
     61         get { tracker.forcedAlarm }
     62         set { tracker.forcedAlarm = newValue }
     63     }
     64     /// Name of the computer written in the dives recorded ("Open Rémora" by default).
     65     public var computerModel: String {
     66         get { tracker.computerModel }
     67         set { tracker.computerModel = newValue }
     68     }
     69     public var tuning: DiveTracker.Tuning {
     70         get { tracker.tuning }
     71         set { tracker.tuning = newValue }
     72     }
     73 
     74     private var configuration: DiveComputer.Configuration {
     75         var c = (try? store.settings.configuration()) ?? DiveComputer.Configuration()
     76         configure?(&c)
     77         return c
     78     }
     79 
     80     /// A reading from the depth source: the dive starts by itself on submersion.
     81     public func receive(_ reading: DiveReading) {
     82         let configuration = configuration, logbook = store.logbook
     83         let events = tracker.handle(reading, now: now(), configuration: configuration, logbook: logbook)
     84         apply(events)
     85     }
     86 
     87     /// Starts a real dive by hand, before getting in the water.
     88     public func startManually() {
     89         guard !tracker.isDiving else { return }
     90         let events = tracker.startManually(now: now(), configuration: configuration, logbook: store.logbook)
     91         apply(events)
     92     }
     93 
     94     /// Marks the current point of the dive.
     95     @discardableResult
     96     public func mark(heading: Double? = nil) -> DiveMark? { tracker.mark(heading: heading) }
     97     public var markCount: Int { tracker.markCount }
     98 
     99     /// Ends the dive and adds it to the logbook (nothing is kept when the diver never went down).
    100     public func end() {
    101         let events = tracker.end()
    102         if events.isEmpty { stopTasks() }
    103         apply(events)
    104     }
    105 
    106     /// Dry demo dive, accelerated `speed` times.
    107     public func startSimulation(_ profile: DemoProfile = .reef, speed: Double = 30) {
    108         guard !tracker.isDiving else { return }
    109         let configuration = configuration, logbook = store.logbook
    110         let events = tracker.startSimulation(now: now(), configuration: configuration, logbook: logbook)
    111         apply(events)
    112         let depths = profile.depths + Array(repeating: 0, count: 61)
    113         simulation = Task { [weak self] in
    114             for (t, d) in depths.enumerated() {
    115                 guard !Task.isCancelled, let self, self.tracker.isDiving else { return }
    116                 let events = self.tracker.simulate(time: Double(t), depth: d,
    117                                                    temperature: DemoProfile.temperature(atDepth: d), now: self.now())
    118                 self.apply(events)
    119                 try? await Task.sleep(for: .seconds(1 / speed))
    120             }
    121         }
    122     }
    123 
    124     private func apply(_ events: [DiveTracker.Event]) {
    125         for event in events {
    126             switch event {
    127             case .diveStarted(let simulated):
    128                 if !simulated { startWatchdog() }
    129                 onDiveStarted?(simulated)
    130             case .cue(let cue):
    131                 feedback(cue)
    132             case .diveEnded(let dive, let simulated):
    133                 stopTasks()
    134                 guard var dive else {
    135                     onDiveEnded?(nil, simulated)
    136                     continue
    137                 }
    138                 if simulated {
    139                     dive.site = simulationSite
    140                 } else if let position = entryPosition {
    141                     dive.latitude = position.latitude
    142                     dive.longitude = position.longitude
    143                     entryPosition = nil
    144                 }
    145                 let saved = store.add(dive)
    146                 finishedDive = saved
    147                 feedback(.diveSaved)
    148                 onDiveEnded?(saved, simulated)
    149             }
    150         }
    151     }
    152 
    153     private func stopTasks() {
    154         simulation?.cancel()
    155         simulation = nil
    156         watchdog?.cancel()
    157         watchdog = nil
    158     }
    159 
    160     private func startWatchdog() {
    161         watchdog?.cancel()
    162         watchdog = Task { [weak self] in
    163             while !Task.isCancelled {
    164                 try? await Task.sleep(for: .seconds(2))
    165                 guard let self, self.tracker.isDiving, !self.tracker.isSimulation else { return }
    166                 let events = self.tracker.tick(now: self.now())
    167                 self.apply(events)
    168             }
    169         }
    170     }
    171 }