BolusStateModel.swift 28 KB

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