BolusStateModel.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  246. } else {
  247. print("authentication failed")
  248. }
  249. } catch {
  250. print("authentication error for pump bolus: \(error.localizedDescription)")
  251. DispatchQueue.main.async {
  252. self.waitForSuggestion = false
  253. if self.addButtonPressed {
  254. self.hideModal()
  255. }
  256. }
  257. }
  258. }
  259. private func savePumpInsulin(amount _: Decimal) {
  260. context.perform {
  261. // create pump event
  262. let newPumpEvent = PumpEventStored(context: self.context)
  263. newPumpEvent.timestamp = Date()
  264. newPumpEvent.type = PumpEvent.bolus.rawValue
  265. // create bolus entry and specify relationship to pump event
  266. let newBolusEntry = BolusStored(context: self.context)
  267. newBolusEntry.pumpEvent = newPumpEvent
  268. newBolusEntry.amount = self.amount as NSDecimalNumber
  269. newBolusEntry.isExternal = false
  270. newBolusEntry.isSMB = false
  271. do {
  272. guard self.context.hasChanges else { return }
  273. try self.context.save()
  274. } catch {
  275. print(error.localizedDescription)
  276. }
  277. }
  278. }
  279. // MARK: - EXTERNAL INSULIN
  280. @MainActor func addExternalInsulin() async {
  281. guard amount > 0 else {
  282. showModal(for: nil)
  283. return
  284. }
  285. amount = min(amount, maxBolus * 3)
  286. do {
  287. let authenticated = try await unlockmanager.unlock()
  288. if authenticated {
  289. storeExternalInsulinEvent()
  290. } else {
  291. print("authentication failed")
  292. }
  293. } catch {
  294. print("authentication error for external insulin: \(error.localizedDescription)")
  295. DispatchQueue.main.async {
  296. self.waitForSuggestion = false
  297. if self.addButtonPressed {
  298. self.hideModal()
  299. }
  300. }
  301. }
  302. }
  303. private func storeExternalInsulinEvent() {
  304. pumpHistoryStorage.storeEvents(
  305. [
  306. PumpHistoryEvent(
  307. id: UUID().uuidString,
  308. type: .bolus,
  309. timestamp: date,
  310. amount: amount,
  311. duration: nil,
  312. durationMin: nil,
  313. rate: nil,
  314. temp: nil,
  315. carbInput: nil,
  316. isExternal: true
  317. )
  318. ]
  319. )
  320. debug(.default, "External insulin saved to pumphistory.json")
  321. // save to core data asynchronously
  322. context.perform {
  323. // create pump event
  324. let newPumpEvent = PumpEventStored(context: self.context)
  325. // newPumpEvent.id = UUID().uuidString
  326. newPumpEvent.timestamp = self.date
  327. newPumpEvent.type = PumpEvent.bolus.rawValue
  328. // create bolus entry and specify relationship to pump event
  329. let newBolusEntry = BolusStored(context: self.context)
  330. newBolusEntry.pumpEvent = newPumpEvent
  331. newBolusEntry.amount = self.amount as NSDecimalNumber
  332. newBolusEntry.isExternal = true
  333. newBolusEntry.isSMB = false
  334. do {
  335. guard self.context.hasChanges else { return }
  336. try self.context.save()
  337. } catch {
  338. print(error.localizedDescription)
  339. }
  340. }
  341. // perform determine basal sync
  342. apsManager.determineBasalSync()
  343. }
  344. // MARK: - Carbs
  345. // 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
  346. func saveMeal() {
  347. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  348. carbs = min(carbs, maxCarbs)
  349. id_ = UUID().uuidString
  350. let carbsToStore = [CarbsEntry(
  351. id: id_,
  352. createdAt: now,
  353. actualDate: date,
  354. carbs: carbs,
  355. fat: fat,
  356. protein: protein,
  357. note: note,
  358. enteredBy: CarbsEntry.manual,
  359. isFPU: false, fpuID: UUID().uuidString
  360. )]
  361. carbsStorage.storeCarbs(carbsToStore)
  362. if carbs > 0 {
  363. // 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
  364. if amount <= 0 {
  365. apsManager.determineBasalSync()
  366. }
  367. }
  368. }
  369. // MARK: - Presets
  370. func deletePreset() {
  371. if selection != nil {
  372. context.delete(selection!)
  373. do {
  374. guard context.hasChanges else { return }
  375. try context.save()
  376. } catch {
  377. print(error.localizedDescription)
  378. }
  379. carbs = 0
  380. fat = 0
  381. protein = 0
  382. }
  383. selection = nil
  384. }
  385. func removePresetFromNewMeal() {
  386. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  387. if a != nil, summation[a ?? 0] != "" {
  388. summation.remove(at: a!)
  389. }
  390. }
  391. func addPresetToNewMeal() {
  392. let test: String = selection?.dish ?? "dontAdd"
  393. if test != "dontAdd" {
  394. summation.append(test)
  395. }
  396. }
  397. func addNewPresetToWaitersNotepad(_ dish: String) {
  398. summation.append(dish)
  399. }
  400. func addToSummation() {
  401. summation.append(selection?.dish ?? "")
  402. }
  403. func waitersNotepad() -> String {
  404. var filteredArray = summation.filter { !$0.isEmpty }
  405. if carbs == 0, protein == 0, fat == 0 {
  406. filteredArray = []
  407. }
  408. guard filteredArray != [] else {
  409. return ""
  410. }
  411. var carbs_: Decimal = 0.0
  412. var fat_: Decimal = 0.0
  413. var protein_: Decimal = 0.0
  414. var presetArray = [Presets]()
  415. context.performAndWait {
  416. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  417. try? presetArray = context.fetch(requestPresets)
  418. }
  419. var waitersNotepad = [String]()
  420. var stringValue = ""
  421. for each in filteredArray {
  422. let countedSet = NSCountedSet(array: filteredArray)
  423. let count = countedSet.count(for: each)
  424. if each != stringValue {
  425. waitersNotepad.append("\(count) \(each)")
  426. }
  427. stringValue = each
  428. for sel in presetArray {
  429. if sel.dish == each {
  430. carbs_ += (sel.carbs)! as Decimal
  431. fat_ += (sel.fat)! as Decimal
  432. protein_ += (sel.protein)! as Decimal
  433. break
  434. }
  435. }
  436. }
  437. let extracarbs = carbs - carbs_
  438. let extraFat = fat - fat_
  439. let extraProtein = protein - protein_
  440. var addedString = ""
  441. if extracarbs > 0, filteredArray.isNotEmpty {
  442. addedString += "Additional carbs: \(extracarbs) ,"
  443. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  444. if extraFat > 0, filteredArray.isNotEmpty {
  445. addedString += "Additional fat: \(extraFat) ,"
  446. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  447. if extraProtein > 0, filteredArray.isNotEmpty {
  448. addedString += "Additional protein: \(extraProtein) ,"
  449. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  450. if addedString != "" {
  451. waitersNotepad.append(addedString)
  452. }
  453. var waitersNotepadString = ""
  454. if waitersNotepad.count == 1 {
  455. waitersNotepadString = waitersNotepad[0]
  456. } else if waitersNotepad.count > 1 {
  457. for each in waitersNotepad {
  458. if each != waitersNotepad.last {
  459. waitersNotepadString += " " + each + ","
  460. } else { waitersNotepadString += " " + each }
  461. }
  462. }
  463. return waitersNotepadString
  464. }
  465. }
  466. }
  467. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  468. func determinationDidUpdate(_: Determination) {
  469. DispatchQueue.main.async {
  470. self.waitForSuggestion = false
  471. if self.addButtonPressed {
  472. self.hideModal()
  473. }
  474. }
  475. }
  476. func bolusDidFail() {
  477. DispatchQueue.main.async {
  478. self.waitForSuggestion = false
  479. if self.addButtonPressed {
  480. self.hideModal()
  481. }
  482. }
  483. }
  484. }
  485. // MARK: - Setup Notifications
  486. extension Bolus.StateModel {
  487. /// listens for the notifications sent when the managedObjectContext has saved!
  488. func setupNotification() {
  489. Foundation.NotificationCenter.default.addObserver(
  490. self,
  491. selector: #selector(contextDidSave(_:)),
  492. name: Notification.Name.NSManagedObjectContextDidSave,
  493. object: backgroundContext
  494. )
  495. }
  496. /// determine the actions when the context has changed
  497. ///
  498. /// its done on a background thread and after that the UI gets updated on the main thread
  499. @objc private func contextDidSave(_ notification: Notification) {
  500. guard let userInfo = notification.userInfo else { return }
  501. Task { [weak self] in
  502. await self?.processUpdates(userInfo: userInfo)
  503. }
  504. }
  505. private func processUpdates(userInfo: [AnyHashable: Any]) async {
  506. var objects = Set((userInfo[NSInsertedObjectsKey] as? Set<NSManagedObject>) ?? [])
  507. objects.formUnion((userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject>) ?? [])
  508. objects.formUnion((userInfo[NSDeletedObjectsKey] as? Set<NSManagedObject>) ?? [])
  509. let glucoseUpdates = objects.filter { $0 is GlucoseStored }
  510. let determinationUpdates = objects.filter { $0 is OrefDetermination }
  511. DispatchQueue.global(qos: .background).async {
  512. if glucoseUpdates.isNotEmpty {
  513. self.setupGlucoseArray()
  514. }
  515. if determinationUpdates.isNotEmpty {
  516. self.setupDeterminationsArray()
  517. }
  518. }
  519. }
  520. }
  521. // MARK: - Setup Glucose and Determinations
  522. extension Bolus.StateModel {
  523. // Glucose
  524. private func setupGlucoseArray() {
  525. Task {
  526. let ids = await self.fetchGlucose()
  527. await updateGlucoseArray(with: ids)
  528. }
  529. }
  530. private func fetchGlucose() async -> [NSManagedObjectID] {
  531. CoreDataStack.shared.fetchEntities(
  532. ofType: GlucoseStored.self,
  533. onContext: context,
  534. predicate: NSPredicate.predicateFor30MinAgo,
  535. key: "date",
  536. ascending: false,
  537. fetchLimit: 3
  538. ).map(\.objectID)
  539. }
  540. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  541. do {
  542. let glucoseObjects = try IDs.compactMap { id in
  543. try context.existingObject(with: id) as? GlucoseStored
  544. }
  545. glucoseFromPersistence = glucoseObjects
  546. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  547. let thirdLastGlucose = glucoseFromPersistence.last?.glucose ?? 0
  548. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  549. currentBG = Decimal(lastGlucose)
  550. deltaBG = delta
  551. } catch {
  552. debugPrint(
  553. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  554. )
  555. }
  556. }
  557. // Determinations
  558. private func setupDeterminationsArray() {
  559. Task {
  560. let ids = await self.fetchDeterminations()
  561. await updateDeterminationsArray(with: ids)
  562. }
  563. }
  564. private func fetchDeterminations() async -> [NSManagedObjectID] {
  565. CoreDataStack.shared.fetchEntities(
  566. ofType: OrefDetermination.self,
  567. onContext: context,
  568. predicate: NSPredicate.enactedDetermination,
  569. key: "deliverAt",
  570. ascending: false,
  571. fetchLimit: 1
  572. ).map(\.objectID)
  573. }
  574. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  575. do {
  576. let determinationObjects = try IDs.compactMap { id in
  577. try context.existingObject(with: id) as? OrefDetermination
  578. }
  579. guard let mostRecentDetermination = determinationObjects.first else { return }
  580. determination = determinationObjects
  581. // setup vars for bolus calculation
  582. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  583. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  584. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  585. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  586. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  587. cob = mostRecentDetermination.cob as Int16
  588. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  589. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  590. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  591. getCurrentBasal()
  592. insulinCalculated = calculateInsulin()
  593. } catch {
  594. debugPrint(
  595. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  596. )
  597. }
  598. }
  599. }