BolusStateModel.swift 28 KB

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