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

DiveWorkout.swift (4410B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 @preconcurrency import HealthKit
      4 import RemoraDeco
      5 
      6 /// Diving workout session (HealthKit). Two roles:
      7 /// 1. keep the app in the foreground and active for the whole dive (without a session, watchOS may suspend it);
      8 /// 2. save the dive in Health, with the depth and the water temperature.
      9 @MainActor
     10 final class DiveWorkout {
     11     enum State { case idle, running }
     12 
     13     private(set) var state = State.idle
     14     private(set) var lastError: String?
     15 
     16     private let health = HKHealthStore()
     17     private var session: HKWorkoutSession?
     18     private var builder: HKLiveWorkoutBuilder?
     19     private var startedAt: Date?
     20 
     21     static var isAvailable: Bool { HKHealthStore.isHealthDataAvailable() }
     22 
     23     private var shareTypes: Set<HKSampleType> {
     24         [HKObjectType.workoutType(),
     25          HKQuantityType(.underwaterDepth),
     26          HKQuantityType(.waterTemperature)]
     27     }
     28 
     29     /// Asks for permission to write to Health (once only; it can be refused, the app still works).
     30     func requestAuthorization() async {
     31         guard Self.isAvailable else { return }
     32         do {
     33             try await health.requestAuthorization(toShare: shareTypes, read: [])
     34         } catch {
     35             lastError = error.localizedDescription
     36         }
     37     }
     38 
     39     /// Starts the session (before getting in the water, or on submersion when the diver did not).
     40     func start() {
     41         guard Self.isAvailable, state == .idle else { return }
     42         let configuration = HKWorkoutConfiguration()
     43         configuration.activityType = .underwaterDiving
     44         configuration.locationType = .outdoor
     45         do {
     46             let session = try HKWorkoutSession(healthStore: health, configuration: configuration)
     47             let builder = session.associatedWorkoutBuilder()
     48             builder.dataSource = HKLiveWorkoutDataSource(healthStore: health, workoutConfiguration: configuration)
     49             self.session = session
     50             self.builder = builder
     51             let now = Date()
     52             startedAt = now
     53             session.startActivity(with: now)
     54             builder.beginCollection(withStart: now) { _, _ in }
     55             state = .running
     56             lastError = nil
     57         } catch {
     58             lastError = error.localizedDescription
     59         }
     60     }
     61 
     62     /// Ends the session. With a dive: the session is saved in Health with its profile;
     63     /// without a dive (cancelled, demo): it is discarded, nothing is written.
     64     func finish(with dive: DiveLog?) async {
     65         guard state == .running, let session, let builder else { return }
     66         let end = Date()
     67         session.end()
     68         state = .idle
     69         self.session = nil
     70         self.builder = nil
     71 
     72         guard let dive, dive.source == .remora else {
     73             builder.discardWorkout()
     74             return
     75         }
     76         do {
     77             // Health rejects a sample dated before the start of the session or after its end.
     78             let from = startedAt ?? dive.start
     79             let samples = Self.samples(for: dive).filter { $0.startDate >= from && $0.endDate <= end }
     80             if !samples.isEmpty { try await builder.addSamples(samples) }
     81             try await builder.endCollection(at: end)
     82             _ = try await builder.finishWorkout()
     83         } catch {
     84             lastError = error.localizedDescription
     85             builder.discardWorkout()
     86         }
     87     }
     88 
     89     /// Depth and water temperature, one point every 10 s at most (Health does not need more).
     90     static func samples(for dive: DiveLog) -> [HKQuantitySample] {
     91         var out: [HKQuantitySample] = []
     92         var lastTime = -Double.infinity
     93         for s in dive.samples where s.time - lastTime >= 10 || s.time == dive.samples.last?.time {
     94             lastTime = s.time
     95             let date = dive.start.addingTimeInterval(s.time)
     96             out.append(HKQuantitySample(type: HKQuantityType(.underwaterDepth),
     97                                         quantity: HKQuantity(unit: .meter(), doubleValue: s.depth),
     98                                         start: date, end: date))
     99             if let t = s.temperature {
    100                 out.append(HKQuantitySample(type: HKQuantityType(.waterTemperature),
    101                                             quantity: HKQuantity(unit: .degreeCelsius(), doubleValue: t),
    102                                             start: date, end: date))
    103             }
    104         }
    105         return out
    106     }
    107 }