BolusStateModel.swift 24 KB

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