BolusStateModel.swift 23 KB

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