-
-
Notifications
You must be signed in to change notification settings - Fork 1
Usage
Latisha. edited this page Dec 27, 2024
·
1 revision
This guide covers common usage patterns and best practices for LibDC-Swift.
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
}
}
func connectToDevice(_ peripheral: CBPeripheral) {
let success = DeviceConfiguration.openBLEDevice(
name: peripheral.name ?? "",
deviceAddress: peripheral.identifier.uuidString
)
if success {
// Handle successful connection
}
}
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
}
}
}
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)
}
}
}
}
}
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)
}
}
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
}
}
- Always Clean Up Resources
func disconnect() {
bleManager.close()
viewModel.clear()
}
- Handle Background Mode
func applicationDidEnterBackground() {
saveState()
pauseOperations()
}
- Restore State
func applicationWillEnterForeground() {
restoreState()
reconnectIfNeeded()
}
- Use Fingerprints
// Store fingerprint after successful download
if let fingerprint = downloadedDive.fingerprint {
viewModel.saveFingerprint(fingerprint)
}
- Batch Processing
func processDives(_ dives: [DiveData]) {
let batchSize = 10
for batch in dives.chunked(into: batchSize) {
processBatch(batch)
}
}
- Data Validation
func validateDiveData(_ dive: DiveData) -> Bool {
guard dive.maxDepth > 0,
dive.divetime > 0,
!dive.profile.isEmpty else {
return false
}
return true
}
// Enable detailed logging
Logger.shared.setMinLevel(.debug)
Logger.shared.setShowRawData(true)
// Disable logging for production
Logger.shared.setMinLevel(.error)
Logger.shared.setShowRawData(false)
struct BLEConfig {
static let scanTimeout: TimeInterval = 30
static let connectionTimeout: TimeInterval = 10
static let retryAttempts = 3
}
struct ParserConfig {
static let maxDepthThreshold = 100.0
static let minimumDiveTime: TimeInterval = 60
static let surfaceThreshold = 0.3
}
struct DownloadConfig {
static let batchSize = 10
static let useFingerprint = true
static let autoReconnect = true
static let maxRetries = 3
}
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
}
}
- Device Not Found
- Check device is in range
- Verify device is in correct mode
- Ensure Bluetooth is enabled
- Connection Drops
- Implement retry logic
- Check battery levels
- Monitor signal strength
- Download Fails
- Use fingerprint system
- Implement resume capability
- Handle partial downloads
class DebugTools {
static func dumpDeviceState() {
// Log device state
}
static func monitorBLEState() {
// Monitor BLE state
}
static func validateDownload() {
// Validate download integrity
}
}