BolusStateModel.swift 23 KB

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