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

Parser.swift (7415B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import CLibDiveComputer
      3 import Foundation
      4 import SubsurfaceLog
      5 
      6 public enum DiveComputerError: Error, Equatable, CustomStringConvertible {
      7     case unknownModel
      8     case library(String, Int32)
      9     case cancelled
     10     case transport(String)
     11 
     12     public var description: String {
     13         switch self {
     14         case .unknownModel: return "unknown dive computer model"
     15         case .library(let what, let status): return "\(what) failed (libdivecomputer status \(status))"
     16         case .cancelled: return "cancelled"
     17         case .transport(let what): return "transport: \(what)"
     18         }
     19     }
     20 }
     21 
     22 /// Collects what libdivecomputer's sample callback reports into our own samples.
     23 final class SampleCollector {
     24     var samples = [ImportedDive.Sample]()
     25     var current: ImportedDive.Sample?
     26     var gases = [(o2: Int, he: Int)]()
     27     var gas = (o2: 21, he: 0)
     28     // Values that libdivecomputer only reports when they change are carried from one sample to the next.
     29     var stopDepth = 0.0, decoTime = 0, tts = 0, cns = 0
     30     var temperature: Double?
     31 
     32     func begin(seconds: Int) {
     33         flush()
     34         var sample = ImportedDive.Sample(time: seconds, depth: 0)
     35         sample.temperature = temperature
     36         sample.stopDepth = stopDepth
     37         sample.decoTime = decoTime
     38         sample.tts = tts
     39         sample.cns = cns
     40         sample.o2 = gas.o2
     41         sample.he = gas.he
     42         current = sample
     43     }
     44 
     45     func flush() {
     46         if let sample = current { samples.append(sample) }
     47         current = nil
     48     }
     49 }
     50 
     51 private let sampleCallback: dc_sample_callback_t = { type, value, userdata in
     52     guard let value, let userdata else { return }
     53     let collector = Unmanaged<SampleCollector>.fromOpaque(userdata).takeUnretainedValue()
     54     let v = value.pointee
     55     switch type {
     56     case DC_SAMPLE_TIME:
     57         collector.begin(seconds: Int(v.time / 1000))
     58     case DC_SAMPLE_DEPTH:
     59         collector.current?.depth = (v.depth * 100).rounded() / 100
     60     case DC_SAMPLE_TEMPERATURE:
     61         collector.temperature = (v.temperature * 10).rounded() / 10
     62         collector.current?.temperature = collector.temperature
     63     case DC_SAMPLE_PRESSURE:
     64         let bar = (v.pressure.value * 10).rounded() / 10
     65         if v.pressure.tank == 0 { collector.current?.pressure1 = bar } else if v.pressure.tank == 1 { collector.current?.pressure2 = bar }
     66     case DC_SAMPLE_CNS:
     67         collector.cns = Int((v.cns * 100).rounded())
     68         collector.current?.cns = collector.cns
     69     case DC_SAMPLE_DECO:
     70         let isStop = v.deco.type == DC_DECO_DECOSTOP.rawValue || v.deco.type == DC_DECO_DEEPSTOP.rawValue
     71         collector.stopDepth = isStop ? v.deco.depth : 0
     72         collector.decoTime = Int(v.deco.time)
     73         collector.tts = Int(v.deco.tts)
     74         collector.current?.stopDepth = collector.stopDepth
     75         collector.current?.decoTime = collector.decoTime
     76         collector.current?.tts = collector.tts
     77     case DC_SAMPLE_TTS:
     78         collector.tts = Int(v.time)
     79         collector.current?.tts = collector.tts
     80     case DC_SAMPLE_GASMIX:
     81         let index = Int(v.gasmix)
     82         if collector.gases.indices.contains(index) {
     83             collector.gas = collector.gases[index]
     84             collector.current?.o2 = collector.gas.o2
     85             collector.current?.he = collector.gas.he
     86         }
     87     default:
     88         break
     89     }
     90 }
     91 
     92 public enum DiveComputerParser {
     93     /// Parses the raw data of one dive, as downloaded from a computer of the given model.
     94     public static func parse(model: DiveComputerModel, data: Data, serial: String = "") throws -> ImportedDive {
     95         var context: OpaquePointer?
     96         guard dc_context_new(&context) == DC_STATUS_SUCCESS, let context else { throw DiveComputerError.library("dc_context_new", -1) }
     97         defer { dc_context_free(context) }
     98         let parsed: ImportedDive?? = try DiveComputerCatalog.withDescriptor(of: model) { descriptor -> ImportedDive? in
     99             try data.withUnsafeBytes { raw -> ImportedDive? in
    100                 var parser: OpaquePointer?
    101                 let status = dc_parser_new2(&parser, context, descriptor, raw.bindMemory(to: UInt8.self).baseAddress, raw.count)
    102                 guard status == DC_STATUS_SUCCESS, let parser else { throw DiveComputerError.library("dc_parser_new2", status.rawValue) }
    103                 defer { dc_parser_destroy(parser) }
    104                 return try dive(from: parser, modelName: model.name, serial: serial)
    105             }
    106         }
    107         guard let found = parsed, let dive = found else { throw DiveComputerError.unknownModel }
    108         return dive
    109     }
    110 
    111     /// Reads everything our logbook keeps from a libdivecomputer parser.
    112     static func dive(from parser: OpaquePointer, modelName: String, serial: String) throws -> ImportedDive {
    113         var datetime = dc_datetime_t()
    114         let status = dc_parser_get_datetime(parser, &datetime)
    115         guard status == DC_STATUS_SUCCESS else { throw DiveComputerError.library("dc_parser_get_datetime", status.rawValue) }
    116         guard let when = NaiveTime.timestamp(year: Int(datetime.year), month: Int(datetime.month), day: Int(datetime.day),
    117                                              hour: Int(datetime.hour), minute: Int(datetime.minute), second: Int(datetime.second)) else {
    118             throw DiveComputerError.library("date of the dive", 0)
    119         }
    120 
    121         var seconds: UInt32 = 0
    122         _ = dc_parser_get_field(parser, DC_FIELD_DIVETIME, 0, &seconds)
    123         var dive = ImportedDive(when: when, durationSeconds: Int(seconds))
    124         dive.model = modelName
    125         dive.serial = serial
    126 
    127         var atmospheric = 0.0
    128         if dc_parser_get_field(parser, DC_FIELD_ATMOSPHERIC, 0, &atmospheric) == DC_STATUS_SUCCESS, atmospheric > 0.5 {
    129             dive.surfacePressureBar = (atmospheric * 1000).rounded() / 1000
    130         }
    131         var salinity = dc_salinity_t()
    132         if dc_parser_get_field(parser, DC_FIELD_SALINITY, 0, &salinity) == DC_STATUS_SUCCESS, salinity.density > 900, salinity.density < 1100 {
    133             dive.salinity = Int(salinity.density.rounded())
    134         }
    135         var decoModel = dc_decomodel_t()
    136         if dc_parser_get_field(parser, DC_FIELD_DECOMODEL, 0, &decoModel) == DC_STATUS_SUCCESS {
    137             if decoModel.type == DC_DECOMODEL_BUHLMANN, decoModel.params.gf.high > 0 {
    138                 dive.decoModel = "GF \(decoModel.params.gf.low)/\(decoModel.params.gf.high)"
    139             }
    140         }
    141 
    142         let collector = SampleCollector()
    143         var gasCount: UInt32 = 0
    144         _ = dc_parser_get_field(parser, DC_FIELD_GASMIX_COUNT, 0, &gasCount)
    145         for index in 0..<min(gasCount, 32) {
    146             var mix = dc_gasmix_t()
    147             guard dc_parser_get_field(parser, DC_FIELD_GASMIX, index, &mix) == DC_STATUS_SUCCESS else { break }
    148             collector.gases.append((o2: Int((mix.oxygen * 100).rounded()), he: Int((mix.helium * 100).rounded())))
    149         }
    150         if let first = collector.gases.first { collector.gas = first }
    151 
    152         let samplesStatus = dc_parser_samples_foreach(parser, sampleCallback, Unmanaged.passUnretained(collector).toOpaque())
    153         guard samplesStatus == DC_STATUS_SUCCESS else { throw DiveComputerError.library("dc_parser_samples_foreach", samplesStatus.rawValue) }
    154         collector.flush()
    155         dive.samples = collector.samples
    156         if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 }
    157         return dive
    158     }
    159 }