APSManager.swift 61 KB

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