Fix transfer errors, save raw data
This commit is contained in:
@@ -1,18 +1,29 @@
|
||||
import Foundation
|
||||
import CoreBluetooth
|
||||
|
||||
protocol BluetoothDeviceDelegate: AnyObject {
|
||||
|
||||
func bluetoothDevice(didUpdate info: DeviceInfo?)
|
||||
}
|
||||
|
||||
actor BluetoothDevice: NSObject, ObservableObject {
|
||||
|
||||
private let peripheral: CBPeripheral!
|
||||
let peripheral: CBPeripheral!
|
||||
|
||||
private let characteristic: CBCharacteristic!
|
||||
|
||||
@MainActor @Published
|
||||
@Published
|
||||
var lastDeviceInfo: DeviceInfo?
|
||||
|
||||
@Published
|
||||
private(set) var lastRSSI: Int = 0
|
||||
|
||||
weak var delegate: BluetoothDeviceDelegate?
|
||||
|
||||
func set(delegate: BluetoothDeviceDelegate?) {
|
||||
self.delegate = delegate
|
||||
}
|
||||
|
||||
init(peripheral: CBPeripheral, characteristic: CBCharacteristic) {
|
||||
self.peripheral = peripheral
|
||||
self.characteristic = characteristic
|
||||
@@ -33,9 +44,10 @@ actor BluetoothDevice: NSObject, ObservableObject {
|
||||
guard let info = await getInfo() else {
|
||||
return
|
||||
}
|
||||
Task { @MainActor in
|
||||
lastDeviceInfo = info
|
||||
}
|
||||
lastDeviceInfo = info
|
||||
delegate?.bluetoothDevice(didUpdate: info)
|
||||
#warning("Don't use global variable")
|
||||
storage.save(deviceInfo: info)
|
||||
}
|
||||
|
||||
func getInfo() async -> DeviceInfo? {
|
||||
|
@@ -26,33 +26,56 @@ final class BluetoothScanner: NSObject, CBCentralManagerDelegate, ObservableObje
|
||||
@Published
|
||||
var configuredDevice: BluetoothDevice?
|
||||
|
||||
@Published
|
||||
var lastDeviceInfo: DeviceInfo?
|
||||
|
||||
private var connectingDevice: CBPeripheral?
|
||||
|
||||
var isScanningForDevices: Bool {
|
||||
get {
|
||||
manager.isScanning
|
||||
}
|
||||
set {
|
||||
if newValue {
|
||||
guard !manager.isScanning else {
|
||||
return
|
||||
}
|
||||
manager.scanForPeripherals(withServices: [serviceUUID])
|
||||
log.info("Scanner: Started scanning for devices")
|
||||
@Published
|
||||
var isScanningForDevices: Bool = false {
|
||||
didSet {
|
||||
if isScanningForDevices {
|
||||
startScanning()
|
||||
} else {
|
||||
guard manager.isScanning else {
|
||||
return
|
||||
}
|
||||
manager.stopScan()
|
||||
log.info("Scanner: Stopped scanning for devices")
|
||||
stopScanning()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func startScanning() {
|
||||
guard !manager.isScanning else {
|
||||
return
|
||||
}
|
||||
manager.scanForPeripherals(withServices: [serviceUUID])
|
||||
log.info("Scanner: Started scanning for devices")
|
||||
}
|
||||
|
||||
private func stopScanning() {
|
||||
guard manager.isScanning else {
|
||||
return
|
||||
}
|
||||
manager.stopScan()
|
||||
log.info("Scanner: Stopped scanning for devices")
|
||||
}
|
||||
|
||||
var isConnectingOrConnected: Bool {
|
||||
configuredDevice != nil || connectingDevice != nil
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
if let configuredDevice {
|
||||
manager.cancelPeripheralConnection(configuredDevice.peripheral)
|
||||
}
|
||||
if let connectingDevice {
|
||||
manager.cancelPeripheralConnection(connectingDevice)
|
||||
}
|
||||
}
|
||||
|
||||
override init() {
|
||||
connectionState = .noDeviceFound
|
||||
super.init()
|
||||
self.manager = CBCentralManager(delegate: self, queue: nil)
|
||||
self.isScanningForDevices = manager.isScanning
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
|
||||
@@ -95,6 +118,7 @@ final class BluetoothScanner: NSObject, CBCentralManagerDelegate, ObservableObje
|
||||
peripheral.discoverServices([serviceUUID])
|
||||
connectingDevice = peripheral
|
||||
configuredDevice = nil
|
||||
isScanningForDevices = false
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
|
||||
@@ -121,13 +145,15 @@ extension BluetoothScanner: CBPeripheralDelegate {
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
connectionState = .noDeviceFound
|
||||
connectingDevice = nil
|
||||
isScanningForDevices = true
|
||||
return
|
||||
}
|
||||
guard let service = services.first(where: { $0.uuid.uuidString == DeviceManager.serviceUUID.uuidString }) else {
|
||||
guard let service = services.first(where: { $0.uuid.uuidString == serviceUUID.uuidString }) else {
|
||||
log.error("Connected device '\(peripheral.name ?? "No Name")': Required service not found: \(services.map { $0.uuid.uuidString})")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
connectionState = .noDeviceFound
|
||||
connectingDevice = nil
|
||||
isScanningForDevices = true
|
||||
return
|
||||
}
|
||||
peripheral.delegate = self
|
||||
@@ -142,6 +168,7 @@ extension BluetoothScanner: CBPeripheralDelegate {
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
connectionState = .noDeviceFound
|
||||
connectingDevice = nil
|
||||
isScanningForDevices = true
|
||||
return
|
||||
}
|
||||
|
||||
@@ -150,6 +177,7 @@ extension BluetoothScanner: CBPeripheralDelegate {
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
connectionState = .noDeviceFound
|
||||
connectingDevice = nil
|
||||
isScanningForDevices = true
|
||||
return
|
||||
}
|
||||
|
||||
@@ -168,9 +196,22 @@ extension BluetoothScanner: CBPeripheralDelegate {
|
||||
guard let desiredCharacteristic else {
|
||||
log.error("Connected device '\(peripheral.name ?? "No Name")': Characteristic not found")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
isScanningForDevices = true
|
||||
return
|
||||
}
|
||||
|
||||
configuredDevice = .init(peripheral: peripheral, characteristic: desiredCharacteristic)
|
||||
Task {
|
||||
await configuredDevice?.set(delegate: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BluetoothScanner: BluetoothDeviceDelegate {
|
||||
|
||||
func bluetoothDevice(didUpdate info: DeviceInfo?) {
|
||||
DispatchQueue.main.async {
|
||||
self.lastDeviceInfo = info
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,405 +0,0 @@
|
||||
import Foundation
|
||||
import CoreBluetooth
|
||||
/*
|
||||
actor DeviceConnection: NSObject, CBCentralManagerDelegate, ObservableObject {
|
||||
|
||||
static let serviceUUID = CBUUID(string: "22071991-cccc-cccc-cccc-000000000001")
|
||||
|
||||
static let characteristicUUID = CBUUID(string: "22071991-cccc-cccc-cccc-000000000002")
|
||||
|
||||
private var manager: CBCentralManager! = nil
|
||||
|
||||
private(set) var lastRSSI: Int = 0 // TODO: Provide function to update
|
||||
|
||||
@Published
|
||||
var state: DeviceState = .disconnected
|
||||
|
||||
var isConnected: Bool {
|
||||
// Automatically updates with device state
|
||||
if case .configured = state {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
self.manager = CBCentralManager(delegate: self, queue: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Allow the client to scan for devices and connect to the first device found with the correct characteristic
|
||||
*/
|
||||
@discardableResult
|
||||
func initiateDeviceConnection() -> Bool {
|
||||
switch state {
|
||||
case .bluetoothDisabled:
|
||||
log.info("Can't connect, bluetooth disabled")
|
||||
return false
|
||||
case .disconnected:
|
||||
break
|
||||
default:
|
||||
return true
|
||||
}
|
||||
guard !manager.isScanning else {
|
||||
state = .scanning
|
||||
return true
|
||||
}
|
||||
shouldConnectIfPossible = true
|
||||
state = .scanning
|
||||
manager.scanForPeripherals(withServices: [DeviceManager.serviceUUID])
|
||||
return true
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func updateRSSIForConnectedDevice() -> Bool {
|
||||
guard let device = state.device else {
|
||||
return false
|
||||
}
|
||||
device.readRSSI()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
Indicate that a connection should be attempted when found.
|
||||
|
||||
This does not necessarily indicate that the phone is scanning for devices.
|
||||
*/
|
||||
@Published
|
||||
var shouldConnectIfPossible = true {
|
||||
didSet {
|
||||
guard oldValue != shouldConnectIfPossible else {
|
||||
return
|
||||
}
|
||||
updateConnectionOnChange()
|
||||
}
|
||||
}
|
||||
|
||||
private func updateConnectionOnChange() {
|
||||
if shouldConnectIfPossible {
|
||||
ensureConnection()
|
||||
} else {
|
||||
disconnectIfNeeded()
|
||||
}
|
||||
}
|
||||
|
||||
private func ensureConnection() {
|
||||
switch state {
|
||||
case .disconnected:
|
||||
initiateDeviceConnection()
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private func disconnectIfNeeded() {
|
||||
switch state {
|
||||
case .bluetoothDisabled, .disconnected:
|
||||
return
|
||||
default:
|
||||
disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
func disconnect() {
|
||||
shouldConnectIfPossible = false
|
||||
switch state {
|
||||
case .bluetoothDisabled, .disconnected:
|
||||
return
|
||||
case .scanning:
|
||||
manager.stopScan()
|
||||
state = .disconnected
|
||||
return
|
||||
case .connecting(let device),
|
||||
.discoveringCharacteristic(let device),
|
||||
.discoveringServices(device: let device),
|
||||
.configured(let device, _):
|
||||
manager.cancelPeripheralConnection(device)
|
||||
manager.stopScan()
|
||||
state = .disconnected
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private var requestContinuation: CheckedContinuation<Data?, Never>?
|
||||
|
||||
func getInfo() async -> DeviceInfo? {
|
||||
await get(DeviceInfoRequest())
|
||||
}
|
||||
|
||||
func getDeviceData(offset: Int, count: Int) async -> Data? {
|
||||
await get(DeviceDataRequest(offset: offset, count: count))
|
||||
}
|
||||
|
||||
func deleteDeviceData(byteCount: Int) async -> Bool {
|
||||
await get(DeviceDataResetRequest(byteCount: byteCount)) != nil
|
||||
}
|
||||
|
||||
private func get<Request>(_ request: Request) async -> Request.Response? where Request: DeviceRequest {
|
||||
guard requestContinuation == nil else {
|
||||
// Prevent parallel requests
|
||||
return nil
|
||||
}
|
||||
guard case .configured(let device, let characteristic) = state else {
|
||||
return nil
|
||||
}
|
||||
let requestData = Data([request.type.rawValue]) + request.payload
|
||||
let responseData: Data? = await withCheckedContinuation { continuation in
|
||||
requestContinuation = continuation
|
||||
device.writeValue(requestData, for: characteristic, type: .withResponse)
|
||||
device.readValue(for: characteristic)
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(5)) { [weak self] in
|
||||
Task {
|
||||
await self?.checkTimeoutForCurrentRequest(request.type)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
guard let responseData else {
|
||||
return nil
|
||||
}
|
||||
guard let responseCode = responseData.first else {
|
||||
log.error("Request \(request.type) got response of zero bytes")
|
||||
return nil
|
||||
}
|
||||
guard let responseType = BluetoothResponseType(rawValue: responseCode) else {
|
||||
log.error("Request \(request.type) got unknown response code \(responseCode)")
|
||||
return nil
|
||||
}
|
||||
switch responseType {
|
||||
case .success, .responseTooLarge, .invalidNumberOfBytesToDelete:
|
||||
break
|
||||
case .invalidCommand:
|
||||
log.error("Request \(request.type) failed: Invalid command")
|
||||
return nil
|
||||
case .unknownCommand:
|
||||
log.error("Request \(request.type) failed: Unknown command")
|
||||
return nil
|
||||
case .responseInProgress:
|
||||
log.info("Request \(request.type) failed: Device is busy")
|
||||
return nil
|
||||
}
|
||||
return request.makeResponse(from: responseData.dropFirst(), responseType: responseType)
|
||||
}
|
||||
|
||||
private func checkTimeoutForCurrentRequest(_ type: BluetoothRequestType) {
|
||||
guard let requestContinuation else { return }
|
||||
log.info("Timed out for request \(type)")
|
||||
requestContinuation.resume(returning: nil)
|
||||
self.requestContinuation = nil
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
|
||||
Task {
|
||||
await didDiscover(peripheral: peripheral)
|
||||
}
|
||||
}
|
||||
|
||||
private func didDiscover(peripheral: CBPeripheral) {
|
||||
guard shouldConnectIfPossible else {
|
||||
return
|
||||
}
|
||||
peripheral.delegate = self
|
||||
manager.connect(peripheral)
|
||||
manager.stopScan()
|
||||
state = .connecting(device: peripheral)
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func centralManagerDidUpdateState(_ central: CBCentralManager) {
|
||||
Task {
|
||||
await didUpdate(state: central.state)
|
||||
}
|
||||
}
|
||||
|
||||
private func didUpdate(state newState: CBManagerState) {
|
||||
switch newState {
|
||||
case .poweredOff:
|
||||
state = .bluetoothDisabled
|
||||
case .poweredOn:
|
||||
state = .disconnected
|
||||
initiateDeviceConnection()
|
||||
case .unsupported:
|
||||
state = .bluetoothDisabled
|
||||
log.info("Bluetooth is not supported")
|
||||
case .unknown:
|
||||
state = .bluetoothDisabled
|
||||
log.info("Bluetooth state is unknown")
|
||||
case .resetting:
|
||||
state = .bluetoothDisabled
|
||||
log.info("Bluetooth is resetting")
|
||||
case .unauthorized:
|
||||
state = .bluetoothDisabled
|
||||
log.info("Bluetooth is not authorized")
|
||||
@unknown default:
|
||||
state = .bluetoothDisabled
|
||||
log.warning("Unknown state \(newState)")
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
||||
Task {
|
||||
await didConnect(to: peripheral)
|
||||
}
|
||||
}
|
||||
|
||||
private func didConnect(to peripheral: CBPeripheral) {
|
||||
log.info("Connected to " + peripheral.name!)
|
||||
peripheral.discoverServices([DeviceManager.serviceUUID])
|
||||
state = .discoveringServices(device: peripheral)
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
|
||||
Task {
|
||||
await didDisconnect(from: peripheral, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
private func didDisconnect(from peripheral: CBPeripheral, error: Error?) {
|
||||
log.info("Disconnected from " + peripheral.name!)
|
||||
state = .disconnected
|
||||
// Attempt to reconnect
|
||||
if shouldConnectIfPossible {
|
||||
initiateDeviceConnection()
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
|
||||
Task {
|
||||
await didFailToConnect(to: peripheral, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
private func didFailToConnect(to peripheral: CBPeripheral, error: Error?) {
|
||||
log.warning("Failed to connect device '\(peripheral.name ?? "NO_NAME")'")
|
||||
if let error = error {
|
||||
log.warning(error.localizedDescription)
|
||||
}
|
||||
state = manager.isScanning ? .scanning : .disconnected
|
||||
// Attempt to reconnect
|
||||
if shouldConnectIfPossible {
|
||||
initiateDeviceConnection()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DeviceConnection: CBPeripheralDelegate {
|
||||
|
||||
nonisolated
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
||||
Task {
|
||||
await didDiscoverServices(for: peripheral)
|
||||
}
|
||||
}
|
||||
|
||||
private func didDiscoverServices(for peripheral: CBPeripheral) {
|
||||
guard let services = peripheral.services, !services.isEmpty else {
|
||||
log.error("No services found for device '\(peripheral.name ?? "NO_NAME")'")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
guard let service = services.first(where: { $0.uuid.uuidString == DeviceManager.serviceUUID.uuidString }) else {
|
||||
log.error("Required service not found for '\(peripheral.name ?? "NO_NAME")': \(services.map { $0.uuid.uuidString})")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
peripheral.discoverCharacteristics([DeviceManager.characteristicUUID], for: service)
|
||||
state = .discoveringCharacteristic(device: peripheral)
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
|
||||
Task {
|
||||
await didDiscoverCharacteristics(for: service, of: peripheral, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
private func didDiscoverCharacteristics(for service: CBService, of peripheral: CBPeripheral, error: Error?) {
|
||||
if let error = error {
|
||||
log.error("Failed to discover characteristics: \(error)")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
guard let characteristics = service.characteristics, !characteristics.isEmpty else {
|
||||
log.error("No characteristics found for device")
|
||||
manager.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
for characteristic in characteristics {
|
||||
guard characteristic.uuid == DeviceManager.characteristicUUID else {
|
||||
log.warning("Unused characteristic \(characteristic.uuid.uuidString)")
|
||||
continue
|
||||
}
|
||||
state = .configured(device: peripheral, characteristic: characteristic)
|
||||
peripheral.setNotifyValue(true, for: characteristic)
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
if let error = error {
|
||||
log.error("Peripheral failed to write value for \(characteristic.uuid.uuidString): \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
|
||||
if let error = error {
|
||||
log.warning("Failed to get RSSI: \(error)")
|
||||
return
|
||||
}
|
||||
Task {
|
||||
await update(rssi: RSSI.intValue)
|
||||
}
|
||||
log.info("RSSI: \(RSSI.intValue)")
|
||||
}
|
||||
|
||||
private func update(rssi: Int) {
|
||||
lastRSSI = rssi
|
||||
}
|
||||
|
||||
nonisolated
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
Task {
|
||||
await didUpdateValue(for: characteristic, of: peripheral, error: error)
|
||||
}
|
||||
}
|
||||
|
||||
private func didUpdateValue(for characteristic: CBCharacteristic, of peripheral: CBPeripheral, error: Error?) {
|
||||
if let error = error {
|
||||
log.error("Failed to read value update: \(error)")
|
||||
continueRequest(with: nil)
|
||||
return
|
||||
}
|
||||
guard case .configured(device: _, characteristic: let storedCharacteristic) = state else {
|
||||
log.warning("Received data while not properly configured")
|
||||
continueRequest(with: nil)
|
||||
return
|
||||
}
|
||||
guard characteristic.uuid == storedCharacteristic.uuid else {
|
||||
log.warning("Read unknown characteristic \(characteristic.uuid.uuidString)")
|
||||
continueRequest(with: nil)
|
||||
return
|
||||
}
|
||||
guard let data = characteristic.value else {
|
||||
log.warning("No data")
|
||||
continueRequest(with: nil)
|
||||
return
|
||||
}
|
||||
continueRequest(with: data)
|
||||
}
|
||||
|
||||
private func continueRequest(with response: Data?) {
|
||||
guard let requestContinuation else {
|
||||
log.error("No continuation to handle request data (\(response?.count ?? 0) bytes)")
|
||||
return
|
||||
}
|
||||
requestContinuation.resume(returning: response)
|
||||
self.requestContinuation = nil
|
||||
}
|
||||
}
|
||||
*/
|
96
TempTrack/Connection/TransferHandler.swift
Normal file
96
TempTrack/Connection/TransferHandler.swift
Normal file
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
|
||||
final class TransferHandler: ObservableObject {
|
||||
|
||||
@Published
|
||||
var bytesTransferred: Double = 0.0
|
||||
|
||||
@Published
|
||||
var totalBytes: Double = 0.0
|
||||
|
||||
@Published
|
||||
var measurements: [TemperatureMeasurement] = []
|
||||
|
||||
@Published
|
||||
var transferIsRunning = false
|
||||
|
||||
func startTransfer(from device: BluetoothDevice, with info: DeviceInfo, storage: PersistentStorage) {
|
||||
#warning("Update device info during transfer")
|
||||
discardTransfer()
|
||||
transferIsRunning = true
|
||||
let total = info.numberOfRecordedBytes
|
||||
let chunkSize = info.transferBlockSize
|
||||
totalBytes = Double(total)
|
||||
Task {
|
||||
defer {
|
||||
DispatchQueue.main.async {
|
||||
self.transferIsRunning = false
|
||||
}
|
||||
}
|
||||
var data = Data(capacity: total)
|
||||
while data.count < total {
|
||||
let remainingBytes = total - data.count
|
||||
let currentChunkSize = min(remainingBytes, chunkSize)
|
||||
guard let chunk = await device.getDeviceData(offset: data.count, count: currentChunkSize) else {
|
||||
log.warning("Failed to finish transfer")
|
||||
return
|
||||
}
|
||||
guard !chunk.isEmpty else {
|
||||
break
|
||||
}
|
||||
data.append(chunk)
|
||||
let count = Double(data.count)
|
||||
DispatchQueue.main.async {
|
||||
self.bytesTransferred = count
|
||||
}
|
||||
}
|
||||
|
||||
if data.count != info.numberOfRecordedBytes {
|
||||
log.warning("Expected \(info.numberOfRecordedBytes) in transfer, got only \(data.count)")
|
||||
}
|
||||
let sum = data.reduce(0) { $0 &+ UInt16($1) }
|
||||
if sum != info.dataChecksum {
|
||||
log.warning("Checksum does not match")
|
||||
}
|
||||
if data.count != 4 * info.numberOfStoredMeasurements {
|
||||
log.warning("expected \(4 * info.numberOfStoredMeasurements) bytes for \(info.numberOfStoredMeasurements) measurements, got \(data.count)")
|
||||
}
|
||||
storage.saveTransferData(data: data, date: info.time.date)
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.bytesTransferred = self.totalBytes
|
||||
}
|
||||
|
||||
let recordingStart = info.currentMeasurementStartTime
|
||||
while !data.isEmpty {
|
||||
guard data.count >= 4 else {
|
||||
log.error("Expected four bytes at index \(total - data.count - 1)")
|
||||
break
|
||||
}
|
||||
let intervalCount = try! data.decodeUInt16()
|
||||
let temp0 = TemperatureValue(byte: data.removeFirst())
|
||||
let temp1 = TemperatureValue(byte: data.removeFirst())
|
||||
let date = recordingStart
|
||||
.addingTimeInterval(TimeInterval(intervalCount) * TimeInterval(info.measurementInterval))
|
||||
let measurement = TemperatureMeasurement(
|
||||
sensor0: temp0,
|
||||
sensor1: temp1,
|
||||
date: date)
|
||||
DispatchQueue.main.async {
|
||||
self.measurements.append(measurement)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func saveTransfer(in storage: PersistentStorage) {
|
||||
storage.add(measurements)
|
||||
discardTransfer()
|
||||
}
|
||||
|
||||
func discardTransfer() {
|
||||
self.measurements = []
|
||||
self.bytesTransferred = 0
|
||||
self.totalBytes = 0
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user