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