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