BolusStateModel.swift 27 KB

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