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. @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. @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, maxBolus * 3)
  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. id_ = UUID().uuidString
  321. let carbsToStore = [CarbsEntry(
  322. id: id_,
  323. createdAt: now,
  324. actualDate: date,
  325. carbs: carbs,
  326. fat: fat,
  327. protein: protein,
  328. note: note,
  329. enteredBy: CarbsEntry.manual,
  330. isFPU: false, fpuID: UUID().uuidString
  331. )]
  332. await carbsStorage.storeCarbs(carbsToStore)
  333. if carbs > 0 || fat > 0 || protein > 0 {
  334. // 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
  335. if amount <= 0 {
  336. await apsManager.determineBasalSync()
  337. }
  338. }
  339. }
  340. // MARK: - Presets
  341. func deletePreset() {
  342. if selection != nil {
  343. context.delete(selection!)
  344. do {
  345. guard context.hasChanges else { return }
  346. try context.save()
  347. } catch {
  348. print(error.localizedDescription)
  349. }
  350. carbs = 0
  351. fat = 0
  352. protein = 0
  353. }
  354. selection = nil
  355. }
  356. func removePresetFromNewMeal() {
  357. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  358. if a != nil, summation[a ?? 0] != "" {
  359. summation.remove(at: a!)
  360. }
  361. }
  362. func addPresetToNewMeal() {
  363. let test: String = selection?.dish ?? "dontAdd"
  364. if test != "dontAdd" {
  365. summation.append(test)
  366. }
  367. }
  368. func addNewPresetToWaitersNotepad(_ dish: String) {
  369. summation.append(dish)
  370. }
  371. func addToSummation() {
  372. summation.append(selection?.dish ?? "")
  373. }
  374. func waitersNotepad() -> String {
  375. var filteredArray = summation.filter { !$0.isEmpty }
  376. if carbs == 0, protein == 0, fat == 0 {
  377. filteredArray = []
  378. }
  379. guard filteredArray != [] else {
  380. return ""
  381. }
  382. var carbs_: Decimal = 0.0
  383. var fat_: Decimal = 0.0
  384. var protein_: Decimal = 0.0
  385. var presetArray = [MealPresetStored]()
  386. context.performAndWait {
  387. let requestPresets = MealPresetStored.fetchRequest() as NSFetchRequest<MealPresetStored>
  388. try? presetArray = context.fetch(requestPresets)
  389. }
  390. var waitersNotepad = [String]()
  391. var stringValue = ""
  392. for each in filteredArray {
  393. let countedSet = NSCountedSet(array: filteredArray)
  394. let count = countedSet.count(for: each)
  395. if each != stringValue {
  396. waitersNotepad.append("\(count) \(each)")
  397. }
  398. stringValue = each
  399. for sel in presetArray {
  400. if sel.dish == each {
  401. carbs_ += (sel.carbs)! as Decimal
  402. fat_ += (sel.fat)! as Decimal
  403. protein_ += (sel.protein)! as Decimal
  404. break
  405. }
  406. }
  407. }
  408. let extracarbs = carbs - carbs_
  409. let extraFat = fat - fat_
  410. let extraProtein = protein - protein_
  411. var addedString = ""
  412. if extracarbs > 0, filteredArray.isNotEmpty {
  413. addedString += "Additional carbs: \(extracarbs) ,"
  414. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  415. if extraFat > 0, filteredArray.isNotEmpty {
  416. addedString += "Additional fat: \(extraFat) ,"
  417. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  418. if extraProtein > 0, filteredArray.isNotEmpty {
  419. addedString += "Additional protein: \(extraProtein) ,"
  420. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  421. if addedString != "" {
  422. waitersNotepad.append(addedString)
  423. }
  424. var waitersNotepadString = ""
  425. if waitersNotepad.count == 1 {
  426. waitersNotepadString = waitersNotepad[0]
  427. } else if waitersNotepad.count > 1 {
  428. for each in waitersNotepad {
  429. if each != waitersNotepad.last {
  430. waitersNotepadString += " " + each + ","
  431. } else { waitersNotepadString += " " + each }
  432. }
  433. }
  434. return waitersNotepadString
  435. }
  436. }
  437. }
  438. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  439. func determinationDidUpdate(_: Determination) {
  440. DispatchQueue.main.async {
  441. self.waitForSuggestion = false
  442. if self.addButtonPressed {
  443. self.hideModal()
  444. }
  445. }
  446. }
  447. func bolusDidFail() {
  448. DispatchQueue.main.async {
  449. self.waitForSuggestion = false
  450. if self.addButtonPressed {
  451. self.hideModal()
  452. }
  453. }
  454. }
  455. }
  456. extension Bolus.StateModel {
  457. private func registerHandlers() {
  458. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  459. guard let self = self else { return }
  460. self.setupDeterminationsArray()
  461. }
  462. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  463. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  464. guard let self = self else { return }
  465. self.setupGlucoseArray()
  466. }
  467. }
  468. private func setupGlucoseNotification() {
  469. /// custom notification that is sent when a batch insert of glucose objects is done
  470. Foundation.NotificationCenter.default.addObserver(
  471. self,
  472. selector: #selector(handleBatchInsert),
  473. name: .didPerformBatchInsert,
  474. object: nil
  475. )
  476. }
  477. @objc private func handleBatchInsert() {
  478. setupGlucoseArray()
  479. }
  480. }
  481. // MARK: - Setup Glucose and Determinations
  482. extension Bolus.StateModel {
  483. // Glucose
  484. private func setupGlucoseArray() {
  485. Task {
  486. let ids = await self.fetchGlucose()
  487. await updateGlucoseArray(with: ids)
  488. }
  489. }
  490. private func fetchGlucose() async -> [NSManagedObjectID] {
  491. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  492. ofType: GlucoseStored.self,
  493. onContext: backgroundContext,
  494. predicate: NSPredicate.predicateFor30MinAgo,
  495. key: "date",
  496. ascending: false,
  497. fetchLimit: 3
  498. )
  499. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  500. return await backgroundContext.perform {
  501. return fetchedResults.map(\.objectID)
  502. }
  503. }
  504. @MainActor private func updateGlucoseArray(with IDs: [NSManagedObjectID]) {
  505. do {
  506. let glucoseObjects = try IDs.compactMap { id in
  507. try context.existingObject(with: id) as? GlucoseStored
  508. }
  509. glucoseFromPersistence = glucoseObjects
  510. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  511. let thirdLastGlucose = glucoseFromPersistence.last?.glucose ?? 0
  512. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  513. currentBG = Decimal(lastGlucose)
  514. deltaBG = delta
  515. } catch {
  516. debugPrint(
  517. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the glucose array: \(error.localizedDescription)"
  518. )
  519. }
  520. }
  521. // Determinations
  522. private func setupDeterminationsArray() {
  523. Task {
  524. let ids = await determinationStorage.fetchLastDeterminationObjectID(
  525. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  526. )
  527. await updateDeterminationsArray(with: ids)
  528. }
  529. }
  530. @MainActor private func updateDeterminationsArray(with IDs: [NSManagedObjectID]) {
  531. do {
  532. let determinationObjects = try IDs.compactMap { id in
  533. try context.existingObject(with: id) as? OrefDetermination
  534. }
  535. guard let mostRecentDetermination = determinationObjects.first else { return }
  536. determination = determinationObjects
  537. // setup vars for bolus calculation
  538. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  539. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  540. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  541. target = (mostRecentDetermination.currentTarget ?? 100) as Decimal
  542. isf = (mostRecentDetermination.insulinSensitivity ?? 0) as Decimal
  543. cob = mostRecentDetermination.cob as Int16
  544. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  545. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  546. carbRatio = (mostRecentDetermination.carbRatio ?? 0) as Decimal
  547. getCurrentBasal()
  548. insulinCalculated = calculateInsulin()
  549. } catch {
  550. debugPrint(
  551. "Home State: \(#function) \(DebuggingIdentifiers.failed) error while updating the determinations array: \(error.localizedDescription)"
  552. )
  553. }
  554. }
  555. }