BolusStateModel.swift 29 KB

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