BolusStateModel.swift 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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 predictions: Predictions?
  22. var amount: Decimal = 0
  23. var insulinRecommended: Decimal = 0
  24. var insulinRequired: Decimal = 0
  25. var units: GlucoseUnits = .mgdL
  26. var threshold: Decimal = 0
  27. var maxBolus: Decimal = 0
  28. var maxExternal: Decimal { maxBolus * 3 }
  29. var errorString: Decimal = 0
  30. var evBG: Decimal = 0
  31. var insulin: Decimal = 0
  32. var isf: Decimal = 0
  33. var error: Bool = false
  34. var minGuardBG: Decimal = 0
  35. var minDelta: Decimal = 0
  36. var expectedDelta: Decimal = 0
  37. var minPredBG: Decimal = 0
  38. var waitForSuggestion: Bool = false
  39. var carbRatio: Decimal = 0
  40. var addButtonPressed: Bool = false
  41. var waitForSuggestionInitial: Bool = false
  42. var target: Decimal = 0
  43. var cob: Int16 = 0
  44. var iob: Decimal = 0
  45. var currentBG: Decimal = 0
  46. var fifteenMinInsulin: Decimal = 0
  47. var deltaBG: Decimal = 0
  48. var targetDifferenceInsulin: Decimal = 0
  49. var targetDifference: Decimal = 0
  50. var wholeCob: Decimal = 0
  51. var wholeCobInsulin: Decimal = 0
  52. var iobInsulinReduction: Decimal = 0
  53. var wholeCalc: Decimal = 0
  54. var insulinCalculated: Decimal = 0
  55. var fraction: Decimal = 0
  56. var basal: Decimal = 0
  57. var fattyMeals: Bool = false
  58. var fattyMealFactor: Decimal = 0
  59. var useFattyMealCorrectionFactor: Bool = false
  60. var displayPresets: Bool = true
  61. var currentBasal: Decimal = 0
  62. var currentCarbRatio: Decimal = 0
  63. var currentBGTarget: Decimal = 0
  64. var currentISF: Decimal = 0
  65. var sweetMeals: Bool = false
  66. var sweetMealFactor: Decimal = 0
  67. var useSuperBolus: Bool = false
  68. var superBolusInsulin: Decimal = 0
  69. var meal: [CarbsEntry]?
  70. var carbs: Decimal = 0
  71. var fat: Decimal = 0
  72. var protein: Decimal = 0
  73. var note: String = ""
  74. var date = Date()
  75. var carbsRequired: Decimal?
  76. var useFPUconversion: Bool = false
  77. var dish: String = ""
  78. var selection: MealPresetStored?
  79. var summation: [String] = []
  80. var maxCarbs: Decimal = 0
  81. var maxFat: Decimal = 0
  82. var maxProtein: Decimal = 0
  83. var id_: String = ""
  84. var summary: String = ""
  85. var externalInsulin: Bool = false
  86. var showInfo: Bool = false
  87. var glucoseFromPersistence: [GlucoseStored] = []
  88. var determination: [OrefDetermination] = []
  89. var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  90. var predictionsForChart: Predictions?
  91. var simulatedDetermination: Determination?
  92. var determinationObjectIDs: [NSManagedObjectID] = []
  93. var minForecast: [Int] = []
  94. var maxForecast: [Int] = []
  95. var minCount: Int = 12 // count of Forecasts drawn in 5 min distances, i.e. 12 means a min of 1 hour
  96. var forecastDisplayType: ForecastDisplayType = .cone
  97. var isSmoothingEnabled: Bool = false
  98. var stops: [Gradient.Stop] = []
  99. let now = Date.now
  100. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  101. let glucoseFetchContext = CoreDataStack.shared.newTaskContext()
  102. let determinationFetchContext = 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. registerHandlers()
  113. registerSubscribers()
  114. setupBolusStateConcurrently()
  115. }
  116. private func setupBolusStateConcurrently() {
  117. Task {
  118. await withTaskGroup(of: Void.self) { group in
  119. group.addTask {
  120. self.setupGlucoseArray()
  121. }
  122. group.addTask {
  123. self.setupDeterminationsAndForecasts()
  124. }
  125. group.addTask {
  126. await self.setupSettings()
  127. }
  128. group.addTask {
  129. self.registerObservers()
  130. }
  131. if self.waitForSuggestionInitial {
  132. group.addTask {
  133. let isDetermineBasalSuccessful = await self.apsManager.determineBasal()
  134. if !isDetermineBasalSuccessful {
  135. await MainActor.run {
  136. self.waitForSuggestion = false
  137. self.insulinRequired = 0
  138. self.insulinRecommended = 0
  139. }
  140. }
  141. }
  142. }
  143. }
  144. }
  145. }
  146. // MARK: - Basal
  147. private enum SettingType {
  148. case basal
  149. case carbRatio
  150. case bgTarget
  151. case isf
  152. }
  153. func getAllSettingsValues() async {
  154. await withTaskGroup(of: Void.self) { group in
  155. group.addTask {
  156. await self.getCurrentSettingValue(for: .basal)
  157. }
  158. group.addTask {
  159. await self.getCurrentSettingValue(for: .carbRatio)
  160. }
  161. group.addTask {
  162. await self.getCurrentSettingValue(for: .bgTarget)
  163. }
  164. group.addTask {
  165. await self.getCurrentSettingValue(for: .isf)
  166. }
  167. group.addTask {
  168. let getMaxBolus = await self.provider.getPumpSettings().maxBolus
  169. await MainActor.run {
  170. self.maxBolus = getMaxBolus
  171. }
  172. }
  173. }
  174. }
  175. private func setupDeterminationsAndForecasts() {
  176. Task {
  177. async let getAllSettingsDefaults: () = getAllSettingsValues()
  178. async let setupDeterminations: () = setupDeterminationsArray()
  179. await getAllSettingsDefaults
  180. await setupDeterminations
  181. // Determination has updated, so we can use this to draw the initial Forecast Chart
  182. let forecastData = await mapForecastsForChart()
  183. await updateForecasts(with: forecastData)
  184. }
  185. }
  186. private func registerObservers() {
  187. broadcaster.register(DeterminationObserver.self, observer: self)
  188. broadcaster.register(BolusFailureObserver.self, observer: self)
  189. }
  190. @MainActor private func setupSettings() async {
  191. units = settingsManager.settings.units
  192. fraction = settings.settings.overrideFactor
  193. fattyMeals = settings.settings.fattyMeals
  194. fattyMealFactor = settings.settings.fattyMealFactor
  195. sweetMeals = settings.settings.sweetMeals
  196. sweetMealFactor = settings.settings.sweetMealFactor
  197. displayPresets = settings.settings.displayPresets
  198. forecastDisplayType = settings.settings.forecastDisplayType
  199. lowGlucose = units == .mgdL ? settingsManager.settings.low : settingsManager.settings.low.asMmolL
  200. highGlucose = units == .mgdL ? settingsManager.settings.high : settingsManager.settings.high.asMmolL
  201. maxCarbs = settings.settings.maxCarbs
  202. maxFat = settings.settings.maxFat
  203. maxProtein = settings.settings.maxProtein
  204. useFPUconversion = settingsManager.settings.useFPUconversion
  205. isSmoothingEnabled = settingsManager.settings.smoothGlucose
  206. }
  207. private func getCurrentSettingValue(for type: SettingType) async {
  208. let now = Date()
  209. let calendar = Calendar.current
  210. let dateFormatter = DateFormatter()
  211. dateFormatter.dateFormat = "HH:mm:ss"
  212. dateFormatter.timeZone = TimeZone.current
  213. let entries: [(start: String, value: Decimal)]
  214. switch type {
  215. case .basal:
  216. let basalEntries = await provider.getBasalProfile()
  217. entries = basalEntries.map { ($0.start, $0.rate) }
  218. case .carbRatio:
  219. let carbRatios = await provider.getCarbRatios()
  220. entries = carbRatios.schedule.map { ($0.start, $0.ratio) }
  221. case .bgTarget:
  222. let bgTargets = await provider.getBGTarget()
  223. entries = bgTargets.targets.map { ($0.start, $0.low) }
  224. case .isf:
  225. let isfValues = await provider.getISFValues()
  226. entries = isfValues.sensitivities.map { ($0.start, $0.sensitivity) }
  227. }
  228. for (index, entry) in entries.enumerated() {
  229. guard let entryTime = dateFormatter.date(from: entry.start) else {
  230. print("Invalid entry start time: \(entry.start)")
  231. continue
  232. }
  233. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  234. let entryStartTime = calendar.date(
  235. bySettingHour: entryComponents.hour!,
  236. minute: entryComponents.minute!,
  237. second: entryComponents.second!,
  238. of: now
  239. )!
  240. let entryEndTime: Date
  241. if index < entries.count - 1,
  242. let nextEntryTime = dateFormatter.date(from: entries[index + 1].start)
  243. {
  244. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  245. entryEndTime = calendar.date(
  246. bySettingHour: nextEntryComponents.hour!,
  247. minute: nextEntryComponents.minute!,
  248. second: nextEntryComponents.second!,
  249. of: now
  250. )!
  251. } else {
  252. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  253. }
  254. if now >= entryStartTime, now < entryEndTime {
  255. await MainActor.run {
  256. switch type {
  257. case .basal:
  258. currentBasal = entry.value
  259. case .carbRatio:
  260. currentCarbRatio = entry.value
  261. case .bgTarget:
  262. currentBGTarget = entry.value
  263. case .isf:
  264. currentISF = entry.value
  265. }
  266. }
  267. return
  268. }
  269. }
  270. }
  271. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  272. /// Calculate insulin recommendation
  273. func calculateInsulin() -> Decimal {
  274. let isfForCalculation = isf
  275. // insulin needed for the current blood glucose
  276. targetDifference = currentBG - target
  277. targetDifferenceInsulin = targetDifference / isfForCalculation
  278. // more or less insulin because of bg trend in the last 15 minutes
  279. fifteenMinInsulin = deltaBG / isfForCalculation
  280. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  281. wholeCob = Decimal(cob) + carbs
  282. wholeCobInsulin = wholeCob / carbRatio
  283. // determine how much the calculator reduces/ increases the bolus because of IOB
  284. iobInsulinReduction = (-1) * iob
  285. // adding everything together
  286. // add a calc for the case that no fifteenMinInsulin is available
  287. if deltaBG != 0 {
  288. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  289. } else {
  290. // add (rare) case that no glucose value is available -> maybe display warning?
  291. // if no bg is available, ?? sets its value to 0
  292. if currentBG == 0 {
  293. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  294. } else {
  295. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  296. }
  297. }
  298. // apply custom factor at the end of the calculations
  299. let result = wholeCalc * fraction
  300. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  301. if useFattyMealCorrectionFactor {
  302. insulinCalculated = result * fattyMealFactor
  303. } else if useSuperBolus {
  304. superBolusInsulin = sweetMealFactor * currentBasal
  305. insulinCalculated = result + superBolusInsulin
  306. } else {
  307. insulinCalculated = result
  308. }
  309. // display no negative insulinCalculated
  310. insulinCalculated = max(insulinCalculated, 0)
  311. insulinCalculated = min(insulinCalculated, maxBolus)
  312. guard let apsManager = apsManager else {
  313. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  314. return insulinCalculated
  315. }
  316. return apsManager.roundBolus(amount: insulinCalculated)
  317. }
  318. // MARK: - Button tasks
  319. func invokeTreatmentsTask() {
  320. Task {
  321. await MainActor.run {
  322. self.addButtonPressed = true
  323. }
  324. let isInsulinGiven = amount > 0
  325. let isCarbsPresent = carbs > 0
  326. let isFatPresent = fat > 0
  327. let isProteinPresent = protein > 0
  328. if isInsulinGiven {
  329. try await handleInsulin(isExternal: externalInsulin)
  330. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  331. await MainActor.run {
  332. self.waitForSuggestion = true
  333. }
  334. } else {
  335. hideModal()
  336. return
  337. }
  338. await saveMeal()
  339. // If glucose data is stale end the custom loading animation by hiding the modal
  340. // Get date on Main thread
  341. let date = await MainActor.run {
  342. glucoseFromPersistence.first?.date
  343. }
  344. guard glucoseStorage.isGlucoseDataFresh(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: glucoseFetchContext,
  536. predicate: NSPredicate.glucose,
  537. key: "date",
  538. ascending: false,
  539. fetchLimit: 288
  540. )
  541. return await glucoseFetchContext.perform {
  542. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  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: determinationFetchContext)
  571. return await determinationFetchContext.perform {
  572. guard let determinationObject = determinationObjects.first else {
  573. return nil
  574. }
  575. let eventualBG = determinationObject.eventualBG?.intValue
  576. let forecastsSet = determinationObject.forecasts ?? []
  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. }