BolusStateModel.swift 29 KB

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