BolusStateModel.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. if self.waitForSuggestionInitial {
  123. group.addTask {
  124. let ok = await self.apsManager.determineBasal()
  125. if !ok {
  126. await MainActor.run {
  127. self.waitForSuggestion = false
  128. self.insulinRequired = 0
  129. self.insulinRecommended = 0
  130. }
  131. }
  132. }
  133. }
  134. }
  135. }
  136. }
  137. // MARK: - Basal
  138. private enum SettingType {
  139. case basal
  140. case carbRatio
  141. case bgTarget
  142. case isf
  143. }
  144. func getAllSettingsValues() async {
  145. await withTaskGroup(of: Void.self) { group in
  146. group.addTask {
  147. await self.getCurrentSettingValue(for: .basal)
  148. }
  149. group.addTask {
  150. await self.getCurrentSettingValue(for: .carbRatio)
  151. }
  152. group.addTask {
  153. await self.getCurrentSettingValue(for: .bgTarget)
  154. }
  155. group.addTask {
  156. await self.getCurrentSettingValue(for: .isf)
  157. }
  158. group.addTask {
  159. let getMaxBolus = await self.provider.getPumpSettings().maxBolus
  160. await MainActor.run {
  161. self.maxBolus = getMaxBolus
  162. }
  163. }
  164. }
  165. }
  166. private func setupDeterminationsAndForecasts() {
  167. Task {
  168. async let getAllSettingsDefaults: () = getAllSettingsValues()
  169. async let setupDeterminations: () = setupDeterminationsArray()
  170. await getAllSettingsDefaults
  171. await setupDeterminations
  172. // Determination has updated, so we can use this to draw the initial Forecast Chart
  173. let forecastData = await mapForecastsForChart()
  174. await updateForecasts(with: forecastData)
  175. }
  176. }
  177. private func setupObservers() {
  178. broadcaster.register(DeterminationObserver.self, observer: self)
  179. broadcaster.register(BolusFailureObserver.self, observer: self)
  180. }
  181. @MainActor private func setupSettings() async {
  182. units = settingsManager.settings.units
  183. fraction = settings.settings.overrideFactor
  184. fattyMeals = settings.settings.fattyMeals
  185. fattyMealFactor = settings.settings.fattyMealFactor
  186. sweetMeals = settings.settings.sweetMeals
  187. sweetMealFactor = settings.settings.sweetMealFactor
  188. displayPresets = settings.settings.displayPresets
  189. forecastDisplayType = settings.settings.forecastDisplayType
  190. lowGlucose = units == .mgdL ? settingsManager.settings.low : settingsManager.settings.low.asMmolL
  191. highGlucose = units == .mgdL ? settingsManager.settings.high : settingsManager.settings.high.asMmolL
  192. maxCarbs = settings.settings.maxCarbs
  193. maxFat = settings.settings.maxFat
  194. maxProtein = settings.settings.maxProtein
  195. useFPUconversion = settingsManager.settings.useFPUconversion
  196. smooth = settingsManager.settings.smoothGlucose
  197. }
  198. private func getCurrentSettingValue(for type: SettingType) async {
  199. let now = Date()
  200. let calendar = Calendar.current
  201. let dateFormatter = DateFormatter()
  202. dateFormatter.dateFormat = "HH:mm:ss"
  203. dateFormatter.timeZone = TimeZone.current
  204. let entries: [(start: String, value: Decimal)]
  205. switch type {
  206. case .basal:
  207. let basalEntries = await provider.getBasalProfile()
  208. entries = basalEntries.map { ($0.start, $0.rate) }
  209. case .carbRatio:
  210. let carbRatios = await provider.getCarbRatios()
  211. entries = carbRatios.schedule.map { ($0.start, $0.ratio) }
  212. case .bgTarget:
  213. let bgTargets = await provider.getBGTarget()
  214. entries = bgTargets.targets.map { ($0.start, $0.low) }
  215. case .isf:
  216. let isfValues = await provider.getISFValues()
  217. entries = isfValues.sensitivities.map { ($0.start, $0.sensitivity) }
  218. }
  219. for (index, entry) in entries.enumerated() {
  220. guard let entryTime = dateFormatter.date(from: entry.start) else {
  221. print("Invalid entry start time: \(entry.start)")
  222. continue
  223. }
  224. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  225. let entryStartTime = calendar.date(
  226. bySettingHour: entryComponents.hour!,
  227. minute: entryComponents.minute!,
  228. second: entryComponents.second!,
  229. of: now
  230. )!
  231. let entryEndTime: Date
  232. if index < entries.count - 1,
  233. let nextEntryTime = dateFormatter.date(from: entries[index + 1].start)
  234. {
  235. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  236. entryEndTime = calendar.date(
  237. bySettingHour: nextEntryComponents.hour!,
  238. minute: nextEntryComponents.minute!,
  239. second: nextEntryComponents.second!,
  240. of: now
  241. )!
  242. } else {
  243. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  244. }
  245. if now >= entryStartTime, now < entryEndTime {
  246. await MainActor.run {
  247. switch type {
  248. case .basal:
  249. currentBasal = entry.value
  250. case .carbRatio:
  251. currentCarbRatio = entry.value
  252. case .bgTarget:
  253. currentBGTarget = entry.value
  254. case .isf:
  255. currentISF = entry.value
  256. }
  257. }
  258. return
  259. }
  260. }
  261. }
  262. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  263. /// Calculate insulin recommendation
  264. func calculateInsulin() -> Decimal {
  265. let isfForCalculation = units == .mmolL ? isf.asMgdL : isf
  266. // insulin needed for the current blood glucose
  267. targetDifference = currentBG - target
  268. targetDifferenceInsulin = targetDifference / isfForCalculation
  269. // more or less insulin because of bg trend in the last 15 minutes
  270. fifteenMinInsulin = deltaBG / isfForCalculation
  271. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  272. wholeCob = Decimal(cob) + carbs
  273. wholeCobInsulin = wholeCob / carbRatio
  274. // determine how much the calculator reduces/ increases the bolus because of IOB
  275. iobInsulinReduction = (-1) * iob
  276. // adding everything together
  277. // add a calc for the case that no fifteenMinInsulin is available
  278. if deltaBG != 0 {
  279. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  280. } else {
  281. // add (rare) case that no glucose value is available -> maybe display warning?
  282. // if no bg is available, ?? sets its value to 0
  283. if currentBG == 0 {
  284. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  285. } else {
  286. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  287. }
  288. }
  289. // apply custom factor at the end of the calculations
  290. let result = wholeCalc * fraction
  291. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  292. if useFattyMealCorrectionFactor {
  293. insulinCalculated = result * fattyMealFactor
  294. } else if useSuperBolus {
  295. superBolusInsulin = sweetMealFactor * currentBasal
  296. insulinCalculated = result + superBolusInsulin
  297. } else {
  298. insulinCalculated = result
  299. }
  300. // display no negative insulinCalculated
  301. insulinCalculated = max(insulinCalculated, 0)
  302. insulinCalculated = min(insulinCalculated, maxBolus)
  303. guard let apsManager = apsManager else {
  304. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  305. return insulinCalculated
  306. }
  307. return apsManager.roundBolus(amount: insulinCalculated)
  308. }
  309. // MARK: - Button tasks
  310. func invokeTreatmentsTask() {
  311. Task {
  312. await MainActor.run {
  313. self.addButtonPressed = true
  314. }
  315. let isInsulinGiven = amount > 0
  316. let isCarbsPresent = carbs > 0
  317. let isFatPresent = fat > 0
  318. let isProteinPresent = protein > 0
  319. if isInsulinGiven {
  320. try await handleInsulin(isExternal: externalInsulin)
  321. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  322. await MainActor.run {
  323. self.waitForSuggestion = true
  324. }
  325. } else {
  326. hideModal()
  327. return
  328. }
  329. await saveMeal()
  330. // if glucose data is stale end the custom loading animation by hiding the modal
  331. guard glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  332. waitForSuggestion = false
  333. return hideModal()
  334. }
  335. }
  336. }
  337. // MARK: - Insulin
  338. private func handleInsulin(isExternal: Bool) async throws {
  339. if !isExternal {
  340. await addPumpInsulin()
  341. } else {
  342. await addExternalInsulin()
  343. }
  344. await MainActor.run {
  345. self.waitForSuggestion = true
  346. }
  347. }
  348. func addPumpInsulin() async {
  349. guard amount > 0 else {
  350. showModal(for: nil)
  351. return
  352. }
  353. let maxAmount = Double(min(amount, maxBolus))
  354. do {
  355. let authenticated = try await unlockmanager.unlock()
  356. if authenticated {
  357. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  358. } else {
  359. print("authentication failed")
  360. }
  361. } catch {
  362. print("authentication error for pump bolus: \(error.localizedDescription)")
  363. await MainActor.run {
  364. self.waitForSuggestion = false
  365. if self.addButtonPressed {
  366. self.hideModal()
  367. }
  368. }
  369. }
  370. }
  371. // MARK: - EXTERNAL INSULIN
  372. func addExternalInsulin() async {
  373. guard amount > 0 else {
  374. showModal(for: nil)
  375. return
  376. }
  377. await MainActor.run {
  378. self.amount = min(self.amount, self.maxBolus * 3)
  379. }
  380. do {
  381. let authenticated = try await unlockmanager.unlock()
  382. if authenticated {
  383. // store external dose to pump history
  384. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  385. // perform determine basal sync
  386. await apsManager.determineBasalSync()
  387. } else {
  388. print("authentication failed")
  389. }
  390. } catch {
  391. print("authentication error for external insulin: \(error.localizedDescription)")
  392. await MainActor.run {
  393. self.waitForSuggestion = false
  394. if self.addButtonPressed {
  395. self.hideModal()
  396. }
  397. }
  398. }
  399. }
  400. private func calculateGradientStops() async {
  401. let glucoseValues = glucoseFromPersistence
  402. .map { units == .mgdL ? Decimal($0.glucose) : Decimal($0.glucose).asMmolL }
  403. let calculatedStops = await GradientStops.calculateGradientStops(
  404. lowGlucose: lowGlucose,
  405. highGlucose: highGlucose,
  406. glucoseValues: glucoseValues
  407. )
  408. await MainActor.run {
  409. stops = calculatedStops
  410. }
  411. }
  412. // MARK: - Carbs
  413. func saveMeal() async {
  414. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  415. await MainActor.run {
  416. self.carbs = min(self.carbs, self.maxCarbs)
  417. self.fat = min(self.fat, self.maxFat)
  418. self.protein = min(self.protein, self.maxProtein)
  419. self.id_ = UUID().uuidString
  420. }
  421. let carbsToStore = [CarbsEntry(
  422. id: id_,
  423. createdAt: now,
  424. actualDate: date,
  425. carbs: carbs,
  426. fat: fat,
  427. protein: protein,
  428. note: note,
  429. enteredBy: CarbsEntry.manual,
  430. isFPU: false, fpuID: UUID().uuidString
  431. )]
  432. await carbsStorage.storeCarbs(carbsToStore, areFetchedFromRemote: false)
  433. if carbs > 0 || fat > 0 || protein > 0 {
  434. // 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
  435. if amount <= 0 {
  436. await apsManager.determineBasalSync()
  437. }
  438. }
  439. }
  440. // MARK: - Presets
  441. func deletePreset() {
  442. if selection != nil {
  443. viewContext.delete(selection!)
  444. do {
  445. guard viewContext.hasChanges else { return }
  446. try viewContext.save()
  447. } catch {
  448. print(error.localizedDescription)
  449. }
  450. carbs = 0
  451. fat = 0
  452. protein = 0
  453. }
  454. selection = nil
  455. }
  456. func removePresetFromNewMeal() {
  457. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  458. if a != nil, summation[a ?? 0] != "" {
  459. summation.remove(at: a!)
  460. }
  461. }
  462. func addPresetToNewMeal() {
  463. let test: String = selection?.dish ?? "dontAdd"
  464. if test != "dontAdd" {
  465. summation.append(test)
  466. }
  467. }
  468. func addNewPresetToWaitersNotepad(_ dish: String) {
  469. summation.append(dish)
  470. }
  471. func addToSummation() {
  472. summation.append(selection?.dish ?? "")
  473. }
  474. }
  475. }
  476. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  477. func determinationDidUpdate(_: Determination) {
  478. DispatchQueue.main.async {
  479. self.waitForSuggestion = false
  480. if self.addButtonPressed {
  481. self.hideModal()
  482. }
  483. }
  484. }
  485. func bolusDidFail() {
  486. DispatchQueue.main.async {
  487. self.waitForSuggestion = false
  488. if self.addButtonPressed {
  489. self.hideModal()
  490. }
  491. }
  492. }
  493. }
  494. extension Bolus.StateModel {
  495. private func registerHandlers() {
  496. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  497. guard let self = self else { return }
  498. Task {
  499. await self.setupDeterminationsArray()
  500. await self.updateForecasts()
  501. }
  502. }
  503. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  504. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  505. guard let self = self else { return }
  506. self.setupGlucoseArray()
  507. }
  508. }
  509. private func setupGlucoseNotification() {
  510. /// custom notification that is sent when a batch insert of glucose objects is done
  511. Foundation.NotificationCenter.default.addObserver(
  512. self,
  513. selector: #selector(handleBatchInsert),
  514. name: .didPerformBatchInsert,
  515. object: nil
  516. )
  517. }
  518. @objc private func handleBatchInsert() {
  519. setupGlucoseArray()
  520. }
  521. }
  522. // MARK: - Setup Glucose and Determinations
  523. extension Bolus.StateModel {
  524. // Glucose
  525. private func setupGlucoseArray() {
  526. Task {
  527. let ids = await self.fetchGlucose()
  528. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  529. await updateGlucoseArray(with: glucoseObjects)
  530. if smooth {
  531. await self.calculateGradientStops()
  532. }
  533. }
  534. }
  535. private func fetchGlucose() async -> [NSManagedObjectID] {
  536. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  537. ofType: GlucoseStored.self,
  538. onContext: backgroundContext,
  539. predicate: NSPredicate.glucose,
  540. key: "date",
  541. ascending: false,
  542. fetchLimit: 288
  543. )
  544. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  545. return await backgroundContext.perform {
  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: backgroundContext)
  574. return await backgroundContext.perform {
  575. guard let determinationObject = determinationObjects.first else {
  576. return nil
  577. }
  578. let eventualBG = determinationObject.eventualBG?.intValue
  579. let forecastsSet = determinationObject.forecasts as? Set<Forecast> ?? []
  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. }