BolusStateModel.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import LoopKit
  2. import SwiftUI
  3. import Swinject
  4. extension Bolus {
  5. final class StateModel: BaseStateModel<Provider> {
  6. @Injected() var unlockmanager: UnlockManager!
  7. @Injected() var apsManager: APSManager!
  8. @Injected() var broadcaster: Broadcaster!
  9. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  10. // added for bolus calculator
  11. @Injected() var settings: SettingsManager!
  12. @Injected() var nsManager: NightscoutManager!
  13. @Published var suggestion: Suggestion?
  14. @Published var predictions: Predictions?
  15. @Published var amount: Decimal = 0
  16. @Published var insulinRecommended: Decimal = 0
  17. @Published var insulinRequired: Decimal = 0
  18. @Published var units: GlucoseUnits = .mmolL
  19. @Published var percentage: Decimal = 0
  20. @Published var threshold: Decimal = 0
  21. @Published var maxBolus: Decimal = 0
  22. @Published var errorString: Decimal = 0
  23. @Published var evBG: Int = 0
  24. @Published var insulin: Decimal = 0
  25. @Published var isf: Decimal = 0
  26. @Published var error: Bool = false
  27. @Published var minGuardBG: Decimal = 0
  28. @Published var minDelta: Decimal = 0
  29. @Published var expectedDelta: Decimal = 0
  30. @Published var minPredBG: Decimal = 0
  31. @Published var waitForSuggestion: Bool = false
  32. @Published var carbRatio: Decimal = 0
  33. var waitForSuggestionInitial: Bool = false
  34. // added for bolus calculator
  35. @Published var recentGlucose: BloodGlucose?
  36. @Published var target: Decimal = 0
  37. @Published var cob: Decimal = 0
  38. @Published var iob: Decimal = 0
  39. @Published var currentBG: Decimal = 0
  40. @Published var fifteenMinInsulin: Decimal = 0
  41. @Published var deltaBG: Decimal = 0
  42. @Published var targetDifferenceInsulin: Decimal = 0
  43. @Published var targetDifference: Decimal = 0
  44. @Published var wholeCobInsulin: Decimal = 0
  45. @Published var iobInsulinReduction: Decimal = 0
  46. @Published var wholeCalc: Decimal = 0
  47. @Published var insulinCalculated: Decimal = 0
  48. @Published var fraction: Decimal = 0
  49. @Published var useCalc: Bool = false
  50. @Published var basal: Decimal = 0
  51. @Published var fattyMeals: Bool = false
  52. @Published var fattyMealFactor: Decimal = 0
  53. @Published var useFattyMealCorrectionFactor: Bool = false
  54. @Published var displayPredictions: Bool = true
  55. @Published var meal: [CarbsEntry]?
  56. @Published var carbs: Decimal = 0
  57. @Published var fat: Decimal = 0
  58. @Published var protein: Decimal = 0
  59. @Published var note: String = ""
  60. override func subscribe() {
  61. setupInsulinRequired()
  62. broadcaster.register(SuggestionObserver.self, observer: self)
  63. units = settingsManager.settings.units
  64. percentage = settingsManager.settings.insulinReqPercentage
  65. threshold = provider.suggestion?.threshold ?? 0
  66. maxBolus = provider.pumpSettings().maxBolus
  67. // added
  68. fraction = settings.settings.overrideFactor
  69. useCalc = settings.settings.useCalc
  70. fattyMeals = settings.settings.fattyMeals
  71. fattyMealFactor = settings.settings.fattyMealFactor
  72. displayPredictions = settings.settings.displayPredictions
  73. if waitForSuggestionInitial {
  74. apsManager.determineBasal()
  75. .receive(on: DispatchQueue.main)
  76. .sink { [weak self] ok in
  77. guard let self = self else { return }
  78. if !ok {
  79. self.waitForSuggestion = false
  80. self.insulinRequired = 0
  81. self.insulinRecommended = 0
  82. }
  83. }.store(in: &lifetime)
  84. }
  85. if let notNilSugguestion = provider.suggestion {
  86. suggestion = notNilSugguestion
  87. if let notNilPredictions = suggestion?.predictions {
  88. predictions = notNilPredictions
  89. }
  90. }
  91. }
  92. func getDeltaBG() {
  93. let glucose = provider.fetchGlucose()
  94. guard glucose.count >= 3 else { return }
  95. let lastGlucose = glucose.first?.glucose ?? 0
  96. let thirdLastGlucose = glucose[2]
  97. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose.glucose)
  98. deltaBG = delta
  99. }
  100. // CALCULATIONS FOR THE BOLUS CALCULATOR
  101. func calculateInsulin() -> Decimal {
  102. var conversion: Decimal = 1.0
  103. if units == .mmolL {
  104. conversion = 0.0555
  105. }
  106. // insulin needed for the current blood glucose
  107. targetDifference = (currentBG - target) * conversion
  108. targetDifferenceInsulin = targetDifference / isf
  109. // more or less insulin because of bg trend in the last 15 minutes
  110. fifteenMinInsulin = (deltaBG * conversion) / isf
  111. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  112. wholeCobInsulin = cob / carbRatio
  113. // determine how much the calculator reduces/ increases the bolus because of IOB
  114. iobInsulinReduction = (-1) * iob
  115. // adding everything together
  116. // add a calc for the case that no fifteenMinInsulin is available
  117. if deltaBG != 0 {
  118. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  119. } else {
  120. // add (rare) case that no glucose value is available -> maybe display warning?
  121. // if no bg is available, ?? sets its value to 0
  122. if currentBG == 0 {
  123. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  124. } else {
  125. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  126. }
  127. }
  128. // apply custom factor at the end of the calculations
  129. let result = wholeCalc * fraction
  130. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  131. if useFattyMealCorrectionFactor {
  132. insulinCalculated = result * fattyMealFactor
  133. } else {
  134. insulinCalculated = result
  135. }
  136. // display no negative insulinCalculated
  137. insulinCalculated = max(insulinCalculated, 0)
  138. insulinCalculated = min(insulinCalculated, maxBolus)
  139. return apsManager
  140. .roundBolus(amount: max(insulinCalculated, 0))
  141. }
  142. func add() {
  143. guard amount > 0 else {
  144. showModal(for: nil)
  145. return
  146. }
  147. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  148. unlockmanager.unlock()
  149. .sink { _ in } receiveValue: { [weak self] _ in
  150. guard let self = self else { return }
  151. self.apsManager.enactBolus(amount: maxAmount, isSMB: false)
  152. self.showModal(for: nil)
  153. }
  154. .store(in: &lifetime)
  155. }
  156. func setupInsulinRequired() {
  157. DispatchQueue.main.async {
  158. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  159. var conversion: Decimal = 1.0
  160. if self.units == .mmolL {
  161. conversion = 0.0555
  162. }
  163. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  164. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  165. self.target = self.provider.suggestion?.current_target ?? 0
  166. self.isf = self.provider.suggestion?.isf ?? 0
  167. self.iob = self.provider.suggestion?.iob ?? 0
  168. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  169. self.cob = self.provider.suggestion?.cob ?? 0
  170. self.basal = self.provider.suggestion?.rate ?? 0
  171. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  172. if self.settingsManager.settings.insulinReqPercentage != 100 {
  173. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  174. } else { self.insulinRecommended = self.insulin }
  175. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  176. if self.errorString != 0 {
  177. self.error = true
  178. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  179. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  180. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  181. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  182. } else { self.error = false }
  183. self.insulinRecommended = self.apsManager
  184. .roundBolus(amount: max(self.insulinRecommended, 0))
  185. if self.useCalc {
  186. self.getDeltaBG()
  187. self.insulinCalculated = self.calculateInsulin()
  188. }
  189. }
  190. }
  191. func backToCarbsView(complexEntry: Bool, _ meal: FetchedResults<Meals>, override: Bool) {
  192. delete(deleteTwice: complexEntry, meal: meal)
  193. showModal(for: .addCarbs(editMode: complexEntry, override: override))
  194. }
  195. func delete(deleteTwice: Bool, meal: FetchedResults<Meals>) {
  196. guard let meals = meal.first else {
  197. return
  198. }
  199. var date = Date()
  200. if let mealDate = meals.actualDate {
  201. date = mealDate
  202. } else if let mealdate = meals.createdAt {
  203. date = mealdate
  204. }
  205. let mealArray = DataTable.Treatment(
  206. units: units,
  207. type: .carbs,
  208. date: date,
  209. id: meals.id ?? "",
  210. isFPU: deleteTwice ? true : false,
  211. fpuID: deleteTwice ? (meals.fpuID ?? "") : ""
  212. )
  213. print(
  214. "meals 2: ID: " + mealArray.id.description + " FPU ID: " + (mealArray.fpuID ?? "")
  215. .description
  216. )
  217. if deleteTwice {
  218. nsManager.deleteCarbs(mealArray, complexMeal: true)
  219. } else {
  220. nsManager.deleteCarbs(mealArray, complexMeal: false)
  221. }
  222. }
  223. }
  224. }
  225. extension Bolus.StateModel: SuggestionObserver {
  226. func suggestionDidUpdate(_: Suggestion) {
  227. DispatchQueue.main.async {
  228. self.waitForSuggestion = false
  229. }
  230. setupInsulinRequired()
  231. }
  232. }