CarbsStorage.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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?.actualDate ?? 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: entries.last?.createdAt ?? Date(), actualDate: useDate,
  76. carbs: equivalent, fat: 0, protein: 0, note: nil,
  77. enteredBy: CarbsEntry.manual, isFPU: true,
  78. fpuID: fpuID
  79. )
  80. futureCarbArray.append(eachCarbEntry)
  81. numberOfEquivalents -= 1
  82. }
  83. // Save the array
  84. if carbEquivalents > 0 {
  85. self.storage.transaction { storage in
  86. storage.append(futureCarbArray, to: file, uniqBy: \.id)
  87. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  88. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  89. .sorted { $0.createdAt > $1.createdAt } ?? []
  90. storage.save(Array(uniqEvents), as: file)
  91. }
  92. }
  93. } // ------------------------- END OF TPU ----------------------------------------
  94. // Store the actual (normal) carbs
  95. if let entry = entries.last, entry.carbs > 0 {
  96. // uniqEvents = []
  97. let onlyCarbs = CarbsEntry(
  98. id: entry.id ?? "",
  99. createdAt: entry.createdAt,
  100. actualDate: entry.actualDate ?? entry.createdAt,
  101. carbs: entry.carbs,
  102. fat: nil,
  103. protein: nil,
  104. note: entry.note ?? "",
  105. enteredBy: entry.enteredBy ?? "",
  106. isFPU: false,
  107. fpuID: ""
  108. )
  109. self.storage.transaction { storage in
  110. storage.append(onlyCarbs, to: file, uniqBy: \.id)
  111. uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  112. .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  113. .sorted { $0.createdAt > $1.createdAt } ?? []
  114. storage.save(Array(uniqEvents), as: file)
  115. }
  116. }
  117. // MARK: Save to CoreData. TEST
  118. var cbs: Decimal = 0
  119. var carbDate = Date()
  120. if entries.isNotEmpty {
  121. cbs = entries[0].carbs
  122. carbDate = entries[0].actualDate ?? entries[0].createdAt
  123. }
  124. if cbs != 0 {
  125. self.coredataContext.perform {
  126. let carbDataForStats = Carbohydrates(context: self.coredataContext)
  127. carbDataForStats.date = carbDate
  128. carbDataForStats.carbs = cbs as NSDecimalNumber
  129. try? self.coredataContext.save()
  130. }
  131. }
  132. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  133. $0.carbsDidUpdate(uniqEvents)
  134. }
  135. }
  136. }
  137. func syncDate() -> Date {
  138. Date().addingTimeInterval(-1.days.timeInterval)
  139. }
  140. func recent() -> [CarbsEntry] {
  141. storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self)?.reversed() ?? []
  142. }
  143. func deleteCarbs(at uniqueID: String, fpuID: String, complex: Bool) {
  144. processQueue.sync {
  145. var allValues = storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  146. if fpuID != "" {
  147. if allValues.firstIndex(where: { $0.fpuID == fpuID }) == nil {
  148. debug(.default, "Didn't find any carb equivalents to delete. ID to search for: " + fpuID.description)
  149. } else {
  150. allValues.removeAll(where: { $0.fpuID == fpuID })
  151. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  152. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  153. $0.carbsDidUpdate(allValues)
  154. }
  155. }
  156. }
  157. if fpuID == "" || complex {
  158. if allValues.firstIndex(where: { $0.id == uniqueID }) == nil {
  159. debug(.default, "Didn't find any carb entries to delete. ID to search for: " + uniqueID.description)
  160. } else {
  161. allValues.removeAll(where: { $0.id == uniqueID })
  162. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  163. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  164. $0.carbsDidUpdate(allValues)
  165. }
  166. }
  167. }
  168. }
  169. }
  170. func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
  171. let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedCarbs, as: [NigtscoutTreatment].self) ?? []
  172. let eventsManual = recent().filter { $0.enteredBy == CarbsEntry.manual }
  173. let treatments = eventsManual.map {
  174. NigtscoutTreatment(
  175. duration: nil,
  176. rawDuration: nil,
  177. rawRate: nil,
  178. absolute: nil,
  179. rate: nil,
  180. eventType: .nsCarbCorrection,
  181. createdAt: $0.actualDate ?? $0.createdAt,
  182. enteredBy: CarbsEntry.manual,
  183. bolus: nil,
  184. insulin: nil,
  185. carbs: $0.carbs,
  186. fat: nil,
  187. protein: nil,
  188. foodType: $0.note,
  189. targetTop: nil,
  190. targetBottom: nil,
  191. id: $0.id,
  192. fpuID: $0.fpuID
  193. )
  194. }
  195. return Array(Set(treatments).subtracting(Set(uploaded)))
  196. }
  197. }