BolusStateModel.swift 13 KB

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