BolusStateModel.swift 25 KB

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