BolusStateModel.swift 12 KB

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