CarbsStorage.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 = MealsStored(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. do {
  140. try self.coredataContext.save()
  141. debugPrint(
  142. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved carbs to core data"
  143. )
  144. } catch {
  145. debugPrint(
  146. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while saving carbs to core data"
  147. )
  148. }
  149. }
  150. }
  151. private func saveFPUToCoreData(entries: [CarbsEntry]) {
  152. guard let entry = entries.last, entry.fat != 0 || entry.protein != 0 else { return }
  153. coredataContext.perform {
  154. let newItem = MealsStored(context: self.coredataContext)
  155. newItem.date = entry.actualDate ?? entry.createdAt
  156. newItem.fat = Double(truncating: NSDecimalNumber(decimal: entry.fat ?? 0))
  157. newItem.protein = Double(truncating: NSDecimalNumber(decimal: entry.protein ?? 0))
  158. newItem.carbs = Double(truncating: NSDecimalNumber(decimal: entry.carbs))
  159. newItem.id = UUID()
  160. newItem.isFPU = true
  161. do {
  162. try self.coredataContext.save()
  163. debugPrint("Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved fpus to core data")
  164. } catch {
  165. debugPrint(
  166. "Carbs Storage: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) error while saving fpus to core data"
  167. )
  168. }
  169. }
  170. }
  171. private func notifyObservers(entries: [CarbsEntry]) {
  172. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  173. $0.carbsDidUpdate(entries)
  174. }
  175. }
  176. // func storeCarbs(_ entries: [CarbsEntry]) {
  177. // processQueue.sync {
  178. // let file = OpenAPS.Monitor.carbHistory
  179. // var uniqEvents: [CarbsEntry] = []
  180. //
  181. // let fat = entries.last?.fat ?? 0
  182. // let protein = entries.last?.protein ?? 0
  183. //
  184. // if fat > 0 || protein > 0 {
  185. // // -------------------------- FPU--------------------------------------
  186. // let interval = settings.settings.minuteInterval // Interval betwwen carbs
  187. // let timeCap = settings.settings.timeCap // Max Duration
  188. // let adjustment = settings.settings.individualAdjustmentFactor
  189. // let delay = settings.settings.delay // Tme before first future carb entry
  190. // let kcal = protein * 4 + fat * 9
  191. // let carbEquivalents = (kcal / 10) * adjustment
  192. // let fpus = carbEquivalents / 10
  193. // // Duration in hours used for extended boluses with Warsaw Method. Here used for total duration of the computed carbquivalents instead, excluding the configurable delay.
  194. // var computedDuration = 0
  195. // switch fpus {
  196. // case ..<2:
  197. // computedDuration = 3
  198. // case 2 ..< 3:
  199. // computedDuration = 4
  200. // case 3 ..< 4:
  201. // computedDuration = 5
  202. // default:
  203. // computedDuration = timeCap
  204. // }
  205. // // Size of each created carb equivalent if 60 minutes interval
  206. // var equivalent: Decimal = carbEquivalents / Decimal(computedDuration)
  207. // // Adjust for interval setting other than 60 minutes
  208. // equivalent /= Decimal(60 / interval)
  209. // // Round to 1 fraction digit
  210. // // equivalent = Decimal(round(Double(equivalent * 10) / 10))
  211. // let roundedEquivalent: Double = round(Double(equivalent * 10)) / 10
  212. // equivalent = Decimal(roundedEquivalent)
  213. // // Number of equivalents
  214. // var numberOfEquivalents = carbEquivalents / equivalent
  215. // // Only use delay in first loop
  216. // var firstIndex = true
  217. // // New date for each carb equivalent
  218. // var useDate = entries.last?.actualDate ?? Date()
  219. // // Group and Identify all FPUs together
  220. // let fpuID = entries.last?.fpuID ?? ""
  221. // // Create an array of all future carb equivalents.
  222. // var futureCarbArray = [CarbsEntry]()
  223. // while carbEquivalents > 0, numberOfEquivalents > 0 {
  224. // if firstIndex {
  225. // useDate = useDate.addingTimeInterval(delay.minutes.timeInterval)
  226. // firstIndex = false
  227. // } else { useDate = useDate.addingTimeInterval(interval.minutes.timeInterval) }
  228. //
  229. // let eachCarbEntry = CarbsEntry(
  230. // id: UUID().uuidString, createdAt: entries.last?.createdAt ?? Date(), actualDate: useDate,
  231. // carbs: equivalent, fat: 0, protein: 0, note: nil,
  232. // enteredBy: CarbsEntry.manual, isFPU: true,
  233. // fpuID: fpuID
  234. // )
  235. // futureCarbArray.append(eachCarbEntry)
  236. // numberOfEquivalents -= 1
  237. // }
  238. // // Save the array
  239. // if carbEquivalents > 0 {
  240. // self.storage.transaction { storage in
  241. // storage.append(futureCarbArray, to: file, uniqBy: \.id)
  242. // uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  243. // .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  244. // .sorted { $0.createdAt > $1.createdAt } ?? []
  245. // storage.save(Array(uniqEvents), as: file)
  246. // }
  247. // }
  248. // } // ------------------------- END OF TPU ----------------------------------------
  249. // // Store the actual (normal) carbs
  250. // if let entry = entries.last, entry.carbs > 0 {
  251. // // uniqEvents = []
  252. // let onlyCarbs = CarbsEntry(
  253. // id: entry.id ?? "",
  254. // createdAt: entry.createdAt,
  255. // actualDate: entry.actualDate ?? entry.createdAt,
  256. // carbs: entry.carbs,
  257. // fat: nil,
  258. // protein: nil,
  259. // note: entry.note ?? "",
  260. // enteredBy: entry.enteredBy ?? "",
  261. // isFPU: false,
  262. // fpuID: ""
  263. // )
  264. //
  265. // self.storage.transaction { storage in
  266. // storage.append(onlyCarbs, to: file, uniqBy: \.id)
  267. // uniqEvents = storage.retrieve(file, as: [CarbsEntry].self)?
  268. // .filter { $0.createdAt.addingTimeInterval(1.days.timeInterval) > Date() }
  269. // .sorted { $0.createdAt > $1.createdAt } ?? []
  270. // storage.save(Array(uniqEvents), as: file)
  271. // }
  272. // }
  273. // MARK: Save to CoreData
  274. // var cbs: Decimal = 0
  275. // var carbDate = Date()
  276. // if entries.isNotEmpty {
  277. // cbs = entries[0].carbs
  278. // carbDate = entries[0].actualDate ?? entries[0].createdAt
  279. // }
  280. // if cbs != 0 {
  281. // self.coredataContext.perform {
  282. // let carbDataForStats = Carbohydrates(context: self.coredataContext)
  283. //
  284. // carbDataForStats.date = carbDate
  285. // carbDataForStats.carbs = cbs as NSDecimalNumber
  286. //
  287. // try? self.coredataContext.save()
  288. // }
  289. // }
  290. // broadcaster.notify(CarbsObserver.self, on: processQueue) {
  291. // $0.carbsDidUpdate(uniqEvents)
  292. // }
  293. // }
  294. // }
  295. func syncDate() -> Date {
  296. Date().addingTimeInterval(-1.days.timeInterval)
  297. }
  298. func recent() -> [CarbsEntry] {
  299. storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self)?.reversed() ?? []
  300. }
  301. func deleteCarbs(at uniqueID: String, fpuID: String, complex: Bool) {
  302. processQueue.sync {
  303. var allValues = storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  304. if fpuID != "" {
  305. if allValues.firstIndex(where: { $0.fpuID == fpuID }) == nil {
  306. debug(.default, "Didn't find any carb equivalents to delete. ID to search for: " + fpuID.description)
  307. } else {
  308. allValues.removeAll(where: { $0.fpuID == fpuID })
  309. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  310. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  311. $0.carbsDidUpdate(allValues)
  312. }
  313. }
  314. }
  315. if fpuID == "" || complex {
  316. if allValues.firstIndex(where: { $0.id == uniqueID }) == nil {
  317. debug(.default, "Didn't find any carb entries to delete. ID to search for: " + uniqueID.description)
  318. } else {
  319. allValues.removeAll(where: { $0.id == uniqueID })
  320. storage.save(allValues, as: OpenAPS.Monitor.carbHistory)
  321. broadcaster.notify(CarbsObserver.self, on: processQueue) {
  322. $0.carbsDidUpdate(allValues)
  323. }
  324. }
  325. }
  326. }
  327. }
  328. func nightscoutTretmentsNotUploaded() -> [NigtscoutTreatment] {
  329. let uploaded = storage.retrieve(OpenAPS.Nightscout.uploadedCarbs, as: [NigtscoutTreatment].self) ?? []
  330. let eventsManual = recent().filter { $0.enteredBy == CarbsEntry.manual }
  331. let treatments = eventsManual.map {
  332. NigtscoutTreatment(
  333. duration: nil,
  334. rawDuration: nil,
  335. rawRate: nil,
  336. absolute: nil,
  337. rate: nil,
  338. eventType: .nsCarbCorrection,
  339. createdAt: $0.actualDate ?? $0.createdAt,
  340. enteredBy: CarbsEntry.manual,
  341. bolus: nil,
  342. insulin: nil,
  343. carbs: $0.carbs,
  344. fat: nil,
  345. protein: nil,
  346. foodType: $0.note,
  347. targetTop: nil,
  348. targetBottom: nil,
  349. id: $0.id,
  350. fpuID: $0.fpuID
  351. )
  352. }
  353. return Array(Set(treatments).subtracting(Set(uploaded)))
  354. }
  355. }