BolusStateModel.swift 25 KB

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