BolusStateModel.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. @Injected() var glucoseStorage: GlucoseStorage!
  17. @Published var suggestion: Suggestion?
  18. @Published var predictions: Predictions?
  19. @Published var amount: Decimal = 0
  20. @Published var insulinRecommended: Decimal = 0
  21. @Published var insulinRequired: Decimal = 0
  22. @Published var units: GlucoseUnits = .mmolL
  23. @Published var percentage: Decimal = 0
  24. @Published var threshold: Decimal = 0
  25. @Published var maxBolus: Decimal = 0
  26. @Published var errorString: Decimal = 0
  27. @Published var evBG: Int = 0
  28. @Published var insulin: Decimal = 0
  29. @Published var isf: Decimal = 0
  30. @Published var error: Bool = false
  31. @Published var minGuardBG: Decimal = 0
  32. @Published var minDelta: Decimal = 0
  33. @Published var expectedDelta: Decimal = 0
  34. @Published var minPredBG: Decimal = 0
  35. @Published var waitForSuggestion: Bool = false
  36. @Published var carbRatio: Decimal = 0
  37. @Published var addButtonPressed: Bool = false
  38. var waitForSuggestionInitial: Bool = false
  39. // added for bolus calculator
  40. @Published var recentGlucose: BloodGlucose?
  41. @Published var target: Decimal = 0
  42. @Published var cob: Decimal = 0
  43. @Published var iob: Decimal = 0
  44. @Published var currentBG: Decimal = 0
  45. @Published var fifteenMinInsulin: Decimal = 0
  46. @Published var deltaBG: Decimal = 0
  47. @Published var targetDifferenceInsulin: Decimal = 0
  48. @Published var targetDifference: Decimal = 0
  49. @Published var wholeCob: Decimal = 0
  50. @Published var wholeCobInsulin: Decimal = 0
  51. @Published var iobInsulinReduction: Decimal = 0
  52. @Published var wholeCalc: Decimal = 0
  53. @Published var insulinCalculated: Decimal = 0
  54. @Published var fraction: Decimal = 0
  55. @Published var useCalc: Bool = false
  56. @Published var basal: Decimal = 0
  57. @Published var fattyMeals: Bool = false
  58. @Published var fattyMealFactor: Decimal = 0
  59. @Published var useFattyMealCorrectionFactor: Bool = false
  60. @Published var displayPresets: Bool = true
  61. @Published var currentBasal: Decimal = 0
  62. @Published var sweetMeals: Bool = false
  63. @Published var sweetMealFactor: Decimal = 0
  64. @Published var useSuperBolus: Bool = false
  65. @Published var superBolusInsulin: Decimal = 0
  66. @Published var meal: [CarbsEntry]?
  67. @Published var carbs: Decimal = 0
  68. @Published var fat: Decimal = 0
  69. @Published var protein: Decimal = 0
  70. @Published var note: String = ""
  71. @Published var date = Date()
  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 id_: String = ""
  79. @Published var summary: String = ""
  80. @Published var skipBolus: Bool = false
  81. @Published var externalInsulin: Bool = false
  82. let now = Date.now
  83. private let treatmentsVM = TreatmentsViewModel()
  84. let context = CoreDataStack.shared.persistentContainer.viewContext
  85. override func subscribe() {
  86. setupInsulinRequired()
  87. broadcaster.register(SuggestionObserver.self, observer: self)
  88. broadcaster.register(BolusFailureObserver.self, observer: self)
  89. units = settingsManager.settings.units
  90. percentage = settingsManager.settings.insulinReqPercentage
  91. threshold = provider.suggestion?.threshold ?? 0
  92. maxBolus = provider.pumpSettings().maxBolus
  93. // added
  94. fraction = settings.settings.overrideFactor
  95. useCalc = settings.settings.useCalc
  96. fattyMeals = settings.settings.fattyMeals
  97. fattyMealFactor = settings.settings.fattyMealFactor
  98. sweetMeals = settings.settings.sweetMeals
  99. sweetMealFactor = settings.settings.sweetMealFactor
  100. displayPresets = settings.settings.displayPresets
  101. carbsRequired = provider.suggestion?.carbsReq
  102. maxCarbs = settings.settings.maxCarbs
  103. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  104. useFPUconversion = settingsManager.settings.useFPUconversion
  105. if waitForSuggestionInitial {
  106. apsManager.determineBasal()
  107. .receive(on: DispatchQueue.main)
  108. .sink { [weak self] ok in
  109. guard let self = self else { return }
  110. if !ok {
  111. self.waitForSuggestion = false
  112. self.insulinRequired = 0
  113. self.insulinRecommended = 0
  114. }
  115. }.store(in: &lifetime)
  116. }
  117. if let notNilSugguestion = provider.suggestion {
  118. suggestion = notNilSugguestion
  119. if let notNilPredictions = suggestion?.predictions {
  120. predictions = notNilPredictions
  121. }
  122. }
  123. }
  124. func getCurrentBasal() {
  125. let basalEntries = provider.getProfile()
  126. let dateFormatter = DateFormatter()
  127. dateFormatter.dateFormat = "HH:mm:ss"
  128. let currentTime = dateFormatter.string(from: Date())
  129. // loop throug entries and get current basal entry
  130. for (index, entry) in basalEntries.enumerated() {
  131. if let entryStartTimeDate = dateFormatter.date(from: entry.start) {
  132. var entryEndTimeDate: Date
  133. if index < basalEntries.count - 1 {
  134. let nextEntry = basalEntries[index + 1]
  135. if let nextEntryStartTimeDate = dateFormatter.date(from: nextEntry.start) {
  136. let timeDifference = nextEntryStartTimeDate.timeIntervalSince(entryStartTimeDate)
  137. entryEndTimeDate = entryStartTimeDate.addingTimeInterval(timeDifference)
  138. } else {
  139. continue
  140. }
  141. } else {
  142. entryEndTimeDate = Date()
  143. }
  144. // if currenTime is between start and end of basal entry -> basal = currentBasal
  145. if let currentTimeDate = dateFormatter.date(from: currentTime) {
  146. if currentTimeDate >= entryStartTimeDate, currentTimeDate <= entryEndTimeDate {
  147. if let basal = entry.rate as? Decimal {
  148. currentBasal = basal
  149. break
  150. }
  151. }
  152. }
  153. }
  154. }
  155. }
  156. func getDeltaBG() {
  157. let glucose = provider.fetchGlucose()
  158. guard glucose.count >= 3 else { return }
  159. let lastGlucose = glucose.first?.glucose ?? 0
  160. let thirdLastGlucose = glucose[2]
  161. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose.glucose)
  162. deltaBG = delta
  163. }
  164. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  165. /// Calculate insulin recommendation
  166. func calculateInsulin() -> Decimal {
  167. // ensure that isf is in mg/dL
  168. var conversion: Decimal {
  169. units == .mmolL ? 0.0555 : 1
  170. }
  171. let isfForCalculation = isf / conversion
  172. // insulin needed for the current blood glucose
  173. targetDifference = (currentBG - target)
  174. targetDifferenceInsulin = targetDifference / isfForCalculation
  175. // more or less insulin because of bg trend in the last 15 minutes
  176. fifteenMinInsulin = deltaBG / isfForCalculation
  177. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  178. wholeCob = cob + carbs
  179. wholeCobInsulin = wholeCob / carbRatio
  180. // determine how much the calculator reduces/ increases the bolus because of IOB
  181. iobInsulinReduction = (-1) * iob
  182. // adding everything together
  183. // add a calc for the case that no fifteenMinInsulin is available
  184. if deltaBG != 0 {
  185. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  186. } else {
  187. // add (rare) case that no glucose value is available -> maybe display warning?
  188. // if no bg is available, ?? sets its value to 0
  189. if currentBG == 0 {
  190. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  191. } else {
  192. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  193. }
  194. }
  195. // apply custom factor at the end of the calculations
  196. let result = wholeCalc * fraction
  197. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  198. if useFattyMealCorrectionFactor {
  199. insulinCalculated = result * fattyMealFactor
  200. } else if useSuperBolus {
  201. superBolusInsulin = sweetMealFactor * currentBasal
  202. insulinCalculated = result + superBolusInsulin
  203. } else {
  204. insulinCalculated = result
  205. }
  206. // display no negative insulinCalculated
  207. insulinCalculated = max(insulinCalculated, 0)
  208. insulinCalculated = min(insulinCalculated, maxBolus)
  209. return apsManager
  210. .roundBolus(amount: max(insulinCalculated, 0))
  211. }
  212. @MainActor func invokeTreatmentsTask() {
  213. Task {
  214. if amount > 0 {
  215. if !externalInsulin {
  216. await add()
  217. } else {
  218. do {
  219. await addExternalInsulin()
  220. }
  221. }
  222. waitForSuggestion = true
  223. } else {
  224. if carbs > 0 {
  225. waitForSuggestion = true
  226. } else {
  227. hideModal()
  228. }
  229. }
  230. addCarbs()
  231. addButtonPressed = true
  232. // if glucose data is stale end the custom loading animation by hiding the modal
  233. // alternatively only set waitforSuggestion to false...
  234. let lastGlucoseDate = glucoseStorage.lastGlucoseDate()
  235. guard lastGlucoseDate >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  236. return hideModal()
  237. }
  238. }
  239. }
  240. @MainActor func add() async {
  241. guard amount > 0 else {
  242. showModal(for: nil)
  243. return
  244. }
  245. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  246. do {
  247. let authenticated = try await unlockmanager.unlock()
  248. if authenticated {
  249. apsManager.enactBolus(amount: maxAmount, isSMB: false)
  250. } else {
  251. print("authentication failed")
  252. }
  253. } catch {
  254. print("authentication error for pump bolus: \(error.localizedDescription)")
  255. DispatchQueue.main.async {
  256. self.waitForSuggestion = false
  257. if self.addButtonPressed {
  258. self.hideModal()
  259. }
  260. }
  261. }
  262. }
  263. func setupInsulinRequired() {
  264. DispatchQueue.main.async {
  265. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  266. var conversion: Decimal = 1.0
  267. if self.units == .mmolL {
  268. conversion = 0.0555
  269. }
  270. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  271. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  272. self.target = self.provider.suggestion?.current_target ?? 0
  273. self.isf = self.provider.suggestion?.isf ?? 0
  274. self.iob = self.provider.suggestion?.iob ?? 0
  275. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  276. self.cob = self.provider.suggestion?.cob ?? 0
  277. self.basal = self.provider.suggestion?.rate ?? 0
  278. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  279. if self.settingsManager.settings.insulinReqPercentage != 100 {
  280. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  281. } else { self.insulinRecommended = self.insulin }
  282. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  283. if self.errorString != 0 {
  284. self.error = true
  285. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  286. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  287. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  288. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  289. } else { self.error = false }
  290. self.insulinRecommended = self.apsManager
  291. .roundBolus(amount: max(self.insulinRecommended, 0))
  292. if self.useCalc {
  293. self.getCurrentBasal()
  294. self.getDeltaBG()
  295. self.insulinCalculated = self.calculateInsulin()
  296. }
  297. }
  298. }
  299. // MARK: - Carbs
  300. // we need to also fetch the data after we have saved them in order to update the array and the UI because of the MVVM Architecture
  301. func addCarbs() {
  302. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  303. carbs = min(carbs, maxCarbs)
  304. id_ = UUID().uuidString
  305. let carbsToStore = [CarbsEntry(
  306. id: id_,
  307. createdAt: now,
  308. actualDate: date,
  309. carbs: carbs,
  310. fat: fat,
  311. protein: protein,
  312. note: note,
  313. enteredBy: CarbsEntry.manual,
  314. isFPU: false, fpuID: UUID().uuidString
  315. )]
  316. carbsStorage.storeCarbs(carbsToStore)
  317. if carbs > 0 {
  318. saveCarbsToCoreData(carbsToStore)
  319. // only perform determine basal sync if the user doesn't use the pump bolus, otherwise the enact bolus func in the APSManger does a sync
  320. if amount <= 0 {
  321. apsManager.determineBasalSync()
  322. }
  323. }
  324. }
  325. func saveCarbsToCoreData(_: [CarbsEntry]) {
  326. context.performAndWait {
  327. // create new object in the view context
  328. let newCarbEntry = MealsStored(context: self.context)
  329. newCarbEntry.id = UUID()
  330. newCarbEntry.note = ""
  331. newCarbEntry.carbs = Double(carbs)
  332. newCarbEntry.fat = Double(fat)
  333. newCarbEntry.protein = Double(protein)
  334. do {
  335. try self.context.save()
  336. debugPrint(
  337. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved carbs to core data"
  338. )
  339. } catch {
  340. debugPrint(
  341. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to save carbs to core data"
  342. )
  343. }
  344. }
  345. }
  346. // MARK: - Presets
  347. func deletePreset() {
  348. if selection != nil {
  349. try? context.delete(selection!)
  350. try? context.save()
  351. carbs = 0
  352. fat = 0
  353. protein = 0
  354. }
  355. selection = nil
  356. }
  357. func removePresetFromNewMeal() {
  358. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  359. if a != nil, summation[a ?? 0] != "" {
  360. summation.remove(at: a!)
  361. }
  362. }
  363. func addPresetToNewMeal() {
  364. let test: String = selection?.dish ?? "dontAdd"
  365. if test != "dontAdd" {
  366. summation.append(test)
  367. }
  368. }
  369. func addNewPresetToWaitersNotepad(_ dish: String) {
  370. summation.append(dish)
  371. }
  372. func addToSummation() {
  373. summation.append(selection?.dish ?? "")
  374. }
  375. func waitersNotepad() -> String {
  376. var filteredArray = summation.filter { !$0.isEmpty }
  377. if carbs == 0, protein == 0, fat == 0 {
  378. filteredArray = []
  379. }
  380. guard filteredArray != [] else {
  381. return ""
  382. }
  383. var carbs_: Decimal = 0.0
  384. var fat_: Decimal = 0.0
  385. var protein_: Decimal = 0.0
  386. var presetArray = [Presets]()
  387. context.performAndWait {
  388. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  389. try? presetArray = context.fetch(requestPresets)
  390. }
  391. var waitersNotepad = [String]()
  392. var stringValue = ""
  393. for each in filteredArray {
  394. let countedSet = NSCountedSet(array: filteredArray)
  395. let count = countedSet.count(for: each)
  396. if each != stringValue {
  397. waitersNotepad.append("\(count) \(each)")
  398. }
  399. stringValue = each
  400. for sel in presetArray {
  401. if sel.dish == each {
  402. carbs_ += (sel.carbs)! as Decimal
  403. fat_ += (sel.fat)! as Decimal
  404. protein_ += (sel.protein)! as Decimal
  405. break
  406. }
  407. }
  408. }
  409. let extracarbs = carbs - carbs_
  410. let extraFat = fat - fat_
  411. let extraProtein = protein - protein_
  412. var addedString = ""
  413. if extracarbs > 0, filteredArray.isNotEmpty {
  414. addedString += "Additional carbs: \(extracarbs) ,"
  415. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  416. if extraFat > 0, filteredArray.isNotEmpty {
  417. addedString += "Additional fat: \(extraFat) ,"
  418. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  419. if extraProtein > 0, filteredArray.isNotEmpty {
  420. addedString += "Additional protein: \(extraProtein) ,"
  421. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  422. if addedString != "" {
  423. waitersNotepad.append(addedString)
  424. }
  425. var waitersNotepadString = ""
  426. if waitersNotepad.count == 1 {
  427. waitersNotepadString = waitersNotepad[0]
  428. } else if waitersNotepad.count > 1 {
  429. for each in waitersNotepad {
  430. if each != waitersNotepad.last {
  431. waitersNotepadString += " " + each + ","
  432. } else { waitersNotepadString += " " + each }
  433. }
  434. }
  435. return waitersNotepadString
  436. }
  437. func loadEntries(_ editMode: Bool) {
  438. if editMode {
  439. context.performAndWait {
  440. var mealToEdit = [Meals]()
  441. let requestMeal = Meals.fetchRequest() as NSFetchRequest<Meals>
  442. let sortMeal = NSSortDescriptor(key: "createdAt", ascending: false)
  443. requestMeal.sortDescriptors = [sortMeal]
  444. requestMeal.fetchLimit = 1
  445. try? mealToEdit = self.context.fetch(requestMeal)
  446. self.carbs = Decimal(mealToEdit.first?.carbs ?? 0)
  447. self.fat = Decimal(mealToEdit.first?.fat ?? 0)
  448. self.protein = Decimal(mealToEdit.first?.protein ?? 0)
  449. self.note = mealToEdit.first?.note ?? ""
  450. self.id_ = mealToEdit.first?.id ?? ""
  451. }
  452. }
  453. }
  454. // MARK: EXTERNAL INSULIN
  455. @MainActor func addExternalInsulin() async {
  456. guard amount > 0 else {
  457. showModal(for: nil)
  458. return
  459. }
  460. amount = min(amount, maxBolus * 3)
  461. do {
  462. let authenticated = try await unlockmanager.unlock()
  463. if authenticated {
  464. storeExternalInsulinEvent()
  465. } else {
  466. print("authentication failed")
  467. }
  468. } catch {
  469. print("authentication error for external insulin: \(error.localizedDescription)")
  470. DispatchQueue.main.async {
  471. self.waitForSuggestion = false
  472. if self.addButtonPressed {
  473. self.hideModal()
  474. }
  475. }
  476. }
  477. }
  478. private func storeExternalInsulinEvent() {
  479. pumpHistoryStorage.storeEvents(
  480. [
  481. PumpHistoryEvent(
  482. id: UUID().uuidString,
  483. type: .bolus,
  484. timestamp: date,
  485. amount: amount,
  486. duration: nil,
  487. durationMin: nil,
  488. rate: nil,
  489. temp: nil,
  490. carbInput: nil,
  491. isExternal: true
  492. )
  493. ]
  494. )
  495. debug(.default, "External insulin saved to pumphistory.json")
  496. // perform determine basal sync
  497. apsManager.determineBasalSync()
  498. }
  499. }
  500. }
  501. extension Bolus.StateModel: SuggestionObserver, BolusFailureObserver {
  502. func suggestionDidUpdate(_: Suggestion) {
  503. DispatchQueue.main.async {
  504. self.waitForSuggestion = false
  505. if self.addButtonPressed {
  506. self.hideModal()
  507. }
  508. }
  509. setupInsulinRequired()
  510. }
  511. func bolusDidFail() {
  512. DispatchQueue.main.async {
  513. self.waitForSuggestion = false
  514. if self.addButtonPressed {
  515. self.hideModal()
  516. }
  517. }
  518. }
  519. }