BolusStateModel.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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 wholeCobInsulin: Decimal = 0
  48. @Published var iobInsulinReduction: Decimal = 0
  49. @Published var wholeCalc: Decimal = 0
  50. @Published var insulinCalculated: Decimal = 0
  51. @Published var fraction: Decimal = 0
  52. @Published var useCalc: Bool = false
  53. @Published var basal: Decimal = 0
  54. @Published var fattyMeals: Bool = false
  55. @Published var fattyMealFactor: Decimal = 0
  56. @Published var useFattyMealCorrectionFactor: Bool = false
  57. @Published var displayPredictions: Bool = true
  58. @Published var currentBasal: Decimal = 0
  59. @Published var sweetMeals: Bool = false
  60. @Published var sweetMealFactor: Decimal = 0
  61. @Published var useSuperBolus: Bool = false
  62. @Published var superBolusInsulin: Decimal = 0
  63. @Published var meal: [CarbsEntry]?
  64. @Published var carbs: Decimal = 0
  65. @Published var fat: Decimal = 0
  66. @Published var protein: Decimal = 0
  67. @Published var note: String = ""
  68. // @Published var carbs: Decimal = 0
  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. var conversion: Decimal = 1.0
  165. if units == .mmolL {
  166. conversion = 0.0555
  167. }
  168. // insulin needed for the current blood glucose
  169. targetDifference = (currentBG - target) * conversion
  170. targetDifferenceInsulin = targetDifference / isf
  171. // more or less insulin because of bg trend in the last 15 minutes
  172. fifteenMinInsulin = (deltaBG * conversion) / isf
  173. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  174. wholeCobInsulin = cob / carbRatio
  175. // determine how much the calculator reduces/ increases the bolus because of IOB
  176. iobInsulinReduction = (-1) * iob
  177. // adding everything together
  178. // add a calc for the case that no fifteenMinInsulin is available
  179. if deltaBG != 0 {
  180. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  181. } else {
  182. // add (rare) case that no glucose value is available -> maybe display warning?
  183. // if no bg is available, ?? sets its value to 0
  184. if currentBG == 0 {
  185. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  186. } else {
  187. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  188. }
  189. }
  190. // apply custom factor at the end of the calculations
  191. let result = wholeCalc * fraction
  192. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  193. if useFattyMealCorrectionFactor {
  194. insulinCalculated = result * fattyMealFactor
  195. } else if useSuperBolus {
  196. superBolusInsulin = sweetMealFactor * currentBasal
  197. insulinCalculated = result + superBolusInsulin
  198. } else {
  199. insulinCalculated = result
  200. }
  201. // display no negative insulinCalculated
  202. insulinCalculated = max(insulinCalculated, 0)
  203. insulinCalculated = min(insulinCalculated, maxBolus)
  204. return apsManager
  205. .roundBolus(amount: max(insulinCalculated, 0))
  206. }
  207. func add() {
  208. guard amount > 0 else {
  209. showModal(for: nil)
  210. return
  211. }
  212. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  213. unlockmanager.unlock()
  214. .sink { _ in } receiveValue: { [weak self] _ in
  215. guard let self = self else { return }
  216. self.apsManager.enactBolus(amount: maxAmount, isSMB: false)
  217. self.showModal(for: nil)
  218. }
  219. .store(in: &lifetime)
  220. }
  221. func setupInsulinRequired() {
  222. DispatchQueue.main.async {
  223. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  224. var conversion: Decimal = 1.0
  225. if self.units == .mmolL {
  226. conversion = 0.0555
  227. }
  228. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  229. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  230. self.target = self.provider.suggestion?.current_target ?? 0
  231. self.isf = self.provider.suggestion?.isf ?? 0
  232. self.iob = self.provider.suggestion?.iob ?? 0
  233. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  234. self.cob = self.provider.suggestion?.cob ?? 0
  235. self.basal = self.provider.suggestion?.rate ?? 0
  236. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  237. if self.settingsManager.settings.insulinReqPercentage != 100 {
  238. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  239. } else { self.insulinRecommended = self.insulin }
  240. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  241. if self.errorString != 0 {
  242. self.error = true
  243. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  244. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  245. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  246. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  247. } else { self.error = false }
  248. self.insulinRecommended = self.apsManager
  249. .roundBolus(amount: max(self.insulinRecommended, 0))
  250. if self.useCalc {
  251. self.getCurrentBasal()
  252. self.getDeltaBG()
  253. self.insulinCalculated = self.calculateInsulin()
  254. }
  255. }
  256. }
  257. func backToCarbsView(complexEntry: Bool, _ meal: FetchedResults<Meals>, override _: Bool) {
  258. delete(deleteTwice: complexEntry, meal: meal)
  259. // showModal(for: .addCarbs(editMode: complexEntry, override: override))
  260. }
  261. func delete(deleteTwice: Bool, meal: FetchedResults<Meals>) {
  262. guard let meals = meal.first else {
  263. return
  264. }
  265. var date = Date()
  266. if let mealDate = meals.actualDate {
  267. date = mealDate
  268. } else if let mealdate = meals.createdAt {
  269. date = mealdate
  270. }
  271. let mealArray = DataTable.Treatment(
  272. units: units,
  273. type: .carbs,
  274. date: date,
  275. id: meals.id ?? "",
  276. isFPU: deleteTwice ? true : false,
  277. fpuID: deleteTwice ? (meals.fpuID ?? "") : ""
  278. )
  279. print(
  280. "meals 2: ID: " + mealArray.id.description + " FPU ID: " + (mealArray.fpuID ?? "")
  281. .description
  282. )
  283. if deleteTwice {
  284. nsManager.deleteCarbs(mealArray, complexMeal: true)
  285. } else {
  286. nsManager.deleteCarbs(mealArray, complexMeal: false)
  287. }
  288. }
  289. func addCarbs(_ continue_: Bool, fetch: Bool) {
  290. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  291. carbs = min(carbs, maxCarbs)
  292. id_ = UUID().uuidString
  293. let carbsToStore = [CarbsEntry(
  294. id: id_,
  295. createdAt: now,
  296. actualDate: date,
  297. carbs: carbs,
  298. fat: fat,
  299. protein: protein,
  300. note: note,
  301. enteredBy: CarbsEntry.manual,
  302. isFPU: false, fpuID: UUID().uuidString
  303. )]
  304. carbsStorage.storeCarbs(carbsToStore)
  305. if skipBolus, !continue_, !fetch {
  306. apsManager.determineBasalSync()
  307. showModal(for: nil)
  308. } else if carbs > 0 {
  309. saveToCoreData(carbsToStore)
  310. apsManager.determineBasalSync()
  311. // showModal(for: .bolus(waitForSuggestion: true, fetch: true, editMode: false, override: false))
  312. } else {
  313. hideModal()
  314. }
  315. }
  316. func deletePreset() {
  317. if selection != nil {
  318. try? coredataContext.delete(selection!)
  319. try? coredataContext.save()
  320. carbs = 0
  321. fat = 0
  322. protein = 0
  323. }
  324. selection = nil
  325. }
  326. func removePresetFromNewMeal() {
  327. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  328. if a != nil, summation[a ?? 0] != "" {
  329. summation.remove(at: a!)
  330. }
  331. }
  332. func addPresetToNewMeal() {
  333. let test: String = selection?.dish ?? "dontAdd"
  334. if test != "dontAdd" {
  335. summation.append(test)
  336. }
  337. }
  338. func addNewPresetToWaitersNotepad(_ dish: String) {
  339. summation.append(dish)
  340. }
  341. func addToSummation() {
  342. summation.append(selection?.dish ?? "")
  343. }
  344. func waitersNotepad() -> String {
  345. var filteredArray = summation.filter { !$0.isEmpty }
  346. if carbs == 0, protein == 0, fat == 0 {
  347. filteredArray = []
  348. }
  349. guard filteredArray != [] else {
  350. return ""
  351. }
  352. var carbs_: Decimal = 0.0
  353. var fat_: Decimal = 0.0
  354. var protein_: Decimal = 0.0
  355. var presetArray = [Presets]()
  356. coredataContext.performAndWait {
  357. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  358. try? presetArray = coredataContext.fetch(requestPresets)
  359. }
  360. var waitersNotepad = [String]()
  361. var stringValue = ""
  362. for each in filteredArray {
  363. let countedSet = NSCountedSet(array: filteredArray)
  364. let count = countedSet.count(for: each)
  365. if each != stringValue {
  366. waitersNotepad.append("\(count) \(each)")
  367. }
  368. stringValue = each
  369. for sel in presetArray {
  370. if sel.dish == each {
  371. carbs_ += (sel.carbs)! as Decimal
  372. fat_ += (sel.fat)! as Decimal
  373. protein_ += (sel.protein)! as Decimal
  374. break
  375. }
  376. }
  377. }
  378. let extracarbs = carbs - carbs_
  379. let extraFat = fat - fat_
  380. let extraProtein = protein - protein_
  381. var addedString = ""
  382. if extracarbs > 0, filteredArray.isNotEmpty {
  383. addedString += "Additional carbs: \(extracarbs) ,"
  384. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  385. if extraFat > 0, filteredArray.isNotEmpty {
  386. addedString += "Additional fat: \(extraFat) ,"
  387. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  388. if extraProtein > 0, filteredArray.isNotEmpty {
  389. addedString += "Additional protein: \(extraProtein) ,"
  390. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  391. if addedString != "" {
  392. waitersNotepad.append(addedString)
  393. }
  394. var waitersNotepadString = ""
  395. if waitersNotepad.count == 1 {
  396. waitersNotepadString = waitersNotepad[0]
  397. } else if waitersNotepad.count > 1 {
  398. for each in waitersNotepad {
  399. if each != waitersNotepad.last {
  400. waitersNotepadString += " " + each + ","
  401. } else { waitersNotepadString += " " + each }
  402. }
  403. }
  404. return waitersNotepadString
  405. }
  406. func loadEntries(_ editMode: Bool) {
  407. if editMode {
  408. coredataContext.performAndWait {
  409. var mealToEdit = [Meals]()
  410. let requestMeal = Meals.fetchRequest() as NSFetchRequest<Meals>
  411. let sortMeal = NSSortDescriptor(key: "createdAt", ascending: false)
  412. requestMeal.sortDescriptors = [sortMeal]
  413. requestMeal.fetchLimit = 1
  414. try? mealToEdit = self.coredataContext.fetch(requestMeal)
  415. self.carbs = Decimal(mealToEdit.first?.carbs ?? 0)
  416. self.fat = Decimal(mealToEdit.first?.fat ?? 0)
  417. self.protein = Decimal(mealToEdit.first?.protein ?? 0)
  418. self.note = mealToEdit.first?.note ?? ""
  419. self.id_ = mealToEdit.first?.id ?? ""
  420. }
  421. }
  422. }
  423. func saveToCoreData(_ stored: [CarbsEntry]) {
  424. coredataContext.performAndWait {
  425. let save = Meals(context: coredataContext)
  426. if let entry = stored.first {
  427. save.createdAt = now
  428. save.actualDate = entry.actualDate ?? Date.now
  429. save.id = entry.id ?? ""
  430. save.fpuID = entry.fpuID ?? ""
  431. save.carbs = Double(entry.carbs)
  432. save.fat = Double(entry.fat ?? 0)
  433. save.protein = Double(entry.protein ?? 0)
  434. save.note = entry.note
  435. try? coredataContext.save()
  436. }
  437. print("meals 1: ID: " + (save.id ?? "").description + " FPU ID: " + (save.fpuID ?? "").description)
  438. }
  439. }
  440. }
  441. }
  442. extension Bolus.StateModel: SuggestionObserver {
  443. func suggestionDidUpdate(_: Suggestion) {
  444. DispatchQueue.main.async {
  445. self.waitForSuggestion = false
  446. }
  447. setupInsulinRequired()
  448. }
  449. }