TreatmentsStateModel.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import LoopKit
  5. import Observation
  6. import SwiftUI
  7. import Swinject
  8. extension Treatments {
  9. @Observable final class StateModel: BaseStateModel<Provider> {
  10. @ObservationIgnored @Injected() var unlockmanager: UnlockManager!
  11. @ObservationIgnored @Injected() var apsManager: APSManager!
  12. @ObservationIgnored @Injected() var broadcaster: Broadcaster!
  13. @ObservationIgnored @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  14. @ObservationIgnored @Injected() var settings: SettingsManager!
  15. @ObservationIgnored @Injected() var nsManager: NightscoutManager!
  16. @ObservationIgnored @Injected() var carbsStorage: CarbsStorage!
  17. @ObservationIgnored @Injected() var glucoseStorage: GlucoseStorage!
  18. @ObservationIgnored @Injected() var determinationStorage: DeterminationStorage!
  19. var lowGlucose: Decimal = 70
  20. var highGlucose: Decimal = 180
  21. var glucoseColorScheme: GlucoseColorScheme = .staticColor
  22. var predictions: Predictions?
  23. var amount: Decimal = 0
  24. var insulinRecommended: Decimal = 0
  25. var insulinRequired: Decimal = 0
  26. var units: GlucoseUnits = .mgdL
  27. var threshold: Decimal = 0
  28. var maxBolus: Decimal = 0
  29. var maxExternal: Decimal { maxBolus * 3 }
  30. var errorString: Decimal = 0
  31. var evBG: Decimal = 0
  32. var insulin: Decimal = 0
  33. var isf: Decimal = 0
  34. var error: Bool = false
  35. var minGuardBG: Decimal = 0
  36. var minDelta: Decimal = 0
  37. var expectedDelta: Decimal = 0
  38. var minPredBG: Decimal = 0
  39. var waitForSuggestion: Bool = false
  40. var carbRatio: Decimal = 0
  41. var addButtonPressed: Bool = false
  42. var waitForSuggestionInitial: Bool = false
  43. var target: Decimal = 0
  44. var cob: Int16 = 0
  45. var iob: Decimal = 0
  46. var currentBG: Decimal = 0
  47. var fifteenMinInsulin: Decimal = 0
  48. var deltaBG: Decimal = 0
  49. var targetDifferenceInsulin: Decimal = 0
  50. var targetDifference: Decimal = 0
  51. var wholeCob: Decimal = 0
  52. var wholeCobInsulin: Decimal = 0
  53. var iobInsulinReduction: Decimal = 0
  54. var wholeCalc: Decimal = 0
  55. var insulinCalculated: Decimal = 0
  56. var fraction: Decimal = 0
  57. var basal: Decimal = 0
  58. var fattyMeals: Bool = false
  59. var fattyMealFactor: Decimal = 0
  60. var useFattyMealCorrectionFactor: Bool = false
  61. var displayPresets: Bool = true
  62. var currentBasal: Decimal = 0
  63. var currentCarbRatio: Decimal = 0
  64. var currentBGTarget: Decimal = 0
  65. var currentISF: Decimal = 0
  66. var sweetMeals: Bool = false
  67. var sweetMealFactor: Decimal = 0
  68. var useSuperBolus: Bool = false
  69. var superBolusInsulin: Decimal = 0
  70. var meal: [CarbsEntry]?
  71. var carbs: Decimal = 0
  72. var fat: Decimal = 0
  73. var protein: Decimal = 0
  74. var note: String = ""
  75. var date = Date()
  76. var carbsRequired: Decimal?
  77. var useFPUconversion: Bool = false
  78. var dish: String = ""
  79. var selection: MealPresetStored?
  80. var summation: [String] = []
  81. var maxCarbs: Decimal = 0
  82. var maxFat: Decimal = 0
  83. var maxProtein: Decimal = 0
  84. var id_: String = ""
  85. var summary: String = ""
  86. var externalInsulin: Bool = false
  87. var showInfo: Bool = false
  88. var glucoseFromPersistence: [GlucoseStored] = []
  89. var determination: [OrefDetermination] = []
  90. var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  91. var predictionsForChart: Predictions?
  92. var simulatedDetermination: Determination?
  93. @MainActor var determinationObjectIDs: [NSManagedObjectID] = []
  94. var minForecast: [Int] = []
  95. var maxForecast: [Int] = []
  96. @MainActor var minCount: Int = 12 // count of Forecasts drawn in 5 min distances, i.e. 12 means a min of 1 hour
  97. var forecastDisplayType: ForecastDisplayType = .cone
  98. var isSmoothingEnabled: Bool = false
  99. var stops: [Gradient.Stop] = []
  100. let now = Date.now
  101. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  102. let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
  103. let determinationFetchContext = CoreDataStack.shared.newTaskContext()
  104. var isActive: Bool = false
  105. private var coreDataPublisher: AnyPublisher<Set<NSManagedObject>, Never>?
  106. private var subscriptions = Set<AnyCancellable>()
  107. typealias PumpEvent = PumpEventStored.EventType
  108. var isBolusInProgress: Bool = false
  109. private var bolusProgressCancellable: AnyCancellable?
  110. func unsubscribe() {
  111. subscriptions.forEach { $0.cancel() }
  112. subscriptions.removeAll()
  113. }
  114. override func subscribe() {
  115. guard isActive else {
  116. return
  117. }
  118. debug(.bolusState, "subscribe fired")
  119. coreDataPublisher =
  120. changedObjectsOnManagedObjectContextDidSavePublisher()
  121. .receive(on: DispatchQueue.global(qos: .background))
  122. .share()
  123. .eraseToAnyPublisher()
  124. registerHandlers()
  125. registerSubscribers()
  126. setupBolusStateConcurrently()
  127. subscribeToBolusProgress()
  128. }
  129. deinit {
  130. // Unregister from broadcaster
  131. broadcaster.unregister(DeterminationObserver.self, observer: self)
  132. broadcaster.unregister(BolusFailureObserver.self, observer: self)
  133. // Cancel Combine subscriptions
  134. unsubscribe()
  135. bolusProgressCancellable?.cancel()
  136. debug(.bolusState, "Bolus.StateModel deinitialized")
  137. }
  138. private func setupBolusStateConcurrently() {
  139. debug(.bolusState, "setupBolusStateConcurrently fired")
  140. Task {
  141. await withTaskGroup(of: Void.self) { group in
  142. group.addTask {
  143. self.setupGlucoseArray()
  144. }
  145. group.addTask {
  146. self.setupDeterminationsAndForecasts()
  147. }
  148. group.addTask {
  149. await self.setupSettings()
  150. }
  151. group.addTask {
  152. self.registerObservers()
  153. }
  154. if self.waitForSuggestionInitial {
  155. group.addTask {
  156. let isDetermineBasalSuccessful = await self.apsManager.determineBasal()
  157. if !isDetermineBasalSuccessful {
  158. await MainActor.run {
  159. self.waitForSuggestion = false
  160. self.insulinRequired = 0
  161. self.insulinRecommended = 0
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. }
  169. /// Observes changes to the `bolusProgress` published by the `apsManager` to update the `isBolusInProgress` property in real time.
  170. ///
  171. /// - Important:
  172. /// - `apsManager.bolusProgress` is a `CurrentValueSubject<Decimal?, Never>`.
  173. /// - When a bolus starts, this subject emits `0` (or a fraction like `0.1, 0.5, etc.`).
  174. /// - When the bolus finishes, the subject is typically set to `nil`.
  175. /// - This treats ANY non-nil value as “bolus in progress.”
  176. ///
  177. private func subscribeToBolusProgress() {
  178. bolusProgressCancellable = apsManager.bolusProgress
  179. .receive(on: DispatchQueue.main)
  180. .sink { [weak self] progressValue in
  181. guard let self = self else { return }
  182. // If progressValue is non-nil, a bolus is in progress.
  183. self.isBolusInProgress = (progressValue != nil)
  184. }
  185. }
  186. // MARK: - Basal
  187. private enum SettingType {
  188. case basal
  189. case carbRatio
  190. case bgTarget
  191. case isf
  192. }
  193. func getAllSettingsValues() async {
  194. await withTaskGroup(of: Void.self) { group in
  195. group.addTask {
  196. await self.getCurrentSettingValue(for: .basal)
  197. }
  198. group.addTask {
  199. await self.getCurrentSettingValue(for: .carbRatio)
  200. }
  201. group.addTask {
  202. await self.getCurrentSettingValue(for: .bgTarget)
  203. }
  204. group.addTask {
  205. await self.getCurrentSettingValue(for: .isf)
  206. }
  207. group.addTask {
  208. let getMaxBolus = await self.provider.getPumpSettings().maxBolus
  209. await MainActor.run {
  210. self.maxBolus = getMaxBolus
  211. }
  212. }
  213. }
  214. }
  215. private func setupDeterminationsAndForecasts() {
  216. Task {
  217. async let getAllSettingsDefaults: () = getAllSettingsValues()
  218. async let setupDeterminations: () = setupDeterminationsArray()
  219. await getAllSettingsDefaults
  220. await setupDeterminations
  221. // Determination has updated, so we can use this to draw the initial Forecast Chart
  222. let forecastData = await mapForecastsForChart()
  223. await updateForecasts(with: forecastData)
  224. }
  225. }
  226. private func registerObservers() {
  227. broadcaster.register(DeterminationObserver.self, observer: self)
  228. broadcaster.register(BolusFailureObserver.self, observer: self)
  229. }
  230. @MainActor private func setupSettings() async {
  231. units = settingsManager.settings.units
  232. fraction = settings.settings.overrideFactor
  233. fattyMeals = settings.settings.fattyMeals
  234. fattyMealFactor = settings.settings.fattyMealFactor
  235. sweetMeals = settings.settings.sweetMeals
  236. sweetMealFactor = settings.settings.sweetMealFactor
  237. displayPresets = settings.settings.displayPresets
  238. forecastDisplayType = settings.settings.forecastDisplayType
  239. lowGlucose = settingsManager.settings.low
  240. highGlucose = settingsManager.settings.high
  241. maxCarbs = settings.settings.maxCarbs
  242. maxFat = settings.settings.maxFat
  243. maxProtein = settings.settings.maxProtein
  244. useFPUconversion = settingsManager.settings.useFPUconversion
  245. isSmoothingEnabled = settingsManager.settings.smoothGlucose
  246. glucoseColorScheme = settingsManager.settings.glucoseColorScheme
  247. }
  248. private func getCurrentSettingValue(for type: SettingType) async {
  249. let now = Date()
  250. let calendar = Calendar.current
  251. let dateFormatter = DateFormatter()
  252. dateFormatter.timeZone = TimeZone.current
  253. let regexWithSeconds = #"^\d{2}:\d{2}:\d{2}$"#
  254. let entries: [(start: String, value: Decimal)]
  255. switch type {
  256. case .basal:
  257. let basalEntries = await provider.getBasalProfile()
  258. entries = basalEntries.map { ($0.start, $0.rate) }
  259. case .carbRatio:
  260. let carbRatios = await provider.getCarbRatios()
  261. entries = carbRatios.schedule.map { ($0.start, $0.ratio) }
  262. case .bgTarget:
  263. let bgTargets = await provider.getBGTarget()
  264. entries = bgTargets.targets.map { ($0.start, $0.low) }
  265. case .isf:
  266. let isfValues = await provider.getISFValues()
  267. entries = isfValues.sensitivities.map { ($0.start, $0.sensitivity) }
  268. }
  269. for (index, entry) in entries.enumerated() {
  270. // Dynamically set the format based on whether it matches the regex
  271. if entry.start.range(of: regexWithSeconds, options: .regularExpression) != nil {
  272. dateFormatter.dateFormat = "HH:mm:ss"
  273. } else {
  274. dateFormatter.dateFormat = "HH:mm"
  275. }
  276. guard let entryTime = dateFormatter.date(from: entry.start) else {
  277. print("Invalid entry start time: \(entry.start)")
  278. continue
  279. }
  280. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  281. let entryStartTime = calendar.date(
  282. bySettingHour: entryComponents.hour!,
  283. minute: entryComponents.minute!,
  284. second: entryComponents.second ?? 0, // Set seconds to 0 if not provided
  285. of: now
  286. )!
  287. let entryEndTime: Date
  288. if index < entries.count - 1 {
  289. // Dynamically set the format again for the next element
  290. if entries[index + 1].start.range(of: regexWithSeconds, options: .regularExpression) != nil {
  291. dateFormatter.dateFormat = "HH:mm:ss"
  292. } else {
  293. dateFormatter.dateFormat = "HH:mm"
  294. }
  295. if let nextEntryTime = dateFormatter.date(from: entries[index + 1].start) {
  296. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  297. entryEndTime = calendar.date(
  298. bySettingHour: nextEntryComponents.hour!,
  299. minute: nextEntryComponents.minute!,
  300. second: nextEntryComponents.second ?? 0,
  301. of: now
  302. )!
  303. } else {
  304. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  305. }
  306. } else {
  307. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  308. }
  309. if now >= entryStartTime, now < entryEndTime {
  310. await MainActor.run {
  311. switch type {
  312. case .basal:
  313. currentBasal = entry.value
  314. case .carbRatio:
  315. currentCarbRatio = entry.value
  316. case .bgTarget:
  317. currentBGTarget = entry.value
  318. case .isf:
  319. currentISF = entry.value
  320. }
  321. }
  322. return
  323. }
  324. }
  325. }
  326. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  327. /// Calculate insulin recommendation
  328. func calculateInsulin() -> Decimal {
  329. debug(.bolusState, "calculateInsulin fired")
  330. let isfForCalculation = isf
  331. // insulin needed for the current blood glucose
  332. targetDifference = currentBG - target
  333. targetDifferenceInsulin = targetDifference / isfForCalculation
  334. // more or less insulin because of bg trend in the last 15 minutes
  335. fifteenMinInsulin = deltaBG / isfForCalculation
  336. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  337. wholeCob = Decimal(cob) + carbs
  338. wholeCobInsulin = wholeCob / carbRatio
  339. // determine how much the calculator reduces/ increases the bolus because of IOB
  340. iobInsulinReduction = (-1) * iob
  341. // adding everything together
  342. // add a calc for the case that no fifteenMinInsulin is available
  343. if deltaBG != 0 {
  344. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  345. } else {
  346. // add (rare) case that no glucose value is available -> maybe display warning?
  347. // if no bg is available, ?? sets its value to 0
  348. if currentBG == 0 {
  349. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  350. } else {
  351. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  352. }
  353. }
  354. // apply custom factor at the end of the calculations
  355. let result = wholeCalc * fraction
  356. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  357. if useFattyMealCorrectionFactor {
  358. insulinCalculated = result * fattyMealFactor
  359. } else if useSuperBolus {
  360. superBolusInsulin = sweetMealFactor * currentBasal
  361. insulinCalculated = result + superBolusInsulin
  362. } else {
  363. insulinCalculated = result
  364. }
  365. // display no negative insulinCalculated
  366. insulinCalculated = max(insulinCalculated, 0)
  367. insulinCalculated = min(insulinCalculated, maxBolus)
  368. guard let apsManager = apsManager else {
  369. return insulinCalculated
  370. }
  371. return apsManager.roundBolus(amount: insulinCalculated)
  372. }
  373. // MARK: - Button tasks
  374. func invokeTreatmentsTask() {
  375. Task {
  376. debug(.bolusState, "invokeTreatmentsTask fired")
  377. await MainActor.run {
  378. self.addButtonPressed = true
  379. }
  380. let isInsulinGiven = amount > 0
  381. let isCarbsPresent = carbs > 0
  382. let isFatPresent = fat > 0
  383. let isProteinPresent = protein > 0
  384. if isInsulinGiven {
  385. try await handleInsulin(isExternal: externalInsulin)
  386. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  387. await MainActor.run {
  388. self.waitForSuggestion = true
  389. }
  390. } else {
  391. hideModal()
  392. return
  393. }
  394. await saveMeal()
  395. // If glucose data is stale end the custom loading animation by hiding the modal
  396. // Get date on Main thread
  397. let date = await MainActor.run {
  398. glucoseFromPersistence.first?.date
  399. }
  400. guard glucoseStorage.isGlucoseDataFresh(date) else {
  401. await MainActor.run {
  402. waitForSuggestion = false
  403. }
  404. return hideModal()
  405. }
  406. }
  407. }
  408. // MARK: - Insulin
  409. private func handleInsulin(isExternal: Bool) async throws {
  410. debug(.bolusState, "handleInsulin fired")
  411. if !isExternal {
  412. await addPumpInsulin()
  413. } else {
  414. await addExternalInsulin()
  415. }
  416. await MainActor.run {
  417. self.waitForSuggestion = true
  418. }
  419. }
  420. func addPumpInsulin() async {
  421. guard amount > 0 else {
  422. showModal(for: nil)
  423. return
  424. }
  425. let maxAmount = Double(min(amount, maxBolus))
  426. do {
  427. let authenticated = try await unlockmanager.unlock()
  428. if authenticated {
  429. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  430. } else {
  431. print("authentication failed")
  432. }
  433. } catch {
  434. print("authentication error for pump bolus: \(error.localizedDescription)")
  435. await MainActor.run {
  436. self.waitForSuggestion = false
  437. if self.addButtonPressed {
  438. self.hideModal()
  439. }
  440. }
  441. }
  442. }
  443. // MARK: - EXTERNAL INSULIN
  444. func addExternalInsulin() async {
  445. guard amount > 0 else {
  446. showModal(for: nil)
  447. return
  448. }
  449. await MainActor.run {
  450. self.amount = min(self.amount, self.maxBolus * 3)
  451. }
  452. do {
  453. let authenticated = try await unlockmanager.unlock()
  454. if authenticated {
  455. // store external dose to pump history
  456. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  457. // perform determine basal sync
  458. await apsManager.determineBasalSync()
  459. } else {
  460. print("authentication failed")
  461. }
  462. } catch {
  463. print("authentication error for external insulin: \(error.localizedDescription)")
  464. await MainActor.run {
  465. self.waitForSuggestion = false
  466. if self.addButtonPressed {
  467. self.hideModal()
  468. }
  469. }
  470. }
  471. }
  472. // MARK: - Carbs
  473. func saveMeal() async {
  474. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  475. await MainActor.run {
  476. self.carbs = min(self.carbs, self.maxCarbs)
  477. self.fat = min(self.fat, self.maxFat)
  478. self.protein = min(self.protein, self.maxProtein)
  479. self.id_ = UUID().uuidString
  480. }
  481. let carbsToStore = [CarbsEntry(
  482. id: id_,
  483. createdAt: now,
  484. actualDate: date,
  485. carbs: carbs,
  486. fat: fat,
  487. protein: protein,
  488. note: note,
  489. enteredBy: CarbsEntry.local,
  490. isFPU: false, fpuID: UUID().uuidString
  491. )]
  492. await carbsStorage.storeCarbs(carbsToStore, areFetchedFromRemote: false)
  493. if carbs > 0 || fat > 0 || protein > 0 {
  494. // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
  495. if amount <= 0 {
  496. await apsManager.determineBasalSync()
  497. }
  498. }
  499. }
  500. // MARK: - Presets
  501. func deletePreset() {
  502. if selection != nil {
  503. viewContext.delete(selection!)
  504. do {
  505. guard viewContext.hasChanges else { return }
  506. try viewContext.save()
  507. } catch {
  508. print(error.localizedDescription)
  509. }
  510. carbs = 0
  511. fat = 0
  512. protein = 0
  513. }
  514. selection = nil
  515. }
  516. func removePresetFromNewMeal() {
  517. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  518. if a != nil, summation[a ?? 0] != "" {
  519. summation.remove(at: a!)
  520. }
  521. }
  522. func addPresetToNewMeal() {
  523. let test: String = selection?.dish ?? "dontAdd"
  524. if test != "dontAdd" {
  525. summation.append(test)
  526. }
  527. }
  528. func addNewPresetToWaitersNotepad(_ dish: String) {
  529. summation.append(dish)
  530. }
  531. func addToSummation() {
  532. summation.append(selection?.dish ?? "")
  533. }
  534. }
  535. }
  536. extension Treatments.StateModel: DeterminationObserver, BolusFailureObserver {
  537. func determinationDidUpdate(_: Determination) {
  538. guard isActive else {
  539. debug(.bolusState, "skipping determinationDidUpdate; view not active")
  540. return
  541. }
  542. DispatchQueue.main.async {
  543. debug(.bolusState, "determinationDidUpdate fired")
  544. self.waitForSuggestion = false
  545. if self.addButtonPressed {
  546. self.hideModal()
  547. }
  548. }
  549. }
  550. func bolusDidFail() {
  551. DispatchQueue.main.async {
  552. debug(.bolusState, "bolusDidFail fired")
  553. self.waitForSuggestion = false
  554. if self.addButtonPressed {
  555. self.hideModal()
  556. }
  557. }
  558. }
  559. }
  560. extension Treatments.StateModel {
  561. private func registerHandlers() {
  562. coreDataPublisher?.filterByEntityName("OrefDetermination").sink { [weak self] _ in
  563. guard let self = self else { return }
  564. Task {
  565. await self.setupDeterminationsArray()
  566. let forecastData = await self.mapForecastsForChart()
  567. await self.updateForecasts(with: forecastData)
  568. }
  569. }.store(in: &subscriptions)
  570. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  571. coreDataPublisher?.filterByEntityName("GlucoseStored").sink { [weak self] _ in
  572. guard let self = self else { return }
  573. self.setupGlucoseArray()
  574. }.store(in: &subscriptions)
  575. }
  576. private func registerSubscribers() {
  577. glucoseStorage.updatePublisher
  578. .receive(on: DispatchQueue.global(qos: .background))
  579. .sink { [weak self] _ in
  580. guard let self = self else { return }
  581. self.setupGlucoseArray()
  582. }
  583. .store(in: &subscriptions)
  584. }
  585. }
  586. // MARK: - Setup Glucose and Determinations
  587. extension Treatments.StateModel {
  588. // Glucose
  589. private func setupGlucoseArray() {
  590. Task {
  591. let ids = await self.fetchGlucose()
  592. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  593. await updateGlucoseArray(with: glucoseObjects)
  594. }
  595. }
  596. private func fetchGlucose() async -> [NSManagedObjectID] {
  597. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  598. ofType: GlucoseStored.self,
  599. onContext: glucoseFetchContext,
  600. predicate: NSPredicate.glucose,
  601. key: "date",
  602. ascending: false,
  603. fetchLimit: 288
  604. )
  605. return await glucoseFetchContext.perform {
  606. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  607. return fetchedResults.map(\.objectID)
  608. }
  609. }
  610. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  611. glucoseFromPersistence = objects
  612. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  613. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  614. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  615. currentBG = Decimal(lastGlucose)
  616. deltaBG = delta
  617. }
  618. // Determinations
  619. private func setupDeterminationsArray() async {
  620. // Fetch object IDs on a background thread
  621. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  622. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  623. )
  624. // Update determinationObjectIDs on the main thread
  625. await MainActor.run {
  626. determinationObjectIDs = fetchedObjectIDs
  627. }
  628. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  629. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  630. await updateDeterminationsArray(with: determinationObjects)
  631. }
  632. private func mapForecastsForChart() async -> Determination? {
  633. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  634. .getNSManagedObject(with: determinationObjectIDs, context: determinationFetchContext)
  635. return await determinationFetchContext.perform {
  636. guard let determinationObject = determinationObjects.first else {
  637. return nil
  638. }
  639. let eventualBG = determinationObject.eventualBG?.intValue
  640. let forecastsSet = determinationObject.forecasts ?? []
  641. let predictions = Predictions(
  642. iob: forecastsSet.extractValues(for: "iob"),
  643. zt: forecastsSet.extractValues(for: "zt"),
  644. cob: forecastsSet.extractValues(for: "cob"),
  645. uam: forecastsSet.extractValues(for: "uam")
  646. )
  647. return Determination(
  648. id: UUID(),
  649. reason: "",
  650. units: 0,
  651. insulinReq: 0,
  652. eventualBG: eventualBG,
  653. sensitivityRatio: 0,
  654. rate: 0,
  655. duration: 0,
  656. iob: 0,
  657. cob: 0,
  658. predictions: predictions.isEmpty ? nil : predictions,
  659. carbsReq: 0,
  660. temp: nil,
  661. bg: 0,
  662. reservoir: 0,
  663. isf: 0,
  664. tdd: 0,
  665. insulin: nil,
  666. current_target: 0,
  667. insulinForManualBolus: 0,
  668. manualBolusErrorString: 0,
  669. minDelta: 0,
  670. expectedDelta: 0,
  671. minGuardBG: 0,
  672. minPredBG: 0,
  673. threshold: 0,
  674. carbRatio: 0,
  675. received: false
  676. )
  677. }
  678. }
  679. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  680. guard let mostRecentDetermination = objects.first else { return }
  681. determination = objects
  682. // setup vars for bolus calculation
  683. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  684. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  685. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  686. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  687. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  688. cob = mostRecentDetermination.cob as Int16
  689. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  690. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  691. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  692. insulinCalculated = calculateInsulin()
  693. }
  694. }
  695. extension Treatments.StateModel {
  696. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  697. guard isActive else {
  698. return
  699. debug(.bolusState, "updateForecasts not fired")
  700. }
  701. debug(.bolusState, "updateForecasts fired")
  702. if let forecastData = forecastData {
  703. simulatedDetermination = forecastData
  704. } else {
  705. simulatedDetermination = await Task { [self] in
  706. debug(.bolusState, "calling simulateDetermineBasal to get forecast data")
  707. return await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  708. }.value
  709. }
  710. predictionsForChart = simulatedDetermination?.predictions
  711. let nonEmptyArrays = [
  712. predictionsForChart?.iob,
  713. predictionsForChart?.zt,
  714. predictionsForChart?.cob,
  715. predictionsForChart?.uam
  716. ]
  717. .compactMap { $0 }
  718. .filter { !$0.isEmpty }
  719. guard !nonEmptyArrays.isEmpty else {
  720. minForecast = []
  721. maxForecast = []
  722. return
  723. }
  724. minCount = max(12, nonEmptyArrays.map(\.count).min() ?? 0)
  725. guard minCount > 0 else { return }
  726. async let minForecastResult = Task {
  727. await (0 ..< self.minCount).map { index in
  728. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  729. }
  730. }.value
  731. async let maxForecastResult = Task {
  732. await (0 ..< self.minCount).map { index in
  733. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  734. }
  735. }.value
  736. minForecast = await minForecastResult
  737. maxForecast = await maxForecastResult
  738. }
  739. }
  740. private extension Set where Element == Forecast {
  741. func extractValues(for type: String) -> [Int]? {
  742. let values = first { $0.type == type }?
  743. .forecastValues?
  744. .sorted { $0.index < $1.index }
  745. .compactMap { Int($0.value) }
  746. return values?.isEmpty ?? true ? nil : values
  747. }
  748. }
  749. private extension Predictions {
  750. var isEmpty: Bool {
  751. iob == nil && zt == nil && cob == nil && uam == nil
  752. }
  753. }