Skip to content
Latisha. edited this page Dec 27, 2024 · 1 revision

Usage Guide

This guide covers common usage patterns and best practices for LibDC-Swift.

Basic Usage Examples

Initialize BLE Manager

import LibDCSwift

class DiveManager: ObservableObject {
    private let bleManager = CoreBluetoothManager.shared
    @Published var isScanning = false
    
    func startScanning() {
        bleManager.startScanning()
        isScanning = true
    }
    
    func stopScanning() {
        bleManager.stopScanning()
        isScanning = false
    }
}

Connect to Device

func connectToDevice(_ peripheral: CBPeripheral) {
    let success = DeviceConfiguration.openBLEDevice(
        name: peripheral.name ?? "",
        deviceAddress: peripheral.identifier.uuidString
    )
    
    if success {
        // Handle successful connection
    }
}

Retrieve Dive Logs

class DiveLogManager {
    private let viewModel = DiveDataViewModel()
    
    func retrieveLogs(from device: CBPeripheral) {
        guard let devicePtr = CoreBluetoothManager.shared.openedDeviceDataPtr else {
            return
        }
        
        DiveLogRetriever.retrieveDiveLogs(
            from: devicePtr,
            deviceName: device.name ?? "",
            viewModel: viewModel
        ) { success in
            if success {
                self.processDiveLogs()
            }
        }
    }
    
    private func processDiveLogs() {
        viewModel.dives.forEach { dive in
            // Process each dive
        }
    }
}

Common Patterns

SwiftUI Integration

struct DiveComputerView: View {
    @StateObject private var bleManager = CoreBluetoothManager.shared
    @StateObject private var diveData = DiveDataViewModel()
    
    var body: some View {
        NavigationView {
            List(bleManager.discoveredPeripherals, id: \.identifier) { peripheral in
                DeviceRow(peripheral: peripheral)
                    .onTapGesture {
                        connectToDevice(peripheral)
                    }
            }
            .navigationTitle("Dive Computers")
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    ScanButton(bleManager: bleManager)
                }
            }
        }
    }
}

Progress Tracking

func downloadDiveLogs() {
    DiveLogRetriever.retrieveDiveLogs(
        from: devicePtr,
        deviceName: name,
        viewModel: viewModel,
        onProgress: { current, total in
            let progress = Float(current) / Float(total)
            updateProgress(progress)
        }
    ) { success in
        handleCompletion(success)
    }
}

Error Handling

enum DiveError: Error {
    case deviceNotFound
    case connectionFailed
    case downloadFailed
    case parseError
}

func handleDiveOperation() async throws {
    do {
        try await connectToDevice()
        try await downloadLogs()
        try parseLogs()
    } catch DiveError.deviceNotFound {
        // Handle device not found
    } catch DiveError.connectionFailed {
        // Handle connection failure
    } catch {
        // Handle other errors
    }
}

Best Practices

Device Management

  1. Always Clean Up Resources
func disconnect() {
    bleManager.close()
    viewModel.clear()
}
  1. Handle Background Mode
func applicationDidEnterBackground() {
    saveState()
    pauseOperations()
}
  1. Restore State
func applicationWillEnterForeground() {
    restoreState()
    reconnectIfNeeded()
}

Data Handling

  1. Use Fingerprints
// Store fingerprint after successful download
if let fingerprint = downloadedDive.fingerprint {
    viewModel.saveFingerprint(fingerprint)
}
  1. Batch Processing
func processDives(_ dives: [DiveData]) {
    let batchSize = 10
    for batch in dives.chunked(into: batchSize) {
        processBatch(batch)
    }
}
  1. Data Validation
func validateDiveData(_ dive: DiveData) -> Bool {
    guard dive.maxDepth > 0,
          dive.divetime > 0,
          !dive.profile.isEmpty else {
        return false
    }
    return true
}

Configuration Options

Logging Configuration

// Enable detailed logging
Logger.shared.setMinLevel(.debug)
Logger.shared.setShowRawData(true)

// Disable logging for production
Logger.shared.setMinLevel(.error)
Logger.shared.setShowRawData(false)

BLE Configuration

struct BLEConfig {
    static let scanTimeout: TimeInterval = 30
    static let connectionTimeout: TimeInterval = 10
    static let retryAttempts = 3
}

Parser Configuration

struct ParserConfig {
    static let maxDepthThreshold = 100.0
    static let minimumDiveTime: TimeInterval = 60
    static let surfaceThreshold = 0.3
}

Download Configuration

struct DownloadConfig {
    static let batchSize = 10
    static let useFingerprint = true
    static let autoReconnect = true
    static let maxRetries = 3
}

Examples

Complete Download Flow

class DiveDownloadManager {
    private let bleManager = CoreBluetoothManager.shared
    private let viewModel = DiveDataViewModel()
    private var cancellables = Set<AnyCancellable>()
    
    func startDownload() {
        // 1. Start scanning
        bleManager.startScanning()
        
        // 2. Watch for devices
        bleManager.$discoveredPeripherals
            .sink { [weak self] peripherals in
                self?.handleDiscoveredDevices(peripherals)
            }
            .store(in: &cancellables)
        
        // 3. Watch connection state
        bleManager.$connectedDevice
            .sink { [weak self] device in
                self?.handleConnectionState(device)
            }
            .store(in: &cancellables)
        
        // 4. Watch download progress
        viewModel.$progress
            .sink { [weak self] progress in
                self?.handleProgress(progress)
            }
            .store(in: &cancellables)
    }
    
    private func handleDiscoveredDevices(_ peripherals: [CBPeripheral]) {
        // Handle discovered devices
    }
    
    private func handleConnectionState(_ device: CBPeripheral?) {
        // Handle connection state changes
    }
    
    private func handleProgress(_ progress: DiveDataViewModel.DownloadProgress) {
        // Handle download progress
    }
}

Troubleshooting

Common Issues

  1. Device Not Found
  • Check device is in range
  • Verify device is in correct mode
  • Ensure Bluetooth is enabled
  1. Connection Drops
  • Implement retry logic
  • Check battery levels
  • Monitor signal strength
  1. Download Fails
  • Use fingerprint system
  • Implement resume capability
  • Handle partial downloads

Debug Tools

class DebugTools {
    static func dumpDeviceState() {
        // Log device state
    }
    
    static func monitorBLEState() {
        // Monitor BLE state
    }
    
    static func validateDownload() {
        // Validate download integrity
    }
}