open-remora

Open Remora, a free secondary dive computer for Apple Watch Ultra
git clone https://git.schurger.org/open-remora.git
Log | Files | Refs | README | LICENSE

DiveSession.swift (14507B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import Observation
      4 import WatchKit
      5 import RemoraDeco
      6 import RemoraUI
      7 
      8 /// The dive in progress on the watch. The dive logic itself (start on submersion, depth held when the reading
      9 /// is missing, alarms, end at the surface, demo dives) is `DiveMonitor` from RemoraDeco, shared with other
     10 /// apps; this adapter feeds it from the watch sensor and adds what belongs to the watch: haptics, the workout
     11 /// session, Apple's dive session, the Action button and "Ready to dive".
     12 @MainActor @Observable
     13 final class DiveSession {
     14     let monitor: DiveMonitor
     15     /// "Ready to dive": the workout session is running, the app stays active until submersion.
     16     private(set) var isReady = false
     17 
     18     var isDiving: Bool { monitor.isDiving }
     19     var isSimulation: Bool { monitor.isSimulation }
     20     var status: DiveComputer.Status? { monitor.status }
     21     var temperature: Double? { monitor.temperature }
     22     var sensorMessage: String? { monitor.sourceMessage }
     23     /// Underwater without a depth reading: the computer holds the last known depth and says so in large type.
     24     var depthUnknown: Bool { monitor.depthUnknown }
     25     var warnings: Set<DiveComputer.Warning> { monitor.warnings }
     26     /// Alarm in progress: a violation, or depth unknown. The whole screen flashes red.
     27     var isAlarming: Bool { monitor.isAlarming }
     28     /// Warnings in progress (violations excluded): only the value concerned blinks.
     29     var activeWarnings: Set<DiveComputer.Warning> { monitor.activeWarnings }
     30     /// Dive that just ended: the home screen opens its summary.
     31     var finishedDive: DiveLog? {
     32         get { monitor.finishedDive }
     33         set { monitor.finishedDive = newValue }
     34     }
     35 
     36     private var sensor: SubmersionSource?
     37     let workout = DiveWorkout()
     38     /// Apple's dive session: app in the foreground and touch screen locked.
     39     let runtime = DiveRuntime()
     40     /// Touch screen locked (Water Lock; long press on the crown to leave it). Read from the watch itself,
     41     /// not deduced from the dive session: the system also locks the screen on its own.
     42     private(set) var screenLocked = false
     43     @ObservationIgnored private var lockWatch: Task<Void, Never>?
     44     /// Page of the dive screen (0 main, 1 details, 2 compass): crown or Action button.
     45     var divePage = 0
     46     /// Banner shown for a few seconds after an Action button press.
     47     private(set) var actionMessage: String?
     48     private var actionMessageTask: Task<Void, Never>?
     49     /// Compass (the Action button sets the bearing there).
     50     var compass: Compass?
     51     /// Position of the entry point, taken while the "Ready" screen is shown.
     52     let position = EntryPosition()
     53     /// Stopwatch of the details page (Action button: start, stop, reset).
     54     private(set) var stopwatch = Stopwatch()
     55     /// Bearing set by the Action button during this dive: the next press turns it around (way back).
     56     private var bearingIsReciprocal = false
     57     private var bearingSetInDive = false
     58     let diagnostics = Diagnostics()
     59     /// The session of the app, for the Action button intents and the app delegate.
     60     static weak var current: DiveSession?
     61     /// Called after every saved dive (sending to the iPhone).
     62     var onDiveSaved: (() -> Void)?
     63 
     64     init(store: LogStore) {
     65         monitor = DiveMonitor(store: store, feedback: { cue in
     66             WKInterfaceDevice.current().play(Self.haptic(for: cue))
     67         })
     68         monitor.simulationSite = String(localized: "Demo")
     69         // Screenshots only (`-testAlarm`).
     70         monitor.forcedAlarm = CommandLine.arguments.contains("-testAlarm")
     71         Self.current = self
     72         monitor.onDiveStarted = { [weak self] simulation in self?.diveStarted(simulation: simulation) }
     73         monitor.onDiveEnded = { [weak self] saved, simulation in self?.diveEnded(saved, simulation: simulation) }
     74         runtime.onChange = { [weak self] _, text in
     75             self?.diagnostics.runtime = text
     76             self?.readScreenLock()
     77         }
     78         // Water Lock has no notification: it is read twice a second.
     79         lockWatch = Task { [weak self] in
     80             while !Task.isCancelled {
     81                 try? await Task.sleep(for: .milliseconds(500))
     82                 guard let self else { return }
     83                 self.readScreenLock()
     84             }
     85         }
     86     }
     87 
     88     private func readScreenLock() {
     89         var locked = WKInterfaceDevice.current().isWaterLockEnabled
     90         // Screenshots and tests in the simulator: `-locked`, or `-lockToggle` (changes every 3 s).
     91         if Self.forcedLock { locked = true }
     92         if Self.toggledLock { locked = Int(Date().timeIntervalSinceReferenceDate / 3) % 2 == 0 }
     93         if locked != screenLocked { screenLocked = locked }
     94         if locked, isReady || isDiving, !diagnostics.lockSeen { diagnostics.lockSeen = true }
     95     }
     96 
     97     private static let forcedLock = CommandLine.arguments.contains("-locked")
     98     private static let toggledLock = CommandLine.arguments.contains("-lockToggle")
     99 
    100     /// The vibration of each cue of the dive logic.
    101     private static func haptic(for cue: DiveCue) -> WKHapticType {
    102         switch cue {
    103         case .depthLost, .alarm: .failure
    104         case .safetyStopStarted: .start
    105         case .safetyStopDone, .diveSaved: .success
    106         case .warning: .notification
    107         }
    108     }
    109 
    110     /// Battery level (0 to 1); nil when unknown.
    111     var batteryLevel: Double? {
    112         let device = WKInterfaceDevice.current()
    113         device.isBatteryMonitoringEnabled = true
    114         return device.batteryLevel >= 0 ? Double(device.batteryLevel) : nil
    115     }
    116 
    117     /// Before getting in the water: starts the diving workout so that the app stays in the foreground.
    118     func getReady() {
    119         guard !isDiving, !isReady else { return }
    120         isReady = true
    121         diagnostics.reset()
    122         workout.start()
    123         startDiveSession()
    124         position.start()
    125     }
    126 
    127     /// From the "Ready" screen: starts the dive now, before getting in the water (Action button).
    128     func startDiveNow() {
    129         guard isReady, !isDiving else { return }
    130         monitor.startManually()
    131     }
    132 
    133     /// Action button wired to the app, and the app kept in the foreground. The diving workout does that (and
    134     /// the watch locks its screen); starting Apple's dive session on top of it fails on the watch
    135     /// (WKExtendedRuntimeSessionError), so it is only started when the workout could not be. The session the
    136     /// system starts by itself below 1 m is still adopted (`AppDelegate`).
    137     private func startDiveSession() {
    138         guard SubmersionSource.isAvailable else { return }
    139         if workout.state == .running {
    140             diagnostics.workout = String(localized: "running")
    141             diagnostics.runtime = String(localized: "not requested (workout running)")
    142         } else {
    143             diagnostics.workout = workout.lastError ?? String(localized: "not started")
    144             runtime.start()
    145         }
    146         Task { [diagnostics] in
    147             diagnostics.donation = await ActionButton.offerNextAction() ?? String(localized: "donated")
    148         }
    149     }
    150 
    151     /// Action button during the session; the touch screen is locked, the crown changes page.
    152     /// "Ready" screen: starts the dive now. During the dive, it acts on the page shown:
    153     /// main page: marks the point in the dive log; details page: stopwatch (start, stop, reset);
    154     /// compass page: sets the bearing, then turns it around for the way back, then clears it.
    155     func actionPressed() {
    156         guard isReady || isDiving else { return }
    157         WKInterfaceDevice.current().play(.click)
    158         diagnostics.notePress(depth: isDiving ? status?.depth : nil)
    159         guard isDiving else {
    160             startDiveNow()
    161             return
    162         }
    163         let text: String
    164         switch divePage {
    165         case 1:
    166             switch stopwatch.press() {
    167             case .running: text = String(localized: "STOPWATCH STARTED")
    168             case .stopped: text = String(localized: "STOPWATCH STOPPED")
    169             case .idle: text = String(localized: "STOPWATCH RESET")
    170             }
    171         case 2:
    172             guard let compass, let heading = compass.heading else { return }
    173             if !bearingSetInDive || compass.bearing == nil {
    174                 compass.setBearing()
    175                 bearingSetInDive = true
    176                 bearingIsReciprocal = false
    177                 text = String(localized: "BEARING SET \(Int(heading.rounded()) % 360)°")
    178             } else if !bearingIsReciprocal, let bearing = compass.bearing {
    179                 let back = (bearing + 180).truncatingRemainder(dividingBy: 360)
    180                 compass.bearing = back
    181                 bearingIsReciprocal = true
    182                 text = String(localized: "WAY BACK \(Int(back.rounded()) % 360)°")
    183             } else {
    184                 compass.clearBearing()
    185                 bearingSetInDive = false
    186                 bearingIsReciprocal = false
    187                 text = String(localized: "BEARING CLEARED")
    188             }
    189         default:
    190             guard let mark = monitor.mark(heading: compass?.heading) else { return }
    191             text = String(localized: "MARK \(monitor.markCount) · \(Format.depth(mark.depth)) m")
    192         }
    193         actionMessage = text
    194         actionMessageTask?.cancel()
    195         actionMessageTask = Task { [weak self] in
    196             try? await Task.sleep(for: .seconds(3))
    197             if !Task.isCancelled { self?.actionMessage = nil }
    198         }
    199     }
    200 
    201     func cancelReady() {
    202         guard isReady, !isDiving else { return }
    203         isReady = false
    204         runtime.stop()
    205         position.stop()
    206         Task { await workout.finish(with: nil) }
    207     }
    208 
    209     var sensorAvailable: Bool { SubmersionSource.isAvailable }
    210 
    211     /// Listens to the sensor: the dive starts by itself on submersion.
    212     func listen() {
    213         guard sensor == nil, SubmersionSource.isAvailable else { return }
    214         sensor = SubmersionSource { [weak self] reading in self?.monitor.receive(reading) }
    215     }
    216 
    217     private func diveStarted(simulation: Bool) {
    218         // Real dive without "Ready to dive": the session starts on submersion.
    219         if !simulation, !isReady {
    220             diagnostics.reset()
    221             workout.start()
    222             startDiveSession()
    223         }
    224         isReady = false
    225         divePage = 0
    226         stopwatch = Stopwatch()
    227         bearingSetInDive = false
    228         bearingIsReciprocal = false
    229         if !simulation {
    230             // The entry point: the best fix taken on the "Ready" screen (none without "Ready to dive").
    231             if let fix = position.fix {
    232                 monitor.entryPosition = (fix.coordinate.latitude, fix.coordinate.longitude)
    233             }
    234             position.stop()
    235             // The compass runs for the whole dive, so that a mark knows its heading.
    236             compass?.start()
    237         }
    238     }
    239 
    240     /// `saved` is nil when nothing was kept (the diver never went down).
    241     private func diveEnded(_ saved: DiveLog?, simulation: Bool) {
    242         if !simulation {
    243             runtime.stop()
    244             compass?.stop()
    245             monitor.entryPosition = nil
    246             Task { await workout.finish(with: saved) }
    247         }
    248         if saved != nil { onDiveSaved?() }
    249     }
    250 
    251     /// Ends the dive and adds it to the logbook (nothing is kept when the diver never went down).
    252     func end() { monitor.end() }
    253 
    254     /// Dry demo dive, accelerated.
    255     func startSimulation(_ profile: DemoProfile = .reef, speed: Double = 30) {
    256         guard !isDiving, !isReady else { return }
    257         monitor.startSimulation(profile, speed: speed)
    258     }
    259 }
    260 
    261 /// Stopwatch driven by a single button: start, stop, reset.
    262 struct Stopwatch {
    263     enum State { case idle, running, stopped }
    264     private(set) var state = State.idle
    265     private var startedAt: Date?
    266     private var frozen = 0.0
    267 
    268     /// Seconds shown at `date`.
    269     func elapsed(at date: Date = Date()) -> Double {
    270         switch state {
    271         case .idle: 0
    272         case .running: max(0, date.timeIntervalSince(startedAt ?? date))
    273         case .stopped: frozen
    274         }
    275     }
    276 
    277     /// One press; returns the new state.
    278     mutating func press(at date: Date = Date()) -> State {
    279         switch state {
    280         case .idle:
    281             startedAt = date
    282             state = .running
    283         case .running:
    284             frozen = elapsed(at: date)
    285             state = .stopped
    286         case .stopped:
    287             state = .idle
    288         }
    289         return state
    290     }
    291 }
    292 
    293 /// What we want to know after a trial in the water: did the Action button reach the app, and did Apple's
    294 /// dive session (screen locked) run. Kept from one launch to the next (the texts are stored as displayed).
    295 @MainActor @Observable
    296 final class Diagnostics {
    297     private let defaults = UserDefaults.standard
    298     private(set) var presses: Int
    299     private(set) var deepestPress: Double?
    300     var runtime: String { didSet { defaults.set(runtime, forKey: "diag.runtime") } }
    301     var donation: String { didSet { defaults.set(donation, forKey: "diag.donation") } }
    302     var workout: String { didSet { defaults.set(workout, forKey: "diag.workout") } }
    303     private(set) var startedAt: Date?
    304     /// The watch reported its screen as locked during the session.
    305     var lockSeen: Bool { didSet { defaults.set(lockSeen, forKey: "diag.lock") } }
    306 
    307     init() {
    308         lockSeen = defaults.bool(forKey: "diag.lock")
    309         presses = defaults.integer(forKey: "diag.presses")
    310         deepestPress = defaults.object(forKey: "diag.deepest") as? Double
    311         runtime = defaults.string(forKey: "diag.runtime") ?? String(localized: "never requested")
    312         donation = defaults.string(forKey: "diag.donation") ?? String(localized: "never donated")
    313         workout = defaults.string(forKey: "diag.workout") ?? "–"
    314         startedAt = defaults.object(forKey: "diag.start") as? Date
    315     }
    316 
    317     func reset() {
    318         presses = 0
    319         deepestPress = nil
    320         lockSeen = false
    321         // Nothing left from an earlier trial (or an earlier build): every line is about this one.
    322         runtime = "–"
    323         donation = "–"
    324         workout = "–"
    325         startedAt = Date()
    326         defaults.set(0, forKey: "diag.presses")
    327         defaults.removeObject(forKey: "diag.deepest")
    328         defaults.set(startedAt, forKey: "diag.start")
    329     }
    330 
    331     func notePress(depth: Double?) {
    332         presses += 1
    333         defaults.set(presses, forKey: "diag.presses")
    334         if let depth, depth > (deepestPress ?? -1) {
    335             deepestPress = depth
    336             defaults.set(depth, forKey: "diag.deepest")
    337         }
    338     }
    339 }