SubsurfaceImport.swift (7222B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 #if canImport(FoundationXML) 4 import FoundationXML 5 #endif 6 7 /// Reads a Subsurface logbook (XML file, `.ssrf` or `.xml`) to review it in Open Rémora. 8 /// Only the first dive computer of each dive is read. Imported dives have neither tissues nor GF. 9 public enum SubsurfaceImport { 10 public enum Failure: Error { case notSubsurface, malformed(String) } 11 12 public static func dives(from data: Data) throws -> [DiveLog] { 13 let delegate = Reader() 14 let parser = XMLParser(data: data) 15 parser.delegate = delegate 16 guard parser.parse() else { 17 throw Failure.malformed(parser.parserError?.localizedDescription ?? "unreadable XML") 18 } 19 guard delegate.sawDivelog else { throw Failure.notSubsurface } 20 return delegate.dives.sorted { $0.start < $1.start } 21 } 22 23 /// "12.3 m", "21.0 C", "1.013 bar", "32.0%" → number. 24 static func number(_ s: String?) -> Double? { 25 guard let s else { return nil } 26 let head = s.prefix { "0123456789.-".contains($0) } 27 return Double(head) 28 } 29 30 /// "45:30 min", "1:02:03", "30" → seconds. 31 static func seconds(_ s: String?) -> Double? { 32 guard let s else { return nil } 33 let head = s.prefix { "0123456789:".contains($0) } 34 let parts = head.split(separator: ":").compactMap { Double($0) } 35 guard !parts.isEmpty else { return nil } 36 if parts.count == 1 { return s.contains("min") ? parts[0] * 60 : parts[0] } 37 return parts.reduce(0) { $0 * 60 + $1 } 38 } 39 40 private final class Reader: NSObject, XMLParserDelegate { 41 var sawDivelog = false 42 var dives: [DiveLog] = [] 43 private var sites: [String: (name: String, lat: Double?, lon: Double?)] = [:] 44 45 private var inDive = false 46 private var computerIndex = 0 47 private var attrs: [String: String] = [:] 48 private var samples: [DiveSample] = [] 49 private var model: String? 50 private var o2: Double? 51 private var surface: Double? 52 private var salinity: Double? 53 private var notes: String? 54 private var location: String? 55 private var text = "" 56 private var lastTemp: Double? 57 58 func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, 59 qualifiedName: String?, attributes a: [String: String] = [:]) { 60 text = "" 61 switch name { 62 case "divelog": sawDivelog = true 63 case "site": 64 if let uuid = a["uuid"]?.trimmingCharacters(in: .whitespaces) { 65 let gps = (a["gps"] ?? "").split(separator: " ").compactMap { Double($0) } 66 sites[uuid] = (a["name"] ?? "", gps.count == 2 ? gps[0] : nil, gps.count == 2 ? gps[1] : nil) 67 } 68 case "dive": 69 inDive = true; attrs = a; samples = []; computerIndex = 0 70 model = nil; o2 = nil; surface = nil; salinity = nil; notes = nil; location = nil; lastTemp = nil 71 case "divecomputer" where inDive: 72 computerIndex += 1 73 if computerIndex == 1 { model = a["model"] } 74 case "cylinder" where inDive && o2 == nil: 75 o2 = SubsurfaceImport.number(a["o2"]).map { $0 / 100 } ?? 0.21 76 case "surface" where inDive && computerIndex <= 1: 77 surface = SubsurfaceImport.number(a["pressure"]) 78 case "water" where inDive && computerIndex <= 1: 79 salinity = SubsurfaceImport.number(a["salinity"]) 80 case "temperature" where inDive && computerIndex <= 1 && lastTemp == nil: 81 break 82 case "sample" where inDive && computerIndex == 1: 83 guard let t = SubsurfaceImport.seconds(a["time"]), 84 let d = SubsurfaceImport.number(a["depth"]) else { break } 85 if let temp = SubsurfaceImport.number(a["temp"]) { lastTemp = temp } 86 let stopDepth = SubsurfaceImport.number(a["stopdepth"]) 87 let stopTime = SubsurfaceImport.seconds(a["stoptime"]) 88 let inDeco = (stopDepth ?? 0) > 0 || a["in_deco"] == "1" 89 samples.append(DiveSample( 90 time: t, depth: d, temperature: lastTemp, ceiling: inDeco ? (stopDepth ?? 0) : 0, 91 noDecompressionLimit: inDeco ? 0 : SubsurfaceImport.seconds(a["ndl"]).map { $0 / 60 }, 92 stopDepth: inDeco ? stopDepth : nil, 93 stopMinutes: inDeco ? stopTime.map { Int(($0 / 60).rounded(.up)) } : nil)) 94 default: break 95 } 96 } 97 98 func parser(_ parser: XMLParser, foundCharacters string: String) { text += string } 99 100 func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, 101 qualifiedName: String?) { 102 let value = text.trimmingCharacters(in: .whitespacesAndNewlines) 103 switch name { 104 case "notes" where inDive: notes = value.isEmpty ? nil : value 105 case "location" where inDive: location = value.isEmpty ? nil : value 106 case "dive": finishDive(); inDive = false 107 default: break 108 } 109 text = "" 110 } 111 112 private func finishDive() { 113 guard let date = attrs["date"] else { return } 114 let f = DateFormatter() 115 f.locale = Locale(identifier: "en_US_POSIX") 116 f.timeZone = TimeZone(secondsFromGMT: 0) // Subsurface stores local time, without a time zone 117 f.dateFormat = "yyyy-MM-dd HH:mm:ss" 118 guard let start = f.date(from: "\(date) \(attrs["time"] ?? "00:00:00")") else { return } 119 120 // No profile (dive entered by hand): two points are enough for the duration. 121 if samples.isEmpty, let duration = SubsurfaceImport.seconds(attrs["duration"]) { 122 samples = [DiveSample(time: 0, depth: 0, temperature: nil, ceiling: 0, noDecompressionLimit: nil, 123 stopDepth: nil, stopMinutes: nil), 124 DiveSample(time: duration, depth: 0, temperature: nil, ceiling: 0, 125 noDecompressionLimit: nil, stopDepth: nil, stopMinutes: nil)] 126 } 127 let site = attrs["divesiteid"].flatMap { sites[$0.trimmingCharacters(in: .whitespaces)] } 128 let water: Water = switch salinity ?? 1020 { 129 case ..<1010: .fresh 130 case 1023...: .salt 131 default: .en13319 132 } 133 let fraction = min(1, max(0.16, o2 ?? 0.21)) 134 dives.append(DiveLog( 135 id: UUID(), source: .subsurface, computerModel: model, 136 number: Int(attrs["number"] ?? "") ?? 0, start: start, 137 surfacePressure: surface ?? standardSurfacePressure, surfaceIntervalBefore: nil, 138 gas: Gas(o2: fraction), gradientFactors: nil, water: water, 139 samples: samples, events: [], tissuesAfter: nil, 140 site: site?.name.isEmpty == false ? site?.name : location, notes: notes, 141 latitude: site?.lat, longitude: site?.lon)) 142 } 143 } 144 }