GlucoseStorage.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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]) async throws
  12. func backfillGlucose(_ glucose: [BloodGlucose]) async throws
  13. func addManualGlucose(glucose: Int)
  14. func isGlucoseDataFresh(_ glucoseDate: Date?) -> Bool
  15. func syncDate() -> Date
  16. func filterTooFrequentGlucose(_ glucose: [BloodGlucose], at: Date) -> [BloodGlucose]
  17. func lastGlucoseDate() -> Date?
  18. func isGlucoseFresh() -> Bool
  19. func getGlucoseNotYetUploadedToNightscout() async throws -> [BloodGlucose]
  20. func getCGMStateNotYetUploadedToNightscout() async throws -> [NightscoutTreatment]
  21. func getManualGlucoseNotYetUploadedToNightscout() async throws -> [NightscoutTreatment]
  22. func getGlucoseNotYetUploadedToHealth() async throws -> [BloodGlucose]
  23. func getManualGlucoseNotYetUploadedToHealth() async throws -> [BloodGlucose]
  24. func getGlucoseNotYetUploadedToTidepool() async throws -> [StoredGlucoseSample]
  25. func getManualGlucoseNotYetUploadedToTidepool() async throws -> [StoredGlucoseSample]
  26. var alarm: GlucoseAlarm? { get }
  27. func deleteGlucose(_ treatmentObjectID: NSManagedObjectID) async
  28. }
  29. final class BaseGlucoseStorage: GlucoseStorage, Injectable {
  30. private let processQueue = DispatchQueue(label: "BaseGlucoseStorage.processQueue")
  31. @Injected() private var storage: FileStorage!
  32. @Injected() private var broadcaster: Broadcaster!
  33. @Injected() private var settingsManager: SettingsManager!
  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. private let context: NSManagedObjectContext
  42. init(resolver: Resolver, context: NSManagedObjectContext? = nil) {
  43. self.context = context ?? CoreDataStack.shared.newTaskContext()
  44. injectServices(resolver)
  45. }
  46. private var glucoseFormatter: NumberFormatter {
  47. let formatter = NumberFormatter()
  48. formatter.numberStyle = .decimal
  49. formatter.maximumFractionDigits = 0
  50. if settingsManager.settings.units == .mmolL {
  51. formatter.maximumFractionDigits = 1
  52. }
  53. formatter.decimalSeparator = "."
  54. return formatter
  55. }
  56. /// Backfills glucose values and stores in CoreData
  57. ///
  58. /// CGM managers will sometimes backfill glucose readings. To handle these backfilled values
  59. /// correctly, we need some logic to handle a few cases:
  60. /// - _Not_ adding back previously deleted glucose
  61. /// - Avoiding duplicate values for the same reading
  62. /// - Avoiding overlapping glucose readings when switching sources
  63. /// Of these corner cases, overlapping glucose readings when switching sources is both
  64. /// the most challenging and most rare since it would happen if wearing two devices and
  65. /// switching or moving from direct glucose handling to xdrip. It's not worth the complexity
  66. /// to deal with source switching perfectly, so instead we will backfill glucose if and only if
  67. /// it isn't within 3.5 minutes of an existing glucose reading, which is simple but not perfect.
  68. /// But since this is a corner case that really shouldn't happen often, it's good enough.
  69. func backfillGlucose(_ glucose: [BloodGlucose]) async throws {
  70. try await context.perform {
  71. // remove already deleted glucose values
  72. let withoutDeletedGlucose = self.filterGlucoseValues(
  73. glucose,
  74. fetchRequest: DeletedGlucoseStored.fetchRequest(),
  75. timeBuffer: 1
  76. )
  77. // check for a 3.5 minute difference between existing values
  78. let filteredGlucose = self.filterGlucoseValues(
  79. withoutDeletedGlucose,
  80. fetchRequest: GlucoseStored.fetchRequest(),
  81. timeBuffer: 3.5 * 60
  82. )
  83. guard !filteredGlucose.isEmpty else { return }
  84. do {
  85. // Store glucose values in Core Data
  86. try self.storeGlucoseInCoreData(filteredGlucose)
  87. } catch {
  88. throw CoreDataError.creationError(
  89. function: #function,
  90. file: #fileID
  91. )
  92. }
  93. }
  94. }
  95. func storeGlucose(_ glucose: [BloodGlucose]) async throws {
  96. try await context.perform {
  97. // Get new glucose values that don't exist yet
  98. let newGlucose = self.filterGlucoseValues(glucose, fetchRequest: GlucoseStored.fetchRequest(), timeBuffer: 1)
  99. guard !newGlucose.isEmpty else { return }
  100. do {
  101. // Store glucose values in Core Data
  102. try self.storeGlucoseInCoreData(newGlucose)
  103. } catch {
  104. throw CoreDataError.creationError(
  105. function: #function,
  106. file: #fileID
  107. )
  108. }
  109. // Store CGM state if needed
  110. self.storeCGMState(glucose)
  111. }
  112. }
  113. /// filter out duplicate CGM readings using matching timestamps
  114. ///
  115. /// This function will fetch dates from the `fetchRequest` and remove any glucose
  116. /// values that are within `timeBuffer` of the fetched dates. This logic is useful for
  117. /// deduplication checks or removing deleted CGM values from a list of backfilled readings.
  118. private func filterGlucoseValues(
  119. _ glucose: [BloodGlucose],
  120. fetchRequest: NSFetchRequest<NSFetchRequestResult>,
  121. timeBuffer: TimeInterval
  122. ) -> [BloodGlucose] {
  123. let datesToCheck = glucose.map(\.dateString).sorted()
  124. guard let firstDate = datesToCheck.first.map({ $0.addingTimeInterval(-timeBuffer) }),
  125. let lastDate = datesToCheck.last.map({ $0.addingTimeInterval(timeBuffer) })
  126. else {
  127. return glucose
  128. }
  129. fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [
  130. NSPredicate(format: "date >= %@", firstDate as NSDate),
  131. NSPredicate(format: "date <= %@", lastDate as NSDate)
  132. ])
  133. fetchRequest.propertiesToFetch = ["date"]
  134. fetchRequest.resultType = .dictionaryResultType
  135. var existingDates = [Date]()
  136. do {
  137. let results = try context.fetch(fetchRequest) as? [NSDictionary]
  138. existingDates = results?.compactMap({ $0["date"] as? Date }) ?? []
  139. } catch {
  140. debugPrint("Failed to fetch existing glucose dates: \(error)")
  141. }
  142. // This is an inefficient filtering algorithm, but I'm assuming that the
  143. // time spans are short and that duplicates are rare, so in the common
  144. // case there won't be any existing dates.
  145. return glucose.filter { glucose in
  146. for existingDate in existingDates {
  147. let difference = abs(existingDate.timeIntervalSince(glucose.dateString))
  148. if difference <= timeBuffer {
  149. return false
  150. }
  151. }
  152. return true
  153. }
  154. }
  155. private func storeGlucoseInCoreData(_ glucose: [BloodGlucose]) throws {
  156. if glucose.count > 1 {
  157. try storeGlucoseBatch(glucose)
  158. } else {
  159. try storeGlucoseRegular(glucose)
  160. }
  161. }
  162. private func storeGlucoseRegular(_ glucose: [BloodGlucose]) throws {
  163. for entry in glucose {
  164. let glucoseEntry = GlucoseStored(context: context)
  165. configureGlucoseEntry(glucoseEntry, with: entry)
  166. }
  167. guard context.hasChanges else { return }
  168. try context.save()
  169. }
  170. private func storeGlucoseBatch(_ glucose: [BloodGlucose]) throws {
  171. var remainingGlucose = glucose
  172. let batchInsert = NSBatchInsertRequest(
  173. entity: GlucoseStored.entity(),
  174. managedObjectHandler: { (managedObject: NSManagedObject) -> Bool in
  175. guard let glucoseEntry = managedObject as? GlucoseStored,
  176. !remainingGlucose.isEmpty
  177. else {
  178. return true
  179. }
  180. let entry = remainingGlucose.removeFirst()
  181. self.configureGlucoseEntry(glucoseEntry, with: entry)
  182. return false
  183. }
  184. )
  185. try context.execute(batchInsert)
  186. // Only send update for batch insert since regular save triggers CoreData notifications
  187. updateSubject.send()
  188. }
  189. private func configureGlucoseEntry(_ entry: GlucoseStored, with glucose: BloodGlucose) {
  190. entry.id = UUID()
  191. entry.glucose = Int16(glucose.glucose ?? 0)
  192. entry.date = glucose.dateString
  193. entry.direction = glucose.direction?.rawValue
  194. entry.isUploadedToNS = false
  195. entry.isUploadedToHealth = false
  196. entry.isUploadedToTidepool = false
  197. }
  198. private func storeCGMState(_ glucose: [BloodGlucose]) {
  199. debug(.deviceManager, "start storage cgmState")
  200. storage.transaction { storage in
  201. let file = OpenAPS.Monitor.cgmState
  202. var treatments = storage.retrieve(file, as: [NightscoutTreatment].self) ?? []
  203. var updated = false
  204. for x in glucose {
  205. guard let sessionStartDate = x.sessionStartDate else { continue }
  206. // Skip if we already have a recent treatment
  207. if let lastTreatment = treatments.last,
  208. let createdAt = lastTreatment.createdAt,
  209. abs(createdAt.timeIntervalSince(sessionStartDate)) < TimeInterval(60)
  210. {
  211. continue
  212. }
  213. let notes = createCGMStateNotes(transmitterID: x.transmitterID, activationDate: x.activationDate)
  214. let treatment = createCGMStateTreatment(sessionStartDate: sessionStartDate, notes: notes)
  215. debug(.deviceManager, "CGM sensor change \(treatment)")
  216. treatments.append(treatment)
  217. updated = true
  218. }
  219. if updated {
  220. storage.save(
  221. treatments.filter { $0.createdAt?.addingTimeInterval(30.days.timeInterval) ?? .distantPast > Date() },
  222. as: file
  223. )
  224. }
  225. }
  226. }
  227. private func createCGMStateNotes(transmitterID: String?, activationDate: Date?) -> String {
  228. var notes = ""
  229. if let t = transmitterID {
  230. notes = t
  231. }
  232. if let a = activationDate {
  233. notes = "\(notes) activated on \(a)"
  234. }
  235. return notes
  236. }
  237. private func createCGMStateTreatment(sessionStartDate: Date, notes: String) -> NightscoutTreatment {
  238. NightscoutTreatment(
  239. duration: nil,
  240. rawDuration: nil,
  241. rawRate: nil,
  242. absolute: nil,
  243. rate: nil,
  244. eventType: .nsSensorChange,
  245. createdAt: sessionStartDate,
  246. enteredBy: NightscoutTreatment.local,
  247. bolus: nil,
  248. insulin: nil,
  249. notes: notes,
  250. carbs: nil,
  251. fat: nil,
  252. protein: nil,
  253. targetTop: nil,
  254. targetBottom: nil
  255. )
  256. }
  257. func addManualGlucose(glucose: Int) {
  258. context.perform {
  259. let newItem = GlucoseStored(context: self.context)
  260. newItem.id = UUID()
  261. newItem.date = Date()
  262. newItem.glucose = Int16(glucose)
  263. newItem.isManual = true
  264. newItem.isUploadedToNS = false
  265. newItem.isUploadedToHealth = false
  266. newItem.isUploadedToTidepool = false
  267. do {
  268. guard self.context.hasChanges else { return }
  269. try self.context.save()
  270. // Glucose subscribers already listen to the update publisher, so call here to update glucose-related data.
  271. self.updateSubject.send()
  272. } catch let error as NSError {
  273. debugPrint(
  274. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save manual glucose to Core Data with error: \(error)"
  275. )
  276. }
  277. }
  278. }
  279. func isGlucoseDataFresh(_ glucoseDate: Date?) -> Bool {
  280. guard let glucoseDate = glucoseDate else { return false }
  281. return glucoseDate > Date().addingTimeInterval(-6 * 60)
  282. }
  283. func syncDate() -> Date {
  284. // Optimize fetch request to only get the date
  285. let taskContext = CoreDataStack.shared.newTaskContext()
  286. let fr = NSFetchRequest<NSDictionary>(entityName: "GlucoseStored")
  287. fr.predicate = NSPredicate.predicateForOneDayAgo
  288. fr.propertiesToFetch = ["date"]
  289. fr.fetchLimit = 1
  290. fr.resultType = .dictionaryResultType
  291. fr.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
  292. var fetchedDate: Date = .distantPast
  293. taskContext.performAndWait {
  294. do {
  295. if let result = try taskContext.fetch(fr).first,
  296. let date = result["date"] as? Date
  297. {
  298. fetchedDate = date
  299. }
  300. } catch {
  301. debugPrint("Fetch error: \(DebuggingIdentifiers.failed) \(error)")
  302. }
  303. }
  304. return fetchedDate
  305. }
  306. func lastGlucoseDate() -> Date? {
  307. let fetchRequest = GlucoseStored.fetchRequest()
  308. fetchRequest.predicate = NSPredicate.predicateForOneDayAgo
  309. fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \GlucoseStored.date, ascending: false)]
  310. fetchRequest.fetchLimit = 1
  311. var date: Date?
  312. context.performAndWait {
  313. do {
  314. let results = try self.context.fetch(fetchRequest)
  315. date = results.first?.date
  316. } catch let error as NSError {
  317. debug(.storage, "Fetch error: \(DebuggingIdentifiers.failed) \(error), \(error.userInfo)")
  318. }
  319. }
  320. return date
  321. }
  322. func isGlucoseFresh() -> Bool {
  323. Date().timeIntervalSince(lastGlucoseDate() ?? .distantPast) <= Config.filterTime
  324. }
  325. func filterTooFrequentGlucose(_ glucose: [BloodGlucose], at date: Date) -> [BloodGlucose] {
  326. var lastDate = date
  327. var filtered: [BloodGlucose] = []
  328. let sorted = glucose.sorted { $0.date < $1.date }
  329. for entry in sorted {
  330. guard entry.dateString.addingTimeInterval(-Config.filterTime) > lastDate else {
  331. continue
  332. }
  333. filtered.append(entry)
  334. lastDate = entry.dateString
  335. }
  336. return filtered
  337. }
  338. func fetchLatestGlucose() throws -> GlucoseStored? {
  339. let predicate = NSPredicate.predicateFor20MinAgo
  340. return (try CoreDataStack.shared.fetchEntities(
  341. ofType: GlucoseStored.self,
  342. onContext: context,
  343. predicate: predicate,
  344. key: "date",
  345. ascending: false,
  346. fetchLimit: 1
  347. ) as? [GlucoseStored] ?? []).first
  348. }
  349. // Fetch glucose that is not uploaded to Nightscout yet
  350. /// - Returns: Array of BloodGlucose to ensure the correct format for the NS Upload
  351. func getGlucoseNotYetUploadedToNightscout() async throws -> [BloodGlucose] {
  352. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  353. ofType: GlucoseStored.self,
  354. onContext: context,
  355. predicate: NSPredicate.glucoseNotYetUploadedToNightscout,
  356. key: "date",
  357. ascending: false
  358. )
  359. return try await context.perform {
  360. guard let fetchedResults = results as? [GlucoseStored] else {
  361. throw CoreDataError.fetchError(function: #function, file: #file)
  362. }
  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. type: "sgv"
  375. )
  376. }
  377. }
  378. }
  379. // Fetch manual glucose that is not uploaded to Nightscout yet
  380. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  381. func getManualGlucoseNotYetUploadedToNightscout() async throws -> [NightscoutTreatment] {
  382. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  383. ofType: GlucoseStored.self,
  384. onContext: context,
  385. predicate: NSPredicate.manualGlucoseNotYetUploadedToNightscout,
  386. key: "date",
  387. ascending: false
  388. )
  389. return try await context.perform {
  390. guard let fetchedResults = results as? [GlucoseStored] else {
  391. throw CoreDataError.fetchError(function: #function, file: #file)
  392. }
  393. return fetchedResults.map { result in
  394. NightscoutTreatment(
  395. duration: nil,
  396. rawDuration: nil,
  397. rawRate: nil,
  398. absolute: nil,
  399. rate: nil,
  400. eventType: .capillaryGlucose,
  401. createdAt: result.date,
  402. enteredBy: CarbsEntry.local,
  403. bolus: nil,
  404. insulin: nil,
  405. notes: "Trio User",
  406. carbs: nil,
  407. fat: nil,
  408. protein: nil,
  409. foodType: nil,
  410. targetTop: nil,
  411. targetBottom: nil,
  412. glucoseType: "Manual",
  413. glucose: self.settingsManager.settings
  414. .units == .mgdL ? (self.glucoseFormatter.string(from: Int(result.glucose) as NSNumber) ?? "")
  415. : (self.glucoseFormatter.string(from: Decimal(result.glucose).asMmolL as NSNumber) ?? ""),
  416. units: self.settingsManager.settings.units == .mmolL ? "mmol" : "mg/dl",
  417. id: result.id?.uuidString
  418. )
  419. }
  420. }
  421. }
  422. func getCGMStateNotYetUploadedToNightscout() async -> [NightscoutTreatment] {
  423. async let alreadyUploaded: [NightscoutTreatment] = storage
  424. .retrieveAsync(OpenAPS.Nightscout.uploadedCGMState, as: [NightscoutTreatment].self) ?? []
  425. async let allValues: [NightscoutTreatment] = storage
  426. .retrieveAsync(OpenAPS.Monitor.cgmState, as: [NightscoutTreatment].self) ?? []
  427. let (alreadyUploadedValues, allValuesSet) = await (alreadyUploaded, allValues)
  428. return Array(Set(allValuesSet).subtracting(Set(alreadyUploadedValues)))
  429. }
  430. // Fetch glucose that is not uploaded to Nightscout yet
  431. /// - Returns: Array of BloodGlucose to ensure the correct format for the NS Upload
  432. func getGlucoseNotYetUploadedToHealth() async throws -> [BloodGlucose] {
  433. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  434. ofType: GlucoseStored.self,
  435. onContext: context,
  436. predicate: NSPredicate.glucoseNotYetUploadedToHealth,
  437. key: "date",
  438. ascending: false
  439. )
  440. return try await context.perform {
  441. guard let fetchedResults = results as? [GlucoseStored] else {
  442. throw CoreDataError.fetchError(function: #function, file: #file)
  443. }
  444. return fetchedResults.map { result in
  445. BloodGlucose(
  446. id: result.id?.uuidString ?? UUID().uuidString,
  447. sgv: Int(result.glucose),
  448. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  449. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  450. dateString: result.date ?? Date(),
  451. unfiltered: Decimal(result.glucose),
  452. filtered: Decimal(result.glucose),
  453. noise: nil,
  454. glucose: Int(result.glucose)
  455. )
  456. }
  457. }
  458. }
  459. // Fetch manual glucose that is not uploaded to Nightscout yet
  460. /// - Returns: Array of NightscoutTreatment to ensure the correct format for the NS Upload
  461. func getManualGlucoseNotYetUploadedToHealth() async throws -> [BloodGlucose] {
  462. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  463. ofType: GlucoseStored.self,
  464. onContext: context,
  465. predicate: NSPredicate.manualGlucoseNotYetUploadedToHealth,
  466. key: "date",
  467. ascending: false
  468. )
  469. return try await context.perform {
  470. guard let fetchedResults = results as? [GlucoseStored] else {
  471. throw CoreDataError.fetchError(function: #function, file: #file)
  472. }
  473. return fetchedResults.map { result in
  474. BloodGlucose(
  475. id: result.id?.uuidString ?? UUID().uuidString,
  476. sgv: Int(result.glucose),
  477. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  478. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  479. dateString: result.date ?? Date(),
  480. unfiltered: Decimal(result.glucose),
  481. filtered: Decimal(result.glucose),
  482. noise: nil,
  483. glucose: Int(result.glucose)
  484. )
  485. }
  486. }
  487. }
  488. // Fetch glucose that is not uploaded to Tidepool yet
  489. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for Tidepool upload
  490. func getGlucoseNotYetUploadedToTidepool() async throws -> [StoredGlucoseSample] {
  491. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  492. ofType: GlucoseStored.self,
  493. onContext: context,
  494. predicate: NSPredicate.glucoseNotYetUploadedToTidepool,
  495. key: "date",
  496. ascending: false
  497. )
  498. return try await context.perform {
  499. guard let fetchedResults = results as? [GlucoseStored] else {
  500. throw CoreDataError.fetchError(function: #function, file: #file)
  501. }
  502. return fetchedResults.map { result in
  503. BloodGlucose(
  504. id: result.id?.uuidString ?? UUID().uuidString,
  505. sgv: Int(result.glucose),
  506. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  507. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  508. dateString: result.date ?? Date(),
  509. unfiltered: Decimal(result.glucose),
  510. filtered: Decimal(result.glucose),
  511. noise: nil,
  512. glucose: Int(result.glucose)
  513. )
  514. }
  515. .map { $0.convertStoredGlucoseSample(isManualGlucose: false) }
  516. }
  517. }
  518. // Fetch manual glucose that is not uploaded to Tidepool yet
  519. /// - Returns: Array of StoredGlucoseSample to ensure the correct format for the Tidepool upload
  520. func getManualGlucoseNotYetUploadedToTidepool() async throws -> [StoredGlucoseSample] {
  521. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  522. ofType: GlucoseStored.self,
  523. onContext: context,
  524. predicate: NSPredicate.manualGlucoseNotYetUploadedToTidepool,
  525. key: "date",
  526. ascending: false
  527. )
  528. return try await context.perform {
  529. guard let fetchedResults = results as? [GlucoseStored] else {
  530. throw CoreDataError.fetchError(function: #function, file: #file)
  531. }
  532. return fetchedResults.map { result in
  533. BloodGlucose(
  534. id: result.id?.uuidString ?? UUID().uuidString,
  535. sgv: Int(result.glucose),
  536. direction: BloodGlucose.Direction(from: result.direction ?? ""),
  537. date: Decimal(result.date?.timeIntervalSince1970 ?? Date().timeIntervalSince1970) * 1000,
  538. dateString: result.date ?? Date(),
  539. unfiltered: Decimal(result.glucose),
  540. filtered: Decimal(result.glucose),
  541. noise: nil,
  542. glucose: Int(result.glucose)
  543. )
  544. }.map { $0.convertStoredGlucoseSample(isManualGlucose: true) }
  545. }
  546. }
  547. func deleteGlucose(_ treatmentObjectID: NSManagedObjectID) async {
  548. // Use injected context if available, otherwise create new task context
  549. let taskContext = context != CoreDataStack.shared.newTaskContext()
  550. ? context
  551. : CoreDataStack.shared.newTaskContext()
  552. taskContext.name = "deleteContext"
  553. taskContext.transactionAuthor = "deleteGlucose"
  554. await taskContext.perform {
  555. do {
  556. let result = try taskContext.existingObject(with: treatmentObjectID) as? GlucoseStored
  557. guard let glucoseToDelete = result else {
  558. debugPrint("Data Table State: \(#function) \(DebuggingIdentifiers.failed) glucose not found in core data")
  559. return
  560. }
  561. // Create a new DeletedGlucoseStored object and copy the properties
  562. if let date = glucoseToDelete.date {
  563. let deletedEntry = DeletedGlucoseStored(context: taskContext)
  564. deletedEntry.date = date
  565. deletedEntry.glucose = glucoseToDelete.glucose
  566. deletedEntry.isManualGlucoseEntry = glucoseToDelete.isManual
  567. }
  568. taskContext.delete(glucoseToDelete)
  569. guard taskContext.hasChanges else { return }
  570. try taskContext.save()
  571. debugPrint("\(#file) \(#function) \(DebuggingIdentifiers.succeeded) deleted glucose from core data")
  572. } catch {
  573. debugPrint(
  574. "\(#file) \(#function) \(DebuggingIdentifiers.failed) error while deleting glucose from core data: \(error)"
  575. )
  576. }
  577. }
  578. }
  579. var alarm: GlucoseAlarm? {
  580. /// glucose can not be older than 20 minutes due to the predicate in the fetch request
  581. context.performAndWait {
  582. do {
  583. guard let glucose = try fetchLatestGlucose() else { return nil }
  584. let glucoseValue = glucose.glucose
  585. if Decimal(glucoseValue) <= settingsManager.settings.lowGlucose {
  586. return .low
  587. }
  588. if Decimal(glucoseValue) >= settingsManager.settings.highGlucose {
  589. return .high
  590. }
  591. return nil
  592. } catch {
  593. debugPrint("Error fetching latest glucose: \(error)")
  594. return nil
  595. }
  596. }
  597. }
  598. }
  599. protocol GlucoseObserver {
  600. func glucoseDidUpdate(_ glucose: [BloodGlucose])
  601. }
  602. enum GlucoseAlarm {
  603. case high
  604. case low
  605. var displayName: String {
  606. switch self {
  607. case .high:
  608. return String(localized: "LOWALERT!", comment: "LOWALERT!")
  609. case .low:
  610. return String(localized: "HIGHALERT!", comment: "HIGHALERT!")
  611. }
  612. }
  613. }