BolusStateModel.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. @Published var suggestion: Suggestion?
  17. @Published var predictions: Predictions?
  18. @Published var amount: Decimal = 0
  19. @Published var insulinRecommended: Decimal = 0
  20. @Published var insulinRequired: Decimal = 0
  21. @Published var units: GlucoseUnits = .mmolL
  22. @Published var percentage: Decimal = 0
  23. @Published var threshold: Decimal = 0
  24. @Published var maxBolus: Decimal = 0
  25. @Published var errorString: Decimal = 0
  26. @Published var evBG: Int = 0
  27. @Published var insulin: Decimal = 0
  28. @Published var isf: Decimal = 0
  29. @Published var error: Bool = false
  30. @Published var minGuardBG: Decimal = 0
  31. @Published var minDelta: Decimal = 0
  32. @Published var expectedDelta: Decimal = 0
  33. @Published var minPredBG: Decimal = 0
  34. @Published var waitForSuggestion: Bool = false
  35. @Published var carbRatio: Decimal = 0
  36. var waitForSuggestionInitial: Bool = false
  37. // added for bolus calculator
  38. @Published var recentGlucose: BloodGlucose?
  39. @Published var target: Decimal = 0
  40. @Published var cob: Decimal = 0
  41. @Published var iob: Decimal = 0
  42. @Published var currentBG: Decimal = 0
  43. @Published var fifteenMinInsulin: Decimal = 0
  44. @Published var deltaBG: Decimal = 0
  45. @Published var targetDifferenceInsulin: Decimal = 0
  46. @Published var targetDifference: Decimal = 0
  47. @Published var wholeCob: Decimal = 0
  48. @Published var wholeCobInsulin: Decimal = 0
  49. @Published var iobInsulinReduction: Decimal = 0
  50. @Published var wholeCalc: Decimal = 0
  51. @Published var insulinCalculated: Decimal = 0
  52. @Published var fraction: Decimal = 0
  53. @Published var useCalc: Bool = false
  54. @Published var basal: Decimal = 0
  55. @Published var fattyMeals: Bool = false
  56. @Published var fattyMealFactor: Decimal = 0
  57. @Published var useFattyMealCorrectionFactor: Bool = false
  58. @Published var displayPresets: Bool = true
  59. @Published var currentBasal: Decimal = 0
  60. @Published var sweetMeals: Bool = false
  61. @Published var sweetMealFactor: Decimal = 0
  62. @Published var useSuperBolus: Bool = false
  63. @Published var superBolusInsulin: Decimal = 0
  64. @Published var meal: [CarbsEntry]?
  65. @Published var carbs: Decimal = 0
  66. @Published var fat: Decimal = 0
  67. @Published var protein: Decimal = 0
  68. @Published var note: String = ""
  69. @Published var date = Date()
  70. @Published var carbsRequired: Decimal?
  71. @Published var useFPUconversion: Bool = false
  72. @Published var dish: String = ""
  73. @Published var selection: Presets?
  74. @Published var summation: [String] = []
  75. @Published var maxCarbs: Decimal = 0
  76. @Published var id_: String = ""
  77. @Published var summary: String = ""
  78. @Published var skipBolus: Bool = false
  79. @Published var externalInsulin: Bool = false
  80. let now = Date.now
  81. let coredataContext = CoreDataStack.shared.persistentContainer.viewContext
  82. override func subscribe() {
  83. setupInsulinRequired()
  84. broadcaster.register(SuggestionObserver.self, observer: self)
  85. units = settingsManager.settings.units
  86. percentage = settingsManager.settings.insulinReqPercentage
  87. threshold = provider.suggestion?.threshold ?? 0
  88. maxBolus = provider.pumpSettings().maxBolus
  89. // added
  90. fraction = settings.settings.overrideFactor
  91. useCalc = settings.settings.useCalc
  92. fattyMeals = settings.settings.fattyMeals
  93. fattyMealFactor = settings.settings.fattyMealFactor
  94. sweetMeals = settings.settings.sweetMeals
  95. sweetMealFactor = settings.settings.sweetMealFactor
  96. displayPresets = settings.settings.displayPresets
  97. carbsRequired = provider.suggestion?.carbsReq
  98. maxCarbs = settings.settings.maxCarbs
  99. skipBolus = settingsManager.settings.skipBolusScreenAfterCarbs
  100. useFPUconversion = settingsManager.settings.useFPUconversion
  101. if waitForSuggestionInitial {
  102. apsManager.determineBasal()
  103. .receive(on: DispatchQueue.main)
  104. .sink { [weak self] ok in
  105. guard let self = self else { return }
  106. if !ok {
  107. self.waitForSuggestion = false
  108. self.insulinRequired = 0
  109. self.insulinRecommended = 0
  110. }
  111. }.store(in: &lifetime)
  112. }
  113. if let notNilSugguestion = provider.suggestion {
  114. suggestion = notNilSugguestion
  115. if let notNilPredictions = suggestion?.predictions {
  116. predictions = notNilPredictions
  117. }
  118. }
  119. }
  120. func getCurrentBasal() {
  121. let basalEntries = provider.getProfile()
  122. let dateFormatter = DateFormatter()
  123. dateFormatter.dateFormat = "HH:mm:ss"
  124. let currentTime = dateFormatter.string(from: Date())
  125. // loop throug entries and get current basal entry
  126. for (index, entry) in basalEntries.enumerated() {
  127. if let entryStartTimeDate = dateFormatter.date(from: entry.start) {
  128. var entryEndTimeDate: Date
  129. if index < basalEntries.count - 1 {
  130. let nextEntry = basalEntries[index + 1]
  131. if let nextEntryStartTimeDate = dateFormatter.date(from: nextEntry.start) {
  132. let timeDifference = nextEntryStartTimeDate.timeIntervalSince(entryStartTimeDate)
  133. entryEndTimeDate = entryStartTimeDate.addingTimeInterval(timeDifference)
  134. } else {
  135. continue
  136. }
  137. } else {
  138. entryEndTimeDate = Date()
  139. }
  140. // if currenTime is between start and end of basal entry -> basal = currentBasal
  141. if let currentTimeDate = dateFormatter.date(from: currentTime) {
  142. if currentTimeDate >= entryStartTimeDate, currentTimeDate <= entryEndTimeDate {
  143. if let basal = entry.rate as? Decimal {
  144. currentBasal = basal
  145. break
  146. }
  147. }
  148. }
  149. }
  150. }
  151. }
  152. func getDeltaBG() {
  153. let glucose = provider.fetchGlucose()
  154. guard glucose.count >= 3 else { return }
  155. let lastGlucose = glucose.first?.glucose ?? 0
  156. let thirdLastGlucose = glucose[2]
  157. let delta = Decimal(lastGlucose) - Decimal(thirdLastGlucose.glucose)
  158. deltaBG = delta
  159. }
  160. // CALCULATIONS FOR THE BOLUS CALCULATOR
  161. func calculateInsulin() -> Decimal {
  162. // ensure that isf is in mg/dL
  163. var conversion: Decimal {
  164. units == .mmolL ? 0.0555 : 1
  165. }
  166. let isfForCalculation = isf / conversion
  167. // insulin needed for the current blood glucose
  168. targetDifference = (currentBG - target)
  169. targetDifferenceInsulin = targetDifference / isfForCalculation
  170. // more or less insulin because of bg trend in the last 15 minutes
  171. fifteenMinInsulin = deltaBG / isfForCalculation
  172. // determine whole COB for which we want to dose insulin for and then determine insulin for wholeCOB
  173. wholeCob = cob + carbs
  174. wholeCobInsulin = wholeCob / carbRatio
  175. // determine how much the calculator reduces/ increases the bolus because of IOB
  176. iobInsulinReduction = (-1) * iob
  177. // adding everything together
  178. // add a calc for the case that no fifteenMinInsulin is available
  179. if deltaBG != 0 {
  180. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin + fifteenMinInsulin)
  181. } else {
  182. // add (rare) case that no glucose value is available -> maybe display warning?
  183. // if no bg is available, ?? sets its value to 0
  184. if currentBG == 0 {
  185. wholeCalc = (iobInsulinReduction + wholeCobInsulin)
  186. } else {
  187. wholeCalc = (targetDifferenceInsulin + iobInsulinReduction + wholeCobInsulin)
  188. }
  189. }
  190. // apply custom factor at the end of the calculations
  191. let result = wholeCalc * fraction
  192. // apply custom factor if fatty meal toggle in bolus calc config settings is on and the box for fatty meals is checked (in RootView)
  193. if useFattyMealCorrectionFactor {
  194. insulinCalculated = result * fattyMealFactor
  195. } else if useSuperBolus {
  196. superBolusInsulin = sweetMealFactor * currentBasal
  197. insulinCalculated = result + superBolusInsulin
  198. } else {
  199. insulinCalculated = result
  200. }
  201. // display no negative insulinCalculated
  202. insulinCalculated = max(insulinCalculated, 0)
  203. insulinCalculated = min(insulinCalculated, maxBolus)
  204. return apsManager
  205. .roundBolus(amount: max(insulinCalculated, 0))
  206. }
  207. func add() async {
  208. guard amount > 0 else {
  209. showModal(for: nil)
  210. return
  211. }
  212. let maxAmount = Double(min(amount, provider.pumpSettings().maxBolus))
  213. do {
  214. let authenticated = try await unlockmanager.unlock()
  215. if authenticated {
  216. apsManager.enactBolus(amount: maxAmount, isSMB: false)
  217. } else {
  218. print("authentication failed")
  219. }
  220. } catch {
  221. print("authentication error: \(error.localizedDescription)")
  222. }
  223. }
  224. func setupInsulinRequired() {
  225. DispatchQueue.main.async {
  226. self.insulinRequired = self.provider.suggestion?.insulinReq ?? 0
  227. var conversion: Decimal = 1.0
  228. if self.units == .mmolL {
  229. conversion = 0.0555
  230. }
  231. self.evBG = self.provider.suggestion?.eventualBG ?? 0
  232. self.insulin = self.provider.suggestion?.insulinForManualBolus ?? 0
  233. self.target = self.provider.suggestion?.current_target ?? 0
  234. self.isf = self.provider.suggestion?.isf ?? 0
  235. self.iob = self.provider.suggestion?.iob ?? 0
  236. self.currentBG = (self.provider.suggestion?.bg ?? 0)
  237. self.cob = self.provider.suggestion?.cob ?? 0
  238. self.basal = self.provider.suggestion?.rate ?? 0
  239. self.carbRatio = self.provider.suggestion?.carbRatio ?? 0
  240. if self.settingsManager.settings.insulinReqPercentage != 100 {
  241. self.insulinRecommended = self.insulin * (self.settingsManager.settings.insulinReqPercentage / 100)
  242. } else { self.insulinRecommended = self.insulin }
  243. self.errorString = self.provider.suggestion?.manualBolusErrorString ?? 0
  244. if self.errorString != 0 {
  245. self.error = true
  246. self.minGuardBG = (self.provider.suggestion?.minGuardBG ?? 0) * conversion
  247. self.minDelta = (self.provider.suggestion?.minDelta ?? 0) * conversion
  248. self.expectedDelta = (self.provider.suggestion?.expectedDelta ?? 0) * conversion
  249. self.minPredBG = (self.provider.suggestion?.minPredBG ?? 0) * conversion
  250. } else { self.error = false }
  251. self.insulinRecommended = self.apsManager
  252. .roundBolus(amount: max(self.insulinRecommended, 0))
  253. if self.useCalc {
  254. self.getCurrentBasal()
  255. self.getDeltaBG()
  256. self.insulinCalculated = self.calculateInsulin()
  257. }
  258. }
  259. }
  260. func addCarbs() {
  261. guard carbs > 0 || fat > 0 || protein > 0 else { return }
  262. carbs = min(carbs, maxCarbs)
  263. id_ = UUID().uuidString
  264. let carbsToStore = [CarbsEntry(
  265. id: id_,
  266. createdAt: now,
  267. actualDate: date,
  268. carbs: carbs,
  269. fat: fat,
  270. protein: protein,
  271. note: note,
  272. enteredBy: CarbsEntry.manual,
  273. isFPU: false, fpuID: UUID().uuidString
  274. )]
  275. carbsStorage.storeCarbs(carbsToStore)
  276. if skipBolus {
  277. apsManager.determineBasalSync()
  278. showModal(for: nil)
  279. } else if carbs > 0 {
  280. saveToCoreData(carbsToStore)
  281. apsManager.determineBasalSync()
  282. } else {
  283. hideModal()
  284. }
  285. }
  286. func deletePreset() {
  287. if selection != nil {
  288. try? coredataContext.delete(selection!)
  289. try? coredataContext.save()
  290. carbs = 0
  291. fat = 0
  292. protein = 0
  293. }
  294. selection = nil
  295. }
  296. func removePresetFromNewMeal() {
  297. let a = summation.firstIndex(where: { $0 == selection?.dish! })
  298. if a != nil, summation[a ?? 0] != "" {
  299. summation.remove(at: a!)
  300. }
  301. }
  302. func addPresetToNewMeal() {
  303. let test: String = selection?.dish ?? "dontAdd"
  304. if test != "dontAdd" {
  305. summation.append(test)
  306. }
  307. }
  308. func addNewPresetToWaitersNotepad(_ dish: String) {
  309. summation.append(dish)
  310. }
  311. func addToSummation() {
  312. summation.append(selection?.dish ?? "")
  313. }
  314. func waitersNotepad() -> String {
  315. var filteredArray = summation.filter { !$0.isEmpty }
  316. if carbs == 0, protein == 0, fat == 0 {
  317. filteredArray = []
  318. }
  319. guard filteredArray != [] else {
  320. return ""
  321. }
  322. var carbs_: Decimal = 0.0
  323. var fat_: Decimal = 0.0
  324. var protein_: Decimal = 0.0
  325. var presetArray = [Presets]()
  326. coredataContext.performAndWait {
  327. let requestPresets = Presets.fetchRequest() as NSFetchRequest<Presets>
  328. try? presetArray = coredataContext.fetch(requestPresets)
  329. }
  330. var waitersNotepad = [String]()
  331. var stringValue = ""
  332. for each in filteredArray {
  333. let countedSet = NSCountedSet(array: filteredArray)
  334. let count = countedSet.count(for: each)
  335. if each != stringValue {
  336. waitersNotepad.append("\(count) \(each)")
  337. }
  338. stringValue = each
  339. for sel in presetArray {
  340. if sel.dish == each {
  341. carbs_ += (sel.carbs)! as Decimal
  342. fat_ += (sel.fat)! as Decimal
  343. protein_ += (sel.protein)! as Decimal
  344. break
  345. }
  346. }
  347. }
  348. let extracarbs = carbs - carbs_
  349. let extraFat = fat - fat_
  350. let extraProtein = protein - protein_
  351. var addedString = ""
  352. if extracarbs > 0, filteredArray.isNotEmpty {
  353. addedString += "Additional carbs: \(extracarbs) ,"
  354. } else if extracarbs < 0 { addedString += "Removed carbs: \(extracarbs) " }
  355. if extraFat > 0, filteredArray.isNotEmpty {
  356. addedString += "Additional fat: \(extraFat) ,"
  357. } else if extraFat < 0 { addedString += "Removed fat: \(extraFat) ," }
  358. if extraProtein > 0, filteredArray.isNotEmpty {
  359. addedString += "Additional protein: \(extraProtein) ,"
  360. } else if extraProtein < 0 { addedString += "Removed protein: \(extraProtein) ," }
  361. if addedString != "" {
  362. waitersNotepad.append(addedString)
  363. }
  364. var waitersNotepadString = ""
  365. if waitersNotepad.count == 1 {
  366. waitersNotepadString = waitersNotepad[0]
  367. } else if waitersNotepad.count > 1 {
  368. for each in waitersNotepad {
  369. if each != waitersNotepad.last {
  370. waitersNotepadString += " " + each + ","
  371. } else { waitersNotepadString += " " + each }
  372. }
  373. }
  374. return waitersNotepadString
  375. }
  376. func loadEntries(_ editMode: Bool) {
  377. if editMode {
  378. coredataContext.performAndWait {
  379. var mealToEdit = [Meals]()
  380. let requestMeal = Meals.fetchRequest() as NSFetchRequest<Meals>
  381. let sortMeal = NSSortDescriptor(key: "createdAt", ascending: false)
  382. requestMeal.sortDescriptors = [sortMeal]
  383. requestMeal.fetchLimit = 1
  384. try? mealToEdit = self.coredataContext.fetch(requestMeal)
  385. self.carbs = Decimal(mealToEdit.first?.carbs ?? 0)
  386. self.fat = Decimal(mealToEdit.first?.fat ?? 0)
  387. self.protein = Decimal(mealToEdit.first?.protein ?? 0)
  388. self.note = mealToEdit.first?.note ?? ""
  389. self.id_ = mealToEdit.first?.id ?? ""
  390. }
  391. }
  392. }
  393. func saveToCoreData(_ stored: [CarbsEntry]) {
  394. coredataContext.performAndWait {
  395. let save = Meals(context: coredataContext)
  396. if let entry = stored.first {
  397. save.createdAt = now
  398. save.actualDate = entry.actualDate ?? Date.now
  399. save.id = entry.id ?? ""
  400. save.fpuID = entry.fpuID ?? ""
  401. save.carbs = Double(entry.carbs)
  402. save.fat = Double(entry.fat ?? 0)
  403. save.protein = Double(entry.protein ?? 0)
  404. save.note = entry.note
  405. try? coredataContext.save()
  406. }
  407. print("meals 1: ID: " + (save.id ?? "").description + " FPU ID: " + (save.fpuID ?? "").description)
  408. }
  409. }
  410. // MARK: EXTERNAL INSULIN
  411. func addExternalInsulin() async {
  412. guard amount > 0 else {
  413. showModal(for: nil)
  414. return
  415. }
  416. amount = min(amount, maxBolus * 3)
  417. do {
  418. let authenticated = try await unlockmanager.unlock()
  419. if authenticated {
  420. storeExternalInsulinEvent()
  421. } else {
  422. print("authentication failed")
  423. }
  424. } catch {
  425. print("authentication error: \(error.localizedDescription)")
  426. }
  427. }
  428. private func storeExternalInsulinEvent() {
  429. pumpHistoryStorage.storeEvents(
  430. [
  431. PumpHistoryEvent(
  432. id: UUID().uuidString,
  433. type: .bolus,
  434. timestamp: date,
  435. amount: amount,
  436. duration: nil,
  437. durationMin: nil,
  438. rate: nil,
  439. temp: nil,
  440. carbInput: nil,
  441. isExternal: true
  442. )
  443. ]
  444. )
  445. debug(.default, "External insulin saved to pumphistory.json")
  446. // Reset amount to 0 for next entry.
  447. amount = 0
  448. // perform determine basal sync
  449. apsManager.determineBasalSync()
  450. }
  451. }
  452. }
  453. extension Bolus.StateModel: SuggestionObserver {
  454. func suggestionDidUpdate(_: Suggestion) {
  455. DispatchQueue.main.async {
  456. self.waitForSuggestion = false
  457. }
  458. setupInsulinRequired()
  459. }
  460. }