BLEManager.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. //
  2. // BLEManager.swift
  3. // LoopFollow
  4. //
  5. import Foundation
  6. import CoreBluetooth
  7. import Combine
  8. class BLEManager: NSObject, ObservableObject {
  9. static let shared = BLEManager()
  10. @Published private(set) var devices: [BLEDevice] = []
  11. private var centralManager: CBCentralManager!
  12. private var activeDevice: BluetoothDevice?
  13. private override init() {
  14. super.init()
  15. centralManager = CBCentralManager(
  16. delegate: self,
  17. queue: .main
  18. )
  19. if let device = Storage.shared.selectedBLEDevice.value {
  20. devices.append(device)
  21. findAndUpdateDevice(with: device.id.uuidString) { device in
  22. device.rssi = 0
  23. }
  24. connect(device: device)
  25. }
  26. }
  27. func getSelectedDevice() -> BLEDevice? {
  28. return devices.first { $0.id == Storage.shared.selectedBLEDevice.value?.id }
  29. }
  30. func startScanning() {
  31. guard centralManager.state == .poweredOn else {
  32. LogManager.shared.log(category: .bluetooth, message: "Not powered on, cannot start scan.")
  33. return
  34. }
  35. centralManager.scanForPeripherals(withServices: nil, options: nil)
  36. cleanupOldDevices()
  37. }
  38. func disconnect() {
  39. if let device = activeDevice {
  40. device.disconnect()
  41. activeDevice = nil
  42. device.lastHeartbeatTime = nil
  43. }
  44. Storage.shared.selectedBLEDevice.value = nil
  45. }
  46. func connect(device: BLEDevice) {
  47. disconnect()
  48. if let matchedType = BackgroundRefreshType.allCases.first(where: { $0.matches(device) }) {
  49. Storage.shared.backgroundRefreshType.value = matchedType
  50. Storage.shared.selectedBLEDevice.value = device
  51. findAndUpdateDevice(with: device.id.uuidString) { device in
  52. device.isConnected = false
  53. device.lastConnected = nil
  54. }
  55. switch matchedType {
  56. case .dexcom:
  57. activeDevice = DexcomHeartbeatBluetoothDevice(address: device.id.uuidString, name: device.name, bluetoothDeviceDelegate: self)
  58. activeDevice?.connect()
  59. case .rileyLink:
  60. activeDevice = RileyLinkHeartbeatBluetoothDevice(address: device.id.uuidString, name: device.name, bluetoothDeviceDelegate: self)
  61. activeDevice?.connect()
  62. case .omnipodDash:
  63. activeDevice = OmnipodDashHeartbeatBluetoothTransmitter(address: device.id.uuidString, name: device.name, bluetoothDeviceDelegate: self)
  64. activeDevice?.connect()
  65. case .silentTune, .none:
  66. return
  67. }
  68. } else {
  69. LogManager.shared.log(category: .bluetooth, message: "No matching BackgroundRefreshType found for this device.")
  70. }
  71. }
  72. func stopScanning() {
  73. centralManager.stopScan()
  74. }
  75. func expectedHeartbeatInterval() -> TimeInterval? {
  76. guard let device = activeDevice else {
  77. return nil
  78. }
  79. return device.expectedHeartbeatInterval()
  80. }
  81. private func addOrUpdateDevice(_ device: BLEDevice) {
  82. LogManager.shared.log(category: .bluetooth, message: "Adding or updating BLE device: \(device)", isDebug: true)
  83. if let idx = devices.firstIndex(where: { $0.id == device.id }) {
  84. var updatedDevice = devices[idx]
  85. updatedDevice.rssi = device.rssi
  86. updatedDevice.lastSeen = Date()
  87. devices[idx] = updatedDevice
  88. } else {
  89. var newDevice = device
  90. newDevice.lastSeen = Date()
  91. devices.append(newDevice)
  92. }
  93. devices = devices
  94. }
  95. private func cleanupOldDevices() {
  96. let expirationDate = Date().addingTimeInterval(-600) // 10 minutes ago
  97. // Get the selected device's ID (if any)
  98. let selectedDeviceID = Storage.shared.selectedBLEDevice.value?.id
  99. // Filter devices, keeping those seen within the last 10 minutes or the selected device
  100. devices = devices.filter { $0.lastSeen > expirationDate || $0.id == selectedDeviceID }
  101. }
  102. }
  103. // MARK: - CBCentralManagerDelegate
  104. extension BLEManager: CBCentralManagerDelegate {
  105. func centralManagerDidUpdateState(_ central: CBCentralManager) {
  106. switch central.state {
  107. case .poweredOn:
  108. LogManager.shared.log(category: .bluetooth, message: "Central poweredOn", isDebug: true)
  109. default:
  110. LogManager.shared.log(category: .bluetooth, message: "Central state = \(central.state.rawValue), not powered on.", isDebug: true)
  111. }
  112. }
  113. func centralManager(_ central: CBCentralManager,
  114. didDiscover peripheral: CBPeripheral,
  115. advertisementData: [String: Any],
  116. rssi RSSI: NSNumber) {
  117. let uuid = peripheral.identifier
  118. let services = (advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID])?
  119. .map { $0.uuidString }
  120. let device = BLEDevice(
  121. id: uuid,
  122. name: peripheral.name,
  123. rssi: RSSI.intValue,
  124. advertisedServices: services,
  125. lastSeen: Date()
  126. )
  127. addOrUpdateDevice(device)
  128. }
  129. func findAndUpdateDevice(with deviceAddress: String, update: (inout BLEDevice) -> Void) {
  130. if let idx = devices.firstIndex(where: { $0.id.uuidString == deviceAddress }) {
  131. var device = devices[idx]
  132. update(&device)
  133. devices[idx] = device
  134. devices = devices
  135. } else {
  136. LogManager.shared.log(category: .bluetooth, message: "Device not found in devices array for update")
  137. }
  138. }
  139. }
  140. extension BLEManager: BluetoothDeviceDelegate {
  141. func didConnectTo(bluetoothDevice: BluetoothDevice) {
  142. LogManager.shared.log(category: .bluetooth, message: "Connected to: \(bluetoothDevice.deviceName ?? "Unknown")", isDebug: true)
  143. findAndUpdateDevice(with: bluetoothDevice.deviceAddress) { device in
  144. device.isConnected = true
  145. device.lastConnected = Date()
  146. }
  147. }
  148. func didDisconnectFrom(bluetoothDevice: BluetoothDevice) {
  149. LogManager.shared.log(category: .bluetooth, message: "Disconnect from: \(bluetoothDevice.deviceName ?? "Unknown")", isDebug: true)
  150. findAndUpdateDevice(with: bluetoothDevice.deviceAddress) { device in
  151. device.isConnected = false
  152. device.lastConnected = Date()
  153. }
  154. }
  155. func heartBeat() {
  156. guard let device = activeDevice else {
  157. return
  158. }
  159. let now = Date()
  160. guard let expectedInterval = device.expectedHeartbeatInterval() else {
  161. LogManager.shared.log(category: .bluetooth, message: "Heartbeat triggered")
  162. device.lastHeartbeatTime = now
  163. TaskScheduler.shared.checkTasksNow()
  164. return
  165. }
  166. let marginPercentage: Double = 0.15 // 15% margin
  167. let margin = expectedInterval * marginPercentage
  168. let threshold = expectedInterval + margin
  169. if let last = device.lastHeartbeatTime {
  170. let elapsedTime = now.timeIntervalSince(last)
  171. if elapsedTime > threshold {
  172. let delay = elapsedTime - expectedInterval
  173. LogManager.shared.log(category: .bluetooth, message: "Heartbeat triggered (Delayed by \(String(format: "%.1f", delay)) seconds)")
  174. }
  175. } else {
  176. LogManager.shared.log(category: .bluetooth, message: "Heartbeat triggered (First heartbeat)")
  177. }
  178. device.lastHeartbeatTime = now
  179. TaskScheduler.shared.checkTasksNow()
  180. }
  181. }
  182. extension BLEManager {
  183. /// Returns the expected sensor fetch offset as a formatted string ("mm:ss (fetch delay: XX sec)")
  184. /// for Dexcom and RileyLink devices. The expected offset is computed as the sensor's schedule offset plus the polling delay.
  185. /// The device’s lastSeen time is used (mod cycleDuration) to calculate the effective delay between when the sensor value
  186. /// becomes available and when the fetch is actually triggered.
  187. func expectedSensorFetchOffsetString(for device: BLEDevice) -> String? {
  188. guard
  189. let matchedType = BackgroundRefreshType.allCases.first(where: { $0.matches(device) }),
  190. let heartBeatInterval = matchedType.heartBeatInterval,
  191. let sensorOffset = Storage.shared.sensorScheduleOffset.value
  192. else {
  193. return nil
  194. }
  195. let heartbeatLast: Date? = {
  196. if matchedType.estimatedDelayBasedOnHeartbeat {
  197. guard device.isConnected, let lastHeartbeat = activeDevice?.lastHeartbeatTime else {
  198. return nil
  199. }
  200. return lastHeartbeat
  201. } else {
  202. return device.lastSeen
  203. }
  204. }()
  205. guard let heartbeatLast = heartbeatLast else {
  206. return nil
  207. }
  208. let pollingDelay: TimeInterval = Double(UserDefaultsRepository.bgUpdateDelay.value)
  209. let expectedOffset = sensorOffset + pollingDelay
  210. // If the heartbeat interval isn't a typical 60 or 300 seconds,
  211. // we simply return a string indicating that the delay is "up to" the heartbeat interval.
  212. if heartBeatInterval != 60 && heartBeatInterval != 300 {
  213. return "up to \(Int(heartBeatInterval)) sec"
  214. }
  215. let effectiveDelay = CycleHelper.computeDelay(sensorOffset: expectedOffset, heartbeatLast: heartbeatLast, heartbeatInterval: heartBeatInterval)
  216. return "\(Int(effectiveDelay)) sec"
  217. }
  218. }