GlucoseStorage.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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. type: "sgv"
  269. )
  270. }
  271. }
  272. }
  273. // Fetch manual glucose that is not uploaded to Nightscout yet
  274. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  275. func getManualGlucoseNotYetUploadedToNightscout() async -> [NightscoutTreatment] {
  276. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  277. ofType: GlucoseStored.self,
  278. onContext: coredataContext,
  279. predicate: NSPredicate.manualGlucoseNotYetUploadedToNightscout,
  280. key: "date",
  281. ascending: false,
  282. fetchLimit: 288
  283. )
  284. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  285. return await coredataContext.perform {
  286. return fetchedResults.map { result in
  287. NightscoutTreatment(
  288. duration: nil,
  289. rawDuration: nil,
  290. rawRate: nil,
  291. absolute: nil,
  292. rate: nil,
  293. eventType: .capillaryGlucose,
  294. createdAt: result.date,
  295. enteredBy: CarbsEntry.local,
  296. bolus: nil,
  297. insulin: nil,
  298. notes: "Trio User",
  299. carbs: nil,
  300. fat: nil,
  301. protein: nil,
  302. foodType: nil,
  303. targetTop: nil,
  304. targetBottom: nil,
  305. glucoseType: "Manual",
  306. glucose: self.settingsManager.settings
  307. .units == .mgdL ? (self.glucoseFormatter.string(from: Int(result.glucose) as NSNumber) ?? "")
  308. : (self.glucoseFormatter.string(from: Decimal(result.glucose).asMmolL as NSNumber) ?? ""),
  309. units: self.settingsManager.settings.units == .mmolL ? "mmol" : "mg/dl",
  310. id: result.id?.uuidString
  311. )
  312. }
  313. }
  314. }
  315. func getCGMStateNotYetUploadedToNightscout() async -> [NightscoutTreatment] {
  316. async let alreadyUploaded: [NightscoutTreatment] = storage
  317. .retrieveAsync(OpenAPS.Nightscout.uploadedCGMState, as: [NightscoutTreatment].self) ?? []
  318. async let allValues: [NightscoutTreatment] = storage
  319. .retrieveAsync(OpenAPS.Monitor.cgmState, as: [NightscoutTreatment].self) ?? []
  320. let (alreadyUploadedValues, allValuesSet) = await (alreadyUploaded, allValues)
  321. return Array(Set(allValuesSet).subtracting(Set(alreadyUploadedValues)))
  322. }
  323. // Fetch glucose that is not uploaded to Nightscout yet
  324. /// - Returns: Array of BloodGlucose to ensure the correct format for the NS Upload
  325. func getGlucoseNotYetUploadedToHealth() async -> [BloodGlucose] {
  326. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  327. ofType: GlucoseStored.self,
  328. onContext: coredataContext,
  329. predicate: NSPredicate.glucoseNotYetUploadedToHealth,
  330. key: "date",
  331. ascending: false,
  332. fetchLimit: 288
  333. )
  334. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  335. return await coredataContext.perform {
  336. return fetchedResults.map { result in
  337. BloodGlucose(
  338. _id: result.id?.uuidString ?? UUID().uuidString,
  339. sgv: Int(result.glucose),
  340. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  341. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  342. dateString: result.date ?? Date(),
  343. unfiltered: Decimal(result.glucose),
  344. filtered: Decimal(result.glucose),
  345. noise: nil,
  346. glucose: Int(result.glucose)
  347. )
  348. }
  349. }
  350. }
  351. // Fetch manual glucose that is not uploaded to Nightscout yet
  352. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  353. func getManualGlucoseNotYetUploadedToHealth() async -> [BloodGlucose] {
  354. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  355. ofType: GlucoseStored.self,
  356. onContext: coredataContext,
  357. predicate: NSPredicate.manualGlucoseNotYetUploadedToHealth,
  358. key: "date",
  359. ascending: false,
  360. fetchLimit: 288
  361. )
  362. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  363. return await coredataContext.perform {
  364. return fetchedResults.map { result in
  365. BloodGlucose(
  366. _id: result.id?.uuidString ?? UUID().uuidString,
  367. sgv: Int(result.glucose),
  368. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  369. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  370. dateString: result.date ?? Date(),
  371. unfiltered: Decimal(result.glucose),
  372. filtered: Decimal(result.glucose),
  373. noise: nil,
  374. glucose: Int(result.glucose)
  375. )
  376. }
  377. }
  378. }
  379. // Fetch glucose that is not uploaded to Tidepool yet
  380. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for Tidepool upload
  381. func getGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample] {
  382. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  383. ofType: GlucoseStored.self,
  384. onContext: coredataContext,
  385. predicate: NSPredicate.glucoseNotYetUploadedToTidepool,
  386. key: "date",
  387. ascending: false,
  388. fetchLimit: 288
  389. )
  390. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  391. return await coredataContext.perform {
  392. return fetchedResults.map { result in
  393. BloodGlucose(
  394. _id: result.id?.uuidString ?? UUID().uuidString,
  395. sgv: Int(result.glucose),
  396. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  397. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  398. dateString: result.date ?? Date(),
  399. unfiltered: Decimal(result.glucose),
  400. filtered: Decimal(result.glucose),
  401. noise: nil,
  402. glucose: Int(result.glucose)
  403. )
  404. }
  405. .map { $0.convertStoredGlucoseSample(isManualGlucose: false) }
  406. }
  407. }
  408. // Fetch manual glucose that is not uploaded to Tidepool yet
  409. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for the Tidepool upload
  410. func getManualGlucoseNotYetUploadedToTidepool() async -> [StoredGlucoseSample] {
  411. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  412. ofType: GlucoseStored.self,
  413. onContext: coredataContext,
  414. predicate: NSPredicate.manualGlucoseNotYetUploadedToTidepool,
  415. key: "date",
  416. ascending: false,
  417. fetchLimit: 288
  418. )
  419. guard let fetchedResults = results as? [GlucoseStored] else { return [] }
  420. return await coredataContext.perform {
  421. return fetchedResults.map { result in
  422. BloodGlucose(
  423. _id: result.id?.uuidString ?? UUID().uuidString,
  424. sgv: Int(result.glucose),
  425. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  426. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  427. dateString: result.date ?? Date(),
  428. unfiltered: Decimal(result.glucose),
  429. filtered: Decimal(result.glucose),
  430. noise: nil,
  431. glucose: Int(result.glucose)
  432. )
  433. }.map { $0.convertStoredGlucoseSample(isManualGlucose: true) }
  434. }
  435. }
  436. func deleteGlucose(_ treatmentObjectID: NSManagedObjectID) async {
  437. let taskContext = CoreDataStack.shared.newTaskContext()
  438. taskContext.name = "deleteContext"
  439. taskContext.transactionAuthor = "deleteGlucose"
  440. await taskContext.perform {
  441. do {
  442. let result = try taskContext.existingObject(with: treatmentObjectID) as? GlucoseStored
  443. guard let glucoseToDelete = result else {
  444. debugPrint("Data Table State: \(#function) \(DebuggingIdentifiers.failed) glucose not found in core data")
  445. return
  446. }
  447. taskContext.delete(glucoseToDelete)
  448. guard taskContext.hasChanges else { return }
  449. try taskContext.save()
  450. debugPrint("\(#file) \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")
  451. } catch {
  452. debugPrint(
  453. "\(#file) \(#function) \(DebuggingIdentifiers.failed) error while deleting glucose from core data: \(error.localizedDescription)"
  454. )
  455. }
  456. }
  457. }
  458. var alarm: GlucoseAlarm? {
  459. /// glucose can not be older than 20 minutes due to the predicate in the fetch request
  460. coredataContext.performAndWait {
  461. guard let glucose = fetchLatestGlucose() else { return nil }
  462. let glucoseValue = glucose.glucose
  463. if Decimal(glucoseValue) <= settingsManager.settings.lowGlucose {
  464. return .low
  465. }
  466. if Decimal(glucoseValue) >= settingsManager.settings.highGlucose {
  467. return .high
  468. }
  469. return nil
  470. }
  471. }
  472. }
  473. protocol GlucoseObserver {
  474. func glucoseDidUpdate(_ glucose: [BloodGlucose])
  475. }
  476. enum GlucoseAlarm {
  477. case high
  478. case low
  479. var displayName: String {
  480. switch self {
  481. case .high:
  482. return NSLocalizedString("LOWALERT!", comment: "LOWALERT!")
  483. case .low:
  484. return NSLocalizedString("HIGHALERT!", comment: "HIGHALERT!")
  485. }
  486. }
  487. }