BolusStateModel.swift 24 KB

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