BolusStateModel.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 displayPresets: 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. displayPresets = settings.settings.displayPresets
  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. } else {
  220. print("authentication failed")
  221. }
  222. } catch {
  223. print("authentication error: \(error.localizedDescription)")
  224. }
  225. }
  226. func setupInsulinRequired() {
  227. DispatchQueue.main.async {
  228. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  229. var conversion: Decimal = 1.0
  230. if self.units == .mmolL {
  231. conversion = 0.0555
  232. }
  233. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  234. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  235. self.target = self.provider.suggestion?.current_target ?? 0
  236. self.isf = self.provider.suggestion?.isf ?? 0
  237. self.iob = self.provider.suggestion?.iob ?? 0
  238. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  239. self.cob = self.provider.suggestion?.cob ?? 0
  240. self.basal = self.provider.suggestion?.rate ?? 0
  241. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  242. if self.settingsManager.settings.insulinReqPercentage != 100 {
  243. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  244. } else { self.insulinRecommended = self.insulin }
  245. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  246. if self.errorString != 0 {
  247. self.error = true
  248. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  249. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  250. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  251. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  252. } else { self.error = false }
  253. self.insulinRecommended = self.apsManager
  254. .roundBolus(amount: max(self.insulinRecommended, 0))
  255. if self.useCalc {
  256. self.getCurrentBasal()
  257. self.getDeltaBG()
  258. self.insulinCalculated = self.calculateInsulin()
  259. }
  260. }
  261. }
  262. func addCarbs() {
  263. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  264. carbs = min(carbs, maxCarbs)
  265. id_ = UUID().uuidString
  266. let carbsToStore = [CarbsEntry(
  267. id: id_,
  268. createdAt: now,
  269. actualDate: date,
  270. carbs: carbs,
  271. fat: fat,
  272. protein: protein,
  273. note: note,
  274. enteredBy: CarbsEntry.manual,
  275. isFPU: false, fpuID: UUID().uuidString
  276. )]
  277. carbsStorage.storeCarbs(carbsToStore)
  278. if skipBolus {
  279. apsManager.determineBasalSync()
  280. showModal(for: nil)
  281. } else if carbs > 0 {
  282. saveToCoreData(carbsToStore)
  283. apsManager.determineBasalSync()
  284. } else {
  285. hideModal()
  286. }
  287. }
  288. func deletePreset() {
  289. if selection != nil {
  290. try? coredataContext.delete(selection!)
  291. try? coredataContext.save()
  292. carbs = 0
  293. fat = 0
  294. protein = 0
  295. }
  296. selection = nil
  297. }
  298. func removePresetFromNewMeal() {
  299. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  300. if a != nil, summation[a ?? 0] != "" {
  301. summation.remove(at: a!)
  302. }
  303. }
  304. func addPresetToNewMeal() {
  305. let test: String = selection?.dish ?? "dontAdd"
  306. if test != "dontAdd" {
  307. summation.append(test)
  308. }
  309. }
  310. func addNewPresetToWaitersNotepad(_ dish: String) {
  311. summation.append(dish)
  312. }
  313. func addToSummation() {
  314. summation.append(selection?.dish ?? "")
  315. }
  316. func waitersNotepad() -> String {
  317. var filteredArray = summation.filter { !$0.isEmpty }
  318. if carbs == 0, protein == 0, fat == 0 {
  319. filteredArray = []
  320. }
  321. guard filteredArray != [] else {
  322. return ""
  323. }
  324. var carbs_: Decimal = 0.0
  325. var fat_: Decimal = 0.0
  326. var protein_: Decimal = 0.0
  327. var presetArray = [Presets]()
  328. coredataContext.performAndWait {
  329. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  330. try? presetArray = coredataContext.fetch(requestPresets)
  331. }
  332. var waitersNotepad = [String]()
  333. var stringValue = ""
  334. for each in filteredArray {
  335. let countedSet = NSCountedSet(array: filteredArray)
  336. let count = countedSet.count(for: each)
  337. if each != stringValue {
  338. waitersNotepad.append("\(count) \(each)")
  339. }
  340. stringValue = each
  341. for sel in presetArray {
  342. if sel.dish == each {
  343. carbs_ += (sel.carbs)! as Decimal
  344. fat_ += (sel.fat)! as Decimal
  345. protein_ += (sel.protein)! as Decimal
  346. break
  347. }
  348. }
  349. }
  350. let extracarbs = carbs - carbs_
  351. let extraFat = fat - fat_
  352. let extraProtein = protein - protein_
  353. var addedString = ""
  354. if extracarbs > 0, filteredArray.isNotEmpty {
  355. addedString += "Additional carbs: \(extracarbs) ,"
  356. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  357. if extraFat > 0, filteredArray.isNotEmpty {
  358. addedString += "Additional fat: \(extraFat) ,"
  359. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  360. if extraProtein > 0, filteredArray.isNotEmpty {
  361. addedString += "Additional protein: \(extraProtein) ,"
  362. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  363. if addedString != "" {
  364. waitersNotepad.append(addedString)
  365. }
  366. var waitersNotepadString = ""
  367. if waitersNotepad.count == 1 {
  368. waitersNotepadString = waitersNotepad[0]
  369. } else if waitersNotepad.count > 1 {
  370. for each in waitersNotepad {
  371. if each != waitersNotepad.last {
  372. waitersNotepadString += " " + each + ","
  373. } else { waitersNotepadString += " " + each }
  374. }
  375. }
  376. return waitersNotepadString
  377. }
  378. func loadEntries(_ editMode: Bool) {
  379. if editMode {
  380. coredataContext.performAndWait {
  381. var mealToEdit = [Meals]()
  382. let requestMeal = Meals.fetchRequest() as NSFetchRequest<Meals>
  383. let sortMeal = NSSortDescriptor(key: "createdAt", ascending: false)
  384. requestMeal.sortDescriptors = [sortMeal]
  385. requestMeal.fetchLimit = 1
  386. try? mealToEdit = self.coredataContext.fetch(requestMeal)
  387. self.carbs = Decimal(mealToEdit.first?.carbs ?? 0)
  388. self.fat = Decimal(mealToEdit.first?.fat ?? 0)
  389. self.protein = Decimal(mealToEdit.first?.protein ?? 0)
  390. self.note = mealToEdit.first?.note ?? ""
  391. self.id_ = mealToEdit.first?.id ?? ""
  392. }
  393. }
  394. }
  395. func saveToCoreData(_ stored: [CarbsEntry]) {
  396. coredataContext.performAndWait {
  397. let save = Meals(context: coredataContext)
  398. if let entry = stored.first {
  399. save.createdAt = now
  400. save.actualDate = entry.actualDate ?? Date.now
  401. save.id = entry.id ?? ""
  402. save.fpuID = entry.fpuID ?? ""
  403. save.carbs = Double(entry.carbs)
  404. save.fat = Double(entry.fat ?? 0)
  405. save.protein = Double(entry.protein ?? 0)
  406. save.note = entry.note
  407. try? coredataContext.save()
  408. }
  409. print("meals 1: ID: " + (save.id ?? "").description + " FPU ID: " + (save.fpuID ?? "").description)
  410. }
  411. }
  412. }
  413. }
  414. extension Bolus.StateModel: SuggestionObserver {
  415. func suggestionDidUpdate(_: Suggestion) {
  416. DispatchQueue.main.async {
  417. self.waitForSuggestion = false
  418. }
  419. setupInsulinRequired()
  420. }
  421. }