BolusStateModel.swift 27 KB

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