|
| 1 | +// |
| 2 | +// CentralViewModel.swift |
| 3 | +// ReliaBLE Demo |
| 4 | +// |
| 5 | +// Created by Justin Bergen on 3/8/25. |
| 6 | +// |
| 7 | +// Copyright (c) 2024 Five3 Apps, LLC <justin@five3apps.com> |
| 8 | +// |
| 9 | +// Permission is hereby granted, free of charge, to any person obtaining a copy |
| 10 | +// of this software and associated documentation files (the "Software"), to deal |
| 11 | +// in the Software without restriction, including without limitation the rights |
| 12 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 13 | +// copies of the Software, and to permit persons to whom the Software is |
| 14 | +// furnished to do so, subject to the following conditions: |
| 15 | +// |
| 16 | +// The above copyright notice and this permission notice shall be included in all |
| 17 | +// copies or substantial portions of the Software. |
| 18 | +// |
| 19 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 20 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 21 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 22 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 23 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 24 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 25 | +// SOFTWARE. |
| 26 | + |
| 27 | +import Combine |
| 28 | +import CoreBluetooth |
| 29 | +import SwiftData |
| 30 | +import SwiftUI |
| 31 | + |
| 32 | +import ReliaBLE |
| 33 | + |
| 34 | +class CentralViewModel: ObservableObject { |
| 35 | + @Published var currentState: BluetoothState = .unknown |
| 36 | + @Published var servicesInput = "" |
| 37 | + |
| 38 | + var cancellables = Set<AnyCancellable>() |
| 39 | + |
| 40 | + private var modelContext: ModelContext? |
| 41 | + private var reliaBLE: ReliaBLEManager? |
| 42 | + |
| 43 | + func setDependencies(modelContext: ModelContext, reliaBLE: ReliaBLEManager) { |
| 44 | + self.modelContext = modelContext |
| 45 | + self.reliaBLE = reliaBLE |
| 46 | + |
| 47 | + setupSubscriptions() |
| 48 | + } |
| 49 | + |
| 50 | + private func setupSubscriptions() { |
| 51 | + guard let reliaBLE = reliaBLE, let modelContext = modelContext else { return } |
| 52 | + |
| 53 | + reliaBLE.state |
| 54 | + .receive(on: DispatchQueue.main) |
| 55 | + .assign(to: \.currentState, on: self) |
| 56 | + .store(in: &cancellables) |
| 57 | + |
| 58 | + reliaBLE.peripheralDiscoveries |
| 59 | + .receive(on: DispatchQueue.main) |
| 60 | + .sink { discoveryEvent in |
| 61 | + let event = DiscoveryEvent( |
| 62 | + peripheralIdentifier: discoveryEvent.id.uuidString, |
| 63 | + name: discoveryEvent.name ?? "Unknown", |
| 64 | + rssi: discoveryEvent.rssi, |
| 65 | + timestamp: Date() |
| 66 | + ) |
| 67 | + modelContext.insert(event) |
| 68 | + try? modelContext.save() |
| 69 | + } |
| 70 | + .store(in: &cancellables) |
| 71 | + |
| 72 | + reliaBLE.discoveredPeripherals |
| 73 | + .receive(on: DispatchQueue.main) |
| 74 | + .sink { peripherals in |
| 75 | + do { |
| 76 | + let allDevices = try modelContext.fetch(FetchDescriptor<Device>()) |
| 77 | + for peripheral in peripherals { |
| 78 | + if let existingDevice = allDevices.first(where: { $0.id == peripheral.id }) { |
| 79 | + existingDevice.name = peripheral.name |
| 80 | + existingDevice.lastSeen = peripheral.lastSeen |
| 81 | + } else { |
| 82 | + let newDevice = Device(id: peripheral.id, name: peripheral.name, lastSeen: Date()) |
| 83 | + modelContext.insert(newDevice) |
| 84 | + } |
| 85 | + } |
| 86 | + try modelContext.save() |
| 87 | + } catch { |
| 88 | + print("Error fetching devices: \(error)") |
| 89 | + } |
| 90 | + } |
| 91 | + .store(in: &cancellables) |
| 92 | + } |
| 93 | + |
| 94 | + func authorizeBluetooth() { |
| 95 | + try? reliaBLE?.authorizeBluetooth() |
| 96 | + } |
| 97 | + |
| 98 | + func startScanning() { |
| 99 | + let services = parseServices(from: servicesInput) |
| 100 | + reliaBLE?.startScanning(services: services) |
| 101 | + } |
| 102 | + |
| 103 | + func stopScanning() { |
| 104 | + reliaBLE?.stopScanning() |
| 105 | + } |
| 106 | + |
| 107 | + func clearAllData() { |
| 108 | + guard let modelContext = modelContext else { return } |
| 109 | + |
| 110 | + do { |
| 111 | + let discoveryDescriptor = FetchDescriptor<DiscoveryEvent>(sortBy: []) |
| 112 | + let discoveries = try modelContext.fetch(discoveryDescriptor) |
| 113 | + discoveries.forEach { modelContext.delete($0) } |
| 114 | + |
| 115 | + let deviceDescriptor = FetchDescriptor<Device>(sortBy: []) |
| 116 | + let devices = try modelContext.fetch(deviceDescriptor) |
| 117 | + devices.forEach { modelContext.delete($0) } |
| 118 | + |
| 119 | + try modelContext.save() |
| 120 | + } catch { |
| 121 | + print("Failed to clear data: \(error)") |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + func deleteDiscoveries(_ items: [DiscoveryEvent]) { |
| 126 | + items.forEach { modelContext?.delete($0) } |
| 127 | + try? modelContext?.save() |
| 128 | + } |
| 129 | + |
| 130 | + func deleteDevices(_ items: [Device]) { |
| 131 | + items.forEach { modelContext?.delete($0) } |
| 132 | + try? modelContext?.save() |
| 133 | + } |
| 134 | + |
| 135 | + private func parseServices(from input: String) -> [CBUUID]? { |
| 136 | + let components = input.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } |
| 137 | + let uuids = components.filter { !$0.isEmpty }.map { CBUUID(string: $0) } |
| 138 | + |
| 139 | + return uuids.isEmpty ? nil : uuids |
| 140 | + } |
| 141 | +} |
0 commit comments