CarbsStorage.swift 11 KB

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