BolusStateModel.swift 24 KB

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