BolusStateModel.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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. var determinationObjectIDs: [NSManagedObjectID] = []
  94. var minForecast: [Int] = []
  95. var maxForecast: [Int] = []
  96. 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.dateFormat = "HH:mm:ss"
  214. dateFormatter.timeZone = TimeZone.current
  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. guard let entryTime = dateFormatter.date(from: entry.start) else {
  232. print("Invalid entry start time: \(entry.start)")
  233. continue
  234. }
  235. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  236. let entryStartTime = calendar.date(
  237. bySettingHour: entryComponents.hour!,
  238. minute: entryComponents.minute!,
  239. second: entryComponents.second!,
  240. of: now
  241. )!
  242. let entryEndTime: Date
  243. if index < entries.count - 1,
  244. let nextEntryTime = dateFormatter.date(from: entries[index + 1].start)
  245. {
  246. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  247. entryEndTime = calendar.date(
  248. bySettingHour: nextEntryComponents.hour!,
  249. minute: nextEntryComponents.minute!,
  250. second: nextEntryComponents.second!,
  251. of: now
  252. )!
  253. } else {
  254. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  255. }
  256. if now >= entryStartTime, now < entryEndTime {
  257. await MainActor.run {
  258. switch type {
  259. case .basal:
  260. currentBasal = entry.value
  261. case .carbRatio:
  262. currentCarbRatio = entry.value
  263. case .bgTarget:
  264. currentBGTarget = entry.value
  265. case .isf:
  266. currentISF = entry.value
  267. }
  268. }
  269. return
  270. }
  271. }
  272. }
  273. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  274. /// Calculate insulin recommendation
  275. func calculateInsulin() -> Decimal {
  276. let isfForCalculation = isf
  277. // insulin needed for the current blood glucose
  278. targetDifference = currentBG - target
  279. targetDifferenceInsulin = targetDifference / isfForCalculation
  280. // more or less insulin because of bg trend in the last 15 minutes
  281. fifteenMinInsulin = deltaBG / isfForCalculation
  282. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  283. wholeCob = Decimal(cob) + carbs
  284. wholeCobInsulin = wholeCob / carbRatio
  285. // determine how much the calculator reduces/ increases the bolus because of IOB
  286. iobInsulinReduction = (-1) * iob
  287. // adding everything together
  288. // add a calc for the case that no fifteenMinInsulin is available
  289. if deltaBG != 0 {
  290. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  291. } else {
  292. // add (rare) case that no glucose value is available -> maybe display warning?
  293. // if no bg is available, ?? sets its value to 0
  294. if currentBG == 0 {
  295. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  296. } else {
  297. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  298. }
  299. }
  300. // apply custom factor at the end of the calculations
  301. let result = wholeCalc * fraction
  302. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  303. if useFattyMealCorrectionFactor {
  304. insulinCalculated = result * fattyMealFactor
  305. } else if useSuperBolus {
  306. superBolusInsulin = sweetMealFactor * currentBasal
  307. insulinCalculated = result + superBolusInsulin
  308. } else {
  309. insulinCalculated = result
  310. }
  311. // display no negative insulinCalculated
  312. insulinCalculated = max(insulinCalculated, 0)
  313. insulinCalculated = min(insulinCalculated, maxBolus)
  314. guard let apsManager = apsManager else {
  315. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  316. return insulinCalculated
  317. }
  318. return apsManager.roundBolus(amount: insulinCalculated)
  319. }
  320. // MARK: - Button tasks
  321. func invokeTreatmentsTask() {
  322. Task {
  323. await MainActor.run {
  324. self.addButtonPressed = true
  325. }
  326. let isInsulinGiven = amount > 0
  327. let isCarbsPresent = carbs > 0
  328. let isFatPresent = fat > 0
  329. let isProteinPresent = protein > 0
  330. if isInsulinGiven {
  331. try await handleInsulin(isExternal: externalInsulin)
  332. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  333. await MainActor.run {
  334. self.waitForSuggestion = true
  335. }
  336. } else {
  337. hideModal()
  338. return
  339. }
  340. await saveMeal()
  341. // If glucose data is stale end the custom loading animation by hiding the modal
  342. // Get date on Main thread
  343. let date = await MainActor.run {
  344. glucoseFromPersistence.first?.date
  345. }
  346. guard glucoseStorage.isGlucoseDataFresh(date) else {
  347. await MainActor.run {
  348. waitForSuggestion = false
  349. }
  350. return hideModal()
  351. }
  352. }
  353. }
  354. // MARK: - Insulin
  355. private func handleInsulin(isExternal: Bool) async throws {
  356. if !isExternal {
  357. await addPumpInsulin()
  358. } else {
  359. await addExternalInsulin()
  360. }
  361. await MainActor.run {
  362. self.waitForSuggestion = true
  363. }
  364. }
  365. func addPumpInsulin() async {
  366. guard amount > 0 else {
  367. showModal(for: nil)
  368. return
  369. }
  370. let maxAmount = Double(min(amount, maxBolus))
  371. do {
  372. let authenticated = try await unlockmanager.unlock()
  373. if authenticated {
  374. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  375. } else {
  376. print("authentication failed")
  377. }
  378. } catch {
  379. print("authentication error for pump bolus: \(error.localizedDescription)")
  380. await MainActor.run {
  381. self.waitForSuggestion = false
  382. if self.addButtonPressed {
  383. self.hideModal()
  384. }
  385. }
  386. }
  387. }
  388. // MARK: - EXTERNAL INSULIN
  389. func addExternalInsulin() async {
  390. guard amount > 0 else {
  391. showModal(for: nil)
  392. return
  393. }
  394. await MainActor.run {
  395. self.amount = min(self.amount, self.maxBolus * 3)
  396. }
  397. do {
  398. let authenticated = try await unlockmanager.unlock()
  399. if authenticated {
  400. // store external dose to pump history
  401. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  402. // perform determine basal sync
  403. await apsManager.determineBasalSync()
  404. } else {
  405. print("authentication failed")
  406. }
  407. } catch {
  408. print("authentication error for external insulin: \(error.localizedDescription)")
  409. await MainActor.run {
  410. self.waitForSuggestion = false
  411. if self.addButtonPressed {
  412. self.hideModal()
  413. }
  414. }
  415. }
  416. }
  417. // MARK: - Carbs
  418. func saveMeal() async {
  419. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  420. await MainActor.run {
  421. self.carbs = min(self.carbs, self.maxCarbs)
  422. self.fat = min(self.fat, self.maxFat)
  423. self.protein = min(self.protein, self.maxProtein)
  424. self.id_ = UUID().uuidString
  425. }
  426. let carbsToStore = [CarbsEntry(
  427. id: id_,
  428. createdAt: now,
  429. actualDate: date,
  430. carbs: carbs,
  431. fat: fat,
  432. protein: protein,
  433. note: note,
  434. enteredBy: CarbsEntry.manual,
  435. isFPU: false, fpuID: UUID().uuidString
  436. )]
  437. await carbsStorage.storeCarbs(carbsToStore, areFetchedFromRemote: false)
  438. if carbs > 0 || fat > 0 || protein > 0 {
  439. // 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
  440. if amount <= 0 {
  441. await apsManager.determineBasalSync()
  442. }
  443. }
  444. }
  445. // MARK: - Presets
  446. func deletePreset() {
  447. if selection != nil {
  448. viewContext.delete(selection!)
  449. do {
  450. guard viewContext.hasChanges else { return }
  451. try viewContext.save()
  452. } catch {
  453. print(error.localizedDescription)
  454. }
  455. carbs = 0
  456. fat = 0
  457. protein = 0
  458. }
  459. selection = nil
  460. }
  461. func removePresetFromNewMeal() {
  462. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  463. if a != nil, summation[a ?? 0] != "" {
  464. summation.remove(at: a!)
  465. }
  466. }
  467. func addPresetToNewMeal() {
  468. let test: String = selection?.dish ?? "dontAdd"
  469. if test != "dontAdd" {
  470. summation.append(test)
  471. }
  472. }
  473. func addNewPresetToWaitersNotepad(_ dish: String) {
  474. summation.append(dish)
  475. }
  476. func addToSummation() {
  477. summation.append(selection?.dish ?? "")
  478. }
  479. }
  480. }
  481. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  482. func determinationDidUpdate(_: Determination) {
  483. DispatchQueue.main.async {
  484. self.waitForSuggestion = false
  485. if self.addButtonPressed {
  486. self.hideModal()
  487. }
  488. }
  489. }
  490. func bolusDidFail() {
  491. DispatchQueue.main.async {
  492. self.waitForSuggestion = false
  493. if self.addButtonPressed {
  494. self.hideModal()
  495. }
  496. }
  497. }
  498. }
  499. extension Bolus.StateModel {
  500. private func registerHandlers() {
  501. coreDataPublisher?.filterByEntityName("OrefDetermination").sink { [weak self] _ in
  502. guard let self = self else { return }
  503. Task {
  504. await self.setupDeterminationsArray()
  505. await self.updateForecasts()
  506. }
  507. }.store(in: &subscriptions)
  508. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  509. coreDataPublisher?.filterByEntityName("GlucoseStored").sink { [weak self] _ in
  510. guard let self = self else { return }
  511. self.setupGlucoseArray()
  512. }.store(in: &subscriptions)
  513. }
  514. private func registerSubscribers() {
  515. glucoseStorage.updatePublisher
  516. .receive(on: DispatchQueue.global(qos: .background))
  517. .sink { [weak self] _ in
  518. guard let self = self else { return }
  519. self.setupGlucoseArray()
  520. }
  521. .store(in: &subscriptions)
  522. }
  523. }
  524. // MARK: - Setup Glucose and Determinations
  525. extension Bolus.StateModel {
  526. // Glucose
  527. private func setupGlucoseArray() {
  528. Task {
  529. let ids = await self.fetchGlucose()
  530. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  531. await updateGlucoseArray(with: glucoseObjects)
  532. }
  533. }
  534. private func fetchGlucose() async -> [NSManagedObjectID] {
  535. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  536. ofType: GlucoseStored.self,
  537. onContext: glucoseFetchContext,
  538. predicate: NSPredicate.glucose,
  539. key: "date",
  540. ascending: false,
  541. fetchLimit: 288
  542. )
  543. return await glucoseFetchContext.perform {
  544. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  545. return fetchedResults.map(\.objectID)
  546. }
  547. }
  548. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  549. glucoseFromPersistence = objects
  550. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  551. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  552. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  553. currentBG = Decimal(lastGlucose)
  554. deltaBG = delta
  555. }
  556. // Determinations
  557. private func setupDeterminationsArray() async {
  558. // Fetch object IDs on a background thread
  559. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  560. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  561. )
  562. // Update determinationObjectIDs on the main thread
  563. await MainActor.run {
  564. determinationObjectIDs = fetchedObjectIDs
  565. }
  566. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  567. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  568. await updateDeterminationsArray(with: determinationObjects)
  569. }
  570. private func mapForecastsForChart() async -> Determination? {
  571. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  572. .getNSManagedObject(with: determinationObjectIDs, context: determinationFetchContext)
  573. return await determinationFetchContext.perform {
  574. guard let determinationObject = determinationObjects.first else {
  575. return nil
  576. }
  577. let eventualBG = determinationObject.eventualBG?.intValue
  578. let forecastsSet = determinationObject.forecasts ?? []
  579. let predictions = Predictions(
  580. iob: forecastsSet.extractValues(for: "iob"),
  581. zt: forecastsSet.extractValues(for: "zt"),
  582. cob: forecastsSet.extractValues(for: "cob"),
  583. uam: forecastsSet.extractValues(for: "uam")
  584. )
  585. return Determination(
  586. id: UUID(),
  587. reason: "",
  588. units: 0,
  589. insulinReq: 0,
  590. eventualBG: eventualBG,
  591. sensitivityRatio: 0,
  592. rate: 0,
  593. duration: 0,
  594. iob: 0,
  595. cob: 0,
  596. predictions: predictions.isEmpty ? nil : predictions,
  597. carbsReq: 0,
  598. temp: nil,
  599. bg: 0,
  600. reservoir: 0,
  601. isf: 0,
  602. tdd: 0,
  603. insulin: nil,
  604. current_target: 0,
  605. insulinForManualBolus: 0,
  606. manualBolusErrorString: 0,
  607. minDelta: 0,
  608. expectedDelta: 0,
  609. minGuardBG: 0,
  610. minPredBG: 0,
  611. threshold: 0,
  612. carbRatio: 0,
  613. received: false
  614. )
  615. }
  616. }
  617. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  618. guard let mostRecentDetermination = objects.first else { return }
  619. determination = objects
  620. // setup vars for bolus calculation
  621. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  622. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  623. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  624. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  625. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  626. cob = mostRecentDetermination.cob as Int16
  627. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  628. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  629. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  630. insulinCalculated = calculateInsulin()
  631. }
  632. }
  633. extension Bolus.StateModel {
  634. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  635. if let forecastData = forecastData {
  636. simulatedDetermination = forecastData
  637. } else {
  638. simulatedDetermination = await Task.detached { [self] in
  639. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  640. }.value
  641. }
  642. predictionsForChart = simulatedDetermination?.predictions
  643. let nonEmptyArrays = [
  644. predictionsForChart?.iob,
  645. predictionsForChart?.zt,
  646. predictionsForChart?.cob,
  647. predictionsForChart?.uam
  648. ]
  649. .compactMap { $0 }
  650. .filter { !$0.isEmpty }
  651. guard !nonEmptyArrays.isEmpty else {
  652. minForecast = []
  653. maxForecast = []
  654. return
  655. }
  656. minCount = max(12, nonEmptyArrays.map(\.count).min() ?? 0)
  657. guard minCount > 0 else { return }
  658. async let minForecastResult = Task.detached {
  659. (0 ..< self.minCount).map { index in
  660. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  661. }
  662. }.value
  663. async let maxForecastResult = Task.detached {
  664. (0 ..< self.minCount).map { index in
  665. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  666. }
  667. }.value
  668. minForecast = await minForecastResult
  669. maxForecast = await maxForecastResult
  670. }
  671. }
  672. private extension Set where Element == Forecast {
  673. func extractValues(for type: String) -> [Int]? {
  674. let values = first { $0.type == type }?
  675. .forecastValues?
  676. .sorted { $0.index < $1.index }
  677. .compactMap { Int($0.value) }
  678. return values?.isEmpty ?? true ? nil : values
  679. }
  680. }
  681. private extension Predictions {
  682. var isEmpty: Bool {
  683. iob == nil && zt == nil && cob == nil && uam == nil
  684. }
  685. }