BolusStateModel.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. @Published var suggestion: Suggestion?
  14. @Published var amount: Decimal = 0
  15. @Published var insulinRecommended: Decimal = 0
  16. @Published var insulinRequired: Decimal = 0
  17. @Published var units: GlucoseUnits = .mmolL
  18. @Published var percentage: Decimal = 0
  19. @Published var threshold: Decimal = 0
  20. @Published var maxBolus: Decimal = 0
  21. @Published var errorString: Decimal = 0
  22. @Published var evBG: Int = 0
  23. @Published var insulin: Decimal = 0
  24. @Published var isf: Decimal = 0
  25. @Published var error: Bool = false
  26. @Published var minGuardBG: Decimal = 0
  27. @Published var minDelta: Decimal = 0
  28. @Published var expectedDelta: Decimal = 0
  29. @Published var minPredBG: Decimal = 0
  30. @Published var waitForSuggestion: Bool = false
  31. @Published var carbRatio: Decimal = 0
  32. var waitForSuggestionInitial: Bool = false
  33. // added for bolus calculator
  34. @Published var glucose: [BloodGlucose] = []
  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 currentTime: String = ""
  56. override func subscribe() {
  57. setupInsulinRequired()
  58. broadcaster.register(SuggestionObserver.self, observer: self)
  59. units = settingsManager.settings.units
  60. percentage = settingsManager.settings.insulinReqPercentage
  61. threshold = provider.suggestion?.threshold ?? 0
  62. maxBolus = provider.pumpSettings().maxBolus
  63. // added
  64. fraction = settings.settings.overrideFactor
  65. useCalc = settings.settings.useCalc
  66. fattyMeals = settings.settings.fattyMeals
  67. fattyMealFactor = settings.settings.fattyMealFactor
  68. // get carb ratio entry schedule
  69. if waitForSuggestionInitial {
  70. apsManager.determineBasal()
  71. .receive(on: DispatchQueue.main)
  72. .sink { [weak self] ok in
  73. guard let self = self else { return }
  74. if !ok {
  75. self.waitForSuggestion = false
  76. self.insulinRequired = 0
  77. self.insulinRecommended = 0
  78. }
  79. }.store(in: &lifetime)
  80. }
  81. }
  82. func getDeltaBG() {
  83. let glucose = glucoseStorage.recent()
  84. guard glucose.count >= 3 else { return }
  85. let lastGlucose = glucose.last!
  86. let thirdLastGlucose = glucose[glucose.count - 3]
  87. let delta = Decimal(lastGlucose.glucose!) - Decimal(thirdLastGlucose.glucose!)
  88. deltaBG = delta
  89. }
  90. // CALCULATIONS FOR THE BOLUS CALCULATOR
  91. func calculateInsulin() -> Decimal {
  92. // for mmol conversion
  93. var conversion: Decimal = 1.0
  94. if units == .mmolL {
  95. conversion = 0.0555
  96. }
  97. // insulin needed for the current blood glucose
  98. let targetDifference = (currentBG - target) * conversion
  99. targetDifferenceInsulin = targetDifference / isf
  100. // more or less insulin because of bg trend in the last 15 minutes
  101. fifteenMinInsulin = (deltaBG * conversion) / isf
  102. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  103. wholeCobInsulin = cob / carbRatio
  104. // determine how much the calculator reduces/ increases the bolus because of IOB
  105. iobInsulinReduction = (-1) * iob
  106. // adding everything together
  107. // add a calc for the case that no fifteenMinInsulin is available
  108. if deltaBG != 0 {
  109. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  110. } else {
  111. // add (rare) case that no glucose value is available -> maybe display warning?
  112. // if no bg is available, ?? sets its value to 0
  113. if currentBG == 0 {
  114. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  115. } else {
  116. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  117. }
  118. }
  119. // rounding
  120. let wholeCalcAsDouble = Double(wholeCalc)
  121. roundedWholeCalc = Decimal(round(100 * wholeCalcAsDouble) / 100)
  122. // apply custom factor at the end of the calculations
  123. let result = wholeCalc * fraction
  124. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  125. if useFattyMealCorrectionFactor {
  126. insulinCalculated = result * fattyMealFactor
  127. } else {
  128. insulinCalculated = result
  129. }
  130. // display no negative insulinCalculated
  131. insulinCalculated = max(insulinCalculated, 0)
  132. let insulinCalculatedAsDouble = Double(insulinCalculated)
  133. roundedInsulinCalculated = Decimal(round(100 * insulinCalculatedAsDouble) / 100)
  134. return insulinCalculated
  135. }
  136. func add() {
  137. guard amount > 0 else {
  138. showModal(for: nil)
  139. return
  140. }
  141. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  142. unlockmanager.unlock()
  143. .sink { _ in } receiveValue: { [weak self] _ in
  144. guard let self = self else { return }
  145. self.apsManager.enactBolus(amount: maxAmount, isSMB: false)
  146. self.showModal(for: nil)
  147. }
  148. .store(in: &lifetime)
  149. }
  150. func addWithoutBolus() {
  151. guard amount > 0 else {
  152. showModal(for: nil)
  153. return
  154. }
  155. amount = min(amount, maxBolus * 3)
  156. pumpHistoryStorage.storeEvents(
  157. [
  158. PumpHistoryEvent(
  159. id: UUID().uuidString,
  160. type: .bolus,
  161. timestamp: Date(),
  162. amount: amount,
  163. duration: nil,
  164. durationMin: nil,
  165. rate: nil,
  166. temp: nil,
  167. carbInput: nil,
  168. isExternal: true
  169. )
  170. ]
  171. )
  172. showModal(for: nil)
  173. }
  174. func setupInsulinRequired() {
  175. DispatchQueue.main.async {
  176. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  177. var conversion: Decimal = 1.0
  178. if self.units == .mmolL {
  179. conversion = 0.0555
  180. }
  181. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  182. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  183. self.target = self.provider.suggestion?.current_target ?? 0
  184. self.isf = self.provider.suggestion?.isf ?? 0
  185. self.iob = self.provider.suggestion?.iob ?? 0
  186. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  187. self.cob = self.provider.suggestion?.cob ?? 0
  188. self.basal = self.provider.suggestion?.rate ?? 0
  189. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  190. if self.settingsManager.settings.insulinReqPercentage != 100 {
  191. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  192. } else { self.insulinRecommended = self.insulin }
  193. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  194. if self.errorString != 0 {
  195. self.error = true
  196. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  197. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  198. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  199. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  200. } else { self.error = false }
  201. self.insulinRecommended = self.apsManager
  202. .roundBolus(amount: max(self.insulinRecommended, 0))
  203. self.getDeltaBG()
  204. }
  205. }
  206. }
  207. }
  208. extension Bolus.StateModel: SuggestionObserver {
  209. func suggestionDidUpdate(_: Suggestion) {
  210. DispatchQueue.main.async {
  211. self.waitForSuggestion = false
  212. }
  213. setupInsulinRequired()
  214. }
  215. }