BolusStateModel.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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(
  167. "Bolus State: \(#function) \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched glucose"
  168. )
  169. } catch {
  170. debugPrint(
  171. "Bolus State: \(#function) \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to fetch glucose"
  172. )
  173. }
  174. }
  175. private func fetchDetermination() {
  176. do {
  177. determination = try context.fetch(OrefDetermination.fetch(NSPredicate.enactedDetermination))
  178. debugPrint(
  179. "Bolus State: \(#function) \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) fetched determinations"
  180. )
  181. } catch {
  182. debugPrint(
  183. "Bolus State: \(#function) \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to fetch determinations"
  184. )
  185. }
  186. }
  187. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  188. /// Calculate insulin recommendation
  189. func calculateInsulin() -> Decimal {
  190. // ensure that isf is in mg/dL
  191. var conversion: Decimal {
  192. units == .mmolL ? 0.0555 : 1
  193. }
  194. let isfForCalculation = isf / conversion
  195. // insulin needed for the current blood glucose
  196. targetDifference = currentBG - target
  197. targetDifferenceInsulin = targetDifference / isfForCalculation
  198. // more or less insulin because of bg trend in the last 15 minutes
  199. fifteenMinInsulin = deltaBG / isfForCalculation
  200. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  201. wholeCob = Decimal(cob) + carbs
  202. wholeCobInsulin = wholeCob / carbRatio
  203. // determine how much the calculator reduces/ increases the bolus because of IOB
  204. iobInsulinReduction = (-1) * iob
  205. // adding everything together
  206. // add a calc for the case that no fifteenMinInsulin is available
  207. if deltaBG != 0 {
  208. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  209. } else {
  210. // add (rare) case that no glucose value is available -> maybe display warning?
  211. // if no bg is available, ?? sets its value to 0
  212. if currentBG == 0 {
  213. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  214. } else {
  215. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  216. }
  217. }
  218. // apply custom factor at the end of the calculations
  219. let result = wholeCalc * fraction
  220. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  221. if useFattyMealCorrectionFactor {
  222. insulinCalculated = result * fattyMealFactor
  223. } else if useSuperBolus {
  224. superBolusInsulin = sweetMealFactor * currentBasal
  225. insulinCalculated = result + superBolusInsulin
  226. } else {
  227. insulinCalculated = result
  228. }
  229. // display no negative insulinCalculated
  230. insulinCalculated = max(insulinCalculated, 0)
  231. insulinCalculated = min(insulinCalculated, maxBolus)
  232. guard let apsManager = apsManager else {
  233. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  234. return insulinCalculated
  235. }
  236. return apsManager.roundBolus(amount: insulinCalculated)
  237. }
  238. func setupInsulinRequired() {
  239. DispatchQueue.main.async {
  240. self.insulinRequired = (self.determination.first?.insulinReq ?? 0) as Decimal
  241. self.evBG = (self.determination.first?.eventualBG ?? 0) as Decimal
  242. self.insulin = (self.determination.first?.insulinForManualBolus ?? 0) as Decimal
  243. self.target = (self.determination.first?.currentTarget ?? 100) as Decimal
  244. self.isf = (self.determination.first?.insulinSensitivity ?? 0) as Decimal
  245. self.iob = (self.determination.first?.iob ?? 0) as Decimal
  246. self.cob = (self.determination.first?.cob ?? 0) as Int16
  247. self.basal = (self.determination.first?.tempBasal ?? 0) as Decimal
  248. self.carbRatio = (self.determination.first?.carbRatio ?? 0) as Decimal
  249. self.getCurrentBasal()
  250. self.insulinCalculated = self.calculateInsulin()
  251. }
  252. }
  253. // MARK: - Button tasks
  254. @MainActor func invokeTreatmentsTask() {
  255. Task {
  256. let isInsulinGiven = amount > 0
  257. let isCarbsPresent = carbs > 0
  258. if isInsulinGiven {
  259. try await handleInsulin(isExternal: externalInsulin)
  260. } else if isCarbsPresent {
  261. waitForSuggestion = true
  262. } else {
  263. hideModal()
  264. return
  265. }
  266. saveMeal()
  267. addButtonPressed = true
  268. // if glucose data is stale end the custom loading animation by hiding the modal
  269. // guard glucoseOfLast20Min.first?.date ?? now >= Date().addingTimeInterval(-12.minutes.timeInterval) else {
  270. // return hideModal()
  271. // }
  272. }
  273. }
  274. // MARK: - Insulin
  275. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  276. if !isExternal {
  277. await addPumpInsulin()
  278. } else {
  279. await addExternalInsulin()
  280. }
  281. waitForSuggestion = true
  282. }
  283. @MainActor func addPumpInsulin() async {
  284. guard amount > 0 else {
  285. showModal(for: nil)
  286. return
  287. }
  288. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  289. do {
  290. let authenticated = try await unlockmanager.unlock()
  291. if authenticated {
  292. apsManager.enactBolus(amount: maxAmount, isSMB: false)
  293. savePumpInsulin(amount: amount)
  294. } else {
  295. print("authentication failed")
  296. }
  297. } catch {
  298. print("authentication error for pump bolus: \(error.localizedDescription)")
  299. DispatchQueue.main.async {
  300. self.waitForSuggestion = false
  301. if self.addButtonPressed {
  302. self.hideModal()
  303. }
  304. }
  305. }
  306. }
  307. private func savePumpInsulin(amount: Decimal) {
  308. let newItem = InsulinStored(context: context)
  309. newItem.id = UUID()
  310. newItem.amount = amount as NSDecimalNumber
  311. newItem.date = Date()
  312. newItem.external = false
  313. newItem.isSMB = false
  314. context.perform {
  315. do {
  316. try self.context.save()
  317. debugPrint(
  318. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved pump insulin to core data"
  319. )
  320. } catch {
  321. debugPrint(
  322. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to save pump insulin to core data"
  323. )
  324. }
  325. }
  326. }
  327. // MARK: - EXTERNAL INSULIN
  328. @MainActor func addExternalInsulin() async {
  329. guard amount > 0 else {
  330. showModal(for: nil)
  331. return
  332. }
  333. amount = min(amount, maxBolus * 3)
  334. do {
  335. let authenticated = try await unlockmanager.unlock()
  336. if authenticated {
  337. storeExternalInsulinEvent()
  338. } else {
  339. print("authentication failed")
  340. }
  341. } catch {
  342. print("authentication error for external insulin: \(error.localizedDescription)")
  343. DispatchQueue.main.async {
  344. self.waitForSuggestion = false
  345. if self.addButtonPressed {
  346. self.hideModal()
  347. }
  348. }
  349. }
  350. }
  351. private func storeExternalInsulinEvent() {
  352. pumpHistoryStorage.storeEvents(
  353. [
  354. PumpHistoryEvent(
  355. id: UUID().uuidString,
  356. type: .bolus,
  357. timestamp: date,
  358. amount: amount,
  359. duration: nil,
  360. durationMin: nil,
  361. rate: nil,
  362. temp: nil,
  363. carbInput: nil,
  364. isExternal: true
  365. )
  366. ]
  367. )
  368. debug(.default, "External insulin saved to pumphistory.json")
  369. // save to core data asynchronously
  370. context.perform {
  371. let newItem = InsulinStored(context: self.context)
  372. newItem.id = UUID()
  373. newItem.amount = self.amount as NSDecimalNumber
  374. newItem.date = Date()
  375. newItem.external = true
  376. newItem.isSMB = false
  377. do {
  378. try self.context.save()
  379. debugPrint(
  380. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved carbs to core data"
  381. )
  382. } catch {
  383. debugPrint(
  384. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to save carbs to core data"
  385. )
  386. }
  387. }
  388. // perform determine basal sync
  389. apsManager.determineBasalSync()
  390. }
  391. // MARK: - Carbs
  392. // 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
  393. func saveMeal() {
  394. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  395. carbs = min(carbs, maxCarbs)
  396. id_ = UUID().uuidString
  397. let carbsToStore = [CarbsEntry(
  398. id: id_,
  399. createdAt: now,
  400. actualDate: date,
  401. carbs: carbs,
  402. fat: fat,
  403. protein: protein,
  404. note: note,
  405. enteredBy: CarbsEntry.manual,
  406. isFPU: false, fpuID: UUID().uuidString
  407. )]
  408. carbsStorage.storeCarbs(carbsToStore)
  409. if carbs > 0 {
  410. // 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
  411. if amount <= 0 {
  412. apsManager.determineBasalSync()
  413. }
  414. }
  415. }
  416. // MARK: - Presets
  417. func deletePreset() {
  418. if selection != nil {
  419. try? context.delete(selection!)
  420. try? context.save()
  421. carbs = 0
  422. fat = 0
  423. protein = 0
  424. }
  425. selection = nil
  426. }
  427. func removePresetFromNewMeal() {
  428. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  429. if a != nil, summation[a ?? 0] != "" {
  430. summation.remove(at: a!)
  431. }
  432. }
  433. func addPresetToNewMeal() {
  434. let test: String = selection?.dish ?? "dontAdd"
  435. if test != "dontAdd" {
  436. summation.append(test)
  437. }
  438. }
  439. func addNewPresetToWaitersNotepad(_ dish: String) {
  440. summation.append(dish)
  441. }
  442. func addToSummation() {
  443. summation.append(selection?.dish ?? "")
  444. }
  445. func waitersNotepad() -> String {
  446. var filteredArray = summation.filter { !$0.isEmpty }
  447. if carbs == 0, protein == 0, fat == 0 {
  448. filteredArray = []
  449. }
  450. guard filteredArray != [] else {
  451. return ""
  452. }
  453. var carbs_: Decimal = 0.0
  454. var fat_: Decimal = 0.0
  455. var protein_: Decimal = 0.0
  456. var presetArray = [Presets]()
  457. context.performAndWait {
  458. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  459. try? presetArray = context.fetch(requestPresets)
  460. }
  461. var waitersNotepad = [String]()
  462. var stringValue = ""
  463. for each in filteredArray {
  464. let countedSet = NSCountedSet(array: filteredArray)
  465. let count = countedSet.count(for: each)
  466. if each != stringValue {
  467. waitersNotepad.append("\(count) \(each)")
  468. }
  469. stringValue = each
  470. for sel in presetArray {
  471. if sel.dish == each {
  472. carbs_ += (sel.carbs)! as Decimal
  473. fat_ += (sel.fat)! as Decimal
  474. protein_ += (sel.protein)! as Decimal
  475. break
  476. }
  477. }
  478. }
  479. let extracarbs = carbs - carbs_
  480. let extraFat = fat - fat_
  481. let extraProtein = protein - protein_
  482. var addedString = ""
  483. if extracarbs > 0, filteredArray.isNotEmpty {
  484. addedString += "Additional carbs: \(extracarbs) ,"
  485. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  486. if extraFat > 0, filteredArray.isNotEmpty {
  487. addedString += "Additional fat: \(extraFat) ,"
  488. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  489. if extraProtein > 0, filteredArray.isNotEmpty {
  490. addedString += "Additional protein: \(extraProtein) ,"
  491. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  492. if addedString != "" {
  493. waitersNotepad.append(addedString)
  494. }
  495. var waitersNotepadString = ""
  496. if waitersNotepad.count == 1 {
  497. waitersNotepadString = waitersNotepad[0]
  498. } else if waitersNotepad.count > 1 {
  499. for each in waitersNotepad {
  500. if each != waitersNotepad.last {
  501. waitersNotepadString += " " + each + ","
  502. } else { waitersNotepadString += " " + each }
  503. }
  504. }
  505. return waitersNotepadString
  506. }
  507. }
  508. }
  509. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  510. func determinationDidUpdate(_: Determination) {
  511. DispatchQueue.main.async {
  512. self.waitForSuggestion = false
  513. if self.addButtonPressed {
  514. self.hideModal()
  515. }
  516. }
  517. setupInsulinRequired()
  518. }
  519. func bolusDidFail() {
  520. DispatchQueue.main.async {
  521. self.waitForSuggestion = false
  522. if self.addButtonPressed {
  523. self.hideModal()
  524. }
  525. }
  526. }
  527. }