CarbsStorage.swift 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import CoreData
  2. import Foundation
  3. import SwiftDate
  4. import Swinject
  5. protocol CarbsObserver {
  6. func carbsDidUpdate(_ carbs: [CarbsEntry])
  7. }
  8. protocol CarbsStorage {
  9. func storeCarbs(_ carbs: [CarbsEntry])
  10. func syncDate() -> Date
  11. func recent() -> [CarbsEntry]
  12. func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment]
  13. func deleteCarbs(at uniqueID: String, fpuID: String, complex: Bool)
  14. }
  15. final class BaseCarbsStorage: CarbsStorage, Injectable {
  16. private let processQueue = DispatchQueue(label: "BaseCarbsStorage.processQueue")
  17. @Injected() private var storage: FileStorage!
  18. @Injected() private var broadcaster: Broadcaster!
  19. @Injected() private var settings: SettingsManager!
  20. let coredataContext = CoreDataStack.shared.persistentContainer.newBackgroundContext()
  21. init(resolver: Resolver) {
  22. injectServices(resolver)
  23. }
  24. func storeCarbs(_ entries: [CarbsEntry]) {
  25. processQueue.sync {
  26. let file = OpenAPS.Monitor.carbHistory
  27. var uniqEvents: [CarbsEntry] = []
  28. let fat = entries.last?.fat ?? 0
  29. let protein = entries.last?.protein ?? 0
  30. if fat > 0 || protein > 0 {
  31. // -------------------------- FPU--------------------------------------
  32. let interval = settings.settings.minuteInterval // Interval betwwen carbs
  33. let timeCap = settings.settings.timeCap // Max Duration
  34. let adjustment = settings.settings.individualAdjustmentFactor
  35. let delay = settings.settings.delay // Tme before first future carb entry
  36. let kcal = protein * 4 + fat * 9
  37. let carbEquivalents = (kcal / 10) * adjustment
  38. let fpus = carbEquivalents / 10
  39. // Duration in hours used for extended boluses with Warsaw Method. Here used for total duration of the computed carbquivalents instead, excluding the configurable delay.
  40. var computedDuration = 0
  41. switch fpus {
  42. case ..<2:
  43. computedDuration = 3
  44. case 2 ..< 3:
  45. computedDuration = 4
  46. case 3 ..< 4:
  47. computedDuration = 5
  48. default:
  49. computedDuration = timeCap
  50. }
  51. // Size of each created carb equivalent if 60 minutes interval
  52. var equivalent: Decimal = carbEquivalents / Decimal(computedDuration)
  53. // Adjust for interval setting other than 60 minutes
  54. equivalent /= Decimal(60 / interval)
  55. // Round to 1 fraction digit
  56. // equivalent = Decimal(round(Double(equivalent * 10) / 10))
  57. let roundedEquivalent: Double = round(Double(equivalent * 10)) / 10
  58. equivalent = Decimal(roundedEquivalent)
  59. // Number of equivalents
  60. var numberOfEquivalents = carbEquivalents / equivalent
  61. // Only use delay in first loop
  62. var firstIndex = true
  63. // New date for each carb equivalent
  64. var useDate = entries.last?.createdAt ?? Date()
  65. // Group and Identify all FPUs together
  66. let fpuID = entries.last?.fpuID ?? ""
  67. // Create an array of all future carb equivalents.
  68. var futureCarbArray = [CarbsEntry]()
  69. while carbEquivalents > 0, numberOfEquivalents > 0 {
  70. if firstIndex {
  71. useDate = useDate.addingTimeInterval(delay.minutes.timeInterval)
  72. firstIndex = false
  73. } else { useDate = useDate.addingTimeInterval(interval.minutes.timeInterval) }
  74. let eachCarbEntry = CarbsEntry(
  75. id: UUID().uuidString, createdAt: useDate, carbs: equivalent, fat: 0, protein: 0, note: nil,
  76. enteredBy: CarbsEntry.manual, isFPU: true,
  77. fpuID: fpuID
  78. )
  79. futureCarbArray.append(eachCarbEntry)
  80. numberOfEquivalents -= 1
  81. }
  82. // Save the array
  83. if carbEquivalents > 0 {
  84. self.storage.transaction { storage in
  85. storage.append(futureCarbArray, to: file, uniqBy: \.createdAt)
  86. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  87. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  88. .sorted { $0.createdAt > $1.createdAt } ?? []
  89. storage.save(Array(uniqEvents), as: file)
  90. }
  91. }
  92. } // ------------------------- END OF TPU ----------------------------------------
  93. // Store the actual (normal) carbs
  94. if let entry = entries.last, entry.carbs > 0 {
  95. // uniqEvents = []
  96. let onlyCarbs = CarbsEntry(
  97. id: entry.id ?? "",
  98. createdAt: entry.createdAt,
  99. carbs: entry.carbs,
  100. fat: nil,
  101. protein: nil,
  102. note: entry.note ?? "",
  103. enteredBy: entry.enteredBy ?? "",
  104. isFPU: false,
  105. fpuID: ""
  106. )
  107. self.storage.transaction { storage in
  108. storage.append(onlyCarbs, to: file, uniqBy: \.createdAt)
  109. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  110. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  111. .sorted { $0.createdAt > $1.createdAt } ?? []
  112. storage.save(Array(uniqEvents), as: file)
  113. }
  114. }
  115. // MARK: Save to CoreData. TEST
  116. var cbs: Decimal = 0
  117. var carbDate = Date()
  118. if entries.isNotEmpty {
  119. cbs = entries[0].carbs
  120. carbDate = entries[0].createdAt
  121. }
  122. if cbs != 0 {
  123. self.coredataContext.perform {
  124. let carbDataForStats = Carbohydrates(context: self.coredataContext)
  125. carbDataForStats.date = carbDate
  126. carbDataForStats.carbs = cbs as NSDecimalNumber
  127. try? self.coredataContext.save()
  128. }
  129. }
  130. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  131. $0.carbsDidUpdate(uniqEvents)
  132. }
  133. }
  134. }
  135. func syncDate() -> Date {
  136. Date().addingTimeInterval(-1.days.timeInterval)
  137. }
  138. func recent() -> [CarbsEntry] {
  139. storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self)?.reversed() ?? []
  140. }
  141. func deleteCarbs(at uniqueID: String, fpuID: String, complex: Bool) {
  142. processQueue.sync {
  143. var allValues = storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  144. if fpuID != "" {
  145. if allValues.firstIndex(where: { $0.fpuID == fpuID }) == nil {
  146. debug(.default, "Didn't find any carb equivalents to delete. ID to search for: " + fpuID.description)
  147. } else {
  148. allValues.removeAll(where: { $0.fpuID == fpuID })
  149. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  150. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  151. $0.carbsDidUpdate(allValues)
  152. }
  153. }
  154. }
  155. if fpuID == "" || complex {
  156. if allValues.firstIndex(where: { $0.id == uniqueID }) == nil {
  157. debug(.default, "Didn't find any carb entries to delete. ID to search for: " + uniqueID.description)
  158. } else {
  159. allValues.removeAll(where: { $0.id == uniqueID })
  160. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  161. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  162. $0.carbsDidUpdate(allValues)
  163. }
  164. }
  165. }
  166. }
  167. }
  168. func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
  169. let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedCarbs, as: [NigtscoutTreatment].self) ?? []
  170. let eventsManual = recent().filter { $0.enteredBy == CarbsEntry.manual }
  171. let treatments = eventsManual.map {
  172. NigtscoutTreatment(
  173. duration: nil,
  174. rawDuration: nil,
  175. rawRate: nil,
  176. absolute: nil,
  177. rate: nil,
  178. eventType: .nsCarbCorrection,
  179. createdAt: $0.createdAt,
  180. enteredBy: CarbsEntry.manual,
  181. bolus: nil,
  182. insulin: nil,
  183. carbs: $0.carbs,
  184. fat: nil,
  185. protein: nil,
  186. foodType: $0.note,
  187. targetTop: nil,
  188. targetBottom: nil,
  189. id: $0.id,
  190. fpuID: $0.fpuID
  191. )
  192. }
  193. return Array(Set(treatments).subtracting(Set(uploaded)))
  194. }
  195. }