BolusStateModel.swift 31 KB

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