BolusStateModel.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. @Published var suggestion: Suggestion?
  18. @Published var predictions: Predictions?
  19. @Published var amount: Decimal = 0
  20. @Published var insulinRecommended: Decimal = 0
  21. @Published var insulinRequired: Decimal = 0
  22. @Published var units: GlucoseUnits = .mmolL
  23. @Published var percentage: Decimal = 0
  24. @Published var threshold: Decimal = 0
  25. @Published var maxBolus: Decimal = 0
  26. @Published var errorString: Decimal = 0
  27. @Published var evBG: Decimal = 0
  28. @Published var insulin: Decimal = 0
  29. @Published var isf: Decimal = 0
  30. @Published var error: Bool = false
  31. @Published var minGuardBG: Decimal = 0
  32. @Published var minDelta: Decimal = 0
  33. @Published var expectedDelta: Decimal = 0
  34. @Published var minPredBG: Decimal = 0
  35. @Published var waitForSuggestion: Bool = false
  36. @Published var carbRatio: Decimal = 0
  37. @Published var addButtonPressed: Bool = false
  38. var waitForSuggestionInitial: Bool = false
  39. // added for bolus calculator
  40. @Published var target: Decimal = 0
  41. @Published var cob: Int16 = 0
  42. @Published var iob: Decimal = 0
  43. @Published var currentBG: Decimal = 0
  44. @Published var fifteenMinInsulin: Decimal = 0
  45. @Published var deltaBG: Decimal = 0
  46. @Published var targetDifferenceInsulin: Decimal = 0
  47. @Published var targetDifference: Decimal = 0
  48. @Published var wholeCob: Decimal = 0
  49. @Published var wholeCobInsulin: Decimal = 0
  50. @Published var iobInsulinReduction: Decimal = 0
  51. @Published var wholeCalc: Decimal = 0
  52. @Published var insulinCalculated: Decimal = 0
  53. @Published var fraction: Decimal = 0
  54. @Published var useCalc: Bool = false
  55. @Published var basal: Decimal = 0
  56. @Published var fattyMeals: Bool = false
  57. @Published var fattyMealFactor: Decimal = 0
  58. @Published var useFattyMealCorrectionFactor: Bool = false
  59. @Published var displayPresets: Bool = true
  60. @Published var currentBasal: Decimal = 0
  61. @Published var sweetMeals: Bool = false
  62. @Published var sweetMealFactor: Decimal = 0
  63. @Published var useSuperBolus: Bool = false
  64. @Published var superBolusInsulin: Decimal = 0
  65. @Published var meal: [CarbsEntry]?
  66. @Published var carbs: Decimal = 0
  67. @Published var fat: Decimal = 0
  68. @Published var protein: Decimal = 0
  69. @Published var note: String = ""
  70. @Published var date = Date()
  71. @Published var carbsRequired: Decimal?
  72. @Published var useFPUconversion: Bool = false
  73. @Published var dish: String = ""
  74. @Published var selection: Presets?
  75. @Published var summation: [String] = []
  76. @Published var maxCarbs: Decimal = 0
  77. @Published var id_: String = ""
  78. @Published var summary: String = ""
  79. @Published var skipBolus: Bool = false
  80. @Published var externalInsulin: Bool = false
  81. @Published var showInfo: Bool = false
  82. @Published var glucoseFromPersistence: [GlucoseStored] = []
  83. @Published var determination: [OrefDetermination] = []
  84. let now = Date.now
  85. let context = CoreDataStack.shared.persistentContainer.viewContext
  86. let backgroundContext = CoreDataStack.shared.newTaskContext()
  87. typealias PumpEvent = PumpEventStored.EventType
  88. override func subscribe() {
  89. setupNotification()
  90. setupGlucoseArray()
  91. setupDeterminationsArray()
  92. broadcaster.register(DeterminationObserver.self, observer: self)
  93. broadcaster.register(BolusFailureObserver.self, observer: self)
  94. units = settingsManager.settings.units
  95. percentage = settingsManager.settings.insulinReqPercentage
  96. threshold = provider.suggestion?.threshold ?? 0
  97. maxBolus = provider.pumpSettings().maxBolus
  98. // added
  99. fraction = settings.settings.overrideFactor
  100. useCalc = settings.settings.useCalc
  101. fattyMeals = settings.settings.fattyMeals
  102. fattyMealFactor = settings.settings.fattyMealFactor
  103. sweetMeals = settings.settings.sweetMeals
  104. sweetMealFactor = settings.settings.sweetMealFactor
  105. displayPresets = settings.settings.displayPresets
  106. carbsRequired = provider.suggestion?.carbsReq
  107. maxCarbs = settings.settings.maxCarbs
  108. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  109. useFPUconversion = settingsManager.settings.useFPUconversion
  110. if waitForSuggestionInitial {
  111. apsManager.determineBasal()
  112. .receive(on: DispatchQueue.main)
  113. .sink { [weak self] ok in
  114. guard let self = self else { return }
  115. if !ok {
  116. self.waitForSuggestion = false
  117. self.insulinRequired = 0
  118. self.insulinRecommended = 0
  119. }
  120. }.store(in: &lifetime)
  121. }
  122. if let notNilSugguestion = provider.suggestion {
  123. suggestion = notNilSugguestion
  124. if let notNilPredictions = suggestion?.predictions {
  125. predictions = notNilPredictions
  126. }
  127. }
  128. }
  129. // MARK: - Basal
  130. func getCurrentBasal() {
  131. let basalEntries = provider.getProfile()
  132. let now = Date()
  133. let dateFormatter = DateFormatter()
  134. dateFormatter.dateFormat = "HH:mm:ss"
  135. // iterate over basal entries
  136. for (index, entry) in basalEntries.enumerated() {
  137. guard let entryStartTime = dateFormatter.date(from: entry.start) else { continue }
  138. let entryEndTime: Date
  139. if index < basalEntries.count - 1,
  140. let nextEntryStartTime = dateFormatter.date(from: basalEntries[index + 1].start)
  141. {
  142. // end of current entry should equal start of next entry
  143. entryEndTime = nextEntryStartTime
  144. } else {
  145. // if it is the last entry use current time as end of entry
  146. entryEndTime = now
  147. }
  148. // proof if current time is between start and end of entry
  149. if now >= entryStartTime, now < entryEndTime {
  150. currentBasal = entry.rate
  151. break
  152. }
  153. }
  154. }
  155. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  156. /// Calculate insulin recommendation
  157. func calculateInsulin() -> Decimal {
  158. // ensure that isf is in mg/dL
  159. var conversion: Decimal {
  160. units == .mmolL ? 0.0555 : 1
  161. }
  162. let isfForCalculation = isf / conversion
  163. // insulin needed for the current blood glucose
  164. targetDifference = currentBG - target
  165. targetDifferenceInsulin = targetDifference / isfForCalculation
  166. // more or less insulin because of bg trend in the last 15 minutes
  167. fifteenMinInsulin = deltaBG / isfForCalculation
  168. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  169. wholeCob = Decimal(cob) + carbs
  170. wholeCobInsulin = wholeCob / carbRatio
  171. // determine how much the calculator reduces/ increases the bolus because of IOB
  172. iobInsulinReduction = (-1) * iob
  173. // adding everything together
  174. // add a calc for the case that no fifteenMinInsulin is available
  175. if deltaBG != 0 {
  176. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  177. } else {
  178. // add (rare) case that no glucose value is available -> maybe display warning?
  179. // if no bg is available, ?? sets its value to 0
  180. if currentBG == 0 {
  181. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  182. } else {
  183. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  184. }
  185. }
  186. // apply custom factor at the end of the calculations
  187. let result = wholeCalc * fraction
  188. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  189. if useFattyMealCorrectionFactor {
  190. insulinCalculated = result * fattyMealFactor
  191. } else if useSuperBolus {
  192. superBolusInsulin = sweetMealFactor * currentBasal
  193. insulinCalculated = result + superBolusInsulin
  194. } else {
  195. insulinCalculated = result
  196. }
  197. // display no negative insulinCalculated
  198. insulinCalculated = max(insulinCalculated, 0)
  199. insulinCalculated = min(insulinCalculated, maxBolus)
  200. guard let apsManager = apsManager else {
  201. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  202. return insulinCalculated
  203. }
  204. return apsManager.roundBolus(amount: insulinCalculated)
  205. }
  206. // MARK: - Button tasks
  207. @MainActor func invokeTreatmentsTask() {
  208. Task {
  209. let isInsulinGiven = amount > 0
  210. let isCarbsPresent = carbs > 0
  211. if isInsulinGiven {
  212. try await handleInsulin(isExternal: externalInsulin)
  213. } else if isCarbsPresent {
  214. waitForSuggestion = true
  215. } else {
  216. hideModal()
  217. return
  218. }
  219. saveMeal()
  220. addButtonPressed = true
  221. // if glucose data is stale end the custom loading animation by hiding the modal
  222. // guard glucoseOfLast20Min.first?.date ?? now >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  223. // return hideModal()
  224. // }
  225. }
  226. }
  227. // MARK: - Insulin
  228. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  229. if !isExternal {
  230. await addPumpInsulin()
  231. } else {
  232. await addExternalInsulin()
  233. }
  234. waitForSuggestion = true
  235. }
  236. @MainActor func addPumpInsulin() async {
  237. guard amount > 0 else {
  238. showModal(for: nil)
  239. return
  240. }
  241. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  242. do {
  243. let authenticated = try await unlockmanager.unlock()
  244. if authenticated {
  245. apsManager.enactBolus(amount: maxAmount, isSMB: false)
  246. // savePumpInsulin(amount: amount)
  247. // already saved via pumphistory through apsManager
  248. } else {
  249. print("authentication failed")
  250. }
  251. } catch {
  252. print("authentication error for pump bolus: \(error.localizedDescription)")
  253. DispatchQueue.main.async {
  254. self.waitForSuggestion = false
  255. if self.addButtonPressed {
  256. self.hideModal()
  257. }
  258. }
  259. }
  260. }
  261. private func savePumpInsulin(amount _: Decimal) {
  262. context.perform {
  263. // create pump event
  264. let newPumpEvent = PumpEventStored(context: self.context)
  265. newPumpEvent.timestamp = Date()
  266. newPumpEvent.type = PumpEvent.bolus.rawValue
  267. // create bolus entry and specify relationship to pump event
  268. let newBolusEntry = BolusStored(context: self.context)
  269. newBolusEntry.pumpEvent = newPumpEvent
  270. newBolusEntry.amount = self.amount as NSDecimalNumber
  271. newBolusEntry.isExternal = false
  272. newBolusEntry.isSMB = false
  273. do {
  274. guard self.context.hasChanges else { return }
  275. try self.context.save()
  276. } catch {
  277. print(error.localizedDescription)
  278. }
  279. }
  280. }
  281. // MARK: - EXTERNAL INSULIN
  282. @MainActor func addExternalInsulin() async {
  283. guard amount > 0 else {
  284. showModal(for: nil)
  285. return
  286. }
  287. amount = min(amount, maxBolus * 3)
  288. do {
  289. let authenticated = try await unlockmanager.unlock()
  290. if authenticated {
  291. storeExternalInsulinEvent()
  292. } else {
  293. print("authentication failed")
  294. }
  295. } catch {
  296. print("authentication error for external insulin: \(error.localizedDescription)")
  297. DispatchQueue.main.async {
  298. self.waitForSuggestion = false
  299. if self.addButtonPressed {
  300. self.hideModal()
  301. }
  302. }
  303. }
  304. }
  305. private func storeExternalInsulinEvent() {
  306. pumpHistoryStorage.storeEvents(
  307. [
  308. PumpHistoryEvent(
  309. id: UUID().uuidString,
  310. type: .bolus,
  311. timestamp: date,
  312. amount: amount,
  313. duration: nil,
  314. durationMin: nil,
  315. rate: nil,
  316. temp: nil,
  317. carbInput: nil,
  318. isExternal: true
  319. )
  320. ]
  321. )
  322. debug(.default, "External insulin saved to pumphistory.json")
  323. // save to core data asynchronously
  324. context.perform {
  325. // create pump event
  326. let newPumpEvent = PumpEventStored(context: self.context)
  327. // newPumpEvent.id = UUID().uuidString
  328. newPumpEvent.timestamp = self.date
  329. newPumpEvent.type = PumpEvent.bolus.rawValue
  330. // create bolus entry and specify relationship to pump event
  331. let newBolusEntry = BolusStored(context: self.context)
  332. newBolusEntry.pumpEvent = newPumpEvent
  333. newBolusEntry.amount = self.amount as NSDecimalNumber
  334. newBolusEntry.isExternal = true
  335. newBolusEntry.isSMB = false
  336. do {
  337. guard self.context.hasChanges else { return }
  338. try self.context.save()
  339. } catch {
  340. print(error.localizedDescription)
  341. }
  342. }
  343. // perform determine basal sync
  344. apsManager.determineBasalSync()
  345. }
  346. // MARK: - Carbs
  347. // we need to also fetch the data after we have saved them in order to update the array and the UI because of the MVVM Architecture
  348. func saveMeal() {
  349. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  350. carbs = min(carbs, maxCarbs)
  351. id_ = UUID().uuidString
  352. let carbsToStore = [CarbsEntry(
  353. id: id_,
  354. createdAt: now,
  355. actualDate: date,
  356. carbs: carbs,
  357. fat: fat,
  358. protein: protein,
  359. note: note,
  360. enteredBy: CarbsEntry.manual,
  361. isFPU: false, fpuID: UUID().uuidString
  362. )]
  363. carbsStorage.storeCarbs(carbsToStore)
  364. if carbs > 0 {
  365. // 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
  366. if amount <= 0 {
  367. apsManager.determineBasalSync()
  368. }
  369. }
  370. }
  371. // MARK: - Presets
  372. func deletePreset() {
  373. if selection != nil {
  374. context.delete(selection!)
  375. do {
  376. guard context.hasChanges else { return }
  377. try context.save()
  378. } catch {
  379. print(error.localizedDescription)
  380. }
  381. carbs = 0
  382. fat = 0
  383. protein = 0
  384. }
  385. selection = nil
  386. }
  387. func removePresetFromNewMeal() {
  388. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  389. if a != nil, summation[a ?? 0] != "" {
  390. summation.remove(at: a!)
  391. }
  392. }
  393. func addPresetToNewMeal() {
  394. let test: String = selection?.dish ?? "dontAdd"
  395. if test != "dontAdd" {
  396. summation.append(test)
  397. }
  398. }
  399. func addNewPresetToWaitersNotepad(_ dish: String) {
  400. summation.append(dish)
  401. }
  402. func addToSummation() {
  403. summation.append(selection?.dish ?? "")
  404. }
  405. func waitersNotepad() -> String {
  406. var filteredArray = summation.filter { !$0.isEmpty }
  407. if carbs == 0, protein == 0, fat == 0 {
  408. filteredArray = []
  409. }
  410. guard filteredArray != [] else {
  411. return ""
  412. }
  413. var carbs_: Decimal = 0.0
  414. var fat_: Decimal = 0.0
  415. var protein_: Decimal = 0.0
  416. var presetArray = [Presets]()
  417. context.performAndWait {
  418. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  419. try? presetArray = context.fetch(requestPresets)
  420. }
  421. var waitersNotepad = [String]()
  422. var stringValue = ""
  423. for each in filteredArray {
  424. let countedSet = NSCountedSet(array: filteredArray)
  425. let count = countedSet.count(for: each)
  426. if each != stringValue {
  427. waitersNotepad.append("\(count) \(each)")
  428. }
  429. stringValue = each
  430. for sel in presetArray {
  431. if sel.dish == each {
  432. carbs_ += (sel.carbs)! as Decimal
  433. fat_ += (sel.fat)! as Decimal
  434. protein_ += (sel.protein)! as Decimal
  435. break
  436. }
  437. }
  438. }
  439. let extracarbs = carbs - carbs_
  440. let extraFat = fat - fat_
  441. let extraProtein = protein - protein_
  442. var addedString = ""
  443. if extracarbs > 0, filteredArray.isNotEmpty {
  444. addedString += "Additional carbs: \(extracarbs) ,"
  445. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  446. if extraFat > 0, filteredArray.isNotEmpty {
  447. addedString += "Additional fat: \(extraFat) ,"
  448. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  449. if extraProtein > 0, filteredArray.isNotEmpty {
  450. addedString += "Additional protein: \(extraProtein) ,"
  451. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  452. if addedString != "" {
  453. waitersNotepad.append(addedString)
  454. }
  455. var waitersNotepadString = ""
  456. if waitersNotepad.count == 1 {
  457. waitersNotepadString = waitersNotepad[0]
  458. } else if waitersNotepad.count > 1 {
  459. for each in waitersNotepad {
  460. if each != waitersNotepad.last {
  461. waitersNotepadString += " " + each + ","
  462. } else { waitersNotepadString += " " + each }
  463. }
  464. }
  465. return waitersNotepadString
  466. }
  467. }
  468. }
  469. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  470. func determinationDidUpdate(_: Determination) {
  471. DispatchQueue.main.async {
  472. self.waitForSuggestion = false
  473. if self.addButtonPressed {
  474. self.hideModal()
  475. }
  476. }
  477. }
  478. func bolusDidFail() {
  479. DispatchQueue.main.async {
  480. self.waitForSuggestion = false
  481. if self.addButtonPressed {
  482. self.hideModal()
  483. }
  484. }
  485. }
  486. }
  487. // MARK: - Setup Notifications
  488. extension Bolus.StateModel {
  489. /// listens for the notifications sent when the managedObjectContext has saved!
  490. func setupNotification() {
  491. Foundation.NotificationCenter.default.addObserver(
  492. self,
  493. selector: #selector(contextDidSave(_:)),
  494. name: Notification.Name.NSManagedObjectContextDidSave,
  495. object: backgroundContext
  496. )
  497. }
  498. /// determine the actions when the context has changed
  499. ///
  500. /// its done on a background thread and after that the UI gets updated on the main thread
  501. @objc private func contextDidSave(_ notification: Notification) {
  502. guard let userInfo = notification.userInfo else { return }
  503. Task { [weak self] in
  504. await self?.processUpdates(userInfo: userInfo)
  505. }
  506. }
  507. private func processUpdates(userInfo: [AnyHashable: Any]) async {
  508. var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
  509. objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
  510. objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
  511. let glucoseUpdates = objects.filter { $0 is GlucoseStored }
  512. let determinationUpdates = objects.filter { $0 is OrefDetermination }
  513. DispatchQueue.global(qos: .background).async {
  514. if glucoseUpdates.isNotEmpty {
  515. self.setupGlucoseArray()
  516. }
  517. if determinationUpdates.isNotEmpty {
  518. self.setupDeterminationsArray()
  519. }
  520. }
  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. await updateGlucoseArray(with: ids)
  530. }
  531. }
  532. private func fetchGlucose() async -> [NSManagedObjectID] {
  533. CoreDataStack.shared.fetchEntities(
  534. ofType: GlucoseStored.self,
  535. onContext: context,
  536. predicate: NSPredicate.predicateFor30MinAgo,
  537. key: "date",
  538. ascending: false,
  539. fetchLimit: 3
  540. ).map(\.objectID)
  541. }
  542. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  543. do {
  544. let glucoseObjects = try IDs.compactMap { id in
  545. try context.existingObject(with: id) as? GlucoseStored
  546. }
  547. glucoseFromPersistence = glucoseObjects
  548. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  549. let thirdLastGlucose = glucoseFromPersistence.last?.glucose ?? 0
  550. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  551. currentBG = Decimal(lastGlucose)
  552. deltaBG = delta
  553. } catch {
  554. debugPrint(
  555. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  556. )
  557. }
  558. }
  559. // Determinations
  560. private func setupDeterminationsArray() {
  561. Task {
  562. let ids = await self.fetchDeterminations()
  563. await updateDeterminationsArray(with: ids)
  564. }
  565. }
  566. private func fetchDeterminations() async -> [NSManagedObjectID] {
  567. CoreDataStack.shared.fetchEntities(
  568. ofType: OrefDetermination.self,
  569. onContext: context,
  570. predicate: NSPredicate.enactedDetermination,
  571. key: "deliverAt",
  572. ascending: false,
  573. fetchLimit: 1
  574. ).map(\.objectID)
  575. }
  576. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  577. do {
  578. let determinationObjects = try IDs.compactMap { id in
  579. try context.existingObject(with: id) as? OrefDetermination
  580. }
  581. guard let mostRecentDetermination = determinationObjects.first else { return }
  582. determination = determinationObjects
  583. // setup vars for bolus calculation
  584. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  585. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  586. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  587. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  588. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  589. cob = mostRecentDetermination.cob as Int16
  590. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  591. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  592. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  593. getCurrentBasal()
  594. insulinCalculated = calculateInsulin()
  595. } catch {
  596. debugPrint(
  597. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  598. )
  599. }
  600. }
  601. }