BolusStateModel.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. waitForSuggestion = false
  346. return hideModal()
  347. }
  348. }
  349. }
  350. // MARK: - Insulin
  351. private func handleInsulin(isExternal: Bool) async throws {
  352. if !isExternal {
  353. await addPumpInsulin()
  354. } else {
  355. await addExternalInsulin()
  356. }
  357. await MainActor.run {
  358. self.waitForSuggestion = true
  359. }
  360. }
  361. func addPumpInsulin() async {
  362. guard amount > 0 else {
  363. showModal(for: nil)
  364. return
  365. }
  366. let maxAmount = Double(min(amount, maxBolus))
  367. do {
  368. let authenticated = try await unlockmanager.unlock()
  369. if authenticated {
  370. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  371. } else {
  372. print("authentication failed")
  373. }
  374. } catch {
  375. print("authentication error for pump bolus: \(error.localizedDescription)")
  376. await MainActor.run {
  377. self.waitForSuggestion = false
  378. if self.addButtonPressed {
  379. self.hideModal()
  380. }
  381. }
  382. }
  383. }
  384. // MARK: - EXTERNAL INSULIN
  385. func addExternalInsulin() async {
  386. guard amount > 0 else {
  387. showModal(for: nil)
  388. return
  389. }
  390. await MainActor.run {
  391. self.amount = min(self.amount, self.maxBolus * 3)
  392. }
  393. do {
  394. let authenticated = try await unlockmanager.unlock()
  395. if authenticated {
  396. // store external dose to pump history
  397. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  398. // perform determine basal sync
  399. await apsManager.determineBasalSync()
  400. } else {
  401. print("authentication failed")
  402. }
  403. } catch {
  404. print("authentication error for external insulin: \(error.localizedDescription)")
  405. await MainActor.run {
  406. self.waitForSuggestion = false
  407. if self.addButtonPressed {
  408. self.hideModal()
  409. }
  410. }
  411. }
  412. }
  413. // MARK: - Carbs
  414. func saveMeal() async {
  415. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  416. await MainActor.run {
  417. self.carbs = min(self.carbs, self.maxCarbs)
  418. self.fat = min(self.fat, self.maxFat)
  419. self.protein = min(self.protein, self.maxProtein)
  420. self.id_ = UUID().uuidString
  421. }
  422. let carbsToStore = [CarbsEntry(
  423. id: id_,
  424. createdAt: now,
  425. actualDate: date,
  426. carbs: carbs,
  427. fat: fat,
  428. protein: protein,
  429. note: note,
  430. enteredBy: CarbsEntry.manual,
  431. isFPU: false, fpuID: UUID().uuidString
  432. )]
  433. await carbsStorage.storeCarbs(carbsToStore, areFetchedFromRemote: false)
  434. if carbs > 0 || fat > 0 || protein > 0 {
  435. // 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
  436. if amount <= 0 {
  437. await apsManager.determineBasalSync()
  438. }
  439. }
  440. }
  441. // MARK: - Presets
  442. func deletePreset() {
  443. if selection != nil {
  444. viewContext.delete(selection!)
  445. do {
  446. guard viewContext.hasChanges else { return }
  447. try viewContext.save()
  448. } catch {
  449. print(error.localizedDescription)
  450. }
  451. carbs = 0
  452. fat = 0
  453. protein = 0
  454. }
  455. selection = nil
  456. }
  457. func removePresetFromNewMeal() {
  458. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  459. if a != nil, summation[a ?? 0] != "" {
  460. summation.remove(at: a!)
  461. }
  462. }
  463. func addPresetToNewMeal() {
  464. let test: String = selection?.dish ?? "dontAdd"
  465. if test != "dontAdd" {
  466. summation.append(test)
  467. }
  468. }
  469. func addNewPresetToWaitersNotepad(_ dish: String) {
  470. summation.append(dish)
  471. }
  472. func addToSummation() {
  473. summation.append(selection?.dish ?? "")
  474. }
  475. }
  476. }
  477. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  478. func determinationDidUpdate(_: Determination) {
  479. DispatchQueue.main.async {
  480. self.waitForSuggestion = false
  481. if self.addButtonPressed {
  482. self.hideModal()
  483. }
  484. }
  485. }
  486. func bolusDidFail() {
  487. DispatchQueue.main.async {
  488. self.waitForSuggestion = false
  489. if self.addButtonPressed {
  490. self.hideModal()
  491. }
  492. }
  493. }
  494. }
  495. extension Bolus.StateModel {
  496. private func registerHandlers() {
  497. coreDataPublisher?.filterByEntityName("OrefDetermination").sink { [weak self] _ in
  498. guard let self = self else { return }
  499. Task {
  500. await self.setupDeterminationsArray()
  501. await self.updateForecasts()
  502. }
  503. }.store(in: &subscriptions)
  504. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  505. coreDataPublisher?.filterByEntityName("GlucoseStored").sink { [weak self] _ in
  506. guard let self = self else { return }
  507. self.setupGlucoseArray()
  508. }.store(in: &subscriptions)
  509. }
  510. private func registerSubscribers() {
  511. glucoseStorage.updatePublisher
  512. .receive(on: DispatchQueue.global(qos: .background))
  513. .sink { [weak self] _ in
  514. guard let self = self else { return }
  515. self.setupGlucoseArray()
  516. }
  517. .store(in: &subscriptions)
  518. }
  519. }
  520. // MARK: - Setup Glucose and Determinations
  521. extension Bolus.StateModel {
  522. // Glucose
  523. private func setupGlucoseArray() {
  524. Task {
  525. let ids = await self.fetchGlucose()
  526. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  527. await updateGlucoseArray(with: glucoseObjects)
  528. }
  529. }
  530. private func fetchGlucose() async -> [NSManagedObjectID] {
  531. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  532. ofType: GlucoseStored.self,
  533. onContext: backgroundContext,
  534. predicate: NSPredicate.glucose,
  535. key: "date",
  536. ascending: false,
  537. fetchLimit: 288
  538. )
  539. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  540. return await backgroundContext.perform {
  541. return fetchedResults.map(\.objectID)
  542. }
  543. }
  544. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  545. glucoseFromPersistence = objects
  546. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  547. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  548. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  549. currentBG = Decimal(lastGlucose)
  550. deltaBG = delta
  551. }
  552. // Determinations
  553. private func setupDeterminationsArray() async {
  554. // Fetch object IDs on a background thread
  555. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  556. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  557. )
  558. // Update determinationObjectIDs on the main thread
  559. await MainActor.run {
  560. determinationObjectIDs = fetchedObjectIDs
  561. }
  562. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  563. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  564. await updateDeterminationsArray(with: determinationObjects)
  565. }
  566. private func mapForecastsForChart() async -> Determination? {
  567. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  568. .getNSManagedObject(with: determinationObjectIDs, context: backgroundContext)
  569. return await backgroundContext.perform {
  570. guard let determinationObject = determinationObjects.first else {
  571. return nil
  572. }
  573. let eventualBG = determinationObject.eventualBG?.intValue
  574. let forecastsSet = determinationObject.forecasts as? Set<Forecast> ?? []
  575. let predictions = Predictions(
  576. iob: forecastsSet.extractValues(for: "iob"),
  577. zt: forecastsSet.extractValues(for: "zt"),
  578. cob: forecastsSet.extractValues(for: "cob"),
  579. uam: forecastsSet.extractValues(for: "uam")
  580. )
  581. return Determination(
  582. id: UUID(),
  583. reason: "",
  584. units: 0,
  585. insulinReq: 0,
  586. eventualBG: eventualBG,
  587. sensitivityRatio: 0,
  588. rate: 0,
  589. duration: 0,
  590. iob: 0,
  591. cob: 0,
  592. predictions: predictions.isEmpty ? nil : predictions,
  593. carbsReq: 0,
  594. temp: nil,
  595. bg: 0,
  596. reservoir: 0,
  597. isf: 0,
  598. tdd: 0,
  599. insulin: nil,
  600. current_target: 0,
  601. insulinForManualBolus: 0,
  602. manualBolusErrorString: 0,
  603. minDelta: 0,
  604. expectedDelta: 0,
  605. minGuardBG: 0,
  606. minPredBG: 0,
  607. threshold: 0,
  608. carbRatio: 0,
  609. received: false
  610. )
  611. }
  612. }
  613. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  614. guard let mostRecentDetermination = objects.first else { return }
  615. determination = objects
  616. // setup vars for bolus calculation
  617. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  618. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  619. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  620. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  621. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  622. cob = mostRecentDetermination.cob as Int16
  623. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  624. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  625. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  626. insulinCalculated = calculateInsulin()
  627. }
  628. }
  629. extension Bolus.StateModel {
  630. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  631. if let forecastData = forecastData {
  632. simulatedDetermination = forecastData
  633. } else {
  634. simulatedDetermination = await Task.detached { [self] in
  635. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  636. }.value
  637. }
  638. predictionsForChart = simulatedDetermination?.predictions
  639. let nonEmptyArrays = [
  640. predictionsForChart?.iob,
  641. predictionsForChart?.zt,
  642. predictionsForChart?.cob,
  643. predictionsForChart?.uam
  644. ]
  645. .compactMap { $0 }
  646. .filter { !$0.isEmpty }
  647. guard !nonEmptyArrays.isEmpty else {
  648. minForecast = []
  649. maxForecast = []
  650. return
  651. }
  652. minCount = max(12, nonEmptyArrays.map(\.count).min() ?? 0)
  653. guard minCount > 0 else { return }
  654. async let minForecastResult = Task.detached {
  655. (0 ..< self.minCount).map { index in
  656. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  657. }
  658. }.value
  659. async let maxForecastResult = Task.detached {
  660. (0 ..< self.minCount).map { index in
  661. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  662. }
  663. }.value
  664. minForecast = await minForecastResult
  665. maxForecast = await maxForecastResult
  666. }
  667. }
  668. private extension Set where Element == Forecast {
  669. func extractValues(for type: String) -> [Int]? {
  670. let values = first { $0.type == type }?
  671. .forecastValues?
  672. .sorted { $0.index < $1.index }
  673. .compactMap { Int($0.value) }
  674. return values?.isEmpty ?? true ? nil : values
  675. }
  676. }
  677. private extension Predictions {
  678. var isEmpty: Bool {
  679. iob == nil && zt == nil && cob == nil && uam == nil
  680. }
  681. }