BolusStateModel.swift 13 KB

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