APSManager.swift 54 KB

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