BolusStateModel.swift 29 KB

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