BolusStateModel.swift 24 KB

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