APSManager.swift 58 KB

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