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

FakePetrel.swift (6096B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import DiveComputerKit
      3 import Foundation
      4 
      5 /// A Shearwater computer on the other end of the link, speaking the protocol libdivecomputer expects over
      6 /// Bluetooth LE: SLIP frames cut into packets with a two-byte header, the "read data by identifier" requests and
      7 /// the block download of the manifest (raw) and of the dives (zero-run-length encoded after a 32-byte XOR).
      8 final class FakePetrel: DiveComputerTransport {
      9     let deviceName = "Petrel 3"
     10     let modelNumber: UInt8
     11     /// Raw logs, newest first.
     12     let logs: [[UInt8]]
     13     var serial = "1A2B3C4D"
     14     private(set) var closed = false
     15     private(set) var requests = 0
     16 
     17     private var incoming = [UInt8]()
     18     private var escaped = false
     19     private var outgoing = [Data]()
     20     private var stream = [UInt8]()
     21     private var sent = 0
     22 
     23     init(modelNumber: UInt8, logs: [[UInt8]]) {
     24         self.modelNumber = modelNumber
     25         self.logs = logs
     26     }
     27 
     28     func setTimeout(milliseconds: Int) {}
     29 
     30     func read(maxLength: Int) throws -> Data {
     31         guard !outgoing.isEmpty else { throw DiveComputerError.transport("timeout") }
     32         return outgoing.removeFirst()
     33     }
     34 
     35     func readCharacteristic(uuid: [UInt8]) throws -> Data { throw DiveComputerError.transport("no such characteristic") }
     36 
     37     func close() { closed = true }
     38 
     39     func write(_ data: Data) throws {
     40         // Two bytes of header (number of packets, index), then SLIP.
     41         for byte in data.dropFirst(2) {
     42             if escaped {
     43                 incoming.append(byte == 0xDC ? 0xC0 : 0xDB)
     44                 escaped = false
     45             } else if byte == 0xDB {
     46                 escaped = true
     47             } else if byte == 0xC0 {
     48                 let frame = incoming
     49                 incoming = []
     50                 if !frame.isEmpty { handle(frame) }
     51             } else {
     52                 incoming.append(byte)
     53             }
     54         }
     55     }
     56 
     57     private func handle(_ frame: [UInt8]) {
     58         guard frame.count >= 5, frame[0] == 0xFF, frame[1] == 0x01, Int(frame[2]) == frame.count - 3 else { return }
     59         requests += 1
     60         let request = Array(frame[4...])
     61         switch request[0] {
     62         case 0x22 where request.count == 3:
     63             let id = Int(request[1]) << 8 | Int(request[2])
     64             let head: [UInt8] = [0x62, request[1], request[2]]
     65             switch id {
     66             case 0x8010: reply(head + Array(serial.utf8))
     67             case 0x8011: reply(head + Array("V93".utf8))
     68             case 0x8060: reply(head + [modelNumber])
     69             case 0x8021: reply(head + [0x01, 0x80, 0, 0, 0, 0, 0, 0, 0])
     70             default: reply([0x7F, 0x22, 0x31])
     71             }
     72         case 0x35 where request.count == 10:
     73             let compressed = request[1] == 0x10
     74             let address = request[3...6].reduce(0) { $0 << 8 | Int($1) }
     75             let size = request[7...9].reduce(0) { $0 << 8 | Int($1) }
     76             if address == 0xE000_0000 {
     77                 stream = manifest(size: size)
     78             } else {
     79                 let index = (address - 0x8000_0000) / 0x10_0000
     80                 stream = logs.indices.contains(index) ? (compressed ? Self.compress(logs[index]) : logs[index]) : []
     81             }
     82             sent = 0
     83             reply([0x75, 0x10, 0x82])
     84         case 0x36:
     85             let chunk = Array(stream[sent..<min(stream.count, sent + 126)])
     86             sent += chunk.count
     87             reply([0x76, request[1]] + chunk)
     88         case 0x37:
     89             reply([0x77, 0x00])
     90         default:
     91             reply([0x7F, request[0], 0x11])
     92         }
     93     }
     94 
     95     private func manifest(size: Int) -> [UInt8] {
     96         var out = [UInt8]()
     97         for (index, log) in logs.enumerated() {
     98             var record = [UInt8](repeating: 0, count: 32)
     99             record[0] = 0xA5
    100             record[1] = 0xC4
    101             record.replaceSubrange(4..<8, with: log[12..<16])
    102             let address = index * 0x10_0000
    103             record[20] = UInt8(address >> 24 & 0xFF)
    104             record[21] = UInt8(address >> 16 & 0xFF)
    105             record[22] = UInt8(address >> 8 & 0xFF)
    106             record[23] = UInt8(address & 0xFF)
    107             out += record
    108         }
    109         return out + [UInt8](repeating: 0, count: max(0, size - out.count))
    110     }
    111 
    112     /// XOR of each byte with the one 32 bytes earlier, then 9-bit values: 1 + a byte, or 0 + a run of zeros.
    113     static func compress(_ data: [UInt8]) -> [UInt8] {
    114         var delta = data
    115         for index in stride(from: data.count - 1, through: 32, by: -1) { delta[index] = data[index] ^ data[index - 32] }
    116         var values = [UInt16]()
    117         var index = 0
    118         while index < delta.count {
    119             if delta[index] == 0 {
    120                 var run = 0
    121                 while index < delta.count, delta[index] == 0, run < 255 { run += 1; index += 1 }
    122                 values.append(UInt16(run))
    123             } else {
    124                 values.append(0x100 | UInt16(delta[index]))
    125                 index += 1
    126             }
    127         }
    128         values.append(0)
    129         while values.count % 8 != 0 { values.append(0) }
    130         var out = [UInt8]()
    131         var accumulator = 0, bits = 0
    132         for value in values {
    133             accumulator = accumulator << 9 | Int(value)
    134             bits += 9
    135             while bits >= 8 {
    136                 out.append(UInt8(accumulator >> (bits - 8) & 0xFF))
    137                 bits -= 8
    138             }
    139             accumulator &= (1 << bits) - 1
    140         }
    141         return out
    142     }
    143 
    144     private func reply(_ payload: [UInt8]) {
    145         let packet: [UInt8] = [0x01, 0xFF, UInt8(payload.count + 1), 0x00] + payload
    146         var slip = [UInt8]()
    147         for byte in packet {
    148             switch byte {
    149             case 0xC0: slip += [0xDB, 0xDC]
    150             case 0xDB: slip += [0xDB, 0xDD]
    151             default: slip.append(byte)
    152             }
    153         }
    154         slip.append(0xC0)
    155         let pieces = stride(from: 0, to: slip.count, by: 18).map { Array(slip[$0..<min(slip.count, $0 + 18)]) }
    156         for (index, piece) in pieces.enumerated() {
    157             outgoing.append(Data([UInt8(pieces.count), UInt8(index)] + piece))
    158         }
    159     }
    160 }