BolusStateModel.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 glucoseStorage: GlucoseStorage!
  12. @Injected() var settings: SettingsManager!
  13. @Injected() var nsManager: NightscoutManager!
  14. @Published var suggestion: Suggestion?
  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 wholeCobInsulin: Decimal = 0
  44. @Published var iobInsulinReduction: Decimal = 0
  45. @Published var wholeCalc: Decimal = 0
  46. @Published var roundedWholeCalc: Decimal = 0
  47. @Published var insulinCalculated: Decimal = 0
  48. @Published var roundedInsulinCalculated: Decimal = 0
  49. @Published var fraction: Decimal = 0
  50. @Published var useCalc: Bool = false
  51. @Published var basal: Decimal = 0
  52. @Published var fattyMeals: Bool = false
  53. @Published var fattyMealFactor: Decimal = 0
  54. @Published var useFattyMealCorrectionFactor: Bool = false
  55. @Published var eventualBG: Int = 0
  56. @Published var meal: [CarbsEntry]?
  57. @Published var carbs: Decimal = 0
  58. @Published var fat: Decimal = 0
  59. @Published var protein: Decimal = 0
  60. @Published var note: String = ""
  61. override func subscribe() {
  62. setupInsulinRequired()
  63. broadcaster.register(SuggestionObserver.self, observer: self)
  64. units = settingsManager.settings.units
  65. percentage = settingsManager.settings.insulinReqPercentage
  66. threshold = provider.suggestion?.threshold ?? 0
  67. maxBolus = provider.pumpSettings().maxBolus
  68. // added
  69. fraction = settings.settings.overrideFactor
  70. useCalc = settings.settings.useCalc
  71. fattyMeals = settings.settings.fattyMeals
  72. fattyMealFactor = settings.settings.fattyMealFactor
  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. }
  86. func getDeltaBG() {
  87. let glucose = glucoseStorage.recent()
  88. guard glucose.count >= 3 else { return }
  89. let lastGlucose = glucose.last!
  90. let thirdLastGlucose = glucose[glucose.count - 3]
  91. let delta = Decimal(lastGlucose.glucose!) - Decimal(thirdLastGlucose.glucose!)
  92. deltaBG = delta
  93. }
  94. // CALCULATIONS FOR THE BOLUS CALCULATOR
  95. func calculateInsulin() {
  96. // for mmol conversion
  97. var conversion: Decimal = 1.0
  98. if units == .mmolL {
  99. conversion = 0.0555
  100. }
  101. // insulin needed for the current blood glucose
  102. let targetDifference = (currentBG - target) * conversion
  103. targetDifferenceInsulin = targetDifference / isf
  104. // more or less insulin because of bg trend in the last 15 minutes
  105. fifteenMinInsulin = (deltaBG * conversion) / isf
  106. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  107. wholeCobInsulin = cob / carbRatio
  108. // determine how much the calculator reduces/ increases the bolus because of IOB
  109. iobInsulinReduction = (-1) * iob
  110. // adding everything together
  111. // add a calc for the case that no fifteenMinInsulin is available
  112. if deltaBG != 0 {
  113. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  114. } else {
  115. // add (rare) case that no glucose value is available -> maybe display warning?
  116. // if no bg is available, ?? sets its value to 0
  117. if currentBG == 0 {
  118. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  119. } else {
  120. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  121. }
  122. }
  123. // rounding
  124. let wholeCalcAsDouble = Double(wholeCalc)
  125. roundedWholeCalc = Decimal(round(100 * wholeCalcAsDouble) / 100)
  126. // apply custom factor at the end of the calculations
  127. let result = wholeCalc * fraction
  128. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  129. if useFattyMealCorrectionFactor {
  130. insulinCalculated = result * fattyMealFactor
  131. } else {
  132. insulinCalculated = result
  133. }
  134. // display no negative insulinCalculated
  135. insulinCalculated = max(insulinCalculated, 0)
  136. let insulinCalculatedAsDouble = Double(insulinCalculated)
  137. roundedInsulinCalculated = Decimal(round(100 * insulinCalculatedAsDouble) / 100)
  138. insulinRecommended = min(insulinCalculated, maxBolus)
  139. }
  140. func add() {
  141. guard amount > 0 else {
  142. showModal(for: nil)
  143. return
  144. }
  145. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  146. unlockmanager.unlock()
  147. .sink { _ in } receiveValue: { [weak self] _ in
  148. guard let self = self else { return }
  149. self.apsManager.enactBolus(amount: maxAmount, isSMB: false)
  150. self.showModal(for: nil)
  151. }
  152. .store(in: &lifetime)
  153. }
  154. func setupInsulinRequired() {
  155. DispatchQueue.main.async {
  156. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  157. var conversion: Decimal = 1.0
  158. if self.units == .mmolL {
  159. conversion = 0.0555
  160. }
  161. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  162. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  163. self.target = self.provider.suggestion?.current_target ?? 0
  164. self.isf = self.provider.suggestion?.isf ?? 0
  165. self.iob = self.provider.suggestion?.iob ?? 0
  166. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  167. self.cob = self.provider.suggestion?.cob ?? 0
  168. self.basal = self.provider.suggestion?.rate ?? 0
  169. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  170. if !self.useCalc {
  171. if self.settingsManager.settings.insulinReqPercentage != 100 {
  172. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  173. } else { self.insulinRecommended = self.insulin }
  174. }
  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. if !self.useCalc {
  184. self.insulinRecommended = self.apsManager
  185. .roundBolus(amount: max(self.insulinRecommended, 0))
  186. }
  187. self.getDeltaBG()
  188. }
  189. }
  190. func backToCarbsView(complexEntry: Bool, _ id: String) {
  191. if complexEntry {
  192. DispatchQueue.safeMainSync {
  193. nsManager.deleteCarbs(
  194. at: id, isFPU: nil, fpuID: nil, syncID: id
  195. )
  196. nsManager.deleteCarbs(
  197. at: id + ".fpu", isFPU: nil, fpuID: nil, syncID: id
  198. )
  199. }
  200. } else {
  201. nsManager.deleteCarbs(
  202. at: id, isFPU: nil, fpuID: nil, syncID: id
  203. )
  204. }
  205. showModal(for: .addCarbs(editMode: complexEntry))
  206. }
  207. }
  208. }
  209. extension Bolus.StateModel: SuggestionObserver {
  210. func suggestionDidUpdate(_: Suggestion) {
  211. DispatchQueue.main.async {
  212. self.waitForSuggestion = false
  213. }
  214. setupInsulinRequired()
  215. if useCalc { calculateInsulin() }
  216. }
  217. }