BolusStateModel.swift 25 KB

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