BolusStateModel.swift 28 KB

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