BolusStateModel.swift 13 KB

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