BolusStateModel.swift 29 KB

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