BolusStateModel.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 backgroundContext = CoreDataStack.shared.newTaskContext()
  103. private var coreDataPublisher: AnyPublisher<Set<NSManagedObject>, Never>?
  104. private var subscriptions = Set<AnyCancellable>()
  105. typealias PumpEvent = PumpEventStored.EventType
  106. override func subscribe() {
  107. coreDataPublisher =
  108. changedObjectsOnManagedObjectContextDidSavePublisher()
  109. .receive(on: DispatchQueue.global(qos: .background))
  110. .share()
  111. .eraseToAnyPublisher()
  112. setupBolusStateConcurrently()
  113. }
  114. private func setupBolusStateConcurrently() {
  115. Task {
  116. await withTaskGroup(of: Void.self) { group in
  117. group.addTask {
  118. self.registerHandlers()
  119. }
  120. group.addTask {
  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 = units == .mmolL ? isf.asMgdL : 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. guard glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  345. await MainActor.run {
  346. waitForSuggestion = false
  347. }
  348. return hideModal()
  349. }
  350. }
  351. }
  352. // MARK: - Insulin
  353. private func handleInsulin(isExternal: Bool) async throws {
  354. if !isExternal {
  355. await addPumpInsulin()
  356. } else {
  357. await addExternalInsulin()
  358. }
  359. await MainActor.run {
  360. self.waitForSuggestion = true
  361. }
  362. }
  363. func addPumpInsulin() async {
  364. guard amount > 0 else {
  365. showModal(for: nil)
  366. return
  367. }
  368. let maxAmount = Double(min(amount, maxBolus))
  369. do {
  370. let authenticated = try await unlockmanager.unlock()
  371. if authenticated {
  372. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  373. } else {
  374. print("authentication failed")
  375. }
  376. } catch {
  377. print("authentication error for pump bolus: \(error.localizedDescription)")
  378. await MainActor.run {
  379. self.waitForSuggestion = false
  380. if self.addButtonPressed {
  381. self.hideModal()
  382. }
  383. }
  384. }
  385. }
  386. // MARK: - EXTERNAL INSULIN
  387. func addExternalInsulin() async {
  388. guard amount > 0 else {
  389. showModal(for: nil)
  390. return
  391. }
  392. await MainActor.run {
  393. self.amount = min(self.amount, self.maxBolus * 3)
  394. }
  395. do {
  396. let authenticated = try await unlockmanager.unlock()
  397. if authenticated {
  398. // store external dose to pump history
  399. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  400. // perform determine basal sync
  401. await apsManager.determineBasalSync()
  402. } else {
  403. print("authentication failed")
  404. }
  405. } catch {
  406. print("authentication error for external insulin: \(error.localizedDescription)")
  407. await MainActor.run {
  408. self.waitForSuggestion = false
  409. if self.addButtonPressed {
  410. self.hideModal()
  411. }
  412. }
  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. coreDataPublisher?.filterByEntityName("OrefDetermination").sink { [weak self] _ in
  500. guard let self = self else { return }
  501. Task {
  502. await self.setupDeterminationsArray()
  503. await self.updateForecasts()
  504. }
  505. }.store(in: &subscriptions)
  506. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  507. coreDataPublisher?.filterByEntityName("GlucoseStored").sink { [weak self] _ in
  508. guard let self = self else { return }
  509. self.setupGlucoseArray()
  510. }.store(in: &subscriptions)
  511. }
  512. private func registerSubscribers() {
  513. glucoseStorage.updatePublisher
  514. .receive(on: DispatchQueue.global(qos: .background))
  515. .sink { [weak self] _ in
  516. guard let self = self else { return }
  517. self.setupGlucoseArray()
  518. }
  519. .store(in: &subscriptions)
  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. }
  531. }
  532. private func fetchGlucose() async -> [NSManagedObjectID] {
  533. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  534. ofType: GlucoseStored.self,
  535. onContext: backgroundContext,
  536. predicate: NSPredicate.glucose,
  537. key: "date",
  538. ascending: false,
  539. fetchLimit: 288
  540. )
  541. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  542. return await backgroundContext.perform {
  543. return fetchedResults.map(\.objectID)
  544. }
  545. }
  546. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  547. glucoseFromPersistence = objects
  548. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  549. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  550. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  551. currentBG = Decimal(lastGlucose)
  552. deltaBG = delta
  553. }
  554. // Determinations
  555. private func setupDeterminationsArray() async {
  556. // Fetch object IDs on a background thread
  557. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  558. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  559. )
  560. // Update determinationObjectIDs on the main thread
  561. await MainActor.run {
  562. determinationObjectIDs = fetchedObjectIDs
  563. }
  564. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  565. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  566. await updateDeterminationsArray(with: determinationObjects)
  567. }
  568. private func mapForecastsForChart() async -> Determination? {
  569. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  570. .getNSManagedObject(with: determinationObjectIDs, context: backgroundContext)
  571. return await backgroundContext.perform {
  572. guard let determinationObject = determinationObjects.first else {
  573. return nil
  574. }
  575. let eventualBG = determinationObject.eventualBG?.intValue
  576. let forecastsSet = determinationObject.forecasts as? Set<Forecast> ?? []
  577. let predictions = Predictions(
  578. iob: forecastsSet.extractValues(for: "iob"),
  579. zt: forecastsSet.extractValues(for: "zt"),
  580. cob: forecastsSet.extractValues(for: "cob"),
  581. uam: forecastsSet.extractValues(for: "uam")
  582. )
  583. return Determination(
  584. id: UUID(),
  585. reason: "",
  586. units: 0,
  587. insulinReq: 0,
  588. eventualBG: eventualBG,
  589. sensitivityRatio: 0,
  590. rate: 0,
  591. duration: 0,
  592. iob: 0,
  593. cob: 0,
  594. predictions: predictions.isEmpty ? nil : predictions,
  595. carbsReq: 0,
  596. temp: nil,
  597. bg: 0,
  598. reservoir: 0,
  599. isf: 0,
  600. tdd: 0,
  601. insulin: nil,
  602. current_target: 0,
  603. insulinForManualBolus: 0,
  604. manualBolusErrorString: 0,
  605. minDelta: 0,
  606. expectedDelta: 0,
  607. minGuardBG: 0,
  608. minPredBG: 0,
  609. threshold: 0,
  610. carbRatio: 0,
  611. received: false
  612. )
  613. }
  614. }
  615. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  616. guard let mostRecentDetermination = objects.first else { return }
  617. determination = objects
  618. // setup vars for bolus calculation
  619. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  620. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  621. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  622. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  623. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  624. cob = mostRecentDetermination.cob as Int16
  625. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  626. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  627. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  628. insulinCalculated = calculateInsulin()
  629. }
  630. }
  631. extension Bolus.StateModel {
  632. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  633. if let forecastData = forecastData {
  634. simulatedDetermination = forecastData
  635. } else {
  636. simulatedDetermination = await Task.detached { [self] in
  637. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  638. }.value
  639. }
  640. predictionsForChart = simulatedDetermination?.predictions
  641. let nonEmptyArrays = [
  642. predictionsForChart?.iob,
  643. predictionsForChart?.zt,
  644. predictionsForChart?.cob,
  645. predictionsForChart?.uam
  646. ]
  647. .compactMap { $0 }
  648. .filter { !$0.isEmpty }
  649. guard !nonEmptyArrays.isEmpty else {
  650. minForecast = []
  651. maxForecast = []
  652. return
  653. }
  654. minCount = max(12, nonEmptyArrays.map(\.count).min() ?? 0)
  655. guard minCount > 0 else { return }
  656. async let minForecastResult = Task.detached {
  657. (0 ..< self.minCount).map { index in
  658. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  659. }
  660. }.value
  661. async let maxForecastResult = Task.detached {
  662. (0 ..< self.minCount).map { index in
  663. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  664. }
  665. }.value
  666. minForecast = await minForecastResult
  667. maxForecast = await maxForecastResult
  668. }
  669. }
  670. private extension Set where Element == Forecast {
  671. func extractValues(for type: String) -> [Int]? {
  672. let values = first { $0.type == type }?
  673. .forecastValues?
  674. .sorted { $0.index < $1.index }
  675. .compactMap { Int($0.value) }
  676. return values?.isEmpty ?? true ? nil : values
  677. }
  678. }
  679. private extension Predictions {
  680. var isEmpty: Bool {
  681. iob == nil && zt == nil && cob == nil && uam == nil
  682. }
  683. }