APSManager.swift 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import LoopKitUI
  6. import SwiftDate
  7. import Swinject
  8. protocol APSManager {
  9. func heartbeat(date: Date)
  10. func enactBolus(amount: Double, isSMB: Bool, callback: ((Bool, String) -> Void)?) async
  11. var pumpManager: PumpManagerUI? { get set }
  12. var bluetoothManager: BluetoothStateManager? { get }
  13. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> { get }
  14. var pumpName: CurrentValueSubject<String, Never> { get }
  15. var isLooping: CurrentValueSubject<Bool, Never> { get }
  16. var lastLoopDate: Date { get }
  17. var lastLoopDateSubject: PassthroughSubject<Date, Never> { get }
  18. var bolusProgress: CurrentValueSubject<Decimal?, Never> { get }
  19. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> { get }
  20. var isManualTempBasal: Bool { get }
  21. func enactTempBasal(rate: Double, duration: TimeInterval) async
  22. func determineBasal() async throws
  23. func determineBasalSync() async throws
  24. func simulateDetermineBasal(
  25. simulatedCarbsAmount: Decimal,
  26. simulatedBolusAmount: Decimal,
  27. simulatedCarbsDate: Date?
  28. ) async -> Determination?
  29. func roundBolus(amount: Decimal) -> Decimal
  30. var lastError: CurrentValueSubject<Error?, Never> { get }
  31. func cancelBolus(_ callback: ((Bool, String) -> Void)?) async
  32. }
  33. enum APSError: LocalizedError {
  34. case pumpError(Error)
  35. case invalidPumpState(message: String)
  36. case glucoseError(message: String)
  37. case apsError(message: String)
  38. case manualBasalTemp(message: String)
  39. var errorDescription: String? {
  40. switch self {
  41. case let .pumpError(error):
  42. return String(localized: "Pump Error (\(error.localizedDescription)).")
  43. case let .invalidPumpState(message):
  44. return String(localized: "Invalid Pump State (\(message)).")
  45. case let .glucoseError(message):
  46. return String(localized: "Invalid Glucose (\(message)).")
  47. case let .apsError(message):
  48. return String(localized: "Invalid Algorithm Response (\(message)).")
  49. case let .manualBasalTemp(message):
  50. return String(localized: "Manual Temporary Basal Rate (\(message)). Looping suspended.")
  51. }
  52. }
  53. static func pumpErrorMatches(message: String) -> Bool {
  54. message.contains(String(localized: "Pump Error"))
  55. }
  56. static func pumpWarningMatches(message: String) -> Bool {
  57. message.contains(String(localized: "Invalid Pump State")) || message
  58. .contains("PumpMessage") || message
  59. .contains("PumpOpsError") || message.contains("RileyLink") || message
  60. .contains(String(localized: "Pump did not respond in time"))
  61. }
  62. }
  63. final class BaseAPSManager: APSManager, Injectable {
  64. private let processQueue = DispatchQueue(label: "BaseAPSManager.processQueue")
  65. @Injected() private var storage: FileStorage!
  66. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  67. @Injected() private var alertHistoryStorage: AlertHistoryStorage!
  68. @Injected() private var tempTargetsStorage: TempTargetsStorage!
  69. @Injected() private var carbsStorage: CarbsStorage!
  70. @Injected() private var determinationStorage: DeterminationStorage!
  71. @Injected() private var deviceDataManager: DeviceDataManager!
  72. @Injected() private var nightscout: NightscoutManager!
  73. @Injected() private var settingsManager: SettingsManager!
  74. @Injected() private var tddStorage: TDDStorage!
  75. @Injected() private var broadcaster: Broadcaster!
  76. @Persisted(key: "lastLoopStartDate") private var lastLoopStartDate: Date = .distantPast
  77. @Persisted(key: "lastLoopDate") var lastLoopDate: Date = .distantPast {
  78. didSet {
  79. lastLoopDateSubject.send(lastLoopDate)
  80. }
  81. }
  82. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  83. let privateContext = CoreDataStack.shared.newTaskContext()
  84. private var openAPS: OpenAPS!
  85. private var lifetime = Lifetime()
  86. private var backgroundTaskID: UIBackgroundTaskIdentifier?
  87. var pumpManager: PumpManagerUI? {
  88. get { deviceDataManager.pumpManager }
  89. set { deviceDataManager.pumpManager = newValue }
  90. }
  91. var bluetoothManager: BluetoothStateManager? { deviceDataManager.bluetoothManager }
  92. @Persisted(key: "isManualTempBasal") var isManualTempBasal: Bool = false
  93. let isLooping = CurrentValueSubject<Bool, Never>(false)
  94. let lastLoopDateSubject = PassthroughSubject<Date, Never>()
  95. let lastError = CurrentValueSubject<Error?, Never>(nil)
  96. let bolusProgress = CurrentValueSubject<Decimal?, Never>(nil)
  97. var pumpDisplayState: CurrentValueSubject<PumpDisplayState?, Never> {
  98. deviceDataManager.pumpDisplayState
  99. }
  100. var pumpName: CurrentValueSubject<String, Never> {
  101. deviceDataManager.pumpName
  102. }
  103. var pumpExpiresAtDate: CurrentValueSubject<Date?, Never> {
  104. deviceDataManager.pumpExpiresAtDate
  105. }
  106. var settings: TrioSettings {
  107. get { settingsManager.settings }
  108. set { settingsManager.settings = newValue }
  109. }
  110. init(resolver: Resolver) {
  111. injectServices(resolver)
  112. openAPS = OpenAPS(storage: storage, tddStorage: tddStorage)
  113. subscribe()
  114. lastLoopDateSubject.send(lastLoopDate)
  115. isLooping
  116. .weakAssign(to: \.deviceDataManager.loopInProgress, on: self)
  117. .store(in: &lifetime)
  118. }
  119. private func subscribe() {
  120. if settingsManager.settings.units == .mmolL {
  121. let wasParsed = storage.parseOnFileSettingsToMgdL()
  122. if wasParsed {
  123. Task {
  124. do {
  125. try await openAPS.createProfiles()
  126. } catch {
  127. debug(
  128. .apsManager,
  129. "\(DebuggingIdentifiers.failed) Error creating profiles: \(error)"
  130. )
  131. }
  132. }
  133. }
  134. }
  135. deviceDataManager.recommendsLoop
  136. .receive(on: processQueue)
  137. .sink { [weak self] in
  138. self?.loop()
  139. }
  140. .store(in: &lifetime)
  141. pumpManager?.addStatusObserver(self, queue: processQueue)
  142. deviceDataManager.errorSubject
  143. .receive(on: processQueue)
  144. .map { APSError.pumpError($0) }
  145. .sink {
  146. self.processError($0)
  147. }
  148. .store(in: &lifetime)
  149. deviceDataManager.bolusTrigger
  150. .receive(on: processQueue)
  151. .sink { bolusing in
  152. if bolusing {
  153. self.createBolusReporter()
  154. } else {
  155. self.clearBolusReporter()
  156. }
  157. }
  158. .store(in: &lifetime)
  159. // manage a manual Temp Basal from OmniPod - Force loop() after stop a temp basal or finished
  160. deviceDataManager.manualTempBasal
  161. .receive(on: processQueue)
  162. .sink { manualBasal in
  163. if manualBasal {
  164. self.isManualTempBasal = true
  165. } else {
  166. if self.isManualTempBasal {
  167. self.isManualTempBasal = false
  168. self.loop()
  169. }
  170. }
  171. }
  172. .store(in: &lifetime)
  173. }
  174. func heartbeat(date: Date) {
  175. deviceDataManager.heartbeat(date: date)
  176. }
  177. // Loop entry point
  178. private func loop() {
  179. Task { [weak self] in
  180. guard let self else { return }
  181. // Check if we can start a new loop
  182. guard await self.canStartNewLoop() else { return }
  183. // Setup loop and background task
  184. var (loopStatRecord, backgroundTask) = await self.setupLoop()
  185. do {
  186. // Execute loop logic
  187. try await self.executeLoop(loopStatRecord: &loopStatRecord)
  188. // Upload data to Nightscout if available
  189. if let nightscoutManager = self.nightscout {
  190. await nightscoutManager.uploadCarbs()
  191. await nightscoutManager.uploadPumpHistory()
  192. await nightscoutManager.uploadOverrides()
  193. await nightscoutManager.uploadTempTargets()
  194. }
  195. } catch {
  196. var updatedStats = loopStatRecord
  197. updatedStats.end = Date()
  198. updatedStats.duration = roundDouble((updatedStats.end! - updatedStats.start).timeInterval / 60, 2)
  199. updatedStats.loopStatus = error.localizedDescription
  200. await loopCompleted(error: error, loopStatRecord: updatedStats)
  201. debug(.apsManager, "\(DebuggingIdentifiers.failed) Failed to complete Loop: \(error)")
  202. }
  203. // Cleanup background task
  204. if let backgroundTask = backgroundTask {
  205. await UIApplication.shared.endBackgroundTask(backgroundTask)
  206. self.backgroundTaskID = .invalid
  207. }
  208. }
  209. }
  210. private func canStartNewLoop() async -> Bool {
  211. // Check if too soon for next loop
  212. if lastLoopDate > lastLoopStartDate {
  213. guard lastLoopStartDate.addingTimeInterval(Config.loopInterval) < Date() else {
  214. debug(.apsManager, "Not enough time have passed since last loop at : \(lastLoopStartDate)")
  215. return false
  216. }
  217. }
  218. // Check if loop already in progress
  219. guard !isLooping.value else {
  220. warning(.apsManager, "Loop already in progress. Skip recommendation.")
  221. return false
  222. }
  223. return true
  224. }
  225. private func setupLoop() async -> (LoopStats, UIBackgroundTaskIdentifier?) {
  226. // Start background task
  227. let backgroundTask = await UIApplication.shared.beginBackgroundTask(withName: "Loop starting") { [weak self] in
  228. guard let self, let backgroundTask = self.backgroundTaskID else { return }
  229. Task {
  230. UIApplication.shared.endBackgroundTask(backgroundTask)
  231. }
  232. self.backgroundTaskID = .invalid
  233. }
  234. backgroundTaskID = backgroundTask
  235. // Set loop start time
  236. lastLoopStartDate = Date()
  237. // Calculate interval from previous loop
  238. let interval = await calculateLoopInterval()
  239. // Create initial loop stats record
  240. let loopStatRecord = LoopStats(
  241. start: lastLoopStartDate,
  242. loopStatus: "Starting",
  243. interval: interval
  244. )
  245. isLooping.send(true)
  246. return (loopStatRecord, backgroundTask)
  247. }
  248. private func executeLoop(loopStatRecord: inout LoopStats) async throws {
  249. try await determineBasal()
  250. // Handle open loop
  251. guard settings.closedLoop else {
  252. loopStatRecord.end = Date()
  253. loopStatRecord.duration = roundDouble((loopStatRecord.end! - loopStatRecord.start).timeInterval / 60, 2)
  254. loopStatRecord.loopStatus = "Success"
  255. await loopCompleted(loopStatRecord: loopStatRecord)
  256. return
  257. }
  258. // Handle closed loop
  259. try await enactDetermination()
  260. loopStatRecord.end = Date()
  261. loopStatRecord.duration = roundDouble((loopStatRecord.end! - loopStatRecord.start).timeInterval / 60, 2)
  262. loopStatRecord.loopStatus = "Success"
  263. await loopCompleted(loopStatRecord: loopStatRecord)
  264. }
  265. private func calculateLoopInterval() async -> Double? {
  266. do {
  267. return try await privateContext.perform {
  268. let requestStats = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  269. let sortStats = NSSortDescriptor(key: "end", ascending: false)
  270. requestStats.sortDescriptors = [sortStats]
  271. requestStats.fetchLimit = 1
  272. let previousLoop = try self.privateContext.fetch(requestStats)
  273. if (previousLoop.first?.end ?? .distantFuture) < self.lastLoopStartDate {
  274. return self.roundDouble(
  275. (self.lastLoopStartDate - (previousLoop.first?.end ?? Date())).timeInterval / 60,
  276. 1
  277. )
  278. }
  279. return nil
  280. }
  281. } catch {
  282. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to fetch the last loop with error: \(error)")
  283. return nil
  284. }
  285. }
  286. // Loop exit point
  287. private func loopCompleted(error: Error? = nil, loopStatRecord: LoopStats) async {
  288. isLooping.send(false)
  289. if let error = error {
  290. warning(.apsManager, "Loop failed with error: \(error)")
  291. if let backgroundTask = backgroundTaskID {
  292. await UIApplication.shared.endBackgroundTask(backgroundTask)
  293. backgroundTaskID = .invalid
  294. }
  295. processError(error)
  296. } else {
  297. debug(.apsManager, "Loop succeeded")
  298. lastLoopDate = Date()
  299. lastError.send(nil)
  300. }
  301. loopStats(loopStatRecord: loopStatRecord)
  302. if settings.closedLoop {
  303. await reportEnacted(wasEnacted: error == nil)
  304. }
  305. // End of the BG tasks
  306. if let backgroundTask = backgroundTaskID {
  307. await UIApplication.shared.endBackgroundTask(backgroundTask)
  308. backgroundTaskID = .invalid
  309. }
  310. }
  311. private func verifyStatus() -> Error? {
  312. guard let pump = pumpManager else {
  313. return APSError.invalidPumpState(message: String(localized: "Pump not set"))
  314. }
  315. let status = pump.status.pumpStatus
  316. guard !status.bolusing else {
  317. return APSError.invalidPumpState(message: String(localized: "Pump is bolusing"))
  318. }
  319. guard !status.suspended else {
  320. return APSError.invalidPumpState(message: String(localized: "Pump suspended"))
  321. }
  322. let reservoir = storage.retrieve(OpenAPS.Monitor.reservoir, as: Decimal.self) ?? 100
  323. guard reservoir >= 0 else {
  324. return APSError.invalidPumpState(message: String(localized: "Reservoir is empty"))
  325. }
  326. return nil
  327. }
  328. func autosense() async throws -> Bool {
  329. guard let autosense = await storage.retrieveAsync(OpenAPS.Settings.autosense, as: Autosens.self),
  330. (autosense.timestamp ?? .distantPast).addingTimeInterval(30.minutes.timeInterval) > Date()
  331. else {
  332. let result = try await openAPS.autosense()
  333. return result != nil
  334. }
  335. return false
  336. }
  337. /// Calculates and stores the Total Daily Dose (TDD)
  338. private func calculateAndStoreTDD() async throws {
  339. guard let pumpManager else { return }
  340. async let pumpHistory = pumpHistoryStorage.getPumpHistory()
  341. async let basalProfile = storage
  342. .retrieveAsync(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self) ??
  343. [BasalProfileEntry](from: OpenAPS.defaults(for: OpenAPS.Settings.basalProfile)) ??
  344. [] // OpenAPS.defaults ensures we at least get default rate of 1u/hr for 24 hrs
  345. // Calculate TDD
  346. let tddResult = try await tddStorage.calculateTDD(
  347. pumpManager: pumpManager,
  348. pumpHistory: pumpHistory,
  349. basalProfile: basalProfile
  350. )
  351. // Store TDD in Core Data
  352. await tddStorage.storeTDD(tddResult)
  353. }
  354. func determineBasal() async throws {
  355. debug(.apsManager, "Start determine basal")
  356. try await calculateAndStoreTDD()
  357. // Fetch glucose asynchronously
  358. let glucose = try await fetchGlucose(predicate: NSPredicate.predicateForOneHourAgo, fetchLimit: 6)
  359. // Perform the context-related checks and actions
  360. let isValidGlucoseData = await privateContext.perform { [weak self] in
  361. guard let self else { return false }
  362. guard glucose.count > 2 else {
  363. debug(.apsManager, "Not enough glucose data")
  364. self.processError(APSError.glucoseError(message: String(localized: "Not enough glucose data")))
  365. return false
  366. }
  367. let dateOfLastGlucose = glucose.first?.date
  368. guard dateOfLastGlucose ?? Date() >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  369. debug(.apsManager, "Glucose data is stale")
  370. self.processError(APSError.glucoseError(message: String(localized: "Glucose data is stale")))
  371. return false
  372. }
  373. guard !GlucoseStored.glucoseIsFlat(glucose) else {
  374. debug(.apsManager, "Glucose data is too flat")
  375. self.processError(APSError.glucoseError(message: String(localized: "Glucose data is too flat")))
  376. return false
  377. }
  378. return true
  379. }
  380. guard isValidGlucoseData else {
  381. debug(.apsManager, "Glucose validation failed")
  382. processError(APSError.glucoseError(message: "Glucose validation failed"))
  383. return
  384. }
  385. do {
  386. let now = Date()
  387. // Parallelize the fetches using async let
  388. async let currentTemp = fetchCurrentTempBasal(date: now)
  389. async let autosenseResult = autosense()
  390. _ = try await autosenseResult
  391. try await openAPS.createProfiles()
  392. let determination = try await openAPS.determineBasal(currentTemp: await currentTemp, clock: now)
  393. if let determination = determination {
  394. // Capture weak self in closure
  395. await MainActor.run { [weak self] in
  396. guard let self else { return }
  397. self.broadcaster.notify(DeterminationObserver.self, on: .main) {
  398. $0.determinationDidUpdate(determination)
  399. }
  400. }
  401. }
  402. } catch {
  403. throw APSError.apsError(message: "Error determining basal: \(error.localizedDescription)")
  404. }
  405. }
  406. func determineBasalSync() async throws {
  407. _ = try await determineBasal()
  408. }
  409. func simulateDetermineBasal(
  410. simulatedCarbsAmount: Decimal,
  411. simulatedBolusAmount: Decimal,
  412. simulatedCarbsDate: Date? = nil
  413. ) async -> Determination? {
  414. do {
  415. let temp = try await fetchCurrentTempBasal(date: Date.now)
  416. return try await openAPS.determineBasal(
  417. currentTemp: temp,
  418. clock: Date(),
  419. simulatedCarbsAmount: simulatedCarbsAmount,
  420. simulatedBolusAmount: simulatedBolusAmount,
  421. simulatedCarbsDate: simulatedCarbsDate,
  422. simulation: true
  423. )
  424. } catch {
  425. debugPrint(
  426. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Error occurred in simulateDetermineBasal: \(error)"
  427. )
  428. return nil
  429. }
  430. }
  431. func roundBolus(amount: Decimal) -> Decimal {
  432. guard let pump = pumpManager else { return amount }
  433. let rounded = Decimal(pump.roundToSupportedBolusVolume(units: Double(amount)))
  434. let maxBolus = Decimal(pump.roundToSupportedBolusVolume(units: Double(settingsManager.pumpSettings.maxBolus)))
  435. return min(rounded, maxBolus)
  436. }
  437. private var bolusReporter: DoseProgressReporter?
  438. func enactBolus(amount: Double, isSMB: Bool, callback: ((Bool, String) -> Void)?) async {
  439. if amount <= 0 {
  440. return
  441. }
  442. if let error = verifyStatus() {
  443. processError(error)
  444. // Capture broadcaster and queue before async context
  445. let broadcaster = self.broadcaster
  446. Task { @MainActor in
  447. broadcaster?.notify(BolusFailureObserver.self, on: .main) {
  448. $0.bolusDidFail()
  449. }
  450. }
  451. callback?(false, String(localized: "Error! Failed to enact bolus.", comment: "Error message for enacting a bolus"))
  452. return
  453. }
  454. guard let pump = pumpManager else {
  455. callback?(false, String(localized: "Error! Failed to enact bolus.", comment: "Error message for enacting a bolus"))
  456. return
  457. }
  458. let roundedAmount = pump.roundToSupportedBolusVolume(units: amount)
  459. debug(.apsManager, "Enact bolus \(roundedAmount), manual \(!isSMB)")
  460. do {
  461. try await pump.enactBolus(units: roundedAmount, automatic: isSMB)
  462. debug(.apsManager, "Bolus succeeded")
  463. if !isSMB {
  464. try await determineBasalSync()
  465. }
  466. bolusProgress.send(0)
  467. callback?(true, String(localized: "Bolus enacted successfully.", comment: "Success message for enacting a bolus"))
  468. } catch {
  469. warning(.apsManager, "Bolus failed with error: \(error)")
  470. processError(APSError.pumpError(error))
  471. if !isSMB {
  472. // Use MainActor to handle broadcaster notification
  473. let broadcaster = self.broadcaster
  474. Task { @MainActor in
  475. broadcaster?.notify(BolusFailureObserver.self, on: .main) {
  476. $0.bolusDidFail()
  477. }
  478. }
  479. }
  480. callback?(
  481. false,
  482. String(localized: "Error! Bolus failed with error: \(error.localizedDescription)")
  483. )
  484. }
  485. }
  486. func cancelBolus(_ callback: ((Bool, String) -> Void)?) async {
  487. guard let pump = pumpManager, pump.status.pumpStatus.bolusing else { return }
  488. debug(.apsManager, "Cancel bolus")
  489. do {
  490. _ = try await pump.cancelBolus()
  491. debug(.apsManager, "Bolus cancelled")
  492. callback?(true, String(localized: "Bolus cancelled successfully.", comment: "Success message for canceling a bolus"))
  493. } catch {
  494. debug(.apsManager, "Bolus cancellation failed with error: \(error)")
  495. processError(APSError.pumpError(error))
  496. callback?(
  497. false,
  498. String(
  499. localized: "Error! Bolus cancellation failed with error: \(error.localizedDescription)",
  500. comment: "Error message for canceling a bolus"
  501. )
  502. )
  503. }
  504. bolusReporter?.removeObserver(self)
  505. bolusReporter = nil
  506. bolusProgress.send(nil)
  507. }
  508. func enactTempBasal(rate: Double, duration: TimeInterval) async {
  509. if let error = verifyStatus() {
  510. processError(error)
  511. return
  512. }
  513. guard let pump = pumpManager else { return }
  514. // unable to do temp basal during manual temp basal 😁
  515. if isManualTempBasal {
  516. processError(APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp"))
  517. return
  518. }
  519. debug(.apsManager, "Enact temp basal \(rate) - \(duration)")
  520. let roundedAmout = pump.roundToSupportedBasalRate(unitsPerHour: rate)
  521. do {
  522. try await pump.enactTempBasal(unitsPerHour: roundedAmout, for: duration)
  523. debug(.apsManager, "Temp Basal succeeded")
  524. } catch {
  525. debug(.apsManager, "Temp Basal failed with error: \(error)")
  526. processError(APSError.pumpError(error))
  527. }
  528. }
  529. private func fetchCurrentTempBasal(date: Date) async throws -> TempBasal {
  530. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  531. ofType: PumpEventStored.self,
  532. onContext: privateContext,
  533. predicate: NSPredicate.recentPumpHistory,
  534. key: "timestamp",
  535. ascending: false,
  536. fetchLimit: 1
  537. )
  538. let fetchedTempBasal = await privateContext.perform {
  539. guard let fetchedResults = results as? [PumpEventStored],
  540. let tempBasalEvent = fetchedResults.first,
  541. let tempBasal = tempBasalEvent.tempBasal,
  542. let eventTimestamp = tempBasalEvent.timestamp
  543. else {
  544. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  545. }
  546. let delta = Int((date.timeIntervalSince1970 - eventTimestamp.timeIntervalSince1970) / 60)
  547. let duration = max(0, Int(tempBasal.duration) - delta)
  548. let rate = tempBasal.rate as? Decimal ?? 0
  549. return TempBasal(duration: duration, rate: rate, temp: .absolute, timestamp: date)
  550. }
  551. guard let state = pumpManager?.status.basalDeliveryState else { return fetchedTempBasal }
  552. switch state {
  553. case .active:
  554. return TempBasal(duration: 0, rate: 0, temp: .absolute, timestamp: date)
  555. case let .tempBasal(dose):
  556. let rate = Decimal(dose.unitsPerHour)
  557. let durationMin = max(0, Int((dose.endDate.timeIntervalSince1970 - date.timeIntervalSince1970) / 60))
  558. return TempBasal(duration: durationMin, rate: rate, temp: .absolute, timestamp: date)
  559. default:
  560. return fetchedTempBasal
  561. }
  562. }
  563. private func enactDetermination() async throws {
  564. guard let determinationID = try await determinationStorage
  565. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  566. else {
  567. throw APSError.apsError(message: "Determination not found")
  568. }
  569. guard let pump = pumpManager else {
  570. throw APSError.apsError(message: "Pump not set")
  571. }
  572. // Unable to do temp basal during manual temp basal 😁
  573. if isManualTempBasal {
  574. throw APSError.manualBasalTemp(message: "Loop not possible during the manual basal temp")
  575. }
  576. let (rateDecimal, durationInSeconds, smbToDeliver) = try await setValues(determinationID: determinationID)
  577. if let rate = rateDecimal, let duration = durationInSeconds {
  578. try await performBasal(pump: pump, rate: rate, duration: duration)
  579. }
  580. // only perform a bolus if smbToDeliver is > 0
  581. if let smb = smbToDeliver, smb.compare(NSDecimalNumber(value: 0)) == .orderedDescending {
  582. try await performBolus(pump: pump, smbToDeliver: smb)
  583. }
  584. }
  585. private func setValues(determinationID: NSManagedObjectID) async throws
  586. -> (NSDecimalNumber?, TimeInterval?, NSDecimalNumber?)
  587. {
  588. return try await privateContext.perform {
  589. do {
  590. let determination = try self.privateContext.existingObject(with: determinationID) as? OrefDetermination
  591. let rate = determination?.rate
  592. let duration = determination?.duration.flatMap { TimeInterval(truncating: $0) * 60 }
  593. let smbToDeliver = determination?.smbToDeliver ?? 0
  594. return (rate, duration, smbToDeliver)
  595. } catch {
  596. throw error
  597. }
  598. }
  599. }
  600. private func performBasal(pump: PumpManager, rate: NSDecimalNumber, duration: TimeInterval) async throws {
  601. try await pump.enactTempBasal(unitsPerHour: Double(truncating: rate), for: duration)
  602. }
  603. private func performBolus(pump: PumpManager, smbToDeliver: NSDecimalNumber) async throws {
  604. try await pump.enactBolus(units: Double(truncating: smbToDeliver), automatic: true)
  605. bolusProgress.send(0)
  606. }
  607. private func reportEnacted(wasEnacted: Bool) async {
  608. do {
  609. guard let determinationID = try await determinationStorage
  610. .fetchLastDeterminationObjectID(predicate: NSPredicate.predicateFor30MinAgoForDetermination).first
  611. else {
  612. debug(.apsManager, "No determination found to report enacted status")
  613. return
  614. }
  615. try await privateContext.perform {
  616. guard let determinationUpdated = try self.privateContext
  617. .existingObject(with: determinationID) as? OrefDetermination
  618. else {
  619. debug(.apsManager, "Could not find determination object in context")
  620. return
  621. }
  622. determinationUpdated.timestamp = Date()
  623. determinationUpdated.enacted = wasEnacted
  624. determinationUpdated.isUploadedToNS = false
  625. guard self.privateContext.hasChanges else { return }
  626. try self.privateContext.save()
  627. debug(.apsManager, "Determination enacted. Enacted: \(wasEnacted)")
  628. }
  629. } catch {
  630. debug(
  631. .apsManager,
  632. "\(DebuggingIdentifiers.failed) Error reporting enacted status: \(error)"
  633. )
  634. }
  635. }
  636. private func roundDecimal(_ decimal: Decimal, _ digits: Double) -> Decimal {
  637. let rounded = round(Double(decimal) * pow(10, digits)) / pow(10, digits)
  638. return Decimal(rounded)
  639. }
  640. private func roundDouble(_ double: Double, _ digits: Double) -> Double {
  641. let rounded = round(Double(double) * pow(10, digits)) / pow(10, digits)
  642. return rounded
  643. }
  644. private func medianCalculationDouble(array: [Double]) -> Double {
  645. guard !array.isEmpty else {
  646. return 0
  647. }
  648. let sorted = array.sorted()
  649. let length = array.count
  650. if length % 2 == 0 {
  651. return (sorted[length / 2 - 1] + sorted[length / 2]) / 2
  652. }
  653. return sorted[length / 2]
  654. }
  655. private func medianCalculation(array: [Int]) -> Double {
  656. guard !array.isEmpty else {
  657. return 0
  658. }
  659. let sorted = array.sorted()
  660. let length = array.count
  661. if length % 2 == 0 {
  662. return Double((sorted[length / 2 - 1] + sorted[length / 2]) / 2)
  663. }
  664. return Double(sorted[length / 2])
  665. }
  666. private func tir(_ glucose: [GlucoseStored]) -> (TIR: Double, hypos: Double, hypers: Double, normal_: Double) {
  667. privateContext.perform {
  668. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  669. let totalReadings = justGlucoseArray.count
  670. let highLimit = settingsManager.settings.high
  671. let lowLimit = settingsManager.settings.low
  672. let hyperArray = glucose.filter({ $0.glucose >= Int(highLimit) })
  673. let hyperReadings = hyperArray.compactMap({ each in each.glucose as Int16 }).count
  674. let hyperPercentage = Double(hyperReadings) / Double(totalReadings) * 100
  675. let hypoArray = glucose.filter({ $0.glucose <= Int(lowLimit) })
  676. let hypoReadings = hypoArray.compactMap({ each in each.glucose as Int16 }).count
  677. let hypoPercentage = Double(hypoReadings) / Double(totalReadings) * 100
  678. // Euglyccemic range
  679. let normalArray = glucose.filter({ $0.glucose >= 70 && $0.glucose <= 140 })
  680. let normalReadings = normalArray.compactMap({ each in each.glucose as Int16 }).count
  681. let normalPercentage = Double(normalReadings) / Double(totalReadings) * 100
  682. // TIR
  683. let tir = 100 - (hypoPercentage + hyperPercentage)
  684. return (
  685. roundDouble(tir, 1),
  686. roundDouble(hypoPercentage, 1),
  687. roundDouble(hyperPercentage, 1),
  688. roundDouble(normalPercentage, 1)
  689. )
  690. }
  691. }
  692. private func glucoseStats(_ fetchedGlucose: [GlucoseStored])
  693. -> (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  694. {
  695. let glucose = fetchedGlucose
  696. // First date
  697. let last = glucose.last?.date ?? Date()
  698. // Last date (recent)
  699. let first = glucose.first?.date ?? Date()
  700. // Total time in days
  701. let numberOfDays = (first - last).timeInterval / 8.64E4
  702. let denominator = numberOfDays < 1 ? 1 : numberOfDays
  703. let justGlucoseArray = glucose.compactMap({ each in Int(each.glucose as Int16) })
  704. let sumReadings = justGlucoseArray.reduce(0, +)
  705. let countReadings = justGlucoseArray.count
  706. let glucoseAverage = Double(sumReadings) / Double(countReadings)
  707. let medianGlucose = medianCalculation(array: justGlucoseArray)
  708. var NGSPa1CStatisticValue = 0.0
  709. var IFCCa1CStatisticValue = 0.0
  710. NGSPa1CStatisticValue = (glucoseAverage + 46.7) / 28.7 // NGSP (%)
  711. IFCCa1CStatisticValue = 10.929 *
  712. (NGSPa1CStatisticValue - 2.152) // IFCC (mmol/mol) A1C(mmol/mol) = 10.929 * (A1C(%) - 2.15)
  713. var sumOfSquares = 0.0
  714. for array in justGlucoseArray {
  715. sumOfSquares += pow(Double(array) - Double(glucoseAverage), 2)
  716. }
  717. var sd = 0.0
  718. var cv = 0.0
  719. // Avoid division by zero
  720. if glucoseAverage > 0 {
  721. sd = sqrt(sumOfSquares / Double(countReadings))
  722. cv = sd / Double(glucoseAverage) * 100
  723. }
  724. let conversionFactor = 0.0555
  725. let units = settingsManager.settings.units
  726. var output: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double)
  727. output = (
  728. ifcc: IFCCa1CStatisticValue,
  729. ngsp: NGSPa1CStatisticValue,
  730. average: glucoseAverage * (units == .mmolL ? conversionFactor : 1),
  731. median: medianGlucose * (units == .mmolL ? conversionFactor : 1),
  732. sd: sd * (units == .mmolL ? conversionFactor : 1), cv: cv,
  733. readings: Double(countReadings) / denominator
  734. )
  735. return output
  736. }
  737. private func loops(_ fetchedLoops: [LoopStatRecord]) -> Loops {
  738. let loops = fetchedLoops
  739. // First date
  740. let previous = loops.last?.end ?? Date()
  741. // Last date (recent)
  742. let current = loops.first?.start ?? Date()
  743. // Total time in days
  744. let totalTime = (current - previous).timeInterval / 8.64E4
  745. //
  746. let durationArray = loops.compactMap({ each in each.duration })
  747. let durationArrayCount = durationArray.count
  748. let durationAverage = durationArray.reduce(0, +) / Double(durationArrayCount) * 60
  749. let medianDuration = medianCalculationDouble(array: durationArray) * 60
  750. let max_duration = (durationArray.max() ?? 0) * 60
  751. let min_duration = (durationArray.min() ?? 0) * 60
  752. let successsNR = loops.compactMap({ each in each.loopStatus }).filter({ each in each!.contains("Success") }).count
  753. let errorNR = durationArrayCount - successsNR
  754. let total = Double(successsNR + errorNR) == 0 ? 1 : Double(successsNR + errorNR)
  755. let successRate: Double? = (Double(successsNR) / total) * 100
  756. let loopNr = totalTime <= 1 ? total : round(total / (totalTime != 0 ? totalTime : 1))
  757. let intervalArray = loops.compactMap({ each in each.interval as Double })
  758. let count = intervalArray.count != 0 ? intervalArray.count : 1
  759. let median_interval = medianCalculationDouble(array: intervalArray)
  760. let intervalAverage = intervalArray.reduce(0, +) / Double(count)
  761. let maximumInterval = intervalArray.max()
  762. let minimumInterval = intervalArray.min()
  763. //
  764. let output = Loops(
  765. loops: Int(loopNr),
  766. errors: errorNR,
  767. success_rate: roundDecimal(Decimal(successRate ?? 0), 1),
  768. avg_interval: roundDecimal(Decimal(intervalAverage), 1),
  769. median_interval: roundDecimal(Decimal(median_interval), 1),
  770. min_interval: roundDecimal(Decimal(minimumInterval ?? 0), 1),
  771. max_interval: roundDecimal(Decimal(maximumInterval ?? 0), 1),
  772. avg_duration: roundDecimal(Decimal(durationAverage), 1),
  773. median_duration: roundDecimal(Decimal(medianDuration), 1),
  774. min_duration: roundDecimal(Decimal(min_duration), 1),
  775. max_duration: roundDecimal(Decimal(max_duration), 1)
  776. )
  777. return output
  778. }
  779. // fetch glucose for time interval
  780. func fetchGlucose(predicate: NSPredicate, fetchLimit: Int? = nil, batchSize: Int? = nil) async throws -> [GlucoseStored] {
  781. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  782. ofType: GlucoseStored.self,
  783. onContext: privateContext,
  784. predicate: predicate,
  785. key: "date",
  786. ascending: false,
  787. fetchLimit: fetchLimit,
  788. batchSize: batchSize
  789. )
  790. return try await privateContext.perform {
  791. guard let glucoseResults = results as? [GlucoseStored] else {
  792. throw CoreDataError.fetchError(function: #function, file: #file)
  793. }
  794. return glucoseResults
  795. }
  796. }
  797. private func lastLoopForStats() async -> Date? {
  798. let requestStats = StatsData.fetchRequest() as NSFetchRequest<StatsData>
  799. let sortStats = NSSortDescriptor(key: "lastrun", ascending: false)
  800. requestStats.sortDescriptors = [sortStats]
  801. requestStats.fetchLimit = 1
  802. return await privateContext.perform {
  803. do {
  804. return try self.privateContext.fetch(requestStats).first?.lastrun
  805. } catch {
  806. print(error.localizedDescription)
  807. return .distantPast
  808. }
  809. }
  810. }
  811. private func loopStats(oneDayGlucose: Double) async -> LoopCycles {
  812. let requestLSR = LoopStatRecord.fetchRequest() as NSFetchRequest<LoopStatRecord>
  813. requestLSR.predicate = NSPredicate(
  814. format: "interval > 0 AND start > %@",
  815. Date().addingTimeInterval(-24.hours.timeInterval) as NSDate
  816. )
  817. let sortLSR = NSSortDescriptor(key: "start", ascending: false)
  818. requestLSR.sortDescriptors = [sortLSR]
  819. return await privateContext.perform {
  820. do {
  821. let lsr = try self.privateContext.fetch(requestLSR)
  822. // Compute LoopStats for 24 hours
  823. let oneDayLoops = self.loops(lsr)
  824. return LoopCycles(
  825. loops: oneDayLoops.loops,
  826. errors: oneDayLoops.errors,
  827. readings: Int(oneDayGlucose),
  828. success_rate: oneDayLoops.success_rate,
  829. avg_interval: oneDayLoops.avg_interval,
  830. median_interval: oneDayLoops.median_interval,
  831. min_interval: oneDayLoops.min_interval,
  832. max_interval: oneDayLoops.max_interval,
  833. avg_duration: oneDayLoops.avg_duration,
  834. median_duration: oneDayLoops.median_duration,
  835. min_duration: oneDayLoops.max_duration,
  836. max_duration: oneDayLoops.max_duration
  837. )
  838. } catch {
  839. debugPrint(
  840. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to get Loop statistics for Statistics Upload"
  841. )
  842. return LoopCycles(
  843. loops: 0,
  844. errors: 0,
  845. readings: 0,
  846. success_rate: 0,
  847. avg_interval: 0,
  848. median_interval: 0,
  849. min_interval: 0,
  850. max_interval: 0,
  851. avg_duration: 0,
  852. median_duration: 0,
  853. min_duration: 0,
  854. max_duration: 0
  855. )
  856. }
  857. }
  858. }
  859. private func glucoseForStats() async -> (
  860. oneDayGlucose: (ifcc: Double, ngsp: Double, average: Double, median: Double, sd: Double, cv: Double, readings: Double),
  861. eA1cDisplayUnit: EstimatedA1cDisplayUnit,
  862. numberofDays: Double,
  863. TimeInRange: TIRs,
  864. avg: Averages,
  865. hbs: Durations,
  866. variance: Variance
  867. )? {
  868. do {
  869. // Get the Glucose Values
  870. let glucose24h = try await fetchGlucose(predicate: NSPredicate.predicateForOneDayAgo, fetchLimit: 288, batchSize: 50)
  871. let glucoseOneWeek = try await fetchGlucose(
  872. predicate: NSPredicate.predicateForOneWeek,
  873. fetchLimit: 288 * 7,
  874. batchSize: 250
  875. )
  876. let glucoseOneMonth = try await fetchGlucose(
  877. predicate: NSPredicate.predicateForOneMonth,
  878. fetchLimit: 288 * 7 * 30,
  879. batchSize: 500
  880. )
  881. let glucoseThreeMonths = try await fetchGlucose(
  882. predicate: NSPredicate.predicateForThreeMonths,
  883. fetchLimit: 288 * 7 * 30 * 3,
  884. batchSize: 1000
  885. )
  886. return await privateContext.perform {
  887. let units = self.settingsManager.settings.units
  888. // First date
  889. let previous = glucoseThreeMonths.last?.date ?? Date()
  890. // Last date (recent)
  891. let current = glucoseThreeMonths.first?.date ?? Date()
  892. // Total time in days
  893. let numberOfDays = (current - previous).timeInterval / 8.64E4
  894. // Get glucose computations for every case
  895. let oneDayGlucose = self.glucoseStats(glucose24h)
  896. let sevenDaysGlucose = self.glucoseStats(glucoseOneWeek)
  897. let thirtyDaysGlucose = self.glucoseStats(glucoseOneMonth)
  898. let totalDaysGlucose = self.glucoseStats(glucoseThreeMonths)
  899. let median = Durations(
  900. day: self.roundDecimal(Decimal(oneDayGlucose.median), 1),
  901. week: self.roundDecimal(Decimal(sevenDaysGlucose.median), 1),
  902. month: self.roundDecimal(Decimal(thirtyDaysGlucose.median), 1),
  903. total: self.roundDecimal(Decimal(totalDaysGlucose.median), 1)
  904. )
  905. let eA1cDisplayUnit = self.settingsManager.settings.eA1cDisplayUnit
  906. let hbs = Durations(
  907. day: eA1cDisplayUnit == .mmolMol ?
  908. self.roundDecimal(Decimal(oneDayGlucose.ifcc), 1) :
  909. self.roundDecimal(Decimal(oneDayGlucose.ngsp), 1),
  910. week: eA1cDisplayUnit == .mmolMol ?
  911. self.roundDecimal(Decimal(sevenDaysGlucose.ifcc), 1) :
  912. self.roundDecimal(Decimal(sevenDaysGlucose.ngsp), 1),
  913. month: eA1cDisplayUnit == .mmolMol ?
  914. self.roundDecimal(Decimal(thirtyDaysGlucose.ifcc), 1) :
  915. self.roundDecimal(Decimal(thirtyDaysGlucose.ngsp), 1),
  916. total: eA1cDisplayUnit == .mmolMol ?
  917. self.roundDecimal(Decimal(totalDaysGlucose.ifcc), 1) :
  918. self.roundDecimal(Decimal(totalDaysGlucose.ngsp), 1)
  919. )
  920. var oneDay_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  921. var sevenDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  922. var thirtyDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  923. var totalDays_: (TIR: Double, hypos: Double, hypers: Double, normal_: Double) = (0.0, 0.0, 0.0, 0.0)
  924. // Get TIR computations for every case
  925. oneDay_ = self.tir(glucose24h)
  926. sevenDays_ = self.tir(glucoseOneWeek)
  927. thirtyDays_ = self.tir(glucoseOneMonth)
  928. totalDays_ = self.tir(glucoseThreeMonths)
  929. let tir = Durations(
  930. day: self.roundDecimal(Decimal(oneDay_.TIR), 1),
  931. week: self.roundDecimal(Decimal(sevenDays_.TIR), 1),
  932. month: self.roundDecimal(Decimal(thirtyDays_.TIR), 1),
  933. total: self.roundDecimal(Decimal(totalDays_.TIR), 1)
  934. )
  935. let hypo = Durations(
  936. day: Decimal(oneDay_.hypos),
  937. week: Decimal(sevenDays_.hypos),
  938. month: Decimal(thirtyDays_.hypos),
  939. total: Decimal(totalDays_.hypos)
  940. )
  941. let hyper = Durations(
  942. day: Decimal(oneDay_.hypers),
  943. week: Decimal(sevenDays_.hypers),
  944. month: Decimal(thirtyDays_.hypers),
  945. total: Decimal(totalDays_.hypers)
  946. )
  947. let normal = Durations(
  948. day: Decimal(oneDay_.normal_),
  949. week: Decimal(sevenDays_.normal_),
  950. month: Decimal(thirtyDays_.normal_),
  951. total: Decimal(totalDays_.normal_)
  952. )
  953. let range = Threshold(
  954. low: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.low.asMmolL, 1) :
  955. self.roundDecimal(self.settingsManager.settings.low, 0),
  956. high: units == .mmolL ? self.roundDecimal(self.settingsManager.settings.high.asMmolL, 1) :
  957. self.roundDecimal(self.settingsManager.settings.high, 0)
  958. )
  959. let TimeInRange = TIRs(
  960. TIR: tir,
  961. Hypos: hypo,
  962. Hypers: hyper,
  963. Threshold: range,
  964. Euglycemic: normal
  965. )
  966. let avgs = Durations(
  967. day: self.roundDecimal(Decimal(oneDayGlucose.average), 1),
  968. week: self.roundDecimal(Decimal(sevenDaysGlucose.average), 1),
  969. month: self.roundDecimal(Decimal(thirtyDaysGlucose.average), 1),
  970. total: self.roundDecimal(Decimal(totalDaysGlucose.average), 1)
  971. )
  972. let avg = Averages(Average: avgs, Median: median)
  973. // Standard Deviations
  974. let standardDeviations = Durations(
  975. day: self.roundDecimal(Decimal(oneDayGlucose.sd), 1),
  976. week: self.roundDecimal(Decimal(sevenDaysGlucose.sd), 1),
  977. month: self.roundDecimal(Decimal(thirtyDaysGlucose.sd), 1),
  978. total: self.roundDecimal(Decimal(totalDaysGlucose.sd), 1)
  979. )
  980. // CV = standard deviation / sample mean x 100
  981. let cvs = Durations(
  982. day: self.roundDecimal(Decimal(oneDayGlucose.cv), 1),
  983. week: self.roundDecimal(Decimal(sevenDaysGlucose.cv), 1),
  984. month: self.roundDecimal(Decimal(thirtyDaysGlucose.cv), 1),
  985. total: self.roundDecimal(Decimal(totalDaysGlucose.cv), 1)
  986. )
  987. let variance = Variance(SD: standardDeviations, CV: cvs)
  988. return (oneDayGlucose, eA1cDisplayUnit, numberOfDays, TimeInRange, avg, hbs, variance)
  989. }
  990. } catch {
  991. debug(
  992. .apsManager,
  993. "\(DebuggingIdentifiers.failed) Error fetching glucose for stats: \(error)"
  994. )
  995. return nil
  996. }
  997. }
  998. private func loopStats(loopStatRecord: LoopStats) {
  999. privateContext.perform {
  1000. let nLS = LoopStatRecord(context: self.privateContext)
  1001. nLS.start = loopStatRecord.start
  1002. nLS.end = loopStatRecord.end ?? Date()
  1003. nLS.loopStatus = loopStatRecord.loopStatus
  1004. nLS.duration = loopStatRecord.duration ?? 0.0
  1005. nLS.interval = loopStatRecord.interval ?? 0.0
  1006. do {
  1007. guard self.privateContext.hasChanges else { return }
  1008. try self.privateContext.save()
  1009. } catch {
  1010. print(error.localizedDescription)
  1011. }
  1012. }
  1013. }
  1014. private func processError(_ error: Error) {
  1015. warning(.apsManager, "\(error)")
  1016. lastError.send(error)
  1017. }
  1018. private func createBolusReporter() {
  1019. bolusReporter = pumpManager?.createBolusProgressReporter(reportingOn: processQueue)
  1020. bolusReporter?.addObserver(self)
  1021. }
  1022. private func clearBolusReporter() {
  1023. bolusReporter?.removeObserver(self)
  1024. bolusReporter = nil
  1025. processQueue.asyncAfter(deadline: .now() + 0.5) {
  1026. self.bolusProgress.send(nil)
  1027. }
  1028. }
  1029. }
  1030. private extension PumpManager {
  1031. func enactTempBasal(unitsPerHour: Double, for duration: TimeInterval) async throws {
  1032. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1033. self.enactTempBasal(unitsPerHour: unitsPerHour, for: duration) { error in
  1034. if let error = error {
  1035. debug(.apsManager, "Temp basal failed: \(unitsPerHour) for: \(duration)")
  1036. continuation.resume(throwing: error)
  1037. } else {
  1038. debug(.apsManager, "Temp basal succeeded: \(unitsPerHour) for: \(duration)")
  1039. continuation.resume(returning: ())
  1040. }
  1041. }
  1042. }
  1043. }
  1044. func enactBolus(units: Double, automatic: Bool) async throws {
  1045. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1046. let automaticValue = automatic ? BolusActivationType.automatic : BolusActivationType.manualRecommendationAccepted
  1047. self.enactBolus(units: units, activationType: automaticValue) { error in
  1048. if let error = error {
  1049. debug(.apsManager, "Bolus failed: \(units)")
  1050. continuation.resume(throwing: error)
  1051. } else {
  1052. debug(.apsManager, "Bolus succeeded: \(units)")
  1053. continuation.resume(returning: ())
  1054. }
  1055. }
  1056. }
  1057. }
  1058. func cancelBolus() async throws -> DoseEntry? {
  1059. try await withCheckedThrowingContinuation { continuation in
  1060. self.cancelBolus { result in
  1061. switch result {
  1062. case let .success(dose):
  1063. debug(.apsManager, "Cancel Bolus succeeded")
  1064. continuation.resume(returning: dose)
  1065. case let .failure(error):
  1066. debug(.apsManager, "Cancel Bolus failed")
  1067. continuation.resume(throwing: APSError.pumpError(error))
  1068. }
  1069. }
  1070. }
  1071. }
  1072. func suspendDelivery() async throws {
  1073. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1074. self.suspendDelivery { error in
  1075. if let error = error {
  1076. continuation.resume(throwing: error)
  1077. } else {
  1078. continuation.resume()
  1079. }
  1080. }
  1081. }
  1082. }
  1083. func resumeDelivery() async throws {
  1084. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  1085. self.resumeDelivery { error in
  1086. if let error = error {
  1087. continuation.resume(throwing: error)
  1088. } else {
  1089. continuation.resume()
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. extension BaseAPSManager: PumpManagerStatusObserver {
  1096. func pumpManager(_: PumpManager, didUpdate status: PumpManagerStatus, oldStatus _: PumpManagerStatus) {
  1097. let percent = Int((status.pumpBatteryChargeRemaining ?? 1) * 100)
  1098. privateContext.perform {
  1099. /// only update the last item with the current battery infos instead of saving a new one each time
  1100. let fetchRequest: NSFetchRequest<OpenAPS_Battery> = OpenAPS_Battery.fetchRequest()
  1101. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
  1102. fetchRequest.predicate = NSPredicate.predicateFor30MinAgo
  1103. fetchRequest.fetchLimit = 1
  1104. do {
  1105. let results = try self.privateContext.fetch(fetchRequest)
  1106. let batteryToStore: OpenAPS_Battery
  1107. if let existingBattery = results.first {
  1108. batteryToStore = existingBattery
  1109. } else {
  1110. batteryToStore = OpenAPS_Battery(context: self.privateContext)
  1111. batteryToStore.id = UUID()
  1112. }
  1113. batteryToStore.date = Date()
  1114. batteryToStore.percent = Double(percent)
  1115. batteryToStore.voltage = nil
  1116. batteryToStore.status = percent > 10 ? "normal" : "low"
  1117. batteryToStore.display = status.pumpBatteryChargeRemaining != nil
  1118. guard self.privateContext.hasChanges else { return }
  1119. try self.privateContext.save()
  1120. } catch {
  1121. print("Failed to fetch or save battery: \(error.localizedDescription)")
  1122. }
  1123. }
  1124. // TODO: - remove this after ensuring that NS still gets the same infos from Core Data
  1125. storage.save(status.pumpStatus, as: OpenAPS.Monitor.status)
  1126. }
  1127. }
  1128. extension BaseAPSManager: DoseProgressObserver {
  1129. func doseProgressReporterDidUpdate(_ doseProgressReporter: DoseProgressReporter) {
  1130. bolusProgress.send(Decimal(doseProgressReporter.progress.percentComplete))
  1131. if doseProgressReporter.progress.isComplete {
  1132. clearBolusReporter()
  1133. }
  1134. }
  1135. }
  1136. extension PumpManagerStatus {
  1137. var pumpStatus: PumpStatus {
  1138. let bolusing = bolusState != .noBolus
  1139. let suspended = basalDeliveryState?.isSuspended ?? true
  1140. let type = suspended ? StatusType.suspended : (bolusing ? .bolusing : .normal)
  1141. return PumpStatus(status: type, bolusing: bolusing, suspended: suspended, timestamp: Date())
  1142. }
  1143. }