BolusStateModel.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  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. @Injected() var determinationStorage: DeterminationStorage!
  18. @Published var lowGlucose: Decimal = 4.asMgdL
  19. @Published var highGlucose: Decimal = 10.asMgdL
  20. @Published var predictions: Predictions?
  21. @Published var amount: Decimal = 0
  22. @Published var insulinRecommended: Decimal = 0
  23. @Published var insulinRequired: Decimal = 0
  24. @Published var units: GlucoseUnits = .mgdL
  25. @Published var percentage: Decimal = 0
  26. @Published var threshold: Decimal = 0
  27. @Published var maxBolus: Decimal = 0
  28. @Published var errorString: Decimal = 0
  29. @Published var evBG: Decimal = 0
  30. @Published var insulin: Decimal = 0
  31. @Published var isf: Decimal = 0
  32. @Published var error: Bool = false
  33. @Published var minGuardBG: Decimal = 0
  34. @Published var minDelta: Decimal = 0
  35. @Published var expectedDelta: Decimal = 0
  36. @Published var minPredBG: Decimal = 0
  37. @Published var waitForSuggestion: Bool = false
  38. @Published var carbRatio: Decimal = 0
  39. @Published var addButtonPressed: Bool = false
  40. var waitForSuggestionInitial: Bool = false
  41. // added for bolus calculator
  42. @Published var target: Decimal = 0
  43. @Published var cob: Int16 = 0
  44. @Published var iob: Decimal = 0
  45. @Published var currentBG: Decimal = 0
  46. @Published var fifteenMinInsulin: Decimal = 0
  47. @Published var deltaBG: Decimal = 0
  48. @Published var targetDifferenceInsulin: Decimal = 0
  49. @Published var targetDifference: Decimal = 0
  50. @Published var wholeCob: Decimal = 0
  51. @Published var wholeCobInsulin: Decimal = 0
  52. @Published var iobInsulinReduction: Decimal = 0
  53. @Published var wholeCalc: Decimal = 0
  54. @Published var insulinCalculated: Decimal = 0
  55. @Published var fraction: Decimal = 0
  56. @Published var useCalc: Bool = false
  57. @Published var basal: Decimal = 0
  58. @Published var fattyMeals: Bool = false
  59. @Published var fattyMealFactor: Decimal = 0
  60. @Published var useFattyMealCorrectionFactor: Bool = false
  61. @Published var displayPresets: Bool = true
  62. @Published var currentBasal: Decimal = 0
  63. @Published var currentCarbRatio: Decimal = 0
  64. @Published var currentBGTarget: Decimal = 0
  65. @Published var currentISF: Decimal = 0
  66. @Published var sweetMeals: Bool = false
  67. @Published var sweetMealFactor: Decimal = 0
  68. @Published var useSuperBolus: Bool = false
  69. @Published var superBolusInsulin: Decimal = 0
  70. @Published var meal: [CarbsEntry]?
  71. @Published var carbs: Decimal = 0
  72. @Published var fat: Decimal = 0
  73. @Published var protein: Decimal = 0
  74. @Published var note: String = ""
  75. @Published var date = Date()
  76. @Published var carbsRequired: Decimal?
  77. @Published var useFPUconversion: Bool = false
  78. @Published var dish: String = ""
  79. @Published var selection: MealPresetStored?
  80. @Published var summation: [String] = []
  81. @Published var maxCarbs: Decimal = 0
  82. @Published var id_: String = ""
  83. @Published var summary: String = ""
  84. @Published var skipBolus: Bool = false
  85. @Published var externalInsulin: Bool = false
  86. @Published var showInfo: Bool = false
  87. @Published var glucoseFromPersistence: [GlucoseStored] = []
  88. @Published var determination: [OrefDetermination] = []
  89. @Published var preprocessedData: [(id: UUID, forecast: Forecast, forecastValue: ForecastValue)] = []
  90. @Published var predictionsForChart: Predictions?
  91. @Published var simulatedDetermination: Determination?
  92. @Published var determinationObjectIDs: [NSManagedObjectID] = []
  93. @Published var minForecast: [Int] = []
  94. @Published var maxForecast: [Int] = []
  95. @Published var minCount: Int = 12 // count of Forecasts drawn in 5 min distances, i.e. 12 means a min of 1 hour
  96. @Published var displayForecastsAsLines: Bool = false
  97. let now = Date.now
  98. let viewContext = CoreDataStack.shared.persistentContainer.viewContext
  99. let backgroundContext = CoreDataStack.shared.newTaskContext()
  100. private var coreDataObserver: CoreDataObserver?
  101. typealias PumpEvent = PumpEventStored.EventType
  102. override func subscribe() {
  103. setupGlucoseNotification()
  104. coreDataObserver = CoreDataObserver()
  105. registerHandlers()
  106. setupGlucoseArray()
  107. Task {
  108. let getMaxBolus = await self.provider.getPumpSettings().maxBolus
  109. await MainActor.run {
  110. maxBolus = getMaxBolus
  111. }
  112. await getCurrentCarbRatio()
  113. await getCurrentBGTarget()
  114. await getCurrentISF()
  115. await setupDeterminationsArray()
  116. // Determination has updated, so we can use this to draw the initial Forecast Chart
  117. let forecastData = await mapForecastsForChart()
  118. await updateForecasts(with: forecastData)
  119. }
  120. broadcaster.register(DeterminationObserver.self, observer: self)
  121. broadcaster.register(BolusFailureObserver.self, observer: self)
  122. units = settingsManager.settings.units
  123. percentage = settingsManager.settings.insulinReqPercentage
  124. fraction = settings.settings.overrideFactor
  125. useCalc = settings.settings.useCalc
  126. fattyMeals = settings.settings.fattyMeals
  127. fattyMealFactor = settings.settings.fattyMealFactor
  128. sweetMeals = settings.settings.sweetMeals
  129. sweetMealFactor = settings.settings.sweetMealFactor
  130. displayPresets = settings.settings.displayPresets
  131. displayForecastsAsLines = settings.settings.displayForecastsAsLines
  132. lowGlucose = units == .mgdL ? settingsManager.settings.low : settingsManager.settings.low.asMmolL
  133. highGlucose = units == .mgdL ? settingsManager.settings.high : settingsManager.settings.high.asMmolL
  134. maxCarbs = settings.settings.maxCarbs
  135. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  136. useFPUconversion = settingsManager.settings.useFPUconversion
  137. if waitForSuggestionInitial {
  138. Task {
  139. let ok = await apsManager.determineBasal()
  140. if !ok {
  141. self.waitForSuggestion = false
  142. self.insulinRequired = 0
  143. self.insulinRecommended = 0
  144. }
  145. }
  146. }
  147. }
  148. // MARK: - Basal
  149. func getCurrentBasal() async {
  150. let basalEntries = await provider.getBasalProfile()
  151. let now = Date()
  152. let calendar = Calendar.current
  153. let dateFormatter = DateFormatter()
  154. dateFormatter.dateFormat = "HH:mm:ss"
  155. dateFormatter.timeZone = TimeZone.current
  156. for (index, entry) in basalEntries.enumerated() {
  157. guard let entryTime = dateFormatter.date(from: entry.start) else {
  158. print("Invalid entry start time: \(entry.start)")
  159. continue
  160. }
  161. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  162. let entryStartTime = calendar.date(
  163. bySettingHour: entryComponents.hour!,
  164. minute: entryComponents.minute!,
  165. second: entryComponents.second!,
  166. of: now
  167. )!
  168. let entryEndTime: Date
  169. if index < basalEntries.count - 1,
  170. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  171. {
  172. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  173. entryEndTime = calendar.date(
  174. bySettingHour: nextEntryComponents.hour!,
  175. minute: nextEntryComponents.minute!,
  176. second: nextEntryComponents.second!,
  177. of: now
  178. )!
  179. } else {
  180. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  181. }
  182. if now >= entryStartTime, now < entryEndTime {
  183. await MainActor.run {
  184. currentBasal = entry.rate
  185. }
  186. break
  187. }
  188. }
  189. }
  190. func getCurrentCarbRatio() async {
  191. let carbRatios = await provider.getCarbRatios()
  192. print("carbRatios \(carbRatios)")
  193. let now = Date()
  194. let calendar = Calendar.current
  195. let dateFormatter = DateFormatter()
  196. dateFormatter.dateFormat = "HH:mm:ss"
  197. dateFormatter.timeZone = TimeZone.current
  198. for (index, entry) in carbRatios.schedule.enumerated() {
  199. guard let entryTime = dateFormatter.date(from: entry.start) else {
  200. print("Invalid entry start time: \(entry.start)")
  201. continue
  202. }
  203. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  204. let entryStartTime = calendar.date(
  205. bySettingHour: entryComponents.hour!,
  206. minute: entryComponents.minute!,
  207. second: entryComponents.second!,
  208. of: now
  209. )!
  210. let entryEndTime: Date
  211. if index < carbRatios.schedule.count - 1,
  212. let nextEntryTime = dateFormatter.date(from: carbRatios.schedule[index + 1].start)
  213. {
  214. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  215. entryEndTime = calendar.date(
  216. bySettingHour: nextEntryComponents.hour!,
  217. minute: nextEntryComponents.minute!,
  218. second: nextEntryComponents.second!,
  219. of: now
  220. )!
  221. } else {
  222. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  223. }
  224. if now >= entryStartTime, now < entryEndTime {
  225. await MainActor.run {
  226. currentCarbRatio = entry.ratio
  227. debugPrint("currentCarbRatio: \(currentCarbRatio)")
  228. }
  229. return
  230. }
  231. }
  232. }
  233. func getCurrentBGTarget() async {
  234. let bgTargets = await provider.getBGTarget()
  235. print("bgTargets \(bgTargets)")
  236. let now = Date()
  237. let calendar = Calendar.current
  238. let dateFormatter = DateFormatter()
  239. dateFormatter.dateFormat = "HH:mm:ss"
  240. dateFormatter.timeZone = TimeZone.current
  241. for (index, entry) in bgTargets.targets.enumerated() {
  242. guard let entryTime = dateFormatter.date(from: entry.start) else {
  243. print("Invalid entry start time: \(entry.start)")
  244. continue
  245. }
  246. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  247. let entryStartTime = calendar.date(
  248. bySettingHour: entryComponents.hour!,
  249. minute: entryComponents.minute!,
  250. second: entryComponents.second!,
  251. of: now
  252. )!
  253. let entryEndTime: Date
  254. if index < bgTargets.targets.count - 1,
  255. let nextEntryTime = dateFormatter.date(from: bgTargets.targets[index + 1].start)
  256. {
  257. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  258. entryEndTime = calendar.date(
  259. bySettingHour: nextEntryComponents.hour!,
  260. minute: nextEntryComponents.minute!,
  261. second: nextEntryComponents.second!,
  262. of: now
  263. )!
  264. } else {
  265. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  266. }
  267. if now >= entryStartTime, now < entryEndTime {
  268. await MainActor.run {
  269. currentBGTarget = entry.low // doesn't matter if we use entry.low or entry.high here
  270. debugPrint("currentBGTarget: \(currentBGTarget)")
  271. }
  272. return
  273. }
  274. }
  275. }
  276. func getCurrentISF() async {
  277. let insulinSensitivities = await provider.getISFValues()
  278. print("insulinSensitivities \(insulinSensitivities)")
  279. let now = Date()
  280. let calendar = Calendar.current
  281. let dateFormatter = DateFormatter()
  282. dateFormatter.dateFormat = "HH:mm:ss"
  283. dateFormatter.timeZone = TimeZone.current
  284. for (index, entry) in insulinSensitivities.sensitivities.enumerated() {
  285. guard let entryTime = dateFormatter.date(from: entry.start) else {
  286. print("Invalid entry start time: \(entry.start)")
  287. continue
  288. }
  289. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  290. let entryStartTime = calendar.date(
  291. bySettingHour: entryComponents.hour!,
  292. minute: entryComponents.minute!,
  293. second: entryComponents.second!,
  294. of: now
  295. )!
  296. let entryEndTime: Date
  297. if index < insulinSensitivities.sensitivities.count - 1,
  298. let nextEntryTime = dateFormatter.date(from: insulinSensitivities.sensitivities[index + 1].start)
  299. {
  300. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  301. entryEndTime = calendar.date(
  302. bySettingHour: nextEntryComponents.hour!,
  303. minute: nextEntryComponents.minute!,
  304. second: nextEntryComponents.second!,
  305. of: now
  306. )!
  307. } else {
  308. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  309. }
  310. if now >= entryStartTime, now < entryEndTime {
  311. await MainActor.run {
  312. currentISF = entry.sensitivity
  313. debugPrint("currentISFValue: \(currentISF)")
  314. }
  315. return
  316. }
  317. }
  318. }
  319. // MARK: CALCULATIONS FOR THE BOLUS CALCULATOR
  320. /// Calculate insulin recommendation
  321. func calculateInsulin() -> Decimal {
  322. let isfForCalculation = units == .mmolL ? isf.asMgdL : isf
  323. // insulin needed for the current blood glucose
  324. targetDifference = currentBG - target
  325. targetDifferenceInsulin = targetDifference / isfForCalculation
  326. // more or less insulin because of bg trend in the last 15 minutes
  327. fifteenMinInsulin = deltaBG / isfForCalculation
  328. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  329. wholeCob = Decimal(cob) + carbs
  330. wholeCobInsulin = wholeCob / carbRatio
  331. // determine how much the calculator reduces/ increases the bolus because of IOB
  332. iobInsulinReduction = (-1) * iob
  333. // adding everything together
  334. // add a calc for the case that no fifteenMinInsulin is available
  335. if deltaBG != 0 {
  336. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  337. } else {
  338. // add (rare) case that no glucose value is available -> maybe display warning?
  339. // if no bg is available, ?? sets its value to 0
  340. if currentBG == 0 {
  341. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  342. } else {
  343. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  344. }
  345. }
  346. // apply custom factor at the end of the calculations
  347. let result = wholeCalc * fraction
  348. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  349. if useFattyMealCorrectionFactor {
  350. insulinCalculated = result * fattyMealFactor
  351. } else if useSuperBolus {
  352. superBolusInsulin = sweetMealFactor * currentBasal
  353. insulinCalculated = result + superBolusInsulin
  354. } else {
  355. insulinCalculated = result
  356. }
  357. // display no negative insulinCalculated
  358. insulinCalculated = max(insulinCalculated, 0)
  359. insulinCalculated = min(insulinCalculated, maxBolus)
  360. guard let apsManager = apsManager else {
  361. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  362. return insulinCalculated
  363. }
  364. return apsManager.roundBolus(amount: insulinCalculated)
  365. }
  366. // MARK: - Button tasks
  367. @MainActor func invokeTreatmentsTask() {
  368. Task {
  369. addButtonPressed = true
  370. let isInsulinGiven = amount > 0
  371. let isCarbsPresent = carbs > 0
  372. let isFatPresent = fat > 0
  373. let isProteinPresent = protein > 0
  374. if isInsulinGiven {
  375. try await handleInsulin(isExternal: externalInsulin)
  376. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  377. waitForSuggestion = true
  378. } else {
  379. hideModal()
  380. return
  381. }
  382. await saveMeal()
  383. // if glucose data is stale end the custom loading animation by hiding the modal
  384. guard glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  385. waitForSuggestion = false
  386. return hideModal()
  387. }
  388. }
  389. }
  390. // MARK: - Insulin
  391. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  392. if !isExternal {
  393. await addPumpInsulin()
  394. } else {
  395. await addExternalInsulin()
  396. }
  397. waitForSuggestion = true
  398. }
  399. @MainActor func addPumpInsulin() async {
  400. guard amount > 0 else {
  401. showModal(for: nil)
  402. return
  403. }
  404. let maxAmount = Double(min(amount, maxBolus))
  405. do {
  406. let authenticated = try await unlockmanager.unlock()
  407. if authenticated {
  408. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  409. } else {
  410. print("authentication failed")
  411. }
  412. } catch {
  413. print("authentication error for pump bolus: \(error.localizedDescription)")
  414. DispatchQueue.main.async {
  415. self.waitForSuggestion = false
  416. if self.addButtonPressed {
  417. self.hideModal()
  418. }
  419. }
  420. }
  421. }
  422. // MARK: - EXTERNAL INSULIN
  423. @MainActor func addExternalInsulin() async {
  424. guard amount > 0 else {
  425. showModal(for: nil)
  426. return
  427. }
  428. amount = min(amount, maxBolus * 3)
  429. do {
  430. let authenticated = try await unlockmanager.unlock()
  431. if authenticated {
  432. // store external dose to pump history
  433. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  434. // perform determine basal sync
  435. await apsManager.determineBasalSync()
  436. } else {
  437. print("authentication failed")
  438. }
  439. } catch {
  440. print("authentication error for external insulin: \(error.localizedDescription)")
  441. DispatchQueue.main.async {
  442. self.waitForSuggestion = false
  443. if self.addButtonPressed {
  444. self.hideModal()
  445. }
  446. }
  447. }
  448. }
  449. // MARK: - Carbs
  450. @MainActor func saveMeal() async {
  451. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  452. await MainActor.run {
  453. self.carbs = min(self.carbs, self.maxCarbs)
  454. self.id_ = UUID().uuidString
  455. }
  456. let carbsToStore = [CarbsEntry(
  457. id: id_,
  458. createdAt: now,
  459. actualDate: date,
  460. carbs: carbs,
  461. fat: fat,
  462. protein: protein,
  463. note: note,
  464. enteredBy: CarbsEntry.manual,
  465. isFPU: false, fpuID: UUID().uuidString
  466. )]
  467. await carbsStorage.storeCarbs(carbsToStore)
  468. if carbs > 0 || fat > 0 || protein > 0 {
  469. // 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
  470. if amount <= 0 {
  471. await apsManager.determineBasalSync()
  472. }
  473. }
  474. }
  475. // MARK: - Presets
  476. func deletePreset() {
  477. if selection != nil {
  478. viewContext.delete(selection!)
  479. do {
  480. guard viewContext.hasChanges else { return }
  481. try viewContext.save()
  482. } catch {
  483. print(error.localizedDescription)
  484. }
  485. carbs = 0
  486. fat = 0
  487. protein = 0
  488. }
  489. selection = nil
  490. }
  491. func removePresetFromNewMeal() {
  492. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  493. if a != nil, summation[a ?? 0] != "" {
  494. summation.remove(at: a!)
  495. }
  496. }
  497. func addPresetToNewMeal() {
  498. let test: String = selection?.dish ?? "dontAdd"
  499. if test != "dontAdd" {
  500. summation.append(test)
  501. }
  502. }
  503. func addNewPresetToWaitersNotepad(_ dish: String) {
  504. summation.append(dish)
  505. }
  506. func addToSummation() {
  507. summation.append(selection?.dish ?? "")
  508. }
  509. }
  510. }
  511. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  512. func determinationDidUpdate(_: Determination) {
  513. DispatchQueue.main.async {
  514. self.waitForSuggestion = false
  515. if self.addButtonPressed {
  516. self.hideModal()
  517. }
  518. }
  519. }
  520. func bolusDidFail() {
  521. DispatchQueue.main.async {
  522. self.waitForSuggestion = false
  523. if self.addButtonPressed {
  524. self.hideModal()
  525. }
  526. }
  527. }
  528. }
  529. extension Bolus.StateModel {
  530. private func registerHandlers() {
  531. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  532. guard let self = self else { return }
  533. Task {
  534. await self.setupDeterminationsArray()
  535. await self.updateForecasts()
  536. }
  537. }
  538. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  539. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  540. guard let self = self else { return }
  541. self.setupGlucoseArray()
  542. }
  543. }
  544. private func setupGlucoseNotification() {
  545. /// custom notification that is sent when a batch insert of glucose objects is done
  546. Foundation.NotificationCenter.default.addObserver(
  547. self,
  548. selector: #selector(handleBatchInsert),
  549. name: .didPerformBatchInsert,
  550. object: nil
  551. )
  552. }
  553. @objc private func handleBatchInsert() {
  554. setupGlucoseArray()
  555. }
  556. }
  557. // MARK: - Setup Glucose and Determinations
  558. extension Bolus.StateModel {
  559. // Glucose
  560. private func setupGlucoseArray() {
  561. Task {
  562. let ids = await self.fetchGlucose()
  563. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  564. await updateGlucoseArray(with: glucoseObjects)
  565. }
  566. }
  567. private func fetchGlucose() async -> [NSManagedObjectID] {
  568. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  569. ofType: GlucoseStored.self,
  570. onContext: backgroundContext,
  571. predicate: NSPredicate.predicateForFourHoursAgo,
  572. key: "date",
  573. ascending: false,
  574. fetchLimit: 48
  575. )
  576. return await backgroundContext.perform {
  577. return results.map(\.objectID)
  578. }
  579. }
  580. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  581. glucoseFromPersistence = objects
  582. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  583. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  584. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  585. currentBG = Decimal(lastGlucose)
  586. deltaBG = delta
  587. }
  588. // Determinations
  589. private func setupDeterminationsArray() async {
  590. // Fetch object IDs on a background thread
  591. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  592. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  593. )
  594. // Update determinationObjectIDs on the main thread
  595. await MainActor.run {
  596. determinationObjectIDs = fetchedObjectIDs
  597. }
  598. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  599. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  600. async let updateDetermination: () = updateDeterminationsArray(with: determinationObjects)
  601. async let getCurrentBasal: () = getCurrentBasal()
  602. await getCurrentBasal
  603. await updateDetermination
  604. }
  605. private func mapForecastsForChart() async -> Determination? {
  606. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  607. .getNSManagedObject(with: determinationObjectIDs, context: backgroundContext)
  608. return await backgroundContext.perform {
  609. guard let determinationObject = determinationObjects.first else {
  610. return nil
  611. }
  612. let eventualBG = determinationObject.eventualBG?.intValue
  613. let forecastsSet = determinationObject.forecasts as? Set<Forecast> ?? []
  614. let predictions = Predictions(
  615. iob: forecastsSet.extractValues(for: "iob"),
  616. zt: forecastsSet.extractValues(for: "zt"),
  617. cob: forecastsSet.extractValues(for: "cob"),
  618. uam: forecastsSet.extractValues(for: "uam")
  619. )
  620. return Determination(
  621. id: UUID(),
  622. reason: "",
  623. units: 0,
  624. insulinReq: 0,
  625. eventualBG: eventualBG,
  626. sensitivityRatio: 0,
  627. rate: 0,
  628. duration: 0,
  629. iob: 0,
  630. cob: 0,
  631. predictions: predictions.isEmpty ? nil : predictions,
  632. carbsReq: 0,
  633. temp: nil,
  634. bg: 0,
  635. reservoir: 0,
  636. isf: 0,
  637. tdd: 0,
  638. insulin: nil,
  639. current_target: 0,
  640. insulinForManualBolus: 0,
  641. manualBolusErrorString: 0,
  642. minDelta: 0,
  643. expectedDelta: 0,
  644. minGuardBG: 0,
  645. minPredBG: 0,
  646. threshold: 0,
  647. carbRatio: 0,
  648. received: false
  649. )
  650. }
  651. }
  652. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  653. guard let mostRecentDetermination = objects.first else { return }
  654. determination = objects
  655. // setup vars for bolus calculation
  656. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  657. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  658. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  659. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  660. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  661. cob = mostRecentDetermination.cob as Int16
  662. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  663. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  664. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  665. insulinCalculated = calculateInsulin()
  666. }
  667. }
  668. extension Bolus.StateModel {
  669. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  670. if let forecastData = forecastData {
  671. simulatedDetermination = forecastData
  672. } else {
  673. simulatedDetermination = await Task.detached { [self] in
  674. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  675. }.value
  676. }
  677. predictionsForChart = simulatedDetermination?.predictions
  678. let nonEmptyArrays = [
  679. predictionsForChart?.iob,
  680. predictionsForChart?.zt,
  681. predictionsForChart?.cob,
  682. predictionsForChart?.uam
  683. ]
  684. .compactMap { $0 }
  685. .filter { !$0.isEmpty }
  686. guard !nonEmptyArrays.isEmpty else {
  687. minForecast = []
  688. maxForecast = []
  689. return
  690. }
  691. minCount = min(12, nonEmptyArrays.map(\.count).min() ?? 0)
  692. guard minCount > 0 else { return }
  693. minForecast = (0 ..< minCount).map { index in
  694. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  695. }
  696. maxForecast = (0 ..< minCount).map { index in
  697. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  698. }
  699. }
  700. }
  701. private extension Set where Element == Forecast {
  702. func extractValues(for type: String) -> [Int]? {
  703. let values = first { $0.type == type }?
  704. .forecastValues?
  705. .sorted { $0.index < $1.index }
  706. .compactMap { Int($0.value) }
  707. return values?.isEmpty ?? true ? nil : values
  708. }
  709. }
  710. private extension Predictions {
  711. var isEmpty: Bool {
  712. iob == nil && zt == nil && cob == nil && uam == nil
  713. }
  714. }