BolusStateModel.swift 29 KB

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