Import.swift (18642B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import GitLite 4 import SQLite3 5 6 /// Dive read from an external file, with its full profile, ready to enter the logbook. 7 public struct ImportedDive: Codable, Sendable, Equatable, Identifiable { 8 public struct Sample: Codable, Sendable, Equatable { 9 public var time: Int // seconds 10 public var depth: Double // metres 11 public var temperature: Double? // °C 12 public var pressure1: Double? // bar, transmitter 1 13 public var pressure2: Double? // bar, transmitter 2 14 public var stopDepth = 0.0 // metres; 0 = no stop 15 public var decoTime = 0 // seconds: stop duration, or no-decompression limit 16 public var tts = 0 // seconds 17 public var cns = 0 // % 18 public var o2 = 21 // % 19 public var he = 0 // % 20 21 public init(time: Int, depth: Double) { 22 self.time = time 23 self.depth = depth 24 } 25 } 26 27 public var when: Int 28 public var durationSeconds: Int 29 public var model = "" 30 public var serial = "" 31 public var sourceID = "" 32 public var site = "" 33 /// Position of the site when the file provides it. 34 public var latitude: Double? 35 public var longitude: Double? 36 public var buddy = "" 37 public var notes = "" 38 public var surfacePressureBar: Double? 39 public var salinity: Int? // g/l 40 public var decoModel: String? 41 public var samples: [Sample] = [] 42 43 public init(when: Int, durationSeconds: Int) { 44 self.when = when 45 self.durationSeconds = durationSeconds 46 } 47 48 public var id: String { sourceID.isEmpty ? String(when) : sourceID } 49 public var maxDepth: Double { samples.map(\.depth).max() ?? 0 } 50 public var minTemperature: Double? { samples.compactMap(\.temperature).min() } 51 52 /// Mean depth underwater. 53 public var meanDepth: Double { 54 let wet = samples.filter { $0.depth > 0 } 55 return wet.isEmpty ? 0 : wet.reduce(0) { $0 + $1.depth } / Double(wet.count) 56 } 57 58 /// Gas mixes breathed, in the order they appear. 59 public var gases: [GasMix] { 60 var list = [GasMix]() 61 for sample in samples where sample.o2 > 0 || sample.he > 0 { 62 let mix = GasMix(o2Permille: sample.o2 == 21 && sample.he == 0 ? 0 : sample.o2 * 10, hePermille: sample.he * 10) 63 if !list.contains(mix) { list.append(mix) } 64 } 65 return list.isEmpty ? [.air] : list 66 } 67 } 68 69 public enum ImportError: Error, Equatable, CustomStringConvertible { 70 case unknownFormat 71 case unreadable(String) 72 case empty 73 74 public var description: String { 75 switch self { 76 case .unknownFormat: return "Unrecognized file format. Supported formats: Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db)." 77 case .unreadable(let why): return "Unreadable file: \(why)" 78 case .empty: return "No dive in this file." 79 } 80 } 81 } 82 83 public enum DiveImporter { 84 /// Detects the format of a file and extracts its dives, from the most recent to the oldest. 85 public static func dives(from data: [UInt8]) throws -> [ImportedDive] { 86 if UDDF.isUDDF(data) { 87 let dives = try UDDF.dives(from: data) 88 guard !dives.isEmpty else { throw ImportError.empty } 89 return dives.sorted { $0.when > $1.when } 90 } 91 var database = data 92 if ZipArchive.isZip(data) { 93 do { 94 let archive = try ZipArchive(data) 95 guard let inner = try archive.contents(named: "dive_data.db") else { throw ImportError.unknownFormat } 96 database = inner 97 } catch let error as GitError { 98 throw ImportError.unreadable(error.description) 99 } 100 } 101 guard database.starts(with: Array("SQLite format 3".utf8)) else { throw ImportError.unknownFormat } 102 let dives = try ShearwaterCloud.dives(database: database) 103 guard !dives.isEmpty else { throw ImportError.empty } 104 return dives.sorted { $0.when > $1.when } 105 } 106 107 /// The raw Shearwater logs of a file (uncompressed, as the computer stores them), each with the dive decoded 108 /// from it. Lets another decoder be checked against ours. 109 public static func shearwaterLogs(from data: [UInt8]) throws -> [(dive: ImportedDive, log: [UInt8])] { 110 var database = data 111 if ZipArchive.isZip(data), let inner = try? ZipArchive(data).contents(named: "dive_data.db") { database = inner } 112 guard database.starts(with: Array("SQLite format 3".utf8)) else { throw ImportError.unknownFormat } 113 var logs = [(dive: ImportedDive, log: [UInt8])]() 114 _ = try ShearwaterCloud.dives(database: database) { dive, log in logs.append((dive, log)) } 115 return logs 116 } 117 } 118 119 /// Shearwater Cloud export: SQLite database `dive_data.db`, logs in the PNF format (32-byte records, 120 /// gzip-compressed). Field layout taken from libdivecomputer (`shearwater_predator_parser.c`). 121 enum ShearwaterCloud { 122 /// Reads either of the two Shearwater databases: the Shearwater Cloud export (`log_data` + `dive_details`, logs 123 /// as blobs) or the database of the Dive Shearwater app (`dive_log_data` + `dive_details` + `geo_site` + 124 /// `dive_buddy`, logs in base64). The logs are the same in both. 125 static func dives(database: [UInt8], onLog: ((ImportedDive, [UInt8]) -> Void)? = nil) throws -> [ImportedDive] { 126 let url = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString).db") 127 try Data(database).write(to: url) 128 defer { try? FileManager.default.removeItem(at: url) } 129 130 var handle: OpaquePointer? 131 guard sqlite3_open_v2(url.path, &handle, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let db = handle else { 132 sqlite3_close(handle) 133 throw ImportError.unreadable("database") 134 } 135 defer { sqlite3_close(db) } 136 137 // Columns returned, in order: identifier, model, log, format, date, duration, site, buddies, notes, serial. 138 let cloud = """ 139 select l.log_id, l.file_name, l.data_bytes_1, l.format, d.DiveDate, d.DiveLengthTime, 140 coalesce(nullif(d.Site, ''), d.Location), d.Buddy, d.Notes, d.SerialNumber 141 from log_data l left join dive_details d on d.DiveId = l.log_id 142 """ 143 let app = """ 144 select l.id, c.dive_computer_product, l.data_bytes_1, l.format, d.date_timestamp, c.duration_sec, 145 g.common_name, d.dive_buddy_ids, d.notes, c.dive_computer_serial, g.latitude, g.longitude 146 from dive_log_data l left join dive_details d on d.id = l.id 147 left join calculated_dive_log_samples c on c.id = l.id 148 left join geo_site g on g.id = d.dive_location 149 """ 150 var statement: OpaquePointer? 151 var fromApp = false 152 if sqlite3_prepare_v2(db, cloud, -1, &statement, nil) != SQLITE_OK { 153 sqlite3_finalize(statement) 154 statement = nil 155 guard sqlite3_prepare_v2(db, app, -1, &statement, nil) == SQLITE_OK else { throw ImportError.unknownFormat } 156 fromApp = true 157 } 158 defer { sqlite3_finalize(statement) } 159 160 func text(_ column: Int32) -> String { 161 sqlite3_column_text(statement, column).map { String(cString: $0) } ?? "" 162 } 163 164 var buddies = [String: String]() 165 if fromApp { 166 var names: OpaquePointer? 167 if sqlite3_prepare_v2(db, "select id, name from dive_buddy", -1, &names, nil) == SQLITE_OK { 168 while sqlite3_step(names) == SQLITE_ROW { 169 if let id = sqlite3_column_text(names, 0), let name = sqlite3_column_text(names, 1) { 170 buddies[String(cString: id)] = String(cString: name) 171 } 172 } 173 } 174 sqlite3_finalize(names) 175 } 176 177 var out = [ImportedDive]() 178 while sqlite3_step(statement) == SQLITE_ROW { 179 guard text(3).isEmpty || text(3) == "sw-pnf" else { continue } 180 let blob: [UInt8] 181 if fromApp { 182 guard let decoded = Data(base64Encoded: text(2)) else { continue } 183 blob = Array(decoded) 184 } else { 185 guard let bytes = sqlite3_column_blob(statement, 2) else { continue } 186 blob = Array(UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: Int(sqlite3_column_bytes(statement, 2)))) 187 } 188 guard blob.count > 4, let records = try? Inflate.decompress(Array(blob[4...]), format: .auto) else { continue } 189 let identifier = text(0) 190 let when: Int? 191 if fromApp { 192 // The identifier ends with the start time (local, to the second); the details record rounds it to the minute. 193 when = timestamp(fromIdentifier: identifier) ?? Int(text(4)) 194 } else { 195 when = timestamp(text(4)) ?? timestamp(fromFileName: text(1)) 196 } 197 guard let when else { continue } 198 var dive = ImportedDive(when: when, durationSeconds: Int(Double(text(5)) ?? 0)) 199 dive.sourceID = identifier 200 dive.serial = text(9) 201 let product = fromApp ? text(1) : text(1).prefix { $0 != "[" }.trimmingCharacters(in: .whitespaces) 202 dive.model = product.isEmpty ? "Shearwater" : "Shearwater \(product)" 203 dive.site = text(6) 204 if fromApp, sqlite3_column_type(statement, 10) != SQLITE_NULL, sqlite3_column_type(statement, 11) != SQLITE_NULL { 205 dive.latitude = sqlite3_column_double(statement, 10) 206 dive.longitude = sqlite3_column_double(statement, 11) 207 } 208 if fromApp { 209 let ids = (try? JSONDecoder().decode([String].self, from: Data(text(7).utf8))) ?? [] 210 dive.buddy = ids.compactMap { buddies[$0] }.joined(separator: ", ") 211 } else { 212 dive.buddy = text(7) 213 } 214 dive.notes = text(8) 215 decode(records, into: &dive) 216 guard !dive.samples.isEmpty else { continue } 217 if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 } 218 onLog?(dive, records) 219 out.append(dive) 220 } 221 return out 222 } 223 224 /// Shearwater log identifier: 9 fixed digits, then the start time in seconds. 225 static func timestamp(fromIdentifier identifier: String) -> Int? { 226 guard identifier.count == 19, identifier.allSatisfy(\.isNumber), let value = Int(identifier.suffix(10)), 227 value > 946_684_800, value < 4_102_444_800 else { return nil } 228 return value 229 } 230 231 static func timestamp(_ text: String) -> Int? { 232 let numbers = text.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) } 233 guard numbers.count >= 5 else { return nil } 234 return NaiveTime.timestamp(year: numbers[0], month: numbers[1], day: numbers[2], hour: numbers[3], minute: numbers[4], 235 second: numbers.count > 5 ? numbers[5] : 0) 236 } 237 238 /// "Petrel 3[B72CDA1C]#9 2025-9-6 11-27-54.swlogzp" 239 static func timestamp(fromFileName name: String) -> Int? { 240 guard let hash = name.firstIndex(of: "#"), let space = name[hash...].firstIndex(of: " ") else { return nil } 241 return timestamp(String(name[space...])) 242 } 243 244 static func decode(_ data: [UInt8], into dive: inout ImportedDive) { 245 func be16(_ record: ArraySlice<UInt8>, _ offset: Int) -> Int { 246 Int(record[record.startIndex + offset]) << 8 | Int(record[record.startIndex + offset + 1]) 247 } 248 var imperial = false 249 var interval = 10_000 250 var samples = [ArraySlice<UInt8>]() 251 var index = 0 252 while index + 32 <= data.count { 253 let record = data[index..<(index + 32)] 254 index += 32 255 switch record[record.startIndex] { 256 case 0x01: samples.append(record) 257 case 0x10: 258 imperial = record[record.startIndex + 8] == 1 259 dive.decoModel = "GF \(record[record.startIndex + 4])/\(record[record.startIndex + 5])" 260 case 0x11: 261 let mbar = be16(record, 16) 262 if mbar > 500 { dive.surfacePressureBar = Double(mbar) / 1000 } 263 case 0x13: 264 let density = be16(record, 3) 265 if density > 900, density < 1100 { dive.salinity = density } 266 case 0x15: 267 let ms = be16(record, 23) 268 if ms > 0 { interval = ms } 269 default: break 270 } 271 } 272 let feet = 0.3048 273 var time = 0 274 for record in samples { 275 let start = record.startIndex 276 time += interval 277 let rawDepth = Double(be16(record, 1)) / 10 278 var sample = ImportedDive.Sample(time: time / 1000, depth: imperial ? rawDepth * feet : rawDepth) 279 var temperature = Int(Int8(bitPattern: record[start + 14])) 280 if temperature < 0 { 281 temperature += 102 282 if temperature > 0 { temperature = 0 } 283 } 284 sample.temperature = imperial ? (Double(temperature) - 32) * 5 / 9 : Double(temperature) 285 let stop = Double(be16(record, 3)) 286 sample.stopDepth = imperial ? stop * feet : stop 287 sample.tts = be16(record, 5) * 60 288 sample.o2 = Int(record[start + 8]) 289 sample.he = Int(record[start + 9]) 290 sample.decoTime = Int(record[start + 10]) * 60 291 sample.cns = Int(record[start + 23]) 292 // Transmitter pressure: low-order 12 bits, in units of 2 psi; ≥ 0xFFF0 = no reading. 293 func pressure(_ offset: Int) -> Double? { 294 let raw = be16(record, offset) 295 guard raw < 0xFFF0, raw & 0x0FFF != 0 else { return nil } 296 return (Double(raw & 0x0FFF) * 2 * 0.0689476 * 10).rounded() / 10 297 } 298 sample.pressure1 = pressure(28) 299 sample.pressure2 = pressure(20) 300 dive.samples.append(sample) 301 } 302 } 303 } 304 305 extension LogEditor { 306 /// "Dive" file of an imported dive. 307 static func diveFile(_ dive: ImportedDive, siteUUID: UInt32?) -> String { 308 var text = "duration \(LogFormat.minutes(dive.durationSeconds)) min\n" 309 if let siteUUID, let line = line(.site, String(siteUUID, radix: 16)) { text += line } 310 if let line = line(.buddy, dive.buddy) { text += line } 311 if let line = line(.notes, dive.notes) { text += line } 312 for (index, gas) in dive.gases.enumerated() { 313 text += "cylinder" 314 if gas.o2Permille > 0 { text += " o2=\(LogFormat.milli(gas.o2Permille * 100))%" } 315 if gas.hePermille > 0 { text += " he=\(LogFormat.milli(gas.hePermille * 100))%" } 316 if index == 0 { 317 let pressures = dive.samples.compactMap(\.pressure1) 318 if let first = pressures.first, let last = pressures.last, first > last { 319 text += " start=\(LogFormat.milli(first))bar end=\(LogFormat.milli(last))bar" 320 } 321 } 322 text += "\n" 323 } 324 return text 325 } 326 327 /// "Divecomputer" file of an imported dive; values are only written when they change. 328 static func computerFile(_ dive: ImportedDive) -> String { 329 var text = "model \(LogFormat.quote(dive.model))\n" 330 text += "maxdepth \(LogFormat.milli(dive.maxDepth))m\n" 331 text += "meandepth \(LogFormat.milli(dive.meanDepth))m\n" 332 if let temperature = dive.minTemperature { text += "watertemp \(LogFormat.milli(temperature))°C\n" } 333 if let pressure = dive.surfacePressureBar { text += "surfacepressure \(LogFormat.milli(pressure))bar\n" } 334 if let salinity = dive.salinity { text += "salinity \(salinity)g/l\n" } 335 if !dive.serial.isEmpty { text += "keyvalue \"Serial\" \(LogFormat.quote(dive.serial))\n" } 336 if let model = dive.decoModel { text += "keyvalue \"Deco model\" \(LogFormat.quote(model))\n" } 337 338 // Gas changes. 339 let gases = dive.gases 340 var current: GasMix? 341 var first = true 342 for sample in dive.samples where sample.o2 > 0 || sample.he > 0 { 343 let mix = GasMix(o2Permille: sample.o2 == 21 && sample.he == 0 ? 0 : sample.o2 * 10, hePermille: sample.he * 10) 344 guard mix != current else { continue } 345 current = mix 346 let cylinder = gases.firstIndex(of: mix) ?? 0 347 let seconds = first ? 0 : sample.time 348 first = false 349 text += "event \(LogFormat.minutes(seconds)) type=25 flags=\(cylinder + 1) name=\"gaschange\" cylinder=\(cylinder)" 350 text += " o2=\(LogFormat.milli(sample.o2 * 1000))%" 351 if sample.he > 0 { text += " he=\(LogFormat.milli(sample.he * 1000))%" } 352 text += "\n" 353 } 354 355 var lastTemp: Double?, lastP1: Double?, lastP2: Double? 356 var lastNDL = -1, lastTTS = 0, lastInDeco = false, lastStopTime = 0, lastStopDepth = 0.0, lastCNS = 0 357 for sample in dive.samples { 358 var line = String(format: "%3d:%02d", sample.time / 60, sample.time % 60) + " \(LogFormat.milli(sample.depth))m" 359 if let t = sample.temperature, t != lastTemp { line += " \(LogFormat.milli(t))°C"; lastTemp = t } 360 if let p = sample.pressure1, p != lastP1 { line += " \(LogFormat.milli(p))bar:0"; lastP1 = p } 361 if let p = sample.pressure2, p != lastP2 { line += " \(LogFormat.milli(p))bar:1"; lastP2 = p } 362 let inDeco = sample.stopDepth > 0 363 let ndl = inDeco ? 0 : sample.decoTime 364 if ndl != lastNDL { line += " ndl=\(LogFormat.minutes(ndl))"; lastNDL = ndl } 365 if sample.tts != lastTTS { line += " tts=\(LogFormat.minutes(sample.tts))"; lastTTS = sample.tts } 366 if inDeco != lastInDeco { line += " in_deco=\(inDeco ? 1 : 0)"; lastInDeco = inDeco } 367 let stopTime = inDeco ? sample.decoTime : 0 368 if stopTime != lastStopTime { line += " stoptime=\(LogFormat.minutes(stopTime))"; lastStopTime = stopTime } 369 if sample.stopDepth != lastStopDepth { line += " stopdepth=\(LogFormat.milli(sample.stopDepth))m"; lastStopDepth = sample.stopDepth } 370 if sample.cns != lastCNS { line += " cns=\(sample.cns)%"; lastCNS = sample.cns } 371 text += line + "\n" 372 } 373 return text 374 } 375 }