GlucoseStorage.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. import AVFAudio
  2. import Combine
  3. import CoreData
  4. import Foundation
  5. import LoopKit
  6. import SwiftDate
  7. import SwiftUI
  8. import Swinject
  9. protocol GlucoseStorage {
  10. var updatePublisher: AnyPublisher<Void, Never> { get }
  11. func storeGlucose(_ glucose: [BloodGlucose])
  12. func addManualGlucose(glucose: Int)
  13. func isGlucoseDataFresh(_ glucoseDate: Date?) -> Bool
  14. func syncDate() -> Date
  15. func filterTooFrequentGlucose(_ glucose: [BloodGlucose], at: Date) -> [BloodGlucose]
  16. func lastGlucoseDate() -> Date
  17. func isGlucoseFresh() -> Bool
  18. func getGlucoseNotYetUploadedToNightscout() async -> [BloodGlucose]
  19. func getCGMStateNotYetUploadedToNightscout() async -> [NightscoutTreatment]
  20. func getManualGlucoseNotYetUploadedToNightscout() async -> [NightscoutTreatment]
  21. func getGlucoseNotYetUploadedToHealth() async -> [BloodGlucose]
  22. func getManualGlucoseNotYetUploadedToHealth() async -> [BloodGlucose]
  23. func getGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample]
  24. func getManualGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample]
  25. var alarm: GlucoseAlarm? { get }
  26. func deleteGlucose(_ treatmentObjectID: NSManagedObjectID) async
  27. }
  28. final class BaseGlucoseStorage: GlucoseStorage, Injectable {
  29. private let processQueue = DispatchQueue(label: "BaseGlucoseStorage.processQueue")
  30. @Injected() private var storage: FileStorage!
  31. @Injected() private var broadcaster: Broadcaster!
  32. @Injected() private var settingsManager: SettingsManager!
  33. let coredataContext = CoreDataStack.shared.newTaskContext()
  34. private let updateSubject = PassthroughSubject<Void, Never>()
  35. var updatePublisher: AnyPublisher<Void, Never> {
  36. updateSubject.eraseToAnyPublisher()
  37. }
  38. private enum Config {
  39. static let filterTime: TimeInterval = 3.5 * 60
  40. }
  41. init(resolver: Resolver) {
  42. injectServices(resolver)
  43. }
  44. private var glucoseFormatter: NumberFormatter {
  45. let formatter = NumberFormatter()
  46. formatter.numberStyle = .decimal
  47. formatter.maximumFractionDigits = 0
  48. if settingsManager.settings.units == .mmolL {
  49. formatter.maximumFractionDigits = 1
  50. }
  51. formatter.decimalSeparator = "."
  52. return formatter
  53. }
  54. func storeGlucose(_ glucose: [BloodGlucose]) {
  55. coredataContext.perform {
  56. let datesToCheck: Set<Date?> = Set(glucose.compactMap { $0.dateString as Date? })
  57. let fetchRequest: NSFetchRequest<NSFetchRequestResult> = GlucoseStored.fetchRequest()
  58. fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
  59. NSPredicate(format: "date IN %@", datesToCheck),
  60. NSPredicate.predicateForOneDayAgo
  61. ])
  62. fetchRequest.propertiesToFetch = ["date"]
  63. fetchRequest.resultType = .dictionaryResultType
  64. var existingDates = Set<Date>()
  65. do {
  66. let results = try self.coredataContext.fetch(fetchRequest) as? [NSDictionary]
  67. existingDates = Set(results?.compactMap({ $0["date"] as? Date }) ?? [])
  68. } catch {
  69. debugPrint("Failed to fetch existing glucose dates: \(error)")
  70. }
  71. var filteredGlucose = glucose.filter { !existingDates.contains($0.dateString) }
  72. // prepare batch insert
  73. let batchInsert = NSBatchInsertRequest(
  74. entity: GlucoseStored.entity(),
  75. managedObjectHandler: { (managedObject: NSManagedObject) -> Bool in
  76. guard let glucoseEntry = managedObject as? GlucoseStored, !filteredGlucose.isEmpty else {
  77. return true // Stop if there are no more items
  78. }
  79. let entry = filteredGlucose.removeFirst()
  80. glucoseEntry.id = UUID()
  81. glucoseEntry.glucose = Int16(entry.glucose ?? 0)
  82. glucoseEntry.date = entry.dateString
  83. glucoseEntry.direction = entry.direction?.rawValue
  84. glucoseEntry.isUploadedToNS = false /// the value is not uploaded to NS (yet)
  85. glucoseEntry.isUploadedToHealth = false /// the value is not uploaded to Health (yet)
  86. glucoseEntry.isUploadedToTidepool = false /// the value is not uploaded to Tidepool (yet)
  87. return false // Continue processing
  88. }
  89. )
  90. // process batch insert
  91. do {
  92. try self.coredataContext.execute(batchInsert)
  93. // Notify subscribers that there is a new glucose value
  94. // We need to do this because the due to the batch insert there is no ManagedObjectContext notification
  95. self.updateSubject.send(())
  96. } catch {
  97. debugPrint(
  98. "Glucose Storage: \(#function) \(DebuggingIdentifiers.failed) failed to execute batch insert: \(error)"
  99. )
  100. }
  101. debug(.deviceManager, "start storage cgmState")
  102. self.storage.transaction { storage in
  103. let file = OpenAPS.Monitor.cgmState
  104. var treatments = storage.retrieve(file, as: [NightscoutTreatment].self) ?? []
  105. var updated = false
  106. for x in glucose {
  107. debug(.deviceManager, "storeGlucose \(x)")
  108. guard let sessionStartDate = x.sessionStartDate else {
  109. continue
  110. }
  111. if let lastTreatment = treatments.last,
  112. let createdAt = lastTreatment.createdAt,
  113. // When a new Dexcom sensor is started, it produces multiple consecutive
  114. // startDates. Disambiguate them by only allowing a session start per minute.
  115. abs(createdAt.timeIntervalSince(sessionStartDate)) < TimeInterval(60)
  116. {
  117. continue
  118. }
  119. var notes = ""
  120. if let t = x.transmitterID {
  121. notes = t
  122. }
  123. if let a = x.activationDate {
  124. notes = "\(notes) activated on \(a)"
  125. }
  126. let treatment = NightscoutTreatment(
  127. duration: nil,
  128. rawDuration: nil,
  129. rawRate: nil,
  130. absolute: nil,
  131. rate: nil,
  132. eventType: .nsSensorChange,
  133. createdAt: sessionStartDate,
  134. enteredBy: NightscoutTreatment.local,
  135. bolus: nil,
  136. insulin: nil,
  137. notes: notes,
  138. carbs: nil,
  139. fat: nil,
  140. protein: nil,
  141. targetTop: nil,
  142. targetBottom: nil
  143. )
  144. debug(.deviceManager, "CGM sensor change \(treatment)")
  145. treatments.append(treatment)
  146. updated = true
  147. }
  148. if updated {
  149. // We have to keep quite a bit of history as sensors start only every 10 days.
  150. storage.save(
  151. treatments.filter
  152. { $0.createdAt != nil && $0.createdAt!.addingTimeInterval(30.days.timeInterval) > Date() },
  153. as: file
  154. )
  155. }
  156. }
  157. }
  158. }
  159. func addManualGlucose(glucose: Int) {
  160. coredataContext.perform {
  161. let newItem = GlucoseStored(context: self.coredataContext)
  162. newItem.id = UUID()
  163. newItem.date = Date()
  164. newItem.glucose = Int16(glucose)
  165. newItem.isManual = true
  166. newItem.isUploadedToNS = false
  167. newItem.isUploadedToHealth = false
  168. newItem.isUploadedToTidepool = false
  169. do {
  170. guard self.coredataContext.hasChanges else { return }
  171. try self.coredataContext.save()
  172. // Glucose subscribers already listen to the update publisher, so call here to update glucose-related data.
  173. self.updateSubject.send(())
  174. } catch let error as NSError {
  175. debugPrint(
  176. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save manual glucose to Core Data with error: \(error)"
  177. )
  178. }
  179. }
  180. }
  181. func isGlucoseDataFresh(_ glucoseDate: Date?) -> Bool {
  182. guard let glucoseDate = glucoseDate else { return false }
  183. return glucoseDate > Date().addingTimeInterval(-6 * 60)
  184. }
  185. func syncDate() -> Date {
  186. let fr = GlucoseStored.fetchRequest()
  187. fr.predicate = NSPredicate.predicateForOneDayAgo
  188. fr.sortDescriptors = [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: false)]
  189. fr.fetchLimit = 1
  190. var date: Date?
  191. coredataContext.performAndWait {
  192. do {
  193. let results = try self.coredataContext.fetch(fr)
  194. date = results.first?.date
  195. } catch let error as NSError {
  196. print("Fetch error: \(DebuggingIdentifiers.failed) \(error.localizedDescription), \(error.userInfo)")
  197. }
  198. }
  199. return date ?? .distantPast
  200. }
  201. func lastGlucoseDate() -> Date {
  202. let fr = GlucoseStored.fetchRequest()
  203. fr.predicate = NSPredicate.predicateForOneDayAgo
  204. fr.sortDescriptors = [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: false)]
  205. fr.fetchLimit = 1
  206. var date: Date?
  207. coredataContext.performAndWait {
  208. do {
  209. let results = try self.coredataContext.fetch(fr)
  210. date = results.first?.date
  211. } catch let error as NSError {
  212. print("Fetch error: \(DebuggingIdentifiers.failed) \(error.localizedDescription), \(error.userInfo)")
  213. }
  214. }
  215. return date ?? .distantPast
  216. }
  217. func isGlucoseFresh() -> Bool {
  218. Date().timeIntervalSince(lastGlucoseDate()) <= Config.filterTime
  219. }
  220. func filterTooFrequentGlucose(_ glucose: [BloodGlucose], at date: Date) -> [BloodGlucose] {
  221. var lastDate = date
  222. var filtered: [BloodGlucose] = []
  223. let sorted = glucose.sorted { $0.date < $1.date }
  224. for entry in sorted {
  225. guard entry.dateString.addingTimeInterval(-Config.filterTime) > lastDate else {
  226. continue
  227. }
  228. filtered.append(entry)
  229. lastDate = entry.dateString
  230. }
  231. return filtered
  232. }
  233. func fetchLatestGlucose() -> GlucoseStored? {
  234. let predicate = NSPredicate.predicateFor20MinAgo
  235. return (CoreDataStack.shared.fetchEntities(
  236. ofType: GlucoseStored.self,
  237. onContext: coredataContext,
  238. predicate: predicate,
  239. key: "date",
  240. ascending: false,
  241. fetchLimit: 1
  242. ) as? [GlucoseStored] ?? []).first
  243. }
  244. // Fetch glucose that is not uploaded to Nightscout yet
  245. /// - Returns: Array of BloodGlucose to ensure the correct format for the NS Upload
  246. func getGlucoseNotYetUploadedToNightscout() async -> [BloodGlucose] {
  247. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  248. ofType: GlucoseStored.self,
  249. onContext: coredataContext,
  250. predicate: NSPredicate.glucoseNotYetUploadedToNightscout,
  251. key: "date",
  252. ascending: false,
  253. fetchLimit: 288
  254. )
  255. return await coredataContext.perform {
  256. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  257. return fetchedResults.map { result in
  258. BloodGlucose(
  259. _id: result.id?.uuidString ?? UUID().uuidString,
  260. sgv: Int(result.glucose),
  261. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  262. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  263. dateString: result.date ?? Date(),
  264. unfiltered: Decimal(result.glucose),
  265. filtered: Decimal(result.glucose),
  266. noise: nil,
  267. glucose: Int(result.glucose)
  268. )
  269. }
  270. }
  271. }
  272. // Fetch manual glucose that is not uploaded to Nightscout yet
  273. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  274. func getManualGlucoseNotYetUploadedToNightscout() async -> [NightscoutTreatment] {
  275. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  276. ofType: GlucoseStored.self,
  277. onContext: coredataContext,
  278. predicate: NSPredicate.manualGlucoseNotYetUploadedToNightscout,
  279. key: "date",
  280. ascending: false,
  281. fetchLimit: 288
  282. )
  283. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  284. return await coredataContext.perform {
  285. return fetchedResults.map { result in
  286. NightscoutTreatment(
  287. duration: nil,
  288. rawDuration: nil,
  289. rawRate: nil,
  290. absolute: nil,
  291. rate: nil,
  292. eventType: .capillaryGlucose,
  293. createdAt: result.date,
  294. enteredBy: CarbsEntry.local,
  295. bolus: nil,
  296. insulin: nil,
  297. notes: "Trio User",
  298. carbs: nil,
  299. fat: nil,
  300. protein: nil,
  301. foodType: nil,
  302. targetTop: nil,
  303. targetBottom: nil,
  304. glucoseType: "Manual",
  305. glucose: self.settingsManager.settings
  306. .units == .mgdL ? (self.glucoseFormatter.string(from: Int(result.glucose) as NSNumber) ?? "")
  307. : (self.glucoseFormatter.string(from: Decimal(result.glucose).asMmolL as NSNumber) ?? ""),
  308. units: self.settingsManager.settings.units == .mmolL ? "mmol" : "mg/dl",
  309. id: result.id?.uuidString
  310. )
  311. }
  312. }
  313. }
  314. func getCGMStateNotYetUploadedToNightscout() async -> [NightscoutTreatment] {
  315. async let alreadyUploaded: [NightscoutTreatment] = storage
  316. .retrieveAsync(OpenAPS.Nightscout.uploadedCGMState, as: [NightscoutTreatment].self) ?? []
  317. async let allValues: [NightscoutTreatment] = storage
  318. .retrieveAsync(OpenAPS.Monitor.cgmState, as: [NightscoutTreatment].self) ?? []
  319. let (alreadyUploadedValues, allValuesSet) = await (alreadyUploaded, allValues)
  320. return Array(Set(allValuesSet).subtracting(Set(alreadyUploadedValues)))
  321. }
  322. // Fetch glucose that is not uploaded to Nightscout yet
  323. /// - Returns: Array of BloodGlucose to ensure the correct format for the NS Upload
  324. func getGlucoseNotYetUploadedToHealth() async -> [BloodGlucose] {
  325. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  326. ofType: GlucoseStored.self,
  327. onContext: coredataContext,
  328. predicate: NSPredicate.glucoseNotYetUploadedToHealth,
  329. key: "date",
  330. ascending: false,
  331. fetchLimit: 288
  332. )
  333. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  334. return await coredataContext.perform {
  335. return fetchedResults.map { result in
  336. BloodGlucose(
  337. _id: result.id?.uuidString ?? UUID().uuidString,
  338. sgv: Int(result.glucose),
  339. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  340. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  341. dateString: result.date ?? Date(),
  342. unfiltered: Decimal(result.glucose),
  343. filtered: Decimal(result.glucose),
  344. noise: nil,
  345. glucose: Int(result.glucose)
  346. )
  347. }
  348. }
  349. }
  350. // Fetch manual glucose that is not uploaded to Nightscout yet
  351. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  352. func getManualGlucoseNotYetUploadedToHealth() async -> [BloodGlucose] {
  353. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  354. ofType: GlucoseStored.self,
  355. onContext: coredataContext,
  356. predicate: NSPredicate.manualGlucoseNotYetUploadedToHealth,
  357. key: "date",
  358. ascending: false,
  359. fetchLimit: 288
  360. )
  361. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  362. return await coredataContext.perform {
  363. return fetchedResults.map { result in
  364. BloodGlucose(
  365. _id: result.id?.uuidString ?? UUID().uuidString,
  366. sgv: Int(result.glucose),
  367. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  368. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  369. dateString: result.date ?? Date(),
  370. unfiltered: Decimal(result.glucose),
  371. filtered: Decimal(result.glucose),
  372. noise: nil,
  373. glucose: Int(result.glucose)
  374. )
  375. }
  376. }
  377. }
  378. // Fetch glucose that is not uploaded to Tidepool yet
  379. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for Tidepool upload
  380. func getGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample] {
  381. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  382. ofType: GlucoseStored.self,
  383. onContext: coredataContext,
  384. predicate: NSPredicate.glucoseNotYetUploadedToTidepool,
  385. key: "date",
  386. ascending: false,
  387. fetchLimit: 288
  388. )
  389. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  390. return await coredataContext.perform {
  391. return fetchedResults.map { result in
  392. BloodGlucose(
  393. _id: result.id?.uuidString ?? UUID().uuidString,
  394. sgv: Int(result.glucose),
  395. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  396. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  397. dateString: result.date ?? Date(),
  398. unfiltered: Decimal(result.glucose),
  399. filtered: Decimal(result.glucose),
  400. noise: nil,
  401. glucose: Int(result.glucose)
  402. )
  403. }
  404. .map { $0.convertStoredGlucoseSample(isManualGlucose: false) }
  405. }
  406. }
  407. // Fetch manual glucose that is not uploaded to Tidepool yet
  408. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for the Tidepool upload
  409. func getManualGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample] {
  410. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  411. ofType: GlucoseStored.self,
  412. onContext: coredataContext,
  413. predicate: NSPredicate.manualGlucoseNotYetUploadedToTidepool,
  414. key: "date",
  415. ascending: false,
  416. fetchLimit: 288
  417. )
  418. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  419. return await coredataContext.perform {
  420. return fetchedResults.map { result in
  421. BloodGlucose(
  422. _id: result.id?.uuidString ?? UUID().uuidString,
  423. sgv: Int(result.glucose),
  424. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  425. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  426. dateString: result.date ?? Date(),
  427. unfiltered: Decimal(result.glucose),
  428. filtered: Decimal(result.glucose),
  429. noise: nil,
  430. glucose: Int(result.glucose)
  431. )
  432. }.map { $0.convertStoredGlucoseSample(isManualGlucose: true) }
  433. }
  434. }
  435. func deleteGlucose(_ treatmentObjectID: NSManagedObjectID) async {
  436. let taskContext = CoreDataStack.shared.newTaskContext()
  437. taskContext.name = "deleteContext"
  438. taskContext.transactionAuthor = "deleteGlucose"
  439. await taskContext.perform {
  440. do {
  441. let result = try taskContext.existingObject(with: treatmentObjectID) as? GlucoseStored
  442. guard let glucoseToDelete = result else {
  443. debugPrint("Data Table State: \(#function) \(DebuggingIdentifiers.failed) glucose not found in core data")
  444. return
  445. }
  446. taskContext.delete(glucoseToDelete)
  447. guard taskContext.hasChanges else { return }
  448. try taskContext.save()
  449. debugPrint("\(#file) \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")
  450. } catch {
  451. debugPrint(
  452. "\(#file) \(#function) \(DebuggingIdentifiers.failed) error while deleting glucose from core data: \(error.localizedDescription)"
  453. )
  454. }
  455. }
  456. }
  457. var alarm: GlucoseAlarm? {
  458. /// glucose can not be older than 20 minutes due to the predicate in the fetch request
  459. coredataContext.performAndWait {
  460. guard let glucose = fetchLatestGlucose() else { return nil }
  461. let glucoseValue = glucose.glucose
  462. if Decimal(glucoseValue) <= settingsManager.settings.lowGlucose {
  463. return .low
  464. }
  465. if Decimal(glucoseValue) >= settingsManager.settings.highGlucose {
  466. return .high
  467. }
  468. return nil
  469. }
  470. }
  471. }
  472. protocol GlucoseObserver {
  473. func glucoseDidUpdate(_ glucose: [BloodGlucose])
  474. }
  475. enum GlucoseAlarm {
  476. case high
  477. case low
  478. var displayName: String {
  479. switch self {
  480. case .high:
  481. return NSLocalizedString("LOWALERT!", comment: "LOWALERT!")
  482. case .low:
  483. return NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!")
  484. }
  485. }
  486. }