BolusStateModel.swift 29 KB

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