subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

Model.swift (8754B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 import GitLite
      4 
      5 public struct GasMix: Sendable, Equatable, Codable, Hashable {
      6     /// Per mille; 0 = air for oxygen.
      7     public var o2Permille: Int
      8     public var hePermille: Int
      9 
     10     public init(o2Permille: Int = 0, hePermille: Int = 0) {
     11         self.o2Permille = o2Permille
     12         self.hePermille = hePermille
     13     }
     14 
     15     public static let air = GasMix()
     16     public var isAir: Bool { (o2Permille == 0 || o2Permille == 209 || o2Permille == 210) && hePermille == 0 }
     17     public var o2Fraction: Double { o2Permille == 0 ? 0.209 : Double(o2Permille) / 1000 }
     18     public var heFraction: Double { Double(hePermille) / 1000 }
     19 
     20     /// "Air", "EAN32", "18/45", "O₂"
     21     public var label: String {
     22         if isAir { return "Air" }
     23         let o2 = Int((Double(o2Permille) / 10).rounded())
     24         let he = Int((Double(hePermille) / 10).rounded())
     25         if he > 0 { return "\(o2)/\(he)" }
     26         if o2 >= 100 { return "O₂" }
     27         return "EAN\(o2)"
     28     }
     29 }
     30 
     31 public struct Cylinder: Sendable, Equatable, Codable {
     32     public var description = ""
     33     public var volumeLiters: Double?
     34     public var workPressureBar: Double?
     35     public var gas = GasMix.air
     36     public var startBar: Double?
     37     public var endBar: Double?
     38     public var use: String?
     39     public init() {}
     40 }
     41 
     42 public struct WeightSystem: Sendable, Equatable, Codable {
     43     public var kilograms = 0.0
     44     public var description = ""
     45     public init() {}
     46 }
     47 
     48 public struct Sample: Sendable, Equatable {
     49     public var time = 0                 // seconds
     50     public var depth = 0.0              // metres
     51     public var temperature: Double?     // °C, carried over from one sample to the next
     52     public var pressures: [SensorPressure] = []   // only when the computer reports one
     53     public var ndl: Int?                // seconds
     54     public var tts: Int?
     55     public var inDeco = false
     56     public var stopDepth: Double?
     57     public var stopTime: Int?
     58     public var cns: Int?
     59     public var heartbeat: Int?
     60     public var setpoint: Double?        // bar
     61     public init() {}
     62 }
     63 
     64 public struct SensorPressure: Sendable, Equatable {
     65     public var sensor: Int
     66     public var bar: Double
     67 }
     68 
     69 public struct DiveEvent: Sendable, Equatable {
     70     public var time = 0
     71     public var type = 0
     72     public var flags = 0
     73     public var value = 0
     74     public var name = ""
     75     public var cylinder: Int?
     76     public var gas: GasMix?
     77     public init() {}
     78 
     79     public var isGasChange: Bool { name == "gaschange" || name == "gaschange!" }
     80 }
     81 
     82 public struct DiveComputer: Sendable, Equatable {
     83     public var model = ""
     84     /// Start of this computer's profile (naive local time) when it differs from the dive's: several computers on
     85     /// one dive do not notice the submersion at the same moment.
     86     public var when: Int?
     87     public var deviceID: String?
     88     public var diveID: String?
     89     public var durationSeconds: Int?
     90     public var maxDepth: Double?
     91     public var meanDepth: Double?
     92     public var airTemperature: Double?
     93     public var waterTemperature: Double?
     94     public var surfacePressureBar: Double?
     95     public var salinity: Double?        // g/l
     96     public var diveMode = "OC"
     97     public var extra: [KeyValue] = []
     98     public var events: [DiveEvent] = []
     99     public var samples: [Sample] = []
    100     public init() {}
    101 
    102     public var isManual: Bool { model == "manually added dive" }
    103     public var serial: String { extra.first { $0.key == "Serial" }?.value ?? "" }
    104 
    105     /// From the start to the end of this computer's recording, on a dive that starts at `dive.when`.
    106     public func timeRange(in dive: Dive) -> ClosedRange<Int> {
    107         let start = when ?? dive.when
    108         return start...(start + max(durationSeconds ?? dive.durationSeconds, samples.last?.time ?? 0, 0))
    109     }
    110 }
    111 
    112 public struct KeyValue: Sendable, Equatable {
    113     public var key: String
    114     public var value: String
    115 }
    116 
    117 public struct DiveSite: Sendable, Equatable, Identifiable {
    118     public var uuid: UInt32
    119     public var name = ""
    120     public var description = ""
    121     public var notes = ""
    122     public var latitude: Double?
    123     public var longitude: Double?
    124     public var country: String?
    125 
    126     public init(uuid: UInt32) { self.uuid = uuid }
    127     public var id: UInt32 { uuid }
    128     public var hasLocation: Bool { latitude != nil && longitude != nil }
    129 }
    130 
    131 public struct Trip: Sendable, Equatable, Identifiable {
    132     public var id: String              // path of the directory in the repository
    133     public var location = ""
    134     public var notes = ""
    135     public init(id: String) { self.id = id }
    136 }
    137 
    138 /// A dive. Subsurface times are "naive" local times, stored as if they were UTC.
    139 public struct Dive: Sendable, Equatable, Identifiable {
    140     public var when: Int               // seconds since 1970, naive local time
    141     public var number = 0
    142     public var path: [String] = []     // directories down to the dive's own
    143     public var diveFile = "Dive"
    144     public var diveBlob: ObjectID?
    145     public var computerBlobs: [ObjectID] = []
    146     public var tripID: String?
    147 
    148     public var durationSeconds = 0
    149     public var rating = 0
    150     public var visibility = 0
    151     public var waveSize = 0
    152     public var current = 0
    153     public var surge = 0
    154     public var chill = 0
    155     public var invalid = false
    156     public var tags: [String] = []
    157     public var siteUUID: UInt32?
    158     public var divemaster = ""
    159     public var buddy = ""
    160     public var suit = ""
    161     public var notes = ""
    162     public var cylinders: [Cylinder] = []
    163     public var weights: [WeightSystem] = []
    164     public var airTemperatureOverride: Double?
    165     public var waterTemperatureOverride: Double?
    166 
    167     /// Headers of the dive computers (without samples until `loadProfile` has been called).
    168     public var computers: [DiveComputer] = []
    169 
    170     public init(when: Int) { self.when = when }
    171 
    172     public var id: String { "\(when)-\(number)" }
    173     public var date: Date { Date(timeIntervalSince1970: TimeInterval(when)) }
    174 
    175     public var maxDepth: Double { computers.compactMap(\.maxDepth).max() ?? 0 }
    176     public var meanDepth: Double? { computers.first?.meanDepth }
    177     public var waterTemperature: Double? { waterTemperatureOverride ?? computers.compactMap(\.waterTemperature).first }
    178     public var airTemperature: Double? { airTemperatureOverride ?? computers.compactMap(\.airTemperature).first }
    179     public var totalWeight: Double { weights.reduce(0) { $0 + $1.kilograms } }
    180     public var computerModel: String? { computers.first(where: { !$0.model.isEmpty && !$0.isManual })?.model }
    181     public var isManual: Bool { computers.allSatisfy { $0.isManual } }
    182     /// A plan saved in the logbook (Subsurface's "planned dive" computer), not a dive that was made.
    183     public var isPlanned: Bool { !computers.isEmpty && computers.allSatisfy { $0.model == "planned dive" } }
    184 
    185     /// From the earliest start to the latest end of what the dive and its computers recorded.
    186     public var timeRange: ClosedRange<Int> {
    187         var range = when...(when + max(durationSeconds, 0))
    188         for computer in computers {
    189             let own = computer.timeRange(in: self)
    190             range = min(range.lowerBound, own.lowerBound)...max(range.upperBound, own.upperBound)
    191         }
    192         return range
    193     }
    194 
    195     /// Surface air consumption, in litres per minute (ideal gas, cylinders with volume and pressures filled in).
    196     public var sac: Double? {
    197         guard durationSeconds > 0, let mean = meanDepth, mean > 0 else { return nil }
    198         var liters = 0.0
    199         for c in cylinders {
    200             guard let v = c.volumeLiters, let s = c.startBar, let e = c.endBar, s > e else { continue }
    201             liters += v * (s - e)
    202         }
    203         guard liters > 0 else { return nil }
    204         return liters / (Double(durationSeconds) / 60) / (mean / 10 + 1)
    205     }
    206 }
    207 
    208 public struct LogSettings: Sendable, Equatable {
    209     public var version = 3
    210     public var units = "METRIC"
    211     public var autogroup = false
    212     public init() {}
    213 }
    214 
    215 public struct Logbook: Sendable, Equatable {
    216     public var dives: [Dive] = []      // from the most recent to the oldest
    217     public var sites: [UInt32: DiveSite] = [:]
    218     public var trips: [String: Trip] = [:]
    219     public var settings = LogSettings()
    220     public var warnings: [String] = []
    221     public init() {}
    222 
    223     public func site(of dive: Dive) -> DiveSite? { dive.siteUUID.flatMap { sites[$0] } }
    224     public func trip(of dive: Dive) -> Trip? { dive.tripID.flatMap { trips[$0] } }
    225     public func dive(when: Int, number: Int? = nil) -> Dive? {
    226         let matches = dives.filter { $0.when == when }
    227         if let number, let exact = matches.first(where: { $0.number == number }) { return exact }
    228         return matches.first
    229     }
    230     public var nextNumber: Int { (dives.map(\.number).max() ?? 0) + 1 }
    231 }