GlucoseStorage.swift 23 KB

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