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

RemoraImport.swift (7716B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 
      4 /// An app that drops its dives into the app group shared with this one: a folder holding, for each dive,
      5 /// `<uuid>.json` (the `DiveLog` of RemoraDeco) and `<uuid>.uddf`.
      6 public struct SharedDiveSource: Sendable, Equatable {
      7     /// Name of the app; also the dive computer model of a dive that does not give one.
      8     public let name: String
      9     /// Folder inside the app group container.
     10     public let folder: String
     11 
     12     /// Open Rémora, a dive computer for Apple Watch.
     13     public static let openRemora = SharedDiveSource(name: "Open Rémora", folder: "OpenRemora/Plongees")
     14     /// Open Mérou, the app of an iPhone underwater housing.
     15     public static let openMerou = SharedDiveSource(name: "Open Mérou", folder: "OpenMerou/Dives")
     16     public static let all = [openRemora, openMerou]
     17 }
     18 
     19 /// Dives dropped by Open Rémora and Open Mérou into the shared folders of the app group.
     20 /// Contract: `docs/SHARING.md` in the open-remora repository. The JSON (`DiveLog` from RemoraDeco) is read without
     21 /// depending on that package: only the fields useful to the logbook are decoded, the others are ignored.
     22 public enum RemoraImport {
     23     public static let appGroup = "group.org.schurger.dive"
     24     public static let folder = SharedDiveSource.openRemora.folder
     25 
     26     struct Log: Decodable {
     27         struct Gas: Decodable { let o2: Double }
     28         struct Factors: Decodable { let low: Double; let high: Double }
     29         struct Sample: Decodable {
     30             let time: Double
     31             let depth: Double
     32             let temperature: Double?
     33             let noDecompressionLimit: Double?
     34             let stopDepth: Double?
     35             let stopMinutes: Int?
     36         }
     37         struct Event: Decodable { let time: Double; let warning: String }
     38         /// Point marked by the diver (Action button of the watch); `heading` in magnetic degrees.
     39         struct Mark: Decodable { let time: Double; let depth: Double; let heading: Double? }
     40 
     41         let id: UUID
     42         let source: String?
     43         let computerModel: String?
     44         let start: Date
     45         let surfacePressure: Double?
     46         let gas: Gas?
     47         let gradientFactors: Factors?
     48         let water: String?
     49         let samples: [Sample]
     50         let events: [Event]?
     51         let marks: [Mark]?
     52         let site: String?
     53         let notes: String?
     54         let latitude: Double?
     55         let longitude: Double?
     56     }
     57 
     58     /// Default (English) labels of the Open Rémora alarms, keyed by the warning identifier found in the JSON.
     59     /// The labels end up in the dive notes, so an app passes its own localized dictionary to `dive(fromJSON:)`.
     60     public static let defaultAlarmLabels = ["ascentFast": "fast ascent", "ascentTooFast": "ascent too fast",
     61                                             "ceilingViolated": "ceiling violated", "ppO2High": "high ppO2",
     62                                             "ppO2Critical": "critical ppO2", "missedSafetyStop": "missed safety stop"]
     63 
     64     /// Decodes a dive. Open Rémora's time is an absolute instant; the Subsurface logbook keeps the "naive" local
     65     /// time, hence the time zone to apply (by default, the device's at the time of the dive).
     66     /// The alarms are appended to the notes as `alarmsPrefix` followed by "m:ss label" entries; `alarmLabels` maps
     67     /// each warning identifier to its label (an identifier missing from the dictionary is written as is).
     68     /// The points marked by the diver follow, as `marksPrefix` and "m:ss depth heading" entries.
     69     /// `defaultModel` names the dive computer of a dive whose JSON has no `computerModel`.
     70     public static func dive(fromJSON data: Data, timeZone: TimeZone = .current, defaultModel: String = SharedDiveSource.openRemora.name,
     71                             alarmLabels: [String: String] = RemoraImport.defaultAlarmLabels,
     72                             alarmsPrefix: String = "Alarms: ",
     73                             marksPrefix: String = "Marks: ") throws -> ImportedDive {
     74         let decoder = JSONDecoder()
     75         decoder.dateDecodingStrategy = .iso8601
     76         let log = try decoder.decode(Log.self, from: data)
     77         guard log.source != "simulation" else { throw ImportError.unreadable("demo dive") }
     78         guard let last = log.samples.last else { throw ImportError.empty }
     79 
     80         let when = Int(log.start.timeIntervalSince1970.rounded()) + timeZone.secondsFromGMT(for: log.start)
     81         var dive = ImportedDive(when: when, durationSeconds: Int(last.time.rounded()))
     82         dive.model = log.computerModel ?? defaultModel
     83         dive.sourceID = log.id.uuidString
     84         dive.site = log.site ?? ""
     85         dive.latitude = log.latitude
     86         dive.longitude = log.longitude
     87         dive.surfacePressureBar = log.surfacePressure
     88         switch log.water {
     89         case "fresh": dive.salinity = 1000
     90         case "en13319": dive.salinity = 1020
     91         case "salt": dive.salinity = 1025
     92         default: break
     93         }
     94         if let gf = log.gradientFactors {
     95             dive.decoModel = "GF \(Int((gf.low * 100).rounded()))/\(Int((gf.high * 100).rounded()))"
     96         }
     97         let o2 = Int(((log.gas?.o2 ?? 0.21) * 100).rounded())
     98         for sample in log.samples {
     99             var out = ImportedDive.Sample(time: Int(sample.time.rounded()), depth: (sample.depth * 10).rounded() / 10)
    100             out.temperature = sample.temperature.map { ($0 * 10).rounded() / 10 }
    101             out.o2 = o2
    102             if let stop = sample.stopDepth, stop > 0 {
    103                 out.stopDepth = stop
    104                 out.decoTime = (sample.stopMinutes ?? 0) * 60
    105             } else {
    106                 // nil = unlimited no-decompression limit: 99 minutes, as dive computers display it.
    107                 out.decoTime = Int(min(sample.noDecompressionLimit ?? 99, 99).rounded()) * 60
    108             }
    109             if let previous = dive.samples.last, out.time <= previous.time { continue }
    110             dive.samples.append(out)
    111         }
    112 
    113         var notes = [String]()
    114         if let text = log.notes, !text.isEmpty { notes.append(text) }
    115         let alarms = (log.events ?? []).map { event -> String in
    116             let seconds = Int(event.time.rounded())
    117             return "\(seconds / 60):" + String(format: "%02d", seconds % 60) + " \(alarmLabels[event.warning] ?? event.warning)"
    118         }
    119         if !alarms.isEmpty { notes.append(alarmsPrefix + alarms.joined(separator: ", ")) }
    120         // The points marked by the diver, as "m:ss depth m heading°" entries.
    121         let marks = (log.marks ?? []).map { mark -> String in
    122             let seconds = Int(mark.time.rounded())
    123             let heading = mark.heading.map { " \(Int($0.rounded()) % 360)°" } ?? ""
    124             return "\(seconds / 60):" + String(format: "%02d", seconds % 60)
    125                 + " " + String(format: "%.1f", mark.depth) + " m" + heading
    126         }
    127         if !marks.isEmpty { notes.append(marksPrefix + marks.joined(separator: ", ")) }
    128         dive.notes = notes.joined(separator: "\n")
    129         return dive
    130     }
    131 
    132     /// JSON files waiting in the shared folder.
    133     public static func pendingFiles(in directory: URL) -> [URL] {
    134         ((try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? [])
    135             .filter { $0.pathExtension.lowercased() == "json" }
    136             .sorted { $0.lastPathComponent < $1.lastPathComponent }
    137     }
    138 
    139     /// Removes both files of a dive (JSON and UDDF): the app that dropped them counts the remaining JSON files as "pending".
    140     public static func consume(_ json: URL) {
    141         try? FileManager.default.removeItem(at: json)
    142         try? FileManager.default.removeItem(at: json.deletingPathExtension().appendingPathExtension("uddf"))
    143     }
    144 }