CarbsStorage.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.backgroundContext
  21. init(resolver: Resolver) {
  22. injectServices(resolver)
  23. }
  24. func storeCarbs(_ entries: [CarbsEntry]) {
  25. processQueue.sync {
  26. self.handleFPUCalculations(entries: entries)
  27. self.storeNormalCarbs(entries: entries)
  28. self.saveCarbsToCoreData(entries: entries)
  29. self.saveFPUToCoreData(entries: entries)
  30. self.notifyObservers(entries: entries)
  31. }
  32. }
  33. private func handleFPUCalculations(entries: [CarbsEntry]) {
  34. let file = OpenAPS.Monitor.carbHistory
  35. var uniqEvents: [CarbsEntry] = []
  36. let fat = entries.last?.fat ?? 0
  37. let protein = entries.last?.protein ?? 0
  38. if fat > 0 || protein > 0 {
  39. // -------------------------- FPU--------------------------------------
  40. let interval = settings.settings.minuteInterval // Interval betwwen carbs
  41. let timeCap = settings.settings.timeCap // Max Duration
  42. let adjustment = settings.settings.individualAdjustmentFactor
  43. let delay = settings.settings.delay // Tme before first future carb entry
  44. let kcal = protein * 4 + fat * 9
  45. let carbEquivalents = (kcal / 10) * adjustment
  46. let fpus = carbEquivalents / 10
  47. // Duration in hours used for extended boluses with Warsaw Method. Here used for total duration of the computed carbquivalents instead, excluding the configurable delay.
  48. var computedDuration = 0
  49. switch fpus {
  50. case ..<2:
  51. computedDuration = 3
  52. case 2 ..< 3:
  53. computedDuration = 4
  54. case 3 ..< 4:
  55. computedDuration = 5
  56. default:
  57. computedDuration = timeCap
  58. }
  59. // Size of each created carb equivalent if 60 minutes interval
  60. var equivalent: Decimal = carbEquivalents / Decimal(computedDuration)
  61. // Adjust for interval setting other than 60 minutes
  62. equivalent /= Decimal(60 / interval)
  63. // Round to 1 fraction digit
  64. // equivalent = Decimal(round(Double(equivalent * 10) / 10))
  65. let roundedEquivalent: Double = round(Double(equivalent * 10)) / 10
  66. equivalent = Decimal(roundedEquivalent)
  67. // Number of equivalents
  68. var numberOfEquivalents = carbEquivalents / equivalent
  69. // Only use delay in first loop
  70. var firstIndex = true
  71. // New date for each carb equivalent
  72. var useDate = entries.last?.actualDate ?? Date()
  73. // Group and Identify all FPUs together
  74. let fpuID = entries.last?.fpuID ?? ""
  75. // Create an array of all future carb equivalents.
  76. var futureCarbArray = [CarbsEntry]()
  77. while carbEquivalents > 0, numberOfEquivalents > 0 {
  78. if firstIndex {
  79. useDate = useDate.addingTimeInterval(delay.minutes.timeInterval)
  80. firstIndex = false
  81. } else { useDate = useDate.addingTimeInterval(interval.minutes.timeInterval) }
  82. let eachCarbEntry = CarbsEntry(
  83. id: UUID().uuidString, createdAt: entries.last?.createdAt ?? Date(), actualDate: useDate,
  84. carbs: equivalent, fat: 0, protein: 0, note: nil,
  85. enteredBy: CarbsEntry.manual, isFPU: true,
  86. fpuID: fpuID
  87. )
  88. futureCarbArray.append(eachCarbEntry)
  89. numberOfEquivalents -= 1
  90. }
  91. // Save the array
  92. if carbEquivalents > 0 {
  93. storage.transaction { storage in
  94. storage.append(futureCarbArray, to: file, uniqBy: \.id)
  95. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  96. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  97. .sorted { $0.createdAt > $1.createdAt } ?? []
  98. storage.save(Array(uniqEvents), as: file)
  99. }
  100. // MARK: - save also to core data
  101. saveFPUToCoreData(entries: futureCarbArray)
  102. }
  103. }
  104. }
  105. private func storeNormalCarbs(entries: [CarbsEntry]) {
  106. let file = OpenAPS.Monitor.carbHistory
  107. var uniqEvents: [CarbsEntry] = []
  108. if let entry = entries.last, entry.carbs > 0 {
  109. // uniqEvents = []
  110. let onlyCarbs = CarbsEntry(
  111. id: entry.id ?? "",
  112. createdAt: entry.createdAt,
  113. actualDate: entry.actualDate ?? entry.createdAt,
  114. carbs: entry.carbs,
  115. fat: nil,
  116. protein: nil,
  117. note: entry.note ?? "",
  118. enteredBy: entry.enteredBy ?? "",
  119. isFPU: false,
  120. fpuID: ""
  121. )
  122. storage.transaction { storage in
  123. storage.append(onlyCarbs, to: file, uniqBy: \.id)
  124. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  125. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  126. .sorted { $0.createdAt > $1.createdAt } ?? []
  127. storage.save(Array(uniqEvents), as: file)
  128. }
  129. }
  130. }
  131. private func saveCarbsToCoreData(entries: [CarbsEntry]) {
  132. guard let entry = entries.last, entry.carbs != 0 else { return }
  133. coredataContext.perform {
  134. let newItem = CarbEntryStored(context: self.coredataContext)
  135. newItem.date = entry.actualDate ?? entry.createdAt
  136. newItem.carbs = Double(truncating: NSDecimalNumber(decimal: entry.carbs))
  137. newItem.id = UUID()
  138. newItem.isFPU = false
  139. if self.coredataContext.hasChanges {
  140. do {
  141. try self.coredataContext.save()
  142. debugPrint(
  143. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved carbs to core data"
  144. )
  145. } catch {
  146. debugPrint(
  147. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while saving carbs to core data"
  148. )
  149. }
  150. }
  151. }
  152. }
  153. private func saveFPUToCoreData(entries: [CarbsEntry]) {
  154. guard let entry = entries.last, entry.fat != 0 || entry.protein != 0 else { return }
  155. coredataContext.perform {
  156. let newItem = CarbEntryStored(context: self.coredataContext)
  157. newItem.date = entry.actualDate ?? entry.createdAt
  158. newItem.fat = Double(truncating: NSDecimalNumber(decimal: entry.fat ?? 0))
  159. newItem.protein = Double(truncating: NSDecimalNumber(decimal: entry.protein ?? 0))
  160. newItem.carbs = Double(truncating: NSDecimalNumber(decimal: entry.carbs))
  161. newItem.id = UUID()
  162. newItem.isFPU = true
  163. if self.coredataContext.hasChanges {
  164. do {
  165. try self.coredataContext.save()
  166. debugPrint(
  167. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved fpus to core data"
  168. )
  169. } catch {
  170. debugPrint(
  171. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) error while saving fpus to core data"
  172. )
  173. }
  174. }
  175. }
  176. }
  177. private func notifyObservers(entries: [CarbsEntry]) {
  178. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  179. $0.carbsDidUpdate(entries)
  180. }
  181. }
  182. func syncDate() -> Date {
  183. Date().addingTimeInterval(-1.days.timeInterval)
  184. }
  185. func recent() -> [CarbsEntry] {
  186. storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self)?.reversed() ?? []
  187. }
  188. func deleteCarbs(at uniqueID: String, fpuID: String, complex: Bool) {
  189. processQueue.sync {
  190. var allValues = storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  191. if fpuID != "" {
  192. if allValues.firstIndex(where: { $0.fpuID == fpuID }) == nil {
  193. debug(.default, "Didn't find any carb equivalents to delete. ID to search for: " + fpuID.description)
  194. } else {
  195. allValues.removeAll(where: { $0.fpuID == fpuID })
  196. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  197. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  198. $0.carbsDidUpdate(allValues)
  199. }
  200. }
  201. }
  202. if fpuID == "" || complex {
  203. if allValues.firstIndex(where: { $0.id == uniqueID }) == nil {
  204. debug(.default, "Didn't find any carb entries to delete. ID to search for: " + uniqueID.description)
  205. } else {
  206. allValues.removeAll(where: { $0.id == uniqueID })
  207. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  208. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  209. $0.carbsDidUpdate(allValues)
  210. }
  211. }
  212. }
  213. }
  214. }
  215. func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
  216. let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedCarbs, as: [NigtscoutTreatment].self) ?? []
  217. let eventsManual = recent().filter { $0.enteredBy == CarbsEntry.manual }
  218. let treatments = eventsManual.map {
  219. NigtscoutTreatment(
  220. duration: nil,
  221. rawDuration: nil,
  222. rawRate: nil,
  223. absolute: nil,
  224. rate: nil,
  225. eventType: .nsCarbCorrection,
  226. createdAt: $0.actualDate ?? $0.createdAt,
  227. enteredBy: CarbsEntry.manual,
  228. bolus: nil,
  229. insulin: nil,
  230. carbs: $0.carbs,
  231. fat: nil,
  232. protein: nil,
  233. foodType: $0.note,
  234. targetTop: nil,
  235. targetBottom: nil,
  236. id: $0.id,
  237. fpuID: $0.fpuID
  238. )
  239. }
  240. return Array(Set(treatments).subtracting(Set(uploaded)))
  241. }
  242. }