BolusStateModel.swift 25 KB

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