BolusStateModel.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. } else {
  296. print("authentication failed")
  297. }
  298. } catch {
  299. print("authentication error for pump bolus: \(error.localizedDescription)")
  300. DispatchQueue.main.async {
  301. self.waitForSuggestion = false
  302. if self.addButtonPressed {
  303. self.hideModal()
  304. }
  305. }
  306. }
  307. }
  308. private func savePumpInsulin(amount _: Decimal) {
  309. // create pump event
  310. let newPumpEvent = PumpEventStored(context: context)
  311. newPumpEvent.id = UUID().uuidString
  312. newPumpEvent.timestamp = Date()
  313. newPumpEvent.type = PumpEvent.bolus.rawValue
  314. // create bolus entry and specify relationship to pump event
  315. let newBolusEntry = BolusStored(context: context)
  316. newBolusEntry.pumpEvent = newPumpEvent
  317. newBolusEntry.amount = amount as NSDecimalNumber
  318. newBolusEntry.isExternal = false
  319. newBolusEntry.isSMB = false
  320. context.perform {
  321. if self.context.hasChanges {
  322. do {
  323. try self.context.save()
  324. debugPrint(
  325. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved pump insulin to core data"
  326. )
  327. } catch {
  328. debugPrint(
  329. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to save pump insulin to core data"
  330. )
  331. }
  332. }
  333. }
  334. }
  335. // MARK: - EXTERNAL INSULIN
  336. @MainActor func addExternalInsulin() async {
  337. guard amount > 0 else {
  338. showModal(for: nil)
  339. return
  340. }
  341. amount = min(amount, maxBolus * 3)
  342. do {
  343. let authenticated = try await unlockmanager.unlock()
  344. if authenticated {
  345. storeExternalInsulinEvent()
  346. } else {
  347. print("authentication failed")
  348. }
  349. } catch {
  350. print("authentication error for external insulin: \(error.localizedDescription)")
  351. DispatchQueue.main.async {
  352. self.waitForSuggestion = false
  353. if self.addButtonPressed {
  354. self.hideModal()
  355. }
  356. }
  357. }
  358. }
  359. private func storeExternalInsulinEvent() {
  360. pumpHistoryStorage.storeEvents(
  361. [
  362. PumpHistoryEvent(
  363. id: UUID().uuidString,
  364. type: .bolus,
  365. timestamp: date,
  366. amount: amount,
  367. duration: nil,
  368. durationMin: nil,
  369. rate: nil,
  370. temp: nil,
  371. carbInput: nil,
  372. isExternal: true
  373. )
  374. ]
  375. )
  376. debug(.default, "External insulin saved to pumphistory.json")
  377. // save to core data asynchronously
  378. context.perform {
  379. // create pump event
  380. let newPumpEvent = PumpEventStored(context: self.context)
  381. newPumpEvent.id = UUID().uuidString
  382. newPumpEvent.timestamp = self.date
  383. newPumpEvent.type = PumpEvent.bolus.rawValue
  384. // create bolus entry and specify relationship to pump event
  385. let newBolusEntry = BolusStored(context: self.context)
  386. newBolusEntry.pumpEvent = newPumpEvent
  387. newBolusEntry.amount = self.amount as NSDecimalNumber
  388. newBolusEntry.isExternal = true
  389. newBolusEntry.isSMB = false
  390. if self.context.hasChanges {
  391. do {
  392. try self.context.save()
  393. debugPrint(
  394. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved carbs to core data"
  395. )
  396. } catch {
  397. debugPrint(
  398. "Bolus State: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) failed to save carbs to core data"
  399. )
  400. }
  401. }
  402. }
  403. // perform determine basal sync
  404. apsManager.determineBasalSync()
  405. }
  406. // MARK: - Carbs
  407. // 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
  408. func saveMeal() {
  409. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  410. carbs = min(carbs, maxCarbs)
  411. id_ = UUID().uuidString
  412. let carbsToStore = [CarbsEntry(
  413. id: id_,
  414. createdAt: now,
  415. actualDate: date,
  416. carbs: carbs,
  417. fat: fat,
  418. protein: protein,
  419. note: note,
  420. enteredBy: CarbsEntry.manual,
  421. isFPU: false, fpuID: UUID().uuidString
  422. )]
  423. carbsStorage.storeCarbs(carbsToStore)
  424. if carbs > 0 {
  425. // 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
  426. if amount <= 0 {
  427. apsManager.determineBasalSync()
  428. }
  429. }
  430. }
  431. // MARK: - Presets
  432. func deletePreset() {
  433. if selection != nil {
  434. try? context.delete(selection!)
  435. if context.hasChanges {
  436. try? context.save()
  437. }
  438. carbs = 0
  439. fat = 0
  440. protein = 0
  441. }
  442. selection = nil
  443. }
  444. func removePresetFromNewMeal() {
  445. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  446. if a != nil, summation[a ?? 0] != "" {
  447. summation.remove(at: a!)
  448. }
  449. }
  450. func addPresetToNewMeal() {
  451. let test: String = selection?.dish ?? "dontAdd"
  452. if test != "dontAdd" {
  453. summation.append(test)
  454. }
  455. }
  456. func addNewPresetToWaitersNotepad(_ dish: String) {
  457. summation.append(dish)
  458. }
  459. func addToSummation() {
  460. summation.append(selection?.dish ?? "")
  461. }
  462. func waitersNotepad() -> String {
  463. var filteredArray = summation.filter { !$0.isEmpty }
  464. if carbs == 0, protein == 0, fat == 0 {
  465. filteredArray = []
  466. }
  467. guard filteredArray != [] else {
  468. return ""
  469. }
  470. var carbs_: Decimal = 0.0
  471. var fat_: Decimal = 0.0
  472. var protein_: Decimal = 0.0
  473. var presetArray = [Presets]()
  474. context.performAndWait {
  475. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  476. try? presetArray = context.fetch(requestPresets)
  477. }
  478. var waitersNotepad = [String]()
  479. var stringValue = ""
  480. for each in filteredArray {
  481. let countedSet = NSCountedSet(array: filteredArray)
  482. let count = countedSet.count(for: each)
  483. if each != stringValue {
  484. waitersNotepad.append("\(count) \(each)")
  485. }
  486. stringValue = each
  487. for sel in presetArray {
  488. if sel.dish == each {
  489. carbs_ += (sel.carbs)! as Decimal
  490. fat_ += (sel.fat)! as Decimal
  491. protein_ += (sel.protein)! as Decimal
  492. break
  493. }
  494. }
  495. }
  496. let extracarbs = carbs - carbs_
  497. let extraFat = fat - fat_
  498. let extraProtein = protein - protein_
  499. var addedString = ""
  500. if extracarbs > 0, filteredArray.isNotEmpty {
  501. addedString += "Additional carbs: \(extracarbs) ,"
  502. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  503. if extraFat > 0, filteredArray.isNotEmpty {
  504. addedString += "Additional fat: \(extraFat) ,"
  505. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  506. if extraProtein > 0, filteredArray.isNotEmpty {
  507. addedString += "Additional protein: \(extraProtein) ,"
  508. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  509. if addedString != "" {
  510. waitersNotepad.append(addedString)
  511. }
  512. var waitersNotepadString = ""
  513. if waitersNotepad.count == 1 {
  514. waitersNotepadString = waitersNotepad[0]
  515. } else if waitersNotepad.count > 1 {
  516. for each in waitersNotepad {
  517. if each != waitersNotepad.last {
  518. waitersNotepadString += " " + each + ","
  519. } else { waitersNotepadString += " " + each }
  520. }
  521. }
  522. return waitersNotepadString
  523. }
  524. }
  525. }
  526. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  527. func determinationDidUpdate(_: Determination) {
  528. DispatchQueue.main.async {
  529. self.waitForSuggestion = false
  530. if self.addButtonPressed {
  531. self.hideModal()
  532. }
  533. }
  534. setupInsulinRequired()
  535. }
  536. func bolusDidFail() {
  537. DispatchQueue.main.async {
  538. self.waitForSuggestion = false
  539. if self.addButtonPressed {
  540. self.hideModal()
  541. }
  542. }
  543. }
  544. }