BolusStateModel.swift 24 KB

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