BolusStateModel.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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. // ensure that isf is in mg/dL
  320. var conversion: Decimal {
  321. units == .mmolL ? 0.0555 : 1
  322. }
  323. let isfForCalculation = isf / conversion
  324. // insulin needed for the current blood glucose
  325. targetDifference = currentBG - target
  326. targetDifferenceInsulin = targetDifference / isfForCalculation
  327. // more or less insulin because of bg trend in the last 15 minutes
  328. fifteenMinInsulin = deltaBG / isfForCalculation
  329. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  330. wholeCob = Decimal(cob) + carbs
  331. wholeCobInsulin = wholeCob / carbRatio
  332. // determine how much the calculator reduces/ increases the bolus because of IOB
  333. iobInsulinReduction = (-1) * iob
  334. // adding everything together
  335. // add a calc for the case that no fifteenMinInsulin is available
  336. if deltaBG != 0 {
  337. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  338. } else {
  339. // add (rare) case that no glucose value is available -> maybe display warning?
  340. // if no bg is available, ?? sets its value to 0
  341. if currentBG == 0 {
  342. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  343. } else {
  344. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  345. }
  346. }
  347. // apply custom factor at the end of the calculations
  348. let result = wholeCalc * fraction
  349. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  350. if useFattyMealCorrectionFactor {
  351. insulinCalculated = result * fattyMealFactor
  352. } else if useSuperBolus {
  353. superBolusInsulin = sweetMealFactor * currentBasal
  354. insulinCalculated = result + superBolusInsulin
  355. } else {
  356. insulinCalculated = result
  357. }
  358. // display no negative insulinCalculated
  359. insulinCalculated = max(insulinCalculated, 0)
  360. insulinCalculated = min(insulinCalculated, maxBolus)
  361. guard let apsManager = apsManager else {
  362. debug(.apsManager, "APSManager could not be gracefully unwrapped")
  363. return insulinCalculated
  364. }
  365. return apsManager.roundBolus(amount: insulinCalculated)
  366. }
  367. // MARK: - Button tasks
  368. @MainActor func invokeTreatmentsTask() {
  369. Task {
  370. addButtonPressed = true
  371. let isInsulinGiven = amount > 0
  372. let isCarbsPresent = carbs > 0
  373. let isFatPresent = fat > 0
  374. let isProteinPresent = protein > 0
  375. if isInsulinGiven {
  376. try await handleInsulin(isExternal: externalInsulin)
  377. } else if isCarbsPresent || isFatPresent || isProteinPresent {
  378. waitForSuggestion = true
  379. } else {
  380. hideModal()
  381. return
  382. }
  383. await saveMeal()
  384. // if glucose data is stale end the custom loading animation by hiding the modal
  385. guard glucoseStorage.isGlucoseDataFresh(glucoseFromPersistence.first?.date) else {
  386. waitForSuggestion = false
  387. return hideModal()
  388. }
  389. }
  390. }
  391. // MARK: - Insulin
  392. @MainActor private func handleInsulin(isExternal: Bool) async throws {
  393. if !isExternal {
  394. await addPumpInsulin()
  395. } else {
  396. await addExternalInsulin()
  397. }
  398. waitForSuggestion = true
  399. }
  400. @MainActor func addPumpInsulin() async {
  401. guard amount > 0 else {
  402. showModal(for: nil)
  403. return
  404. }
  405. let maxAmount = Double(min(amount, maxBolus))
  406. do {
  407. let authenticated = try await unlockmanager.unlock()
  408. if authenticated {
  409. await apsManager.enactBolus(amount: maxAmount, isSMB: false)
  410. } else {
  411. print("authentication failed")
  412. }
  413. } catch {
  414. print("authentication error for pump bolus: \(error.localizedDescription)")
  415. DispatchQueue.main.async {
  416. self.waitForSuggestion = false
  417. if self.addButtonPressed {
  418. self.hideModal()
  419. }
  420. }
  421. }
  422. }
  423. // MARK: - EXTERNAL INSULIN
  424. @MainActor func addExternalInsulin() async {
  425. guard amount > 0 else {
  426. showModal(for: nil)
  427. return
  428. }
  429. amount = min(amount, maxBolus * 3)
  430. do {
  431. let authenticated = try await unlockmanager.unlock()
  432. if authenticated {
  433. // store external dose to pump history
  434. await pumpHistoryStorage.storeExternalInsulinEvent(amount: amount, timestamp: date)
  435. // perform determine basal sync
  436. await apsManager.determineBasalSync()
  437. } else {
  438. print("authentication failed")
  439. }
  440. } catch {
  441. print("authentication error for external insulin: \(error.localizedDescription)")
  442. DispatchQueue.main.async {
  443. self.waitForSuggestion = false
  444. if self.addButtonPressed {
  445. self.hideModal()
  446. }
  447. }
  448. }
  449. }
  450. // MARK: - Carbs
  451. @MainActor func saveMeal() async {
  452. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  453. await MainActor.run {
  454. self.carbs = min(self.carbs, self.maxCarbs)
  455. self.id_ = UUID().uuidString
  456. }
  457. let carbsToStore = [CarbsEntry(
  458. id: id_,
  459. createdAt: now,
  460. actualDate: date,
  461. carbs: carbs,
  462. fat: fat,
  463. protein: protein,
  464. note: note,
  465. enteredBy: CarbsEntry.manual,
  466. isFPU: false, fpuID: UUID().uuidString
  467. )]
  468. await carbsStorage.storeCarbs(carbsToStore)
  469. if carbs > 0 || fat > 0 || protein > 0 {
  470. // 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
  471. if amount <= 0 {
  472. await apsManager.determineBasalSync()
  473. }
  474. }
  475. }
  476. // MARK: - Presets
  477. func deletePreset() {
  478. if selection != nil {
  479. viewContext.delete(selection!)
  480. do {
  481. guard viewContext.hasChanges else { return }
  482. try viewContext.save()
  483. } catch {
  484. print(error.localizedDescription)
  485. }
  486. carbs = 0
  487. fat = 0
  488. protein = 0
  489. }
  490. selection = nil
  491. }
  492. func removePresetFromNewMeal() {
  493. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  494. if a != nil, summation[a ?? 0] != "" {
  495. summation.remove(at: a!)
  496. }
  497. }
  498. func addPresetToNewMeal() {
  499. let test: String = selection?.dish ?? "dontAdd"
  500. if test != "dontAdd" {
  501. summation.append(test)
  502. }
  503. }
  504. func addNewPresetToWaitersNotepad(_ dish: String) {
  505. summation.append(dish)
  506. }
  507. func addToSummation() {
  508. summation.append(selection?.dish ?? "")
  509. }
  510. }
  511. }
  512. extension Bolus.StateModel: DeterminationObserver, BolusFailureObserver {
  513. func determinationDidUpdate(_: Determination) {
  514. DispatchQueue.main.async {
  515. self.waitForSuggestion = false
  516. if self.addButtonPressed {
  517. self.hideModal()
  518. }
  519. }
  520. }
  521. func bolusDidFail() {
  522. DispatchQueue.main.async {
  523. self.waitForSuggestion = false
  524. if self.addButtonPressed {
  525. self.hideModal()
  526. }
  527. }
  528. }
  529. }
  530. extension Bolus.StateModel {
  531. private func registerHandlers() {
  532. coreDataObserver?.registerHandler(for: "OrefDetermination") { [weak self] in
  533. guard let self = self else { return }
  534. Task {
  535. await self.setupDeterminationsArray()
  536. await self.updateForecasts()
  537. }
  538. }
  539. // Due to the Batch insert this only is used for observing Deletion of Glucose entries
  540. coreDataObserver?.registerHandler(for: "GlucoseStored") { [weak self] in
  541. guard let self = self else { return }
  542. self.setupGlucoseArray()
  543. }
  544. }
  545. private func setupGlucoseNotification() {
  546. /// custom notification that is sent when a batch insert of glucose objects is done
  547. Foundation.NotificationCenter.default.addObserver(
  548. self,
  549. selector: #selector(handleBatchInsert),
  550. name: .didPerformBatchInsert,
  551. object: nil
  552. )
  553. }
  554. @objc private func handleBatchInsert() {
  555. setupGlucoseArray()
  556. }
  557. }
  558. // MARK: - Setup Glucose and Determinations
  559. extension Bolus.StateModel {
  560. // Glucose
  561. private func setupGlucoseArray() {
  562. Task {
  563. let ids = await self.fetchGlucose()
  564. let glucoseObjects: [GlucoseStored] = await CoreDataStack.shared.getNSManagedObject(with: ids, context: viewContext)
  565. await updateGlucoseArray(with: glucoseObjects)
  566. }
  567. }
  568. private func fetchGlucose() async -> [NSManagedObjectID] {
  569. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  570. ofType: GlucoseStored.self,
  571. onContext: backgroundContext,
  572. predicate: NSPredicate.predicateForFourHoursAgo,
  573. key: "date",
  574. ascending: false,
  575. fetchLimit: 48
  576. )
  577. return await backgroundContext.perform {
  578. return results.map(\.objectID)
  579. }
  580. }
  581. @MainActor private func updateGlucoseArray(with objects: [GlucoseStored]) {
  582. glucoseFromPersistence = objects
  583. let lastGlucose = glucoseFromPersistence.first?.glucose ?? 0
  584. let thirdLastGlucose = glucoseFromPersistence.dropFirst(2).first?.glucose ?? 0
  585. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose)
  586. currentBG = Decimal(lastGlucose)
  587. deltaBG = delta
  588. }
  589. // Determinations
  590. private func setupDeterminationsArray() async {
  591. // Fetch object IDs on a background thread
  592. let fetchedObjectIDs = await determinationStorage.fetchLastDeterminationObjectID(
  593. predicate: NSPredicate.predicateFor30MinAgoForDetermination
  594. )
  595. // Update determinationObjectIDs on the main thread
  596. await MainActor.run {
  597. determinationObjectIDs = fetchedObjectIDs
  598. }
  599. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  600. .getNSManagedObject(with: determinationObjectIDs, context: viewContext)
  601. async let updateDetermination: () = updateDeterminationsArray(with: determinationObjects)
  602. async let getCurrentBasal: () = getCurrentBasal()
  603. await getCurrentBasal
  604. await updateDetermination
  605. }
  606. private func mapForecastsForChart() async -> Determination? {
  607. let determinationObjects: [OrefDetermination] = await CoreDataStack.shared
  608. .getNSManagedObject(with: determinationObjectIDs, context: backgroundContext)
  609. return await backgroundContext.perform {
  610. guard let determinationObject = determinationObjects.first else {
  611. return nil
  612. }
  613. let eventualBG = determinationObject.eventualBG?.intValue
  614. let forecastsSet = determinationObject.forecasts as? Set<Forecast> ?? []
  615. let predictions = Predictions(
  616. iob: forecastsSet.extractValues(for: "iob"),
  617. zt: forecastsSet.extractValues(for: "zt"),
  618. cob: forecastsSet.extractValues(for: "cob"),
  619. uam: forecastsSet.extractValues(for: "uam")
  620. )
  621. return Determination(
  622. id: UUID(),
  623. reason: "",
  624. units: 0,
  625. insulinReq: 0,
  626. eventualBG: eventualBG,
  627. sensitivityRatio: 0,
  628. rate: 0,
  629. duration: 0,
  630. iob: 0,
  631. cob: 0,
  632. predictions: predictions.isEmpty ? nil : predictions,
  633. carbsReq: 0,
  634. temp: nil,
  635. bg: 0,
  636. reservoir: 0,
  637. isf: 0,
  638. tdd: 0,
  639. insulin: nil,
  640. current_target: 0,
  641. insulinForManualBolus: 0,
  642. manualBolusErrorString: 0,
  643. minDelta: 0,
  644. expectedDelta: 0,
  645. minGuardBG: 0,
  646. minPredBG: 0,
  647. threshold: 0,
  648. carbRatio: 0,
  649. received: false
  650. )
  651. }
  652. }
  653. @MainActor private func updateDeterminationsArray(with objects: [OrefDetermination]) {
  654. guard let mostRecentDetermination = objects.first else { return }
  655. determination = objects
  656. // setup vars for bolus calculation
  657. insulinRequired = (mostRecentDetermination.insulinReq ?? 0) as Decimal
  658. evBG = (mostRecentDetermination.eventualBG ?? 0) as Decimal
  659. insulin = (mostRecentDetermination.insulinForManualBolus ?? 0) as Decimal
  660. target = (mostRecentDetermination.currentTarget ?? currentBGTarget as NSDecimalNumber) as Decimal
  661. isf = (mostRecentDetermination.insulinSensitivity ?? currentISF as NSDecimalNumber) as Decimal
  662. cob = mostRecentDetermination.cob as Int16
  663. iob = (mostRecentDetermination.iob ?? 0) as Decimal
  664. basal = (mostRecentDetermination.tempBasal ?? 0) as Decimal
  665. carbRatio = (mostRecentDetermination.carbRatio ?? currentCarbRatio as NSDecimalNumber) as Decimal
  666. insulinCalculated = calculateInsulin()
  667. }
  668. }
  669. extension Bolus.StateModel {
  670. func calculateForecasts(predictions: Predictions?) -> ([Int], [Int]) {
  671. let iob: [Int] = predictions?.iob ?? []
  672. let zt: [Int] = predictions?.zt ?? []
  673. let cob: [Int] = predictions?.cob ?? []
  674. let uam: [Int] = predictions?.uam ?? []
  675. // Filter out the empty arrays and find the maximum length of the remaining arrays
  676. let nonEmptyArrays: [[Int]] = [iob, zt, cob, uam].filter { !$0.isEmpty }
  677. guard !nonEmptyArrays.isEmpty, let maxCount = nonEmptyArrays.map(\.count).max(), maxCount > 0 else {
  678. return ([], [])
  679. }
  680. let minForecast = (0 ..< maxCount).map { index -> Int in
  681. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  682. return valuesAtCurrentIndex.min() ?? 0
  683. }
  684. let maxForecast = (0 ..< maxCount).map { index -> Int in
  685. let valuesAtCurrentIndex = nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }
  686. return valuesAtCurrentIndex.max() ?? 0
  687. }
  688. return (minForecast, maxForecast)
  689. }
  690. @MainActor func updateForecasts(with forecastData: Determination? = nil) async {
  691. if let forecastData = forecastData {
  692. simulatedDetermination = forecastData
  693. } else {
  694. simulatedDetermination = await Task.detached { [self] in
  695. await apsManager.simulateDetermineBasal(carbs: carbs, iob: amount)
  696. }.value
  697. }
  698. predictionsForChart = simulatedDetermination?.predictions
  699. let nonEmptyArrays = [
  700. predictionsForChart?.iob,
  701. predictionsForChart?.zt,
  702. predictionsForChart?.cob,
  703. predictionsForChart?.uam
  704. ]
  705. .compactMap { $0 }
  706. .filter { !$0.isEmpty }
  707. guard !nonEmptyArrays.isEmpty else {
  708. minForecast = []
  709. maxForecast = []
  710. return
  711. }
  712. let maxCount = min(36, nonEmptyArrays.map(\.count).max() ?? 0)
  713. guard maxCount > 0 else { return }
  714. minForecast = (0 ..< maxCount).map { index in
  715. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.min() ?? 0
  716. }
  717. maxForecast = (0 ..< maxCount).map { index in
  718. nonEmptyArrays.compactMap { $0.indices.contains(index) ? $0[index] : nil }.max() ?? 0
  719. }
  720. }
  721. }
  722. private extension Set where Element == Forecast {
  723. func extractValues(for type: String) -> [Int]? {
  724. let values = first { $0.type == type }?
  725. .forecastValues?
  726. .sorted { $0.index < $1.index }
  727. .compactMap { Int($0.value) }
  728. return values?.isEmpty ?? true ? nil : values
  729. }
  730. }
  731. private extension Predictions {
  732. var isEmpty: Bool {
  733. iob == nil && zt == nil && cob == nil && uam == nil
  734. }
  735. }