BolusStateModel.swift 25 KB

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