BolusStateModel.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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 skipBolus: Bool = false
  80. @Published var externalInsulin: Bool = false
  81. @Published var showInfo: Bool = false
  82. @Published var glucoseFromPersistence: [GlucoseStored] = []
  83. @Published var determination: [OrefDetermination] = []
  84. let now = Date.now
  85. let context = CoreDataStack.shared.persistentContainer.viewContext
  86. let backgroundContext = CoreDataStack.shared.newTaskContext()
  87. private var coreDataObserver: CoreDataObserver?
  88. typealias PumpEvent = PumpEventStored.EventType
  89. override func subscribe() {
  90. setupGlucoseNotification()
  91. coreDataObserver = CoreDataObserver()
  92. registerHandlers()
  93. setupGlucoseArray()
  94. setupDeterminationsArray()
  95. broadcaster.register(DeterminationObserver.self, observer: self)
  96. broadcaster.register(BolusFailureObserver.self, observer: self)
  97. units = settingsManager.settings.units
  98. percentage = settingsManager.settings.insulinReqPercentage
  99. maxBolus = provider.pumpSettings().maxBolus
  100. // added
  101. fraction = settings.settings.overrideFactor
  102. useCalc = settings.settings.useCalc
  103. fattyMeals = settings.settings.fattyMeals
  104. fattyMealFactor = settings.settings.fattyMealFactor
  105. sweetMeals = settings.settings.sweetMeals
  106. sweetMealFactor = settings.settings.sweetMealFactor
  107. displayPresets = settings.settings.displayPresets
  108. maxCarbs = settings.settings.maxCarbs
  109. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  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. func invokeTreatmentsTask() {
  216. Task {
  217. await MainActor.run {
  218. self.addButtonPressed = true
  219. }
  220. let isInsulinGiven = amount > 0
  221. let isCarbsPresent = carbs > 0
  222. let isFatPresent = fat > 0
  223. let isProteinPresent = protein > 0
  224. if isInsulinGiven {
  225. try await handleInsulin(isExternal: externalInsulin)
  226. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  227. await MainActor.run {
  228. self.waitForSuggestion = true
  229. }
  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. private func handleInsulin(isExternal: Bool) async throws {
  243. if !isExternal {
  244. await addPumpInsulin()
  245. } else {
  246. await addExternalInsulin()
  247. }
  248. await MainActor.run {
  249. self.waitForSuggestion = true
  250. }
  251. }
  252. func addPumpInsulin() async {
  253. guard amount > 0 else {
  254. showModal(for: nil)
  255. return
  256. }
  257. let maxAmount = Double(min(amount, maxBolus))
  258. do {
  259. let authenticated = try await unlockmanager.unlock()
  260. if authenticated {
  261. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  262. } else {
  263. print("authentication failed")
  264. }
  265. } catch {
  266. print("authentication error for pump bolus: \(error.localizedDescription)")
  267. await MainActor.run {
  268. self.waitForSuggestion = false
  269. if self.addButtonPressed {
  270. self.hideModal()
  271. }
  272. }
  273. }
  274. }
  275. private func savePumpInsulin(amount _: Decimal) {
  276. context.perform {
  277. // create pump event
  278. let newPumpEvent = PumpEventStored(context: self.context)
  279. newPumpEvent.timestamp = Date()
  280. newPumpEvent.type = PumpEvent.bolus.rawValue
  281. // create bolus entry and specify relationship to pump event
  282. let newBolusEntry = BolusStored(context: self.context)
  283. newBolusEntry.pumpEvent = newPumpEvent
  284. newBolusEntry.amount = self.amount as NSDecimalNumber
  285. newBolusEntry.isExternal = false
  286. newBolusEntry.isSMB = false
  287. do {
  288. guard self.context.hasChanges else { return }
  289. try self.context.save()
  290. } catch {
  291. print(error.localizedDescription)
  292. }
  293. }
  294. }
  295. // MARK: - EXTERNAL INSULIN
  296. func addExternalInsulin() async {
  297. guard amount > 0 else {
  298. showModal(for: nil)
  299. return
  300. }
  301. await MainActor.run {
  302. self.amount = min(self.amount, self.maxBolus * 3)
  303. }
  304. do {
  305. let authenticated = try await unlockmanager.unlock()
  306. if authenticated {
  307. // store external dose to pump history
  308. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  309. // perform determine basal sync
  310. await apsManager.determineBasalSync()
  311. } else {
  312. print("authentication failed")
  313. }
  314. } catch {
  315. print("authentication error for external insulin: \(error.localizedDescription)")
  316. await MainActor.run {
  317. self.waitForSuggestion = false
  318. if self.addButtonPressed {
  319. self.hideModal()
  320. }
  321. }
  322. }
  323. }
  324. // MARK: - Carbs
  325. func saveMeal() async {
  326. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  327. DispatchQueue.main.async {
  328. self.carbs = min(self.carbs, self.maxCarbs)
  329. self.id_ = UUID().uuidString
  330. }
  331. let carbsToStore = [CarbsEntry(
  332. id: id_,
  333. createdAt: now,
  334. actualDate: date,
  335. carbs: carbs,
  336. fat: fat,
  337. protein: protein,
  338. note: note,
  339. enteredBy: CarbsEntry.manual,
  340. isFPU: false, fpuID: UUID().uuidString
  341. )]
  342. await carbsStorage.storeCarbs(carbsToStore)
  343. if carbs > 0 || fat > 0 || protein > 0 {
  344. // 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
  345. if amount <= 0 {
  346. await apsManager.determineBasalSync()
  347. }
  348. }
  349. }
  350. // MARK: - Presets
  351. func deletePreset() {
  352. if selection != nil {
  353. context.delete(selection!)
  354. do {
  355. guard context.hasChanges else { return }
  356. try context.save()
  357. } catch {
  358. print(error.localizedDescription)
  359. }
  360. carbs = 0
  361. fat = 0
  362. protein = 0
  363. }
  364. selection = nil
  365. }
  366. func removePresetFromNewMeal() {
  367. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  368. if a != nil, summation[a ?? 0] != "" {
  369. summation.remove(at: a!)
  370. }
  371. }
  372. func addPresetToNewMeal() {
  373. let test: String = selection?.dish ?? "dontAdd"
  374. if test != "dontAdd" {
  375. summation.append(test)
  376. }
  377. }
  378. func addNewPresetToWaitersNotepad(_ dish: String) {
  379. summation.append(dish)
  380. }
  381. func addToSummation() {
  382. summation.append(selection?.dish ?? "")
  383. }
  384. func waitersNotepad() -> String {
  385. var filteredArray = summation.filter { !$0.isEmpty }
  386. if carbs == 0, protein == 0, fat == 0 {
  387. filteredArray = []
  388. }
  389. guard filteredArray != [] else {
  390. return ""
  391. }
  392. var carbs_: Decimal = 0.0
  393. var fat_: Decimal = 0.0
  394. var protein_: Decimal = 0.0
  395. var presetArray = [MealPresetStored]()
  396. context.performAndWait {
  397. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  398. try? presetArray = context.fetch(requestPresets)
  399. }
  400. var waitersNotepad = [String]()
  401. var stringValue = ""
  402. for each in filteredArray {
  403. let countedSet = NSCountedSet(array: filteredArray)
  404. let count = countedSet.count(for: each)
  405. if each != stringValue {
  406. waitersNotepad.append("\(count) \(each)")
  407. }
  408. stringValue = each
  409. for sel in presetArray {
  410. if sel.dish == each {
  411. carbs_ += (sel.carbs)! as Decimal
  412. fat_ += (sel.fat)! as Decimal
  413. protein_ += (sel.protein)! as Decimal
  414. break
  415. }
  416. }
  417. }
  418. let extracarbs = carbs - carbs_
  419. let extraFat = fat - fat_
  420. let extraProtein = protein - protein_
  421. var addedString = ""
  422. if extracarbs > 0, filteredArray.isNotEmpty {
  423. addedString += "Additional carbs: \(extracarbs) ,"
  424. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  425. if extraFat > 0, filteredArray.isNotEmpty {
  426. addedString += "Additional fat: \(extraFat) ,"
  427. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  428. if extraProtein > 0, filteredArray.isNotEmpty {
  429. addedString += "Additional protein: \(extraProtein) ,"
  430. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  431. if addedString != "" {
  432. waitersNotepad.append(addedString)
  433. }
  434. var waitersNotepadString = ""
  435. if waitersNotepad.count == 1 {
  436. waitersNotepadString = waitersNotepad[0]
  437. } else if waitersNotepad.count > 1 {
  438. for each in waitersNotepad {
  439. if each != waitersNotepad.last {
  440. waitersNotepadString += " " + each + ","
  441. } else { waitersNotepadString += " " + each }
  442. }
  443. }
  444. return waitersNotepadString
  445. }
  446. }
  447. }
  448. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  449. func determinationDidUpdate(_: Determination) {
  450. DispatchQueue.main.async {
  451. self.waitForSuggestion = false
  452. if self.addButtonPressed {
  453. self.hideModal()
  454. }
  455. }
  456. }
  457. func bolusDidFail() {
  458. DispatchQueue.main.async {
  459. self.waitForSuggestion = false
  460. if self.addButtonPressed {
  461. self.hideModal()
  462. }
  463. }
  464. }
  465. }
  466. extension Bolus.StateModel {
  467. private func registerHandlers() {
  468. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  469. guard let self = self else { return }
  470. self.setupDeterminationsArray()
  471. }
  472. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  473. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  474. guard let self = self else { return }
  475. self.setupGlucoseArray()
  476. }
  477. }
  478. private func setupGlucoseNotification() {
  479. /// custom notification that is sent when a batch insert of glucose objects is done
  480. Foundation.NotificationCenter.default.addObserver(
  481. self,
  482. selector: #selector(handleBatchInsert),
  483. name: .didPerformBatchInsert,
  484. object: nil
  485. )
  486. }
  487. @objc private func handleBatchInsert() {
  488. setupGlucoseArray()
  489. }
  490. }
  491. // MARK: - Setup Glucose and Determinations
  492. extension Bolus.StateModel {
  493. // Glucose
  494. private func setupGlucoseArray() {
  495. Task {
  496. let ids = await self.fetchGlucose()
  497. await updateGlucoseArray(with: ids)
  498. }
  499. }
  500. private func fetchGlucose() async -> [NSManagedObjectID] {
  501. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  502. ofType: GlucoseStored.self,
  503. onContext: backgroundContext,
  504. predicate: NSPredicate.predicateFor30MinAgo,
  505. key: "date",
  506. ascending: false,
  507. fetchLimit: 3
  508. )
  509. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  510. return await backgroundContext.perform {
  511. return fetchedResults.map(\.objectID)
  512. }
  513. }
  514. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  515. do {
  516. let glucoseObjects = try IDs.compactMap { id in
  517. try context.existingObject(with: id) as? GlucoseStored
  518. }
  519. glucoseFromPersistence = glucoseObjects
  520. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  521. let thirdLastGlucose = glucoseFromPersistence.last?.glucose ?? 0
  522. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  523. currentBG = Decimal(lastGlucose)
  524. deltaBG = delta
  525. } catch {
  526. debugPrint(
  527. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  528. )
  529. }
  530. }
  531. // Determinations
  532. private func setupDeterminationsArray() {
  533. Task {
  534. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  535. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  536. )
  537. await updateDeterminationsArray(with: ids)
  538. }
  539. }
  540. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  541. do {
  542. let determinationObjects = try IDs.compactMap { id in
  543. try context.existingObject(with: id) as? OrefDetermination
  544. }
  545. guard let mostRecentDetermination = determinationObjects.first else { return }
  546. determination = determinationObjects
  547. // setup vars for bolus calculation
  548. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  549. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  550. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  551. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  552. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  553. cob = mostRecentDetermination.cob as Int16
  554. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  555. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  556. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  557. getCurrentBasal()
  558. insulinCalculated = calculateInsulin()
  559. } catch {
  560. debugPrint(
  561. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  562. )
  563. }
  564. }
  565. }