BolusStateModel.swift 13 KB

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