BolusStateModel.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import CoreData
  2. import Foundation
  3. import LoopKit
  4. import SwiftUI
  5. import Swinject
  6. extension Bolus {
  7. final class StateModel: BaseStateModel<Provider> {
  8. @Injected() var unlockmanager: UnlockManager!
  9. @Injected() var apsManager: APSManager!
  10. @Injected() var broadcaster: Broadcaster!
  11. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  12. // added for bolus calculator
  13. @Injected() var settings: SettingsManager!
  14. @Injected() var nsManager: NightscoutManager!
  15. @Injected() var carbsStorage: CarbsStorage!
  16. @Published var suggestion: Suggestion?
  17. @Published var predictions: Predictions?
  18. @Published var amount: Decimal = 0
  19. @Published var insulinRecommended: Decimal = 0
  20. @Published var insulinRequired: Decimal = 0
  21. @Published var units: GlucoseUnits = .mmolL
  22. @Published var percentage: Decimal = 0
  23. @Published var threshold: Decimal = 0
  24. @Published var maxBolus: Decimal = 0
  25. @Published var errorString: Decimal = 0
  26. @Published var evBG: Int = 0
  27. @Published var insulin: Decimal = 0
  28. @Published var isf: Decimal = 0
  29. @Published var error: Bool = false
  30. @Published var minGuardBG: Decimal = 0
  31. @Published var minDelta: Decimal = 0
  32. @Published var expectedDelta: Decimal = 0
  33. @Published var minPredBG: Decimal = 0
  34. @Published var waitForSuggestion: Bool = false
  35. @Published var carbRatio: Decimal = 0
  36. var waitForSuggestionInitial: Bool = false
  37. // added for bolus calculator
  38. @Published var recentGlucose: BloodGlucose?
  39. @Published var target: Decimal = 0
  40. @Published var cob: Decimal = 0
  41. @Published var iob: Decimal = 0
  42. @Published var currentBG: Decimal = 0
  43. @Published var fifteenMinInsulin: Decimal = 0
  44. @Published var deltaBG: Decimal = 0
  45. @Published var targetDifferenceInsulin: Decimal = 0
  46. @Published var targetDifference: Decimal = 0
  47. @Published var wholeCob: Decimal = 0
  48. @Published var wholeCobInsulin: Decimal = 0
  49. @Published var iobInsulinReduction: Decimal = 0
  50. @Published var wholeCalc: Decimal = 0
  51. @Published var insulinCalculated: Decimal = 0
  52. @Published var fraction: Decimal = 0
  53. @Published var useCalc: Bool = false
  54. @Published var basal: Decimal = 0
  55. @Published var fattyMeals: Bool = false
  56. @Published var fattyMealFactor: Decimal = 0
  57. @Published var useFattyMealCorrectionFactor: Bool = false
  58. @Published var displayPredictions: Bool = true
  59. @Published var currentBasal: Decimal = 0
  60. @Published var sweetMeals: Bool = false
  61. @Published var sweetMealFactor: Decimal = 0
  62. @Published var useSuperBolus: Bool = false
  63. @Published var superBolusInsulin: Decimal = 0
  64. @Published var meal: [CarbsEntry]?
  65. @Published var carbs: Decimal = 0
  66. @Published var fat: Decimal = 0
  67. @Published var protein: Decimal = 0
  68. @Published var note: String = ""
  69. @Published var date = Date()
  70. // @Published var protein: Decimal = 0
  71. // @Published var fat: Decimal = 0
  72. @Published var carbsRequired: Decimal?
  73. @Published var useFPUconversion: Bool = false
  74. @Published var dish: String = ""
  75. @Published var selection: Presets?
  76. @Published var summation: [String] = []
  77. @Published var maxCarbs: Decimal = 0
  78. // @Published var note: String = ""
  79. @Published var id_: String = ""
  80. @Published var summary: String = ""
  81. @Published var skipBolus: Bool = false
  82. let now = Date.now
  83. let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
  84. override func subscribe() {
  85. setupInsulinRequired()
  86. broadcaster.register(SuggestionObserver.self, observer: self)
  87. units = settingsManager.settings.units
  88. percentage = settingsManager.settings.insulinReqPercentage
  89. threshold = provider.suggestion?.threshold ?? 0
  90. maxBolus = provider.pumpSettings().maxBolus
  91. // added
  92. fraction = settings.settings.overrideFactor
  93. useCalc = settings.settings.useCalc
  94. fattyMeals = settings.settings.fattyMeals
  95. fattyMealFactor = settings.settings.fattyMealFactor
  96. sweetMeals = settings.settings.sweetMeals
  97. sweetMealFactor = settings.settings.sweetMealFactor
  98. displayPredictions = settings.settings.displayPredictions
  99. carbsRequired = provider.suggestion?.carbsReq
  100. maxCarbs = settings.settings.maxCarbs
  101. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  102. useFPUconversion = settingsManager.settings.useFPUconversion
  103. if waitForSuggestionInitial {
  104. apsManager.determineBasal()
  105. .receive(on: DispatchQueue.main)
  106. .sink { [weak self] ok in
  107. guard let self = self else { return }
  108. if !ok {
  109. self.waitForSuggestion = false
  110. self.insulinRequired = 0
  111. self.insulinRecommended = 0
  112. }
  113. }.store(in: &lifetime)
  114. }
  115. if let notNilSugguestion = provider.suggestion {
  116. suggestion = notNilSugguestion
  117. if let notNilPredictions = suggestion?.predictions {
  118. predictions = notNilPredictions
  119. }
  120. }
  121. }
  122. func getCurrentBasal() {
  123. let basalEntries = provider.getProfile()
  124. let dateFormatter = DateFormatter()
  125. dateFormatter.dateFormat = "HH:mm:ss"
  126. let currentTime = dateFormatter.string(from: Date())
  127. // loop throug entries and get current basal entry
  128. for (index, entry) in basalEntries.enumerated() {
  129. if let entryStartTimeDate = dateFormatter.date(from: entry.start) {
  130. var entryEndTimeDate: Date
  131. if index < basalEntries.count - 1 {
  132. let nextEntry = basalEntries[index + 1]
  133. if let nextEntryStartTimeDate = dateFormatter.date(from: nextEntry.start) {
  134. let timeDifference = nextEntryStartTimeDate.timeIntervalSince(entryStartTimeDate)
  135. entryEndTimeDate = entryStartTimeDate.addingTimeInterval(timeDifference)
  136. } else {
  137. continue
  138. }
  139. } else {
  140. entryEndTimeDate = Date()
  141. }
  142. // if currenTime is between start and end of basal entry -> basal = currentBasal
  143. if let currentTimeDate = dateFormatter.date(from: currentTime) {
  144. if currentTimeDate >= entryStartTimeDate, currentTimeDate <= entryEndTimeDate {
  145. if let basal = entry.rate as? Decimal {
  146. currentBasal = basal
  147. break
  148. }
  149. }
  150. }
  151. }
  152. }
  153. }
  154. func getDeltaBG() {
  155. let glucose = provider.fetchGlucose()
  156. guard glucose.count >= 3 else { return }
  157. let lastGlucose = glucose.first?.glucose ?? 0
  158. let thirdLastGlucose = glucose[2]
  159. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose.glucose)
  160. deltaBG = delta
  161. }
  162. // CALCULATIONS FOR THE BOLUS CALCULATOR
  163. func calculateInsulin() -> Decimal {
  164. //ensure that isf is in mg/dL
  165. var conversion: Decimal {
  166. units == .mmolL ? 0.0555 : 1
  167. }
  168. let isfForCalculation = isf / conversion
  169. // insulin needed for the current blood glucose
  170. targetDifference = (currentBG - target)
  171. targetDifferenceInsulin = targetDifference / isfForCalculation
  172. // more or less insulin because of bg trend in the last 15 minutes
  173. fifteenMinInsulin = deltaBG / isfForCalculation
  174. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  175. wholeCob = cob + carbs
  176. wholeCobInsulin = wholeCob / carbRatio
  177. // determine how much the calculator reduces/ increases the bolus because of IOB
  178. iobInsulinReduction = (-1) * iob
  179. // adding everything together
  180. // add a calc for the case that no fifteenMinInsulin is available
  181. if deltaBG != 0 {
  182. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  183. } else {
  184. // add (rare) case that no glucose value is available -> maybe display warning?
  185. // if no bg is available, ?? sets its value to 0
  186. if currentBG == 0 {
  187. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  188. } else {
  189. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  190. }
  191. }
  192. // apply custom factor at the end of the calculations
  193. let result = wholeCalc * fraction
  194. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  195. if useFattyMealCorrectionFactor {
  196. insulinCalculated = result * fattyMealFactor
  197. } else if useSuperBolus {
  198. superBolusInsulin = sweetMealFactor * currentBasal
  199. insulinCalculated = result + superBolusInsulin
  200. } else {
  201. insulinCalculated = result
  202. }
  203. // display no negative insulinCalculated
  204. insulinCalculated = max(insulinCalculated, 0)
  205. insulinCalculated = min(insulinCalculated, maxBolus)
  206. return apsManager
  207. .roundBolus(amount: max(insulinCalculated, 0))
  208. }
  209. func add() async {
  210. guard amount > 0 else {
  211. showModal(for: nil)
  212. return
  213. }
  214. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  215. do {
  216. let authenticated = try await unlockmanager.unlock()
  217. if authenticated {
  218. apsManager.enactBolus(amount: maxAmount, isSMB: false)
  219. showModal(for: nil)
  220. } else {
  221. print("authentication failed")
  222. }
  223. } catch {
  224. print("authentication error: \(error.localizedDescription)")
  225. }
  226. }
  227. func setupInsulinRequired() {
  228. DispatchQueue.main.async {
  229. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  230. var conversion: Decimal = 1.0
  231. if self.units == .mmolL {
  232. conversion = 0.0555
  233. }
  234. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  235. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  236. self.target = self.provider.suggestion?.current_target ?? 0
  237. self.isf = self.provider.suggestion?.isf ?? 0
  238. self.iob = self.provider.suggestion?.iob ?? 0
  239. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  240. self.cob = self.provider.suggestion?.cob ?? 0
  241. self.basal = self.provider.suggestion?.rate ?? 0
  242. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  243. if self.settingsManager.settings.insulinReqPercentage != 100 {
  244. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  245. } else { self.insulinRecommended = self.insulin }
  246. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  247. if self.errorString != 0 {
  248. self.error = true
  249. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  250. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  251. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  252. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  253. } else { self.error = false }
  254. self.insulinRecommended = self.apsManager
  255. .roundBolus(amount: max(self.insulinRecommended, 0))
  256. if self.useCalc {
  257. self.getCurrentBasal()
  258. self.getDeltaBG()
  259. self.insulinCalculated = self.calculateInsulin()
  260. }
  261. }
  262. }
  263. func addCarbs() {
  264. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  265. carbs = min(carbs, maxCarbs)
  266. id_ = UUID().uuidString
  267. let carbsToStore = [CarbsEntry(
  268. id: id_,
  269. createdAt: now,
  270. actualDate: date,
  271. carbs: carbs,
  272. fat: fat,
  273. protein: protein,
  274. note: note,
  275. enteredBy: CarbsEntry.manual,
  276. isFPU: false, fpuID: UUID().uuidString
  277. )]
  278. carbsStorage.storeCarbs(carbsToStore)
  279. if skipBolus {
  280. apsManager.determineBasalSync()
  281. showModal(for: nil)
  282. } else if carbs > 0 {
  283. saveToCoreData(carbsToStore)
  284. apsManager.determineBasalSync()
  285. } else {
  286. hideModal()
  287. }
  288. }
  289. func deletePreset() {
  290. if selection != nil {
  291. try? coredataContext.delete(selection!)
  292. try? coredataContext.save()
  293. carbs = 0
  294. fat = 0
  295. protein = 0
  296. }
  297. selection = nil
  298. }
  299. func removePresetFromNewMeal() {
  300. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  301. if a != nil, summation[a ?? 0] != "" {
  302. summation.remove(at: a!)
  303. }
  304. }
  305. func addPresetToNewMeal() {
  306. let test: String = selection?.dish ?? "dontAdd"
  307. if test != "dontAdd" {
  308. summation.append(test)
  309. }
  310. }
  311. func addNewPresetToWaitersNotepad(_ dish: String) {
  312. summation.append(dish)
  313. }
  314. func addToSummation() {
  315. summation.append(selection?.dish ?? "")
  316. }
  317. func waitersNotepad() -> String {
  318. var filteredArray = summation.filter { !$0.isEmpty }
  319. if carbs == 0, protein == 0, fat == 0 {
  320. filteredArray = []
  321. }
  322. guard filteredArray != [] else {
  323. return ""
  324. }
  325. var carbs_: Decimal = 0.0
  326. var fat_: Decimal = 0.0
  327. var protein_: Decimal = 0.0
  328. var presetArray = [Presets]()
  329. coredataContext.performAndWait {
  330. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  331. try? presetArray = coredataContext.fetch(requestPresets)
  332. }
  333. var waitersNotepad = [String]()
  334. var stringValue = ""
  335. for each in filteredArray {
  336. let countedSet = NSCountedSet(array: filteredArray)
  337. let count = countedSet.count(for: each)
  338. if each != stringValue {
  339. waitersNotepad.append("\(count) \(each)")
  340. }
  341. stringValue = each
  342. for sel in presetArray {
  343. if sel.dish == each {
  344. carbs_ += (sel.carbs)! as Decimal
  345. fat_ += (sel.fat)! as Decimal
  346. protein_ += (sel.protein)! as Decimal
  347. break
  348. }
  349. }
  350. }
  351. let extracarbs = carbs - carbs_
  352. let extraFat = fat - fat_
  353. let extraProtein = protein - protein_
  354. var addedString = ""
  355. if extracarbs > 0, filteredArray.isNotEmpty {
  356. addedString += "Additional carbs: \(extracarbs) ,"
  357. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  358. if extraFat > 0, filteredArray.isNotEmpty {
  359. addedString += "Additional fat: \(extraFat) ,"
  360. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  361. if extraProtein > 0, filteredArray.isNotEmpty {
  362. addedString += "Additional protein: \(extraProtein) ,"
  363. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  364. if addedString != "" {
  365. waitersNotepad.append(addedString)
  366. }
  367. var waitersNotepadString = ""
  368. if waitersNotepad.count == 1 {
  369. waitersNotepadString = waitersNotepad[0]
  370. } else if waitersNotepad.count > 1 {
  371. for each in waitersNotepad {
  372. if each != waitersNotepad.last {
  373. waitersNotepadString += " " + each + ","
  374. } else { waitersNotepadString += " " + each }
  375. }
  376. }
  377. return waitersNotepadString
  378. }
  379. func loadEntries(_ editMode: Bool) {
  380. if editMode {
  381. coredataContext.performAndWait {
  382. var mealToEdit = [Meals]()
  383. let requestMeal = Meals.fetchRequest() as NSFetchRequest<Meals>
  384. let sortMeal = NSSortDescriptor(key: "createdAt", ascending: false)
  385. requestMeal.sortDescriptors = [sortMeal]
  386. requestMeal.fetchLimit = 1
  387. try? mealToEdit = self.coredataContext.fetch(requestMeal)
  388. self.carbs = Decimal(mealToEdit.first?.carbs ?? 0)
  389. self.fat = Decimal(mealToEdit.first?.fat ?? 0)
  390. self.protein = Decimal(mealToEdit.first?.protein ?? 0)
  391. self.note = mealToEdit.first?.note ?? ""
  392. self.id_ = mealToEdit.first?.id ?? ""
  393. }
  394. }
  395. }
  396. func saveToCoreData(_ stored: [CarbsEntry]) {
  397. coredataContext.performAndWait {
  398. let save = Meals(context: coredataContext)
  399. if let entry = stored.first {
  400. save.createdAt = now
  401. save.actualDate = entry.actualDate ?? Date.now
  402. save.id = entry.id ?? ""
  403. save.fpuID = entry.fpuID ?? ""
  404. save.carbs = Double(entry.carbs)
  405. save.fat = Double(entry.fat ?? 0)
  406. save.protein = Double(entry.protein ?? 0)
  407. save.note = entry.note
  408. try? coredataContext.save()
  409. }
  410. print("meals 1: ID: " + (save.id ?? "").description + " FPU ID: " + (save.fpuID ?? "").description)
  411. }
  412. }
  413. }
  414. }
  415. extension Bolus.StateModel: SuggestionObserver {
  416. func suggestionDidUpdate(_: Suggestion) {
  417. DispatchQueue.main.async {
  418. self.waitForSuggestion = false
  419. }
  420. setupInsulinRequired()
  421. }
  422. }