Download.swift (12024B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import CDiveComputerShims 3 import CLibDiveComputer 4 import Foundation 5 import SubsurfaceLog 6 7 /// The link to the dive computer, provided by the app (Bluetooth LE on iOS). libdivecomputer drives it from the 8 /// download thread with blocking calls: every method blocks until done, and throws on timeout or failure. 9 public protocol DiveComputerTransport: AnyObject { 10 /// Name the device advertises (some protocols derive a serial number or a key from it). 11 var deviceName: String { get } 12 /// Timeout of the following reads, in milliseconds (negative: wait forever). 13 func setTimeout(milliseconds: Int) 14 /// Next packet received from the device, at most `maxLength` bytes. 15 func read(maxLength: Int) throws -> Data 16 func write(_ data: Data) throws 17 /// Reads a GATT characteristic of the service in use, by its 16-byte UUID. 18 func readCharacteristic(uuid: [UInt8]) throws -> Data 19 func close() 20 } 21 22 public struct DiveComputerInfo: Sendable, Equatable { 23 public var model: UInt32 = 0 24 public var firmware: UInt32 = 0 25 public var serial: UInt32 = 0 26 /// The exact model, once the computer has said which one it is (the Bluetooth name is not always enough). 27 public var modelName = "" 28 29 /// Serial number the way most computers show it. 30 public var serialText: String { serial == 0 ? "" : String(format: "%08x", serial) } 31 } 32 33 public struct DiveComputerDownloadResult: Sendable { 34 public var dives: [ImportedDive] = [] 35 public var info = DiveComputerInfo() 36 /// Fingerprint of the newest dive: pass it to the next download to fetch only newer dives. 37 public var newestFingerprint: Data? 38 /// libdivecomputer's own log of the session, for troubleshooting. 39 public var log: [String] = [] 40 /// Dives the computer sent but that could not be parsed. 41 public var unparsed = 0 42 } 43 44 /// One download session. Runs synchronously: call it from a background thread. 45 public final class DiveComputerDownload { 46 private let model: DiveComputerModel 47 private let transport: DiveComputerTransport 48 private let progress: (Double) -> Void 49 private let isCancelled: () -> Bool 50 private var result = DiveComputerDownloadResult() 51 private var device: OpaquePointer? 52 private var timeout = 5000 53 private let logLock = NSLock() 54 55 public init(model: DiveComputerModel, transport: DiveComputerTransport, 56 progress: @escaping (Double) -> Void = { _ in }, isCancelled: @escaping () -> Bool = { false }) { 57 self.model = model 58 self.transport = transport 59 self.progress = progress 60 self.isCancelled = isCancelled 61 } 62 63 private func log(_ line: String) { 64 logLock.lock(); defer { logLock.unlock() } 65 if result.log.count < 4000 { result.log.append(line) } 66 } 67 68 /// Downloads the dives newer than `fingerprint` (all of them when nil). 69 public func run(fingerprint: Data? = nil) throws -> DiveComputerDownloadResult { 70 let me = Unmanaged.passUnretained(self).toOpaque() 71 var context: OpaquePointer? 72 guard dc_context_new(&context) == DC_STATUS_SUCCESS, let context else { throw DiveComputerError.library("dc_context_new", -1) } 73 defer { dc_context_free(context) } 74 dc_context_set_loglevel(context, DC_LOGLEVEL_INFO) 75 dc_context_set_logfunc(context, { _, level, _, _, _, message, userdata in 76 guard let message, let userdata else { return } 77 Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue().log("[\(level.rawValue)] " + String(cString: message)) 78 }, me) 79 80 var callbacks = dc_custom_cbs_t() 81 callbacks.set_timeout = { userdata, timeout in 82 guard let userdata else { return DC_STATUS_INVALIDARGS } 83 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 84 me.timeout = Int(timeout) 85 me.transport.setTimeout(milliseconds: Int(timeout)) 86 return DC_STATUS_SUCCESS 87 } 88 callbacks.read = { userdata, data, size, actual in 89 guard let userdata, let data else { return DC_STATUS_INVALIDARGS } 90 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 91 actual?.pointee = 0 92 do { 93 let packet = try me.transport.read(maxLength: size) 94 guard packet.count <= size else { 95 me.log("packet too large (\(packet.count) > \(size))") 96 return DC_STATUS_IO 97 } 98 packet.copyBytes(to: data.assumingMemoryBound(to: UInt8.self), count: packet.count) 99 actual?.pointee = packet.count 100 return DC_STATUS_SUCCESS 101 } catch DiveComputerError.transport(let what) where what == "timeout" { 102 return DC_STATUS_TIMEOUT 103 } catch { 104 me.log("read: \(error)") 105 return DC_STATUS_IO 106 } 107 } 108 callbacks.write = { userdata, data, size, actual in 109 guard let userdata, let data else { return DC_STATUS_INVALIDARGS } 110 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 111 actual?.pointee = 0 112 do { 113 try me.transport.write(Data(bytes: data, count: size)) 114 actual?.pointee = size 115 return DC_STATUS_SUCCESS 116 } catch { 117 me.log("write: \(error)") 118 return DC_STATUS_IO 119 } 120 } 121 callbacks.ioctl = { userdata, request, data, size in 122 guard let userdata, let data else { return DC_STATUS_INVALIDARGS } 123 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 124 if request == dcshim_ioctl_ble_get_name() { 125 let name = Array(me.transport.deviceName.utf8.prefix(max(size - 1, 0))) 126 guard !name.isEmpty else { return DC_STATUS_UNSUPPORTED } 127 let out = data.assumingMemoryBound(to: UInt8.self) 128 for (index, byte) in name.enumerated() { out[index] = byte } 129 out[name.count] = 0 130 return DC_STATUS_SUCCESS 131 } 132 if request == dcshim_ioctl_ble_characteristic_read(), size > 16 { 133 // The buffer starts with the 16-byte UUID; the value read goes right after it. 134 let bytes = data.assumingMemoryBound(to: UInt8.self) 135 let uuid = Array(UnsafeBufferPointer(start: bytes, count: 16)) 136 do { 137 let value = try me.transport.readCharacteristic(uuid: uuid) 138 guard value.count == size - 16 else { return DC_STATUS_DATAFORMAT } 139 value.copyBytes(to: bytes + 16, count: value.count) 140 return DC_STATUS_SUCCESS 141 } catch { 142 me.log("characteristic read: \(error)") 143 return DC_STATUS_IO 144 } 145 } 146 return DC_STATUS_UNSUPPORTED 147 } 148 callbacks.sleep = { _, milliseconds in 149 Thread.sleep(forTimeInterval: Double(milliseconds) / 1000) 150 return DC_STATUS_SUCCESS 151 } 152 callbacks.close = { userdata in 153 guard let userdata else { return DC_STATUS_SUCCESS } 154 Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue().transport.close() 155 return DC_STATUS_SUCCESS 156 } 157 158 var iostream: OpaquePointer? 159 let opened = dc_custom_open(&iostream, context, DC_TRANSPORT_BLE, &callbacks, me) 160 guard opened == DC_STATUS_SUCCESS, let iostream else { throw DiveComputerError.library("dc_custom_open", opened.rawValue) } 161 defer { dc_iostream_close(iostream) } 162 163 let status: dc_status_t? = try DiveComputerCatalog.withDescriptor(of: model) { descriptor -> dc_status_t in 164 var device: OpaquePointer? 165 let status = dc_device_open(&device, context, descriptor, iostream) 166 guard status == DC_STATUS_SUCCESS, let device else { return status } 167 defer { dc_device_close(device) } 168 self.device = device 169 170 dc_device_set_cancel(device, { userdata in 171 guard let userdata else { return 0 } 172 return Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue().isCancelled() ? 1 : 0 173 }, me) 174 let events = UInt32(DC_EVENT_PROGRESS.rawValue | DC_EVENT_DEVINFO.rawValue) 175 dc_device_set_events(device, events, { _, event, data, userdata in 176 guard let data, let userdata else { return } 177 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 178 if event == DC_EVENT_PROGRESS { 179 let p = data.assumingMemoryBound(to: dc_event_progress_t.self).pointee 180 if p.maximum > 0 { me.progress(min(1, Double(p.current) / Double(p.maximum))) } 181 } else if event == DC_EVENT_DEVINFO { 182 let info = data.assumingMemoryBound(to: dc_event_devinfo_t.self).pointee 183 me.result.info.model = info.model 184 me.result.info.firmware = info.firmware 185 me.result.info.serial = info.serial 186 // The model number the computer reports selects the exact model within the family. 187 // (`product_name` is left alone: several drivers do not fill it in.) 188 let family = me.model.family 189 me.result.info.modelName = DiveComputerCatalog.all.first { $0.family == family && $0.model == info.model }?.name ?? me.model.name 190 } 191 }, me) 192 if let fingerprint, !fingerprint.isEmpty { 193 _ = fingerprint.withUnsafeBytes { dc_device_set_fingerprint(device, $0.bindMemory(to: UInt8.self).baseAddress, UInt32($0.count)) } 194 } 195 196 return dc_device_foreach(device, { data, size, fingerprint, fingerprintSize, userdata in 197 guard let data, let userdata else { return 1 } 198 let me = Unmanaged<DiveComputerDownload>.fromOpaque(userdata).takeUnretainedValue() 199 // Dives come newest first: the first fingerprint is the one to remember. 200 if me.result.newestFingerprint == nil, let fingerprint, fingerprintSize > 0 { 201 me.result.newestFingerprint = Data(bytes: fingerprint, count: Int(fingerprintSize)) 202 } 203 var parser: OpaquePointer? 204 if dc_parser_new(&parser, me.device, data, Int(size)) == DC_STATUS_SUCCESS, let parser { 205 defer { dc_parser_destroy(parser) } 206 let name = me.result.info.modelName.isEmpty ? me.model.name : me.result.info.modelName 207 if var dive = try? DiveComputerParser.dive(from: parser, modelName: name, serial: me.result.info.serialText) { 208 dive.sourceID = me.result.info.serialText + "-" + String(dive.when) 209 me.result.dives.append(dive) 210 } else { 211 me.result.unparsed += 1 212 } 213 } else { 214 me.result.unparsed += 1 215 } 216 return me.isCancelled() ? 0 : 1 217 }, me) 218 } 219 self.device = nil 220 221 guard let status else { throw DiveComputerError.unknownModel } 222 if isCancelled() { throw DiveComputerError.cancelled } 223 guard status == DC_STATUS_SUCCESS else { 224 let tail = result.log.suffix(3).joined(separator: " | ") 225 throw DiveComputerError.library("download" + (tail.isEmpty ? "" : " (\(tail))"), status.rawValue) 226 } 227 return result 228 } 229 230 /// Log lines gathered so far (also available after a failure). 231 public var logLines: [String] { 232 logLock.lock(); defer { logLock.unlock() } 233 return result.log 234 } 235 }