HomeStateModel.swift 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKitUI
  5. import SwiftDate
  6. import SwiftUI
  7. extension Home {
  8. final class StateModel: BaseStateModel<Provider> {
  9. @Injected() var broadcaster: Broadcaster!
  10. @Injected() var apsManager: APSManager!
  11. @Injected() var fetchGlucoseManager: FetchGlucoseManager!
  12. @Injected() var nightscoutManager: NightscoutManager!
  13. @Injected() var determinationStorage: DeterminationStorage!
  14. private let timer = DispatchTimer(timeInterval: 5)
  15. private(set) var filteredHours = 24
  16. @Published var manualGlucose: [BloodGlucose] = []
  17. @Published var announcement: [Announcement] = []
  18. @Published var uploadStats = false
  19. @Published var recentGlucose: BloodGlucose?
  20. @Published var maxBasal: Decimal = 2
  21. @Published var autotunedBasalProfile: [BasalProfileEntry] = []
  22. @Published var basalProfile: [BasalProfileEntry] = []
  23. @Published var tempTargets: [TempTarget] = []
  24. @Published var timerDate = Date()
  25. @Published var closedLoop = false
  26. @Published var pumpSuspended = false
  27. @Published var isLooping = false
  28. @Published var statusTitle = ""
  29. @Published var lastLoopDate: Date = .distantPast
  30. @Published var battery: Battery?
  31. @Published var reservoir: Decimal?
  32. @Published var pumpName = ""
  33. @Published var pumpExpiresAtDate: Date?
  34. @Published var tempTarget: TempTarget?
  35. @Published var setupPump = false
  36. @Published var errorMessage: String? = nil
  37. @Published var errorDate: Date? = nil
  38. @Published var bolusProgress: Decimal?
  39. @Published var eventualBG: Int?
  40. @Published var allowManualTemp = false
  41. @Published var units: GlucoseUnits = .mgdL
  42. @Published var pumpDisplayState: PumpDisplayState?
  43. @Published var alarm: GlucoseAlarm?
  44. @Published var manualTempBasal = false
  45. @Published var smooth = false
  46. @Published var maxValue: Decimal = 1.2
  47. @Published var lowGlucose: Decimal = 4 / 0.0555
  48. @Published var highGlucose: Decimal = 10 / 0.0555
  49. @Published var overrideUnit: Bool = false
  50. @Published var displayXgridLines: Bool = false
  51. @Published var displayYgridLines: Bool = false
  52. @Published var thresholdLines: Bool = false
  53. @Published var timeZone: TimeZone?
  54. @Published var hours: Int16 = 6
  55. @Published var totalBolus: Decimal = 0
  56. @Published var isStatusPopupPresented: Bool = false
  57. @Published var isLegendPresented: Bool = false
  58. @Published var legendSheetDetent = PresentationDetent.large
  59. @Published var totalInsulinDisplayType: TotalInsulinDisplayType = .totalDailyDose
  60. @Published var isTempTargetActive: Bool = false
  61. @Published var roundedTotalBolus: String = ""
  62. @Published var selectedTab: Int = 0
  63. @Published var waitForSuggestion: Bool = false
  64. @Published var glucoseFromPersistence: [GlucoseStored] = []
  65. @Published var manualGlucoseFromPersistence: [GlucoseStored] = []
  66. @Published var carbsFromPersistence: [CarbEntryStored] = []
  67. @Published var fpusFromPersistence: [CarbEntryStored] = []
  68. @Published var determinationsFromPersistence: [OrefDetermination] = []
  69. @Published var enactedAndNonEnactedDeterminations: [OrefDetermination] = []
  70. @Published var insulinFromPersistence: [PumpEventStored] = []
  71. @Published var tempBasals: [PumpEventStored] = []
  72. @Published var suspensions: [PumpEventStored] = []
  73. @Published var batteryFromPersistence: [OpenAPS_Battery] = []
  74. @Published var lastPumpBolus: PumpEventStored?
  75. @Published var overrides: [OverrideStored] = []
  76. @Published var overrideRunStored: [OverrideRunStored] = []
  77. @Published var isOverrideCancelled: Bool = false
  78. @Published var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  79. @Published var pumpStatusHighlightMessage: String? = nil
  80. @Published var cgmAvailable: Bool = false
  81. @Published var showCarbsRequiredBadge: Bool = true
  82. private(set) var setupPumpType: PumpConfig.PumpType = .minimed
  83. let context = CoreDataStack.shared.newTaskContext()
  84. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  85. private var coreDataObserver: CoreDataObserver?
  86. typealias PumpEvent = PumpEventStored.EventType
  87. override func subscribe() {
  88. setupNotification()
  89. coreDataObserver = CoreDataObserver()
  90. registerHandlers()
  91. setupGlucoseArray()
  92. setupManualGlucoseArray()
  93. setupCarbsArray()
  94. setupFPUsArray()
  95. setupDeterminationsArray()
  96. setupInsulinArray()
  97. setupLastBolus()
  98. setupBatteryArray()
  99. setupPumpSettings()
  100. setupBasalProfile()
  101. setupTempTargets()
  102. setupReservoir()
  103. setupAnnouncements()
  104. setupCurrentPumpTimezone()
  105. setupOverrides()
  106. setupOverrideRunStored()
  107. // TODO: isUploadEnabled the right var here??
  108. uploadStats = settingsManager.settings.isUploadEnabled
  109. units = settingsManager.settings.units
  110. allowManualTemp = !settingsManager.settings.closedLoop
  111. closedLoop = settingsManager.settings.closedLoop
  112. lastLoopDate = apsManager.lastLoopDate
  113. alarm = provider.glucoseStorage.alarm
  114. manualTempBasal = apsManager.isManualTempBasal
  115. setupCurrentTempTarget()
  116. smooth = settingsManager.settings.smoothGlucose
  117. maxValue = settingsManager.preferences.autosensMax
  118. lowGlucose = settingsManager.settings.low
  119. highGlucose = settingsManager.settings.high
  120. overrideUnit = settingsManager.settings.overrideHbA1cUnit
  121. displayXgridLines = settingsManager.settings.xGridLines
  122. displayYgridLines = settingsManager.settings.yGridLines
  123. thresholdLines = settingsManager.settings.rulerMarks
  124. totalInsulinDisplayType = settingsManager.settings.totalInsulinDisplayType
  125. cgmAvailable = fetchGlucoseManager.cgmGlucoseSourceType != CGMType.none
  126. showCarbsRequiredBadge = settingsManager.settings.showCarbsRequiredBadge
  127. broadcaster.register(GlucoseObserver.self, observer: self)
  128. broadcaster.register(DeterminationObserver.self, observer: self)
  129. broadcaster.register(SettingsObserver.self, observer: self)
  130. broadcaster.register(PumpSettingsObserver.self, observer: self)
  131. broadcaster.register(BasalProfileObserver.self, observer: self)
  132. broadcaster.register(TempTargetsObserver.self, observer: self)
  133. broadcaster.register(PumpReservoirObserver.self, observer: self)
  134. broadcaster.register(PumpDeactivatedObserver.self, observer: self)
  135. timer.eventHandler = {
  136. DispatchQueue.main.async { [weak self] in
  137. self?.timerDate = Date()
  138. self?.setupCurrentTempTarget()
  139. }
  140. }
  141. timer.resume()
  142. apsManager.isLooping
  143. .receive(on: DispatchQueue.main)
  144. .weakAssign(to: \.isLooping, on: self)
  145. .store(in: &lifetime)
  146. apsManager.lastLoopDateSubject
  147. .receive(on: DispatchQueue.main)
  148. .weakAssign(to: \.lastLoopDate, on: self)
  149. .store(in: &lifetime)
  150. apsManager.pumpName
  151. .receive(on: DispatchQueue.main)
  152. .weakAssign(to: \.pumpName, on: self)
  153. .store(in: &lifetime)
  154. apsManager.pumpExpiresAtDate
  155. .receive(on: DispatchQueue.main)
  156. .weakAssign(to: \.pumpExpiresAtDate, on: self)
  157. .store(in: &lifetime)
  158. apsManager.lastError
  159. .receive(on: DispatchQueue.main)
  160. .map { [weak self] error in
  161. self?.errorDate = error == nil ? nil : Date()
  162. if let error = error {
  163. info(.default, error.localizedDescription)
  164. }
  165. return error?.localizedDescription
  166. }
  167. .weakAssign(to: \.errorMessage, on: self)
  168. .store(in: &lifetime)
  169. apsManager.bolusProgress
  170. .receive(on: DispatchQueue.main)
  171. .weakAssign(to: \.bolusProgress, on: self)
  172. .store(in: &lifetime)
  173. apsManager.pumpDisplayState
  174. .receive(on: DispatchQueue.main)
  175. .sink { [weak self] state in
  176. guard let self = self else { return }
  177. self.pumpDisplayState = state
  178. if state == nil {
  179. self.reservoir = nil
  180. self.battery = nil
  181. self.pumpName = ""
  182. self.pumpExpiresAtDate = nil
  183. self.setupPump = false
  184. } else {
  185. self.setupReservoir()
  186. self.displayPumpStatusHighlightMessage()
  187. self.setupBatteryArray()
  188. }
  189. }
  190. .store(in: &lifetime)
  191. }
  192. private func registerHandlers() {
  193. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  194. guard let self = self else { return }
  195. Task {
  196. self.setupDeterminationsArray()
  197. await self.updateForecastData()
  198. }
  199. }
  200. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  201. guard let self = self else { return }
  202. self.setupGlucoseArray()
  203. self.setupManualGlucoseArray()
  204. }
  205. coreDataObserver?.registerHandler(for: "CarbEntryStored") { [weak self] in
  206. guard let self = self else { return }
  207. self.setupCarbsArray()
  208. }
  209. coreDataObserver?.registerHandler(for: "PumpEventStored") { [weak self] in
  210. guard let self = self else { return }
  211. self.setupInsulinArray()
  212. self.setupLastBolus()
  213. self.displayPumpStatusHighlightMessage()
  214. }
  215. coreDataObserver?.registerHandler(for: "OpenAPS_Battery") { [weak self] in
  216. guard let self = self else { return }
  217. self.setupBatteryArray()
  218. }
  219. coreDataObserver?.registerHandler(for: "OverrideStored") { [weak self] in
  220. guard let self = self else { return }
  221. self.setupOverrides()
  222. }
  223. coreDataObserver?.registerHandler(for: "OverrideRunStored") { [weak self] in
  224. guard let self = self else { return }
  225. self.setupOverrideRunStored()
  226. }
  227. }
  228. func addPump(_ type: PumpConfig.PumpType) {
  229. setupPumpType = type
  230. setupPump = true
  231. }
  232. /// Display the eventual status message provided by the manager of the pump
  233. /// Only display if state is warning or critical message else return nil
  234. private func displayPumpStatusHighlightMessage(_ didDeactivate: Bool = false) {
  235. DispatchQueue.main.async { [weak self] in
  236. guard let self = self else { return }
  237. if let statusHighlight = self.provider.deviceManager.pumpManager?.pumpStatusHighlight,
  238. statusHighlight.state == .warning || statusHighlight.state == .critical, !didDeactivate
  239. {
  240. pumpStatusHighlightMessage = (statusHighlight.state == .warning ? "⚠️\n" : "‼️\n") + statusHighlight
  241. .localizedMessage
  242. } else {
  243. pumpStatusHighlightMessage = nil
  244. }
  245. }
  246. }
  247. func runLoop() {
  248. provider.heartbeatNow()
  249. }
  250. func cancelBolus() {
  251. Task {
  252. await apsManager.cancelBolus()
  253. // perform determine basal sync, otherwise you have could end up with too much iob when opening the calculator again
  254. await apsManager.determineBasalSync()
  255. }
  256. }
  257. @MainActor func cancelOverride(withID id: NSManagedObjectID) async {
  258. do {
  259. let profileToCancel = try viewContext.existingObject(with: id) as? OverrideStored
  260. profileToCancel?.enabled = false
  261. await saveToOverrideRunStored(withID: id)
  262. guard viewContext.hasChanges else { return }
  263. try viewContext.save()
  264. Foundation.NotificationCenter.default.post(name: .didUpdateOverrideConfiguration, object: nil)
  265. } catch {
  266. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to cancel Profile")
  267. }
  268. }
  269. func calculateTINS() -> String {
  270. let startTime = calculateStartTime(hours: Int(hours))
  271. let totalBolus = calculateTotalBolus(from: insulinFromPersistence, since: startTime)
  272. let totalBasal = calculateTotalBasal(from: insulinFromPersistence, since: startTime)
  273. let totalInsulin = totalBolus + totalBasal
  274. return formatInsulinAmount(totalInsulin)
  275. }
  276. private func calculateStartTime(hours: Int) -> Date {
  277. let date = Date()
  278. let calendar = Calendar.current
  279. var offsetComponents = DateComponents()
  280. offsetComponents.hour = -hours
  281. return calendar.date(byAdding: offsetComponents, to: date)!
  282. }
  283. private func calculateTotalBolus(from events: [PumpEventStored], since startTime: Date) -> Double {
  284. let bolusEvents = events.filter { $0.timestamp ?? .distantPast >= startTime && $0.type == PumpEvent.bolus.rawValue }
  285. return bolusEvents.compactMap { $0.bolus?.amount?.doubleValue }.reduce(0, +)
  286. }
  287. private func calculateTotalBasal(from events: [PumpEventStored], since startTime: Date) -> Double {
  288. let basalEvents = events
  289. .filter { $0.timestamp ?? .distantPast >= startTime && $0.type == PumpEvent.tempBasal.rawValue }
  290. .sorted { $0.timestamp ?? .distantPast < $1.timestamp ?? .distantPast }
  291. var basalDurations: [Double] = []
  292. for (index, basalEntry) in basalEvents.enumerated() {
  293. if index + 1 < basalEvents.count {
  294. let nextEntry = basalEvents[index + 1]
  295. let durationInSeconds = nextEntry.timestamp?.timeIntervalSince(basalEntry.timestamp ?? Date()) ?? 0
  296. basalDurations.append(durationInSeconds / 3600) // Conversion to hours
  297. }
  298. }
  299. return zip(basalEvents, basalDurations).map { entry, duration in
  300. guard let rate = entry.tempBasal?.rate?.doubleValue else { return 0 }
  301. return rate * duration
  302. }.reduce(0, +)
  303. }
  304. private func formatInsulinAmount(_ amount: Double) -> String {
  305. let roundedAmount = Decimal(round(100 * amount) / 100)
  306. return roundedAmount.formatted()
  307. }
  308. private func setupPumpSettings() {
  309. DispatchQueue.main.async { [weak self] in
  310. guard let self = self else { return }
  311. self.maxBasal = self.provider.pumpSettings().maxBasal
  312. }
  313. }
  314. private func setupBasalProfile() {
  315. DispatchQueue.main.async { [weak self] in
  316. guard let self = self else { return }
  317. self.autotunedBasalProfile = self.provider.autotunedBasalProfile()
  318. self.basalProfile = self.provider.basalProfile()
  319. }
  320. }
  321. private func setupTempTargets() {
  322. DispatchQueue.main.async { [weak self] in
  323. guard let self = self else { return }
  324. self.manualTempBasal = self.apsManager.isManualTempBasal
  325. self.tempTargets = self.provider.tempTargets(hours: self.filteredHours)
  326. }
  327. }
  328. private func setupAnnouncements() {
  329. DispatchQueue.main.async { [weak self] in
  330. guard let self = self else { return }
  331. self.announcement = self.provider.announcement(self.filteredHours)
  332. }
  333. }
  334. private func setupReservoir() {
  335. DispatchQueue.main.async { [weak self] in
  336. guard let self = self else { return }
  337. self.reservoir = self.provider.pumpReservoir()
  338. }
  339. }
  340. private func setupCurrentTempTarget() {
  341. tempTarget = provider.tempTarget()
  342. }
  343. private func setupCurrentPumpTimezone() {
  344. DispatchQueue.main.async { [weak self] in
  345. guard let self = self else { return }
  346. self.timeZone = self.provider.pumpTimeZone()
  347. }
  348. }
  349. func openCGM() {
  350. router.mainSecondaryModalView.send(router.view(for: .cgmDirect))
  351. }
  352. func infoPanelTTPercentage(_ hbt_: Double, _ target: Decimal) -> Decimal {
  353. guard hbt_ != 0 || target != 0 else {
  354. return 0
  355. }
  356. let c = Decimal(hbt_ - 100)
  357. let ratio = min(c / (target + c - 100), maxValue)
  358. return (ratio * 100)
  359. }
  360. }
  361. }
  362. extension Home.StateModel:
  363. GlucoseObserver,
  364. DeterminationObserver,
  365. SettingsObserver,
  366. PumpSettingsObserver,
  367. BasalProfileObserver,
  368. TempTargetsObserver,
  369. PumpReservoirObserver,
  370. PumpTimeZoneObserver,
  371. PumpDeactivatedObserver
  372. {
  373. // TODO: still needed?
  374. func glucoseDidUpdate(_: [BloodGlucose]) {
  375. // setupGlucose()
  376. }
  377. func determinationDidUpdate(_: Determination) {
  378. waitForSuggestion = false
  379. }
  380. func settingsDidChange(_ settings: FreeAPSSettings) {
  381. allowManualTemp = !settings.closedLoop
  382. closedLoop = settingsManager.settings.closedLoop
  383. units = settingsManager.settings.units
  384. manualTempBasal = apsManager.isManualTempBasal
  385. smooth = settingsManager.settings.smoothGlucose
  386. lowGlucose = settingsManager.settings.low
  387. highGlucose = settingsManager.settings.high
  388. overrideUnit = settingsManager.settings.overrideHbA1cUnit
  389. displayXgridLines = settingsManager.settings.xGridLines
  390. displayYgridLines = settingsManager.settings.yGridLines
  391. thresholdLines = settingsManager.settings.rulerMarks
  392. totalInsulinDisplayType = settingsManager.settings.totalInsulinDisplayType
  393. showCarbsRequiredBadge = settingsManager.settings.showCarbsRequiredBadge
  394. cgmAvailable = (fetchGlucoseManager.cgmGlucoseSourceType != CGMType.none)
  395. displayPumpStatusHighlightMessage()
  396. setupBatteryArray()
  397. }
  398. // TODO: is this ever really triggered? react to MOC changes?
  399. func pumpHistoryDidUpdate(_: [PumpHistoryEvent]) {
  400. displayPumpStatusHighlightMessage()
  401. }
  402. func pumpSettingsDidChange(_: PumpSettings) {
  403. setupPumpSettings()
  404. setupBatteryArray()
  405. }
  406. func basalProfileDidChange(_: [BasalProfileEntry]) {
  407. setupBasalProfile()
  408. }
  409. func tempTargetsDidUpdate(_: [TempTarget]) {
  410. setupTempTargets()
  411. }
  412. func pumpReservoirDidChange(_: Decimal) {
  413. setupReservoir()
  414. displayPumpStatusHighlightMessage()
  415. }
  416. func pumpDeactivatedDidChange() {
  417. displayPumpStatusHighlightMessage(true)
  418. batteryFromPersistence = []
  419. }
  420. func pumpTimeZoneDidChange(_: TimeZone) {
  421. setupCurrentPumpTimezone()
  422. }
  423. }
  424. extension Home.StateModel: CompletionDelegate {
  425. func completionNotifyingDidComplete(_: CompletionNotifying) {
  426. setupPump = false
  427. }
  428. }
  429. extension Home.StateModel: PumpManagerOnboardingDelegate {
  430. func pumpManagerOnboarding(didCreatePumpManager pumpManager: PumpManagerUI) {
  431. provider.apsManager.pumpManager = pumpManager
  432. if let insulinType = pumpManager.status.insulinType {
  433. settingsManager.updateInsulinCurve(insulinType)
  434. }
  435. }
  436. func pumpManagerOnboarding(didOnboardPumpManager _: PumpManagerUI) {
  437. // nothing to do
  438. }
  439. func pumpManagerOnboarding(didPauseOnboarding _: PumpManagerUI) {
  440. // TODO:
  441. }
  442. }
  443. // MARK: - Setup Core Data observation
  444. extension Home.StateModel {
  445. /// listens for the notifications sent when the managedObjectContext has saved!
  446. func setupNotification() {
  447. /// custom notification that is sent when a batch insert of glucose objects is done
  448. Foundation.NotificationCenter.default.addObserver(
  449. self,
  450. selector: #selector(handleBatchInsert),
  451. name: .didPerformBatchInsert,
  452. object: nil
  453. )
  454. /// custom notification that is sent when a batch delete of fpus is done
  455. Foundation.NotificationCenter.default.addObserver(
  456. self,
  457. selector: #selector(handleBatchDelete),
  458. name: .didPerformBatchDelete,
  459. object: nil
  460. )
  461. }
  462. @objc private func handleBatchInsert() {
  463. setupFPUsArray()
  464. setupGlucoseArray()
  465. }
  466. @objc private func handleBatchDelete() {
  467. setupFPUsArray()
  468. }
  469. }
  470. // MARK: - Handle Core Data changes and update Arrays to display them in the UI
  471. extension Home.StateModel {
  472. // Setup Glucose
  473. private func setupGlucoseArray() {
  474. Task {
  475. let ids = await self.fetchGlucose()
  476. await updateGlucoseArray(with: ids)
  477. }
  478. }
  479. private func fetchGlucose() async -> [NSManagedObjectID] {
  480. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  481. ofType: GlucoseStored.self,
  482. onContext: context,
  483. predicate: NSPredicate.glucose,
  484. key: "date",
  485. ascending: false,
  486. fetchLimit: 288
  487. )
  488. return await context.perform {
  489. return results.map(\.objectID)
  490. }
  491. }
  492. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  493. do {
  494. let glucoseObjects = try IDs.compactMap { id in
  495. try viewContext.existingObject(with: id) as? GlucoseStored
  496. }
  497. glucoseFromPersistence = glucoseObjects
  498. } catch {
  499. debugPrint(
  500. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  501. )
  502. }
  503. }
  504. // Setup Manual Glucose
  505. private func setupManualGlucoseArray() {
  506. Task {
  507. let ids = await self.fetchManualGlucose()
  508. await updateManualGlucoseArray(with: ids)
  509. }
  510. }
  511. private func fetchManualGlucose() async -> [NSManagedObjectID] {
  512. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  513. ofType: GlucoseStored.self,
  514. onContext: context,
  515. predicate: NSPredicate.manualGlucose,
  516. key: "date",
  517. ascending: false,
  518. fetchLimit: 288
  519. )
  520. return await context.perform {
  521. return results.map(\.objectID)
  522. }
  523. }
  524. @MainActor private func updateManualGlucoseArray(with IDs: [NSManagedObjectID]) {
  525. do {
  526. let manualGlucoseObjects = try IDs.compactMap { id in
  527. try viewContext.existingObject(with: id) as? GlucoseStored
  528. }
  529. manualGlucoseFromPersistence = manualGlucoseObjects
  530. } catch {
  531. debugPrint(
  532. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the manual glucose array: \(error.localizedDescription)"
  533. )
  534. }
  535. }
  536. // Setup Carbs
  537. private func setupCarbsArray() {
  538. Task {
  539. let ids = await self.fetchCarbs()
  540. await updateCarbsArray(with: ids)
  541. }
  542. }
  543. private func fetchCarbs() async -> [NSManagedObjectID] {
  544. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  545. ofType: CarbEntryStored.self,
  546. onContext: context,
  547. predicate: NSPredicate.carbsForChart,
  548. key: "date",
  549. ascending: false
  550. )
  551. return await context.perform {
  552. return results.map(\.objectID)
  553. }
  554. }
  555. @MainActor private func updateCarbsArray(with IDs: [NSManagedObjectID]) {
  556. do {
  557. let carbObjects = try IDs.compactMap { id in
  558. try viewContext.existingObject(with: id) as? CarbEntryStored
  559. }
  560. carbsFromPersistence = carbObjects
  561. } catch {
  562. debugPrint(
  563. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the carbs array: \(error.localizedDescription)"
  564. )
  565. }
  566. }
  567. // Setup FPUs
  568. private func setupFPUsArray() {
  569. Task {
  570. let ids = await self.fetchFPUs()
  571. await updateFPUsArray(with: ids)
  572. }
  573. }
  574. private func fetchFPUs() async -> [NSManagedObjectID] {
  575. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  576. ofType: CarbEntryStored.self,
  577. onContext: context,
  578. predicate: NSPredicate.fpusForChart,
  579. key: "date",
  580. ascending: false
  581. )
  582. return await context.perform {
  583. return results.map(\.objectID)
  584. }
  585. }
  586. @MainActor private func updateFPUsArray(with IDs: [NSManagedObjectID]) {
  587. do {
  588. let fpuObjects = try IDs.compactMap { id in
  589. try viewContext.existingObject(with: id) as? CarbEntryStored
  590. }
  591. fpusFromPersistence = fpuObjects
  592. } catch {
  593. debugPrint(
  594. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the fpus array: \(error.localizedDescription)"
  595. )
  596. }
  597. }
  598. // Custom fetch to more efficiently filter only for cob and iob
  599. private func fetchCobAndIob() async -> [NSManagedObjectID] {
  600. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  601. ofType: OrefDetermination.self,
  602. onContext: context,
  603. predicate: NSPredicate.determinationsForCobIobCharts,
  604. key: "deliverAt",
  605. ascending: false,
  606. batchSize: 50,
  607. propertiesToFetch: ["cob", "iob", "deliverAt"]
  608. )
  609. return await context.perform {
  610. return results.map(\.objectID)
  611. }
  612. }
  613. // Setup Determinations
  614. private func setupDeterminationsArray() {
  615. Task {
  616. async let enactedObjectIDs = determinationStorage
  617. .fetchLastDeterminationObjectID(predicate: NSPredicate.enactedDetermination)
  618. async let enactedAndNonEnactedObjectIDs = fetchCobAndIob()
  619. let enactedIDs = await enactedObjectIDs
  620. let enactedAndNonEnactedIDs = await enactedAndNonEnactedObjectIDs
  621. async let updateEnacted: () = updateDeterminationsArray(with: enactedIDs, keyPath: \.determinationsFromPersistence)
  622. async let updateEnactedAndNonEnacted: () = updateDeterminationsArray(
  623. with: enactedAndNonEnactedIDs,
  624. keyPath: \.enactedAndNonEnactedDeterminations
  625. )
  626. await updateEnacted
  627. await updateEnactedAndNonEnacted
  628. await updateForecastData()
  629. }
  630. }
  631. @MainActor private func updateDeterminationsArray(
  632. with IDs: [NSManagedObjectID],
  633. keyPath: ReferenceWritableKeyPath<Home.StateModel, [OrefDetermination]>
  634. ) {
  635. do {
  636. let determinationObjects = try IDs.compactMap { id in
  637. try viewContext.existingObject(with: id) as? OrefDetermination
  638. }
  639. self[keyPath: keyPath] = determinationObjects
  640. } catch {
  641. debugPrint(
  642. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  643. )
  644. }
  645. }
  646. // Setup Insulin
  647. private func setupInsulinArray() {
  648. Task {
  649. let ids = await self.fetchInsulin()
  650. await updateInsulinArray(with: ids)
  651. }
  652. }
  653. private func fetchInsulin() async -> [NSManagedObjectID] {
  654. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  655. ofType: PumpEventStored.self,
  656. onContext: context,
  657. predicate: NSPredicate.pumpHistoryLast24h,
  658. key: "timestamp",
  659. ascending: true
  660. )
  661. return await context.perform {
  662. return results.map(\.objectID)
  663. }
  664. }
  665. @MainActor private func updateInsulinArray(with IDs: [NSManagedObjectID]) {
  666. do {
  667. let insulinObjects = try IDs.compactMap { id in
  668. try viewContext.existingObject(with: id) as? PumpEventStored
  669. }
  670. insulinFromPersistence = insulinObjects
  671. // filter tempbasals
  672. manualTempBasal = apsManager.isManualTempBasal
  673. tempBasals = insulinFromPersistence.filter({ $0.tempBasal != nil })
  674. // suspension and resume events
  675. suspensions = insulinFromPersistence
  676. .filter({ $0.type == EventType.pumpSuspend.rawValue || $0.type == EventType.pumpResume.rawValue })
  677. let lastSuspension = suspensions.last
  678. pumpSuspended = tempBasals.last?.timestamp ?? Date() > lastSuspension?.timestamp ?? .distantPast && lastSuspension?
  679. .type == EventType.pumpSuspend
  680. .rawValue
  681. } catch {
  682. debugPrint(
  683. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the insulin array: \(error.localizedDescription)"
  684. )
  685. }
  686. }
  687. // Setup Last Bolus to display the bolus progress bar
  688. // The predicate filters out all external boluses to prevent the progress bar from displaying the amount of an external bolus when an external bolus is added after a pump bolus
  689. private func setupLastBolus() {
  690. Task {
  691. guard let id = await self.fetchLastBolus() else { return }
  692. await updateLastBolus(with: id)
  693. }
  694. }
  695. private func fetchLastBolus() async -> NSManagedObjectID? {
  696. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  697. ofType: PumpEventStored.self,
  698. onContext: context,
  699. predicate: NSPredicate.lastPumpBolus,
  700. key: "timestamp",
  701. ascending: false,
  702. fetchLimit: 1
  703. )
  704. return await context.perform {
  705. return results.map(\.objectID).first
  706. }
  707. }
  708. @MainActor private func updateLastBolus(with ID: NSManagedObjectID) {
  709. do {
  710. lastPumpBolus = try viewContext.existingObject(with: ID) as? PumpEventStored
  711. } catch {
  712. debugPrint(
  713. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the insulin array: \(error.localizedDescription)"
  714. )
  715. }
  716. }
  717. // Setup Battery
  718. private func setupBatteryArray() {
  719. Task {
  720. let ids = await self.fetchBattery()
  721. await updateBatteryArray(with: ids)
  722. }
  723. }
  724. private func fetchBattery() async -> [NSManagedObjectID] {
  725. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  726. ofType: OpenAPS_Battery.self,
  727. onContext: context,
  728. predicate: NSPredicate.predicateFor30MinAgo,
  729. key: "date",
  730. ascending: false
  731. )
  732. return await context.perform {
  733. return results.map(\.objectID)
  734. }
  735. }
  736. @MainActor private func updateBatteryArray(with IDs: [NSManagedObjectID]) {
  737. do {
  738. let batteryObjects = try IDs.compactMap { id in
  739. try viewContext.existingObject(with: id) as? OpenAPS_Battery
  740. }
  741. batteryFromPersistence = batteryObjects
  742. } catch {
  743. debugPrint(
  744. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the battery array: \(error.localizedDescription)"
  745. )
  746. }
  747. }
  748. }
  749. extension Home.StateModel {
  750. // Setup Overrides
  751. private func setupOverrides() {
  752. Task {
  753. let ids = await self.fetchOverrides()
  754. await updateOverrideArray(with: ids)
  755. }
  756. }
  757. private func fetchOverrides() async -> [NSManagedObjectID] {
  758. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  759. ofType: OverrideStored.self,
  760. onContext: context,
  761. predicate: NSPredicate.lastActiveOverride, // this predicate filters for all Overrides within the last 24h
  762. key: "date",
  763. ascending: false
  764. )
  765. return await context.perform {
  766. return results.map(\.objectID)
  767. }
  768. }
  769. @MainActor private func updateOverrideArray(with IDs: [NSManagedObjectID]) {
  770. do {
  771. let overrideObjects = try IDs.compactMap { id in
  772. try viewContext.existingObject(with: id) as? OverrideStored
  773. }
  774. overrides = overrideObjects
  775. } catch {
  776. debugPrint(
  777. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the override array: \(error.localizedDescription)"
  778. )
  779. }
  780. }
  781. @MainActor func calculateDuration(override: OverrideStored) -> TimeInterval {
  782. guard let overrideDuration = override.duration as? Double, overrideDuration != 0 else {
  783. return TimeInterval(60 * 60 * 24) // one day
  784. }
  785. return TimeInterval(overrideDuration * 60) // return seconds
  786. }
  787. @MainActor func calculateTarget(override: OverrideStored) -> Decimal {
  788. guard let overrideTarget = override.target, overrideTarget != 0 else {
  789. return 100 // default
  790. }
  791. return overrideTarget.decimalValue
  792. }
  793. // Setup expired Overrides
  794. private func setupOverrideRunStored() {
  795. Task {
  796. let ids = await self.fetchOverrideRunStored()
  797. await updateOverrideRunStoredArray(with: ids)
  798. }
  799. }
  800. private func fetchOverrideRunStored() async -> [NSManagedObjectID] {
  801. let predicate = NSPredicate(format: "startDate >= %@", Date.oneDayAgo as NSDate)
  802. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  803. ofType: OverrideRunStored.self,
  804. onContext: context,
  805. predicate: predicate,
  806. key: "startDate",
  807. ascending: false
  808. )
  809. return await context.perform {
  810. return results.map(\.objectID)
  811. }
  812. }
  813. @MainActor private func updateOverrideRunStoredArray(with IDs: [NSManagedObjectID]) {
  814. do {
  815. let overrideObjects = try IDs.compactMap { id in
  816. try viewContext.existingObject(with: id) as? OverrideRunStored
  817. }
  818. overrideRunStored = overrideObjects
  819. debugPrint("expiredOverrides: \(DebuggingIdentifiers.inProgress) \(overrideRunStored)")
  820. } catch {
  821. debugPrint(
  822. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the Override Run Stored array: \(error.localizedDescription)"
  823. )
  824. }
  825. }
  826. @MainActor func saveToOverrideRunStored(withID id: NSManagedObjectID) async {
  827. await viewContext.perform {
  828. do {
  829. guard let object = try self.viewContext.existingObject(with: id) as? OverrideStored else { return }
  830. let newOverrideRunStored = OverrideRunStored(context: self.viewContext)
  831. newOverrideRunStored.id = UUID()
  832. newOverrideRunStored.name = object.name
  833. newOverrideRunStored.startDate = object.date ?? .distantPast
  834. newOverrideRunStored.endDate = Date()
  835. newOverrideRunStored.target = NSDecimalNumber(decimal: self.calculateTarget(override: object))
  836. newOverrideRunStored.override = object
  837. newOverrideRunStored.isUploadedToNS = false
  838. } catch {
  839. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to initialize a new Override Run Object")
  840. }
  841. }
  842. }
  843. }
  844. // MARK: Extension for Main Chart to draw Forecasts
  845. extension Home.StateModel {
  846. func preprocessForecastData() async -> [(id: UUID, forecastID: NSManagedObjectID, forecastValueIDs: [NSManagedObjectID])] {
  847. guard let id = determinationsFromPersistence.first?.objectID else {
  848. return []
  849. }
  850. // Get forecast and forecast values
  851. let forecastIDs = await determinationStorage.getForecastIDs(for: id, in: context)
  852. var result: [(id: UUID, forecastID: NSManagedObjectID, forecastValueIDs: [NSManagedObjectID])] = []
  853. for forecastID in forecastIDs {
  854. // Get the forecast value IDs for the given forecast ID
  855. let forecastValueIDs = await determinationStorage.getForecastValueIDs(for: forecastID, in: context)
  856. let uuid = UUID()
  857. result.append((id: uuid, forecastID: forecastID, forecastValueIDs: forecastValueIDs))
  858. }
  859. return result
  860. }
  861. @MainActor func updateForecastData() async {
  862. let forecastData = await preprocessForecastData()
  863. preprocessedData = forecastData.reduce(into: []) { result, data in
  864. guard let forecast = try? viewContext.existingObject(with: data.forecastID) as? Forecast else {
  865. return
  866. }
  867. for forecastValueID in data.forecastValueIDs {
  868. if let forecastValue = try? viewContext.existingObject(with: forecastValueID) as? ForecastValue {
  869. result.append((id: data.id, forecast: forecast, forecastValue: forecastValue))
  870. }
  871. }
  872. }
  873. }
  874. }