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

UDDF.swift (19230B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 #if canImport(FoundationXML)
      4 import FoundationXML
      5 #endif
      6 
      7 /// UDDF (Universal Dive Data Format, version 3.2): the neutral exchange format that most dive log software reads
      8 /// and writes. SI units throughout: metres, seconds, kelvins, pascals, cubic metres.
      9 /// Reference: https://www.streit.cc/extern/uddf_v321/en/index.html
     10 public enum UDDF {
     11     public static func isUDDF(_ data: [UInt8]) -> Bool {
     12         let head = String(decoding: data.prefix(4096), as: UTF8.self)
     13         return head.contains("<uddf")
     14     }
     15 
     16     // MARK: Import
     17 
     18     /// The dives of a UDDF document, as the importer handles them.
     19     public static func dives(from data: [UInt8], timeZone: TimeZone = .current) throws -> [ImportedDive] {
     20         let reader = Reader(timeZone: timeZone)
     21         let parser = XMLParser(data: Data(data))
     22         parser.delegate = reader
     23         guard parser.parse() else {
     24             throw ImportError.unreadable(parser.parserError?.localizedDescription ?? "XML")
     25         }
     26         return reader.finished()
     27     }
     28 
     29     private final class Reader: NSObject, XMLParserDelegate {
     30         struct Mix { var o2 = 0.21, he = 0.0 }
     31         struct Site { var name = "", latitude: Double?, longitude: Double? }
     32         struct Pending {
     33             var dive = ImportedDive(when: 0, durationSeconds: 0)
     34             var links = [String]()
     35             var hasDate = false
     36             var notes = [String]()
     37             var number: Int?
     38         }
     39 
     40         let timeZone: TimeZone
     41         private var path = [String]()
     42         private var text = ""
     43         private var generator = ""
     44         private var mixes = [String: Mix]()
     45         private var sites = [String: Site]()
     46         private var buddies = [String: String]()
     47         private var currentID = ""
     48         private var mix = Mix()
     49         private var site = Site()
     50         private var firstName = "", lastName = ""
     51         private var pending: Pending?
     52         private var sample: ImportedDive.Sample?
     53         private var sampleSwitch: String?
     54         private var gas = Mix()
     55         private var done = [Pending]()
     56 
     57         init(timeZone: TimeZone) { self.timeZone = timeZone }
     58 
     59         private func inside(_ name: String) -> Bool { path.contains(name) }
     60         private var number: Double? { Double(text.trimmingCharacters(in: .whitespacesAndNewlines)) }
     61         private var trimmed: String { text.trimmingCharacters(in: .whitespacesAndNewlines) }
     62 
     63         func parser(_ parser: XMLParser, didStartElement element: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String]) {
     64             path.append(element)
     65             text = ""
     66             switch element {
     67             case "mix":
     68                 currentID = attributes["id"] ?? ""
     69                 mix = Mix()
     70             case "site":
     71                 currentID = attributes["id"] ?? ""
     72                 site = Site()
     73             case "buddy", "owner":
     74                 currentID = attributes["id"] ?? ""
     75                 firstName = ""
     76                 lastName = ""
     77             case "dive":
     78                 pending = Pending()
     79                 gas = Mix()
     80             case "link":
     81                 if inside("informationbeforedive") || inside("informationafterdive") || path.dropLast().last == "dive" {
     82                     if let ref = attributes["ref"] { pending?.links.append(ref) }
     83                 } else if inside("tankdata"), pending?.dive.samples.isEmpty == true, let ref = attributes["ref"], let found = mixes[ref] {
     84                     // The first cylinder's gas is the one breathed until a switch says otherwise.
     85                     if !(pending?.links.contains("mix:") ?? false) {
     86                         gas = found
     87                         pending?.links.append("mix:")
     88                     }
     89                 }
     90             case "waypoint":
     91                 sample = ImportedDive.Sample(time: 0, depth: 0)
     92                 sampleSwitch = nil
     93             case "switchmix":
     94                 sampleSwitch = attributes["ref"]
     95             case "decostop":
     96                 if attributes["kind"] != "safety" {
     97                     sample?.stopDepth = Double(attributes["decodepth"] ?? "") ?? 0
     98                     sample?.decoTime = Int(Double(attributes["duration"] ?? "") ?? 0)
     99                 }
    100             default:
    101                 break
    102             }
    103         }
    104 
    105         func parser(_ parser: XMLParser, foundCharacters string: String) { text += string }
    106 
    107         func parser(_ parser: XMLParser, didEndElement element: String, namespaceURI: String?, qualifiedName: String?) {
    108             defer {
    109                 path.removeLast()
    110                 text = ""
    111             }
    112             let parent = path.dropLast().last ?? ""
    113             switch element {
    114             case "name":
    115                 if parent == "generator" { generator = trimmed } else if parent == "site" { site.name = trimmed }
    116             case "o2": if parent == "mix", let value = number { mix.o2 = value }
    117             case "he": if parent == "mix", let value = number { mix.he = value }
    118             case "mix": mixes[currentID] = mix
    119             case "latitude": if inside("site") { site.latitude = number }
    120             case "longitude": if inside("site") { site.longitude = number }
    121             case "location": if inside("site"), site.name.isEmpty { site.name = trimmed }
    122             case "site": sites[currentID] = site
    123             case "firstname": firstName = trimmed
    124             case "lastname": lastName = trimmed
    125             case "buddy":
    126                 buddies[currentID] = [firstName, lastName].filter { !$0.isEmpty }.joined(separator: " ")
    127 
    128             case "datetime":
    129                 if inside("informationbeforedive"), let when = timestamp(trimmed) {
    130                     pending?.dive.when = when
    131                     pending?.hasDate = true
    132                 }
    133             case "divenumber": pending?.number = number.map { Int($0) }
    134             case "atmosphericpressure":
    135                 if let value = number, value > 50_000 { pending?.dive.surfacePressureBar = (value / 100).rounded() / 1000 }
    136             case "density":
    137                 if inside("informationbeforedive") || inside("informationafterdive"), let value = number, value > 900, value < 1100 {
    138                     pending?.dive.salinity = Int(value.rounded())
    139                 }
    140 
    141             case "divetime": if let value = number { sample?.time = Int(value.rounded()) }
    142             case "depth": if parent == "waypoint", let value = number { sample?.depth = (value * 100).rounded() / 100 }
    143             case "temperature": if parent == "waypoint", let value = number { sample?.temperature = ((value - 273.15) * 10).rounded() / 10 }
    144             case "tankpressure":
    145                 if parent == "waypoint", let value = number {
    146                     let bar = (value / 10_000).rounded() / 10
    147                     if sample?.pressure1 == nil { sample?.pressure1 = bar } else { sample?.pressure2 = bar }
    148                 }
    149             case "cns": if parent == "waypoint", let value = number { sample?.cns = Int((value * (value <= 3 ? 100 : 1)).rounded()) }
    150             case "nodecotime": if parent == "waypoint", let value = number, sample?.stopDepth == 0 { sample?.decoTime = Int(value) }
    151             case "waypoint":
    152                 if let ref = sampleSwitch, let found = mixes[ref] { gas = found }
    153                 if var finished = sample {
    154                     finished.o2 = Int((gas.o2 * 100).rounded())
    155                     finished.he = Int((gas.he * 100).rounded())
    156                     pending?.dive.samples.append(finished)
    157                 }
    158                 sample = nil
    159 
    160             case "diveduration": if inside("informationafterdive"), let value = number { pending?.dive.durationSeconds = Int(value.rounded()) }
    161             case "para", "text": if inside("notes"), inside("dive"), !trimmed.isEmpty { pending?.notes.append(trimmed) }
    162             case "notes":
    163                 // Notes written without paragraphs.
    164                 if inside("dive"), pending?.notes.isEmpty == true, !trimmed.isEmpty { pending?.notes.append(trimmed) }
    165             case "dive":
    166                 if let finished = pending { done.append(finished) }
    167                 pending = nil
    168             default:
    169                 break
    170             }
    171         }
    172 
    173         /// "2026-06-21T15:00:00", local time; with a "Z" it is a universal time, brought back to the local one.
    174         private func timestamp(_ text: String) -> Int? {
    175             let numbers = text.prefix(19).split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) }
    176             guard numbers.count >= 3 else { return nil }
    177             guard let naive = NaiveTime.timestamp(year: numbers[0], month: numbers[1], day: numbers[2],
    178                                                   hour: numbers.count > 3 ? numbers[3] : 0, minute: numbers.count > 4 ? numbers[4] : 0,
    179                                                   second: numbers.count > 5 ? numbers[5] : 0) else { return nil }
    180             guard text.hasSuffix("Z") else { return naive }
    181             return naive + timeZone.secondsFromGMT(for: Date(timeIntervalSince1970: TimeInterval(naive)))
    182         }
    183 
    184         func finished() -> [ImportedDive] {
    185             done.compactMap { entry -> ImportedDive? in
    186                 var dive = entry.dive
    187                 guard entry.hasDate, !dive.samples.isEmpty || dive.durationSeconds > 0 else { return nil }
    188                 dive.samples.sort { $0.time < $1.time }
    189                 if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 }
    190                 dive.model = generator.isEmpty ? "UDDF" : generator
    191                 dive.sourceID = "uddf-\(dive.when)"
    192                 for link in entry.links {
    193                     if let site = sites[link] {
    194                         dive.site = site.name
    195                         dive.latitude = site.latitude
    196                         dive.longitude = site.longitude
    197                     } else if let buddy = buddies[link], !buddy.isEmpty {
    198                         dive.buddy = dive.buddy.isEmpty ? buddy : dive.buddy + ", " + buddy
    199                     }
    200                 }
    201                 dive.notes = entry.notes.joined(separator: "\n")
    202                 return dive
    203             }
    204         }
    205     }
    206 
    207     // MARK: Export
    208 
    209     /// One dive to write: the dive, its profile, and the name and position of its site.
    210     public struct ExportedDive {
    211         public var dive: Dive
    212         public var computers: [DiveComputer]
    213         public var site: DiveSite?
    214 
    215         public init(dive: Dive, computers: [DiveComputer], site: DiveSite?) {
    216             self.dive = dive
    217             self.computers = computers
    218             self.site = site
    219         }
    220     }
    221 
    222     /// A UDDF 3.2 document holding the dives, with their sites, buddies, gases, cylinders and profiles.
    223     public static func document(_ dives: [ExportedDive], generator: String, version: String) -> String {
    224         func escape(_ text: String) -> String {
    225             text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
    226                 .replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
    227         }
    228         func fixed(_ value: Double, _ digits: Int = 2) -> String { String(format: "%.\(digits)f", locale: Locale(identifier: "en_US_POSIX"), value) }
    229         func kelvin(_ celsius: Double) -> String { fixed(celsius + 273.15) }
    230 
    231         // What the dives refer to: gases, sites, buddies.
    232         var mixes = [GasMix]()
    233         func mixID(_ mix: GasMix) -> String {
    234             let normal = mix.isAir ? GasMix.air : mix
    235             if let index = mixes.firstIndex(of: normal) { return "mix\(index + 1)" }
    236             mixes.append(normal)
    237             return "mix\(mixes.count)"
    238         }
    239         var siteIDs = [UInt32: String]()
    240         var siteList = [DiveSite]()
    241         var buddyIDs = [String: String]()
    242         var buddyList = [String]()
    243         var body = ""
    244         for (index, entry) in dives.sorted(by: { $0.dive.when < $1.dive.when }).enumerated() {
    245             let dive = entry.dive
    246             let computer = entry.computers.first
    247             body += "      <dive id=\"dive\(index + 1)\">\n        <informationbeforedive>\n"
    248             if let site = entry.site, !site.name.isEmpty {
    249                 if siteIDs[site.uuid] == nil {
    250                     siteList.append(site)
    251                     siteIDs[site.uuid] = "site\(siteList.count)"
    252                 }
    253                 body += "          <link ref=\"\(siteIDs[site.uuid]!)\"/>\n"
    254             }
    255             let people = (dive.buddy.split(separator: ",") + dive.divemaster.split(separator: ","))
    256                 .map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
    257             for person in people {
    258                 if buddyIDs[person] == nil {
    259                     buddyList.append(person)
    260                     buddyIDs[person] = "buddy\(buddyList.count)"
    261                 }
    262                 body += "          <link ref=\"\(buddyIDs[person]!)\"/>\n"
    263             }
    264             if dive.number > 0 { body += "          <divenumber>\(dive.number)</divenumber>\n" }
    265             let c = NaiveTime.components(dive.when)
    266             body += String(format: "          <datetime>%04d-%02d-%02dT%02d:%02d:%02d</datetime>\n",
    267                            c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
    268             if let surface = computer?.surfacePressureBar, surface > 0 {
    269                 body += "          <atmosphericpressure>\(fixed(surface * 100_000, 0))</atmosphericpressure>\n"
    270             }
    271             body += "        </informationbeforedive>\n"
    272 
    273             for (cylinderIndex, cylinder) in dive.cylinders.enumerated() {
    274                 body += "        <tankdata id=\"dive\(index + 1)tank\(cylinderIndex + 1)\">\n          <link ref=\"\(mixID(cylinder.gas))\"/>\n"
    275                 if let liters = cylinder.volumeLiters, liters > 0 { body += "          <tankvolume>\(fixed(liters / 1000, 5))</tankvolume>\n" }
    276                 if let start = cylinder.startBar { body += "          <tankpressurebegin>\(fixed(start * 100_000, 0))</tankpressurebegin>\n" }
    277                 if let end = cylinder.endBar { body += "          <tankpressureend>\(fixed(end * 100_000, 0))</tankpressureend>\n" }
    278                 body += "        </tankdata>\n"
    279             }
    280 
    281             body += "        <samples>\n"
    282             let changes = (computer?.events ?? []).filter(\.isGasChange)
    283             var switched = Set<Int>()
    284             let firstMix = dive.cylinders.first?.gas ?? .air
    285             for (sampleIndex, sample) in (computer?.samples ?? []).enumerated() {
    286                 body += "          <waypoint><depth>\(fixed(sample.depth))</depth><divetime>\(sample.time)</divetime>"
    287                 if let temperature = sample.temperature { body += "<temperature>\(kelvin(temperature))</temperature>" }
    288                 for pressure in sample.pressures where dive.cylinders.indices.contains(pressure.sensor) || dive.cylinders.isEmpty {
    289                     let ref = dive.cylinders.isEmpty ? "" : " ref=\"dive\(index + 1)tank\(pressure.sensor + 1)\""
    290                     body += "<tankpressure\(ref)>\(fixed(pressure.bar * 100_000, 0))</tankpressure>"
    291                 }
    292                 if sampleIndex == 0 { body += "<switchmix ref=\"\(mixID(firstMix))\"/>" }
    293                 for (changeIndex, change) in changes.enumerated() where change.time <= sample.time && !switched.contains(changeIndex) && change.time > 0 {
    294                     switched.insert(changeIndex)
    295                     if let mix = change.gas ?? change.cylinder.flatMap({ dive.cylinders.indices.contains($0) ? dive.cylinders[$0].gas : nil }) {
    296                         body += "<switchmix ref=\"\(mixID(mix))\"/>"
    297                     }
    298                 }
    299                 if sample.inDeco, let depth = sample.stopDepth, depth > 0 {
    300                     body += "<decostop kind=\"mandatory\" decodepth=\"\(fixed(depth, 1))\" duration=\"\(sample.stopTime ?? 0)\"/>"
    301                 } else if let ndl = sample.ndl {
    302                     body += "<nodecotime>\(ndl)</nodecotime>"
    303                 }
    304                 if let cns = sample.cns { body += "<cns>\(fixed(Double(cns) / 100, 2))</cns>" }
    305                 body += "</waypoint>\n"
    306             }
    307             body += "        </samples>\n        <informationafterdive>\n"
    308             if let lowest = dive.waterTemperatureOverride ?? computer?.waterTemperature { body += "          <lowesttemperature>\(kelvin(lowest))</lowesttemperature>\n" }
    309             body += "          <greatestdepth>\(fixed(dive.maxDepth))</greatestdepth>\n"
    310             if let mean = dive.meanDepth { body += "          <averagedepth>\(fixed(mean))</averagedepth>\n" }
    311             body += "          <diveduration>\(dive.durationSeconds)</diveduration>\n"
    312             if !dive.notes.isEmpty {
    313                 body += "          <notes>\n"
    314                 for paragraph in dive.notes.split(separator: "\n", omittingEmptySubsequences: true) {
    315                     body += "            <para>\(escape(String(paragraph)))</para>\n"
    316                 }
    317                 body += "          </notes>\n"
    318             }
    319             if dive.rating > 0 { body += "          <rating><ratingvalue>\(dive.rating * 2)</ratingvalue></rating>\n" }
    320             body += "        </informationafterdive>\n      </dive>\n"
    321         }
    322 
    323         var out = """
    324         <?xml version="1.0" encoding="UTF-8"?>
    325         <uddf xmlns="http://www.streit.cc/uddf/3.2/" version="3.2.3">
    326           <generator>
    327             <name>\(escape(generator))</name>
    328             <type>logbook</type>
    329             <version>\(escape(version))</version>
    330           </generator>
    331 
    332         """
    333         out += "  <diver>\n    <owner id=\"owner\"><personal><firstname></firstname><lastname></lastname></personal></owner>\n"
    334         for person in buddyList {
    335             let parts = person.split(separator: " ", maxSplits: 1).map(String.init)
    336             out += "    <buddy id=\"\(buddyIDs[person]!)\"><personal><firstname>\(escape(parts[0]))</firstname>"
    337                 + "<lastname>\(escape(parts.count > 1 ? parts[1] : ""))</lastname></personal></buddy>\n"
    338         }
    339         out += "  </diver>\n  <divesite>\n"
    340         for site in siteList {
    341             out += "    <site id=\"\(siteIDs[site.uuid]!)\"><name>\(escape(site.name))</name>"
    342             if let latitude = site.latitude, let longitude = site.longitude {
    343                 out += "<geography><latitude>\(fixed(latitude, 6))</latitude><longitude>\(fixed(longitude, 6))</longitude></geography>"
    344             }
    345             out += "</site>\n"
    346         }
    347         out += "  </divesite>\n  <gasdefinitions>\n"
    348         for (index, mix) in mixes.enumerated() {
    349             let o2 = mix.o2Fraction, he = mix.heFraction
    350             let name = he > 0 ? "Tx\(Int((o2 * 100).rounded()))/\(Int((he * 100).rounded()))" : (mix.isAir ? "Air" : "EAN\(Int((o2 * 100).rounded()))")
    351             out += "    <mix id=\"mix\(index + 1)\"><name>\(name)</name><o2>\(fixed(o2, 3))</o2><n2>\(fixed(max(0, 1 - o2 - he), 3))</n2><he>\(fixed(he, 3))</he></mix>\n"
    352         }
    353         out += "  </gasdefinitions>\n  <profiledata>\n    <repetitiongroup id=\"rg1\">\n" + body + "    </repetitiongroup>\n  </profiledata>\n</uddf>\n"
    354         return out
    355     }
    356 }