BolusStateModel.swift 29 KB

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