TreatmentsStateModel.swift 31 KB

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