BolusStateModel.swift 24 KB

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