TidepoolManager.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import HealthKit
  5. import LoopKit
  6. import LoopKitUI
  7. import Swinject
  8. protocol TidepoolManager {
  9. func addTidepoolService(service: Service)
  10. func getTidepoolServiceUI() -> ServiceUI?
  11. func getTidepoolPluginHost() -> PluginHost?
  12. func uploadCarbs() async
  13. func deleteCarbs(withSyncId id: UUID, carbs: Decimal, at: Date, enteredBy: String)
  14. func uploadInsulin() async
  15. func deleteInsulin(withSyncId id: String, amount: Decimal, at: Date)
  16. func uploadGlucose() async
  17. func forceTidepoolDataUpload()
  18. }
  19. final class BaseTidepoolManager: TidepoolManager, Injectable {
  20. @Injected() private var broadcaster: Broadcaster!
  21. @Injected() private var pluginManager: PluginManager!
  22. @Injected() private var glucoseStorage: GlucoseStorage!
  23. @Injected() private var carbsStorage: CarbsStorage!
  24. @Injected() private var storage: FileStorage!
  25. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  26. @Injected() private var apsManager: APSManager!
  27. private let processQueue = DispatchQueue(label: "BaseNetworkManager.processQueue")
  28. private var tidepoolService: RemoteDataService? {
  29. didSet {
  30. if let tidepoolService = tidepoolService {
  31. rawTidepoolManager = tidepoolService.rawValue
  32. } else {
  33. rawTidepoolManager = nil
  34. }
  35. }
  36. }
  37. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  38. // Queue for handling Core Data change notifications
  39. private let queue = DispatchQueue(label: "BaseTidepoolManager.queue", qos: .background)
  40. private var coreDataPublisher: AnyPublisher<Set<NSManagedObjectID>, Never>?
  41. private var subscriptions = Set<AnyCancellable>()
  42. @PersistedProperty(key: "TidepoolState") var rawTidepoolManager: Service.RawValue?
  43. init(resolver: Resolver) {
  44. injectServices(resolver)
  45. loadTidepoolManager()
  46. coreDataPublisher =
  47. changedObjectsOnManagedObjectContextDidSavePublisher()
  48. .receive(on: queue)
  49. .share()
  50. .eraseToAnyPublisher()
  51. glucoseStorage.updatePublisher
  52. .receive(on: DispatchQueue.global(qos: .background))
  53. .sink { [weak self] _ in
  54. guard let self = self else { return }
  55. Task {
  56. await self.uploadGlucose()
  57. }
  58. }
  59. .store(in: &subscriptions)
  60. registerHandlers()
  61. }
  62. /// Loads the Tidepool service from saved state
  63. fileprivate func loadTidepoolManager() {
  64. if let rawTidepoolManager = rawTidepoolManager {
  65. tidepoolService = tidepoolServiceFromRaw(rawTidepoolManager)
  66. tidepoolService?.serviceDelegate = self
  67. tidepoolService?.stateDelegate = self
  68. }
  69. }
  70. /// Returns the Tidepool service UI if available
  71. func getTidepoolServiceUI() -> ServiceUI? {
  72. tidepoolService as? ServiceUI
  73. }
  74. /// Returns the Tidepool plugin host
  75. func getTidepoolPluginHost() -> PluginHost? {
  76. self as PluginHost
  77. }
  78. /// Adds a Tidepool service
  79. func addTidepoolService(service: Service) {
  80. tidepoolService = service as? RemoteDataService
  81. }
  82. /// Loads the Tidepool service from raw stored data
  83. private func tidepoolServiceFromRaw(_ rawValue: [String: Any]) -> RemoteDataService? {
  84. guard let rawState = rawValue["state"] as? Service.RawStateValue,
  85. let serviceType = pluginManager.getServiceTypeByIdentifier("TidepoolService")
  86. else { return nil }
  87. if let service = serviceType.init(rawState: rawState) {
  88. return service as? RemoteDataService
  89. }
  90. return nil
  91. }
  92. /// Registers handlers for Core Data changes
  93. private func registerHandlers() {
  94. coreDataPublisher?.filteredByEntityName("PumpEventStored").sink { [weak self] _ in
  95. guard let self = self else { return }
  96. Task { [weak self] in
  97. guard let self = self else { return }
  98. await self.uploadInsulin()
  99. }
  100. }.store(in: &subscriptions)
  101. coreDataPublisher?.filteredByEntityName("CarbEntryStored").sink { [weak self] _ in
  102. guard let self = self else { return }
  103. Task { [weak self] in
  104. guard let self = self else { return }
  105. await self.uploadCarbs()
  106. }
  107. }.store(in: &subscriptions)
  108. // This works only for manual Glucose
  109. coreDataPublisher?.filteredByEntityName("GlucoseStored").sink { [weak self] _ in
  110. guard let self = self else { return }
  111. Task { [weak self] in
  112. guard let self = self else { return }
  113. await self.uploadGlucose()
  114. }
  115. }.store(in: &subscriptions)
  116. }
  117. func sourceInfo() -> [String: Any]? {
  118. nil
  119. }
  120. /// Forces a full data upload to Tidepool
  121. func forceTidepoolDataUpload() {
  122. Task {
  123. await uploadInsulin()
  124. await uploadCarbs()
  125. await uploadGlucose()
  126. }
  127. }
  128. }
  129. extension BaseTidepoolManager: ServiceDelegate {
  130. var hostIdentifier: String {
  131. // TODO: shouldn't this rather be `org.nightscout.Trio` ?
  132. "com.loopkit.Loop" // To check
  133. }
  134. var hostVersion: String {
  135. var semanticVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
  136. while semanticVersion.split(separator: ".").count < 3 {
  137. semanticVersion += ".0"
  138. }
  139. semanticVersion += "+\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String)"
  140. return semanticVersion
  141. }
  142. func issueAlert(_: LoopKit.Alert) {}
  143. func retractAlert(identifier _: LoopKit.Alert.Identifier) {}
  144. func enactRemoteOverride(name _: String, durationTime _: TimeInterval?, remoteAddress _: String) async throws {}
  145. func cancelRemoteOverride() async throws {}
  146. func deliverRemoteCarbs(
  147. amountInGrams _: Double,
  148. absorptionTime _: TimeInterval?,
  149. foodType _: String?,
  150. startDate _: Date?
  151. ) async throws {}
  152. func deliverRemoteBolus(amountInUnits _: Double) async throws {}
  153. }
  154. /// Carb Upload and Deletion Functionality
  155. extension BaseTidepoolManager {
  156. func uploadCarbs() async {
  157. do {
  158. try uploadCarbs(await carbsStorage.getCarbsNotYetUploadedToTidepool())
  159. } catch {
  160. debug(.service, "\(DebuggingIdentifiers.failed) Failed to upload carbs with error: \(error.localizedDescription)")
  161. }
  162. }
  163. func uploadCarbs(_ carbs: [CarbsEntry]) {
  164. guard !carbs.isEmpty, let tidepoolService = self.tidepoolService else { return }
  165. processQueue.async {
  166. carbs.chunks(ofCount: tidepoolService.carbDataLimit ?? 100).forEach { chunk in
  167. let syncCarb: [SyncCarbObject] = Array(chunk).map {
  168. $0.convertSyncCarb()
  169. }
  170. tidepoolService.uploadCarbData(created: syncCarb, updated: [], deleted: []) { result in
  171. switch result {
  172. case let .failure(error):
  173. debug(.nightscout, "Error synchronizing carbs data with Tidepool: \(String(describing: error))")
  174. case .success:
  175. debug(.nightscout, "Success synchronizing carbs data. Upload to Tidepool complete.")
  176. // After successful upload, update the isUploadedToTidepool flag in Core Data
  177. Task {
  178. await self.updateCarbsAsUploaded(carbs)
  179. }
  180. }
  181. }
  182. }
  183. }
  184. }
  185. private func updateCarbsAsUploaded(_ carbs: [CarbsEntry]) async {
  186. await backgroundContext.perform {
  187. let ids = carbs.map(\.id) as NSArray
  188. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  189. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  190. do {
  191. let results = try self.backgroundContext.fetch(fetchRequest)
  192. for result in results {
  193. result.isUploadedToTidepool = true
  194. }
  195. guard self.backgroundContext.hasChanges else { return }
  196. try self.backgroundContext.save()
  197. } catch let error as NSError {
  198. debugPrint(
  199. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToTidepool: \(error.userInfo)"
  200. )
  201. }
  202. }
  203. }
  204. func deleteCarbs(withSyncId id: UUID, carbs: Decimal, at: Date, enteredBy: String) {
  205. guard let tidepoolService = self.tidepoolService else { return }
  206. processQueue.async {
  207. let syncCarb: [SyncCarbObject] = [SyncCarbObject(
  208. absorptionTime: nil,
  209. createdByCurrentApp: true,
  210. foodType: nil,
  211. grams: Double(carbs),
  212. startDate: at,
  213. uuid: id,
  214. provenanceIdentifier: enteredBy,
  215. syncIdentifier: id.uuidString,
  216. syncVersion: nil,
  217. userCreatedDate: nil,
  218. userUpdatedDate: nil,
  219. userDeletedDate: nil,
  220. operation: LoopKit.Operation.delete,
  221. addedDate: nil,
  222. supercededDate: nil
  223. )]
  224. tidepoolService.uploadCarbData(created: [], updated: [], deleted: syncCarb) { result in
  225. switch result {
  226. case let .failure(error):
  227. debug(.nightscout, "Error synchronizing carbs data with Tidepool: \(String(describing: error))")
  228. case .success:
  229. debug(.nightscout, "Success synchronizing carbs data. Upload to Tidepool complete.")
  230. }
  231. }
  232. }
  233. }
  234. }
  235. /// Insulin Upload and Deletion Functionality
  236. extension BaseTidepoolManager {
  237. func uploadInsulin() async {
  238. do {
  239. let events = try await pumpHistoryStorage.getPumpHistoryNotYetUploadedToTidepool()
  240. await uploadDose(events)
  241. } catch {
  242. debug(.service, "Error fetching pump history: \(error.localizedDescription)")
  243. }
  244. }
  245. func uploadDose(_ events: [PumpHistoryEvent]) async {
  246. guard !events.isEmpty, let tidepoolService = self.tidepoolService else { return }
  247. do {
  248. // Fetch all temp basal entries from Core Data for the last 24 hours
  249. let results = try await CoreDataStack.shared.fetchEntitiesAsync(
  250. ofType: PumpEventStored.self,
  251. onContext: backgroundContext,
  252. predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [
  253. NSPredicate.pumpHistoryLast24h,
  254. NSPredicate(format: "tempBasal != nil")
  255. ]),
  256. key: "timestamp",
  257. ascending: true,
  258. batchSize: 50
  259. )
  260. // Ensure that the processing happens within the background context for thread safety
  261. try await backgroundContext.perform {
  262. guard let existingTempBasalEntries = results as? [PumpEventStored] else {
  263. throw CoreDataError.fetchError(function: #function, file: #file)
  264. }
  265. let insulinDoseEvents: [DoseEntry] = events.reduce([]) { result, event in
  266. var result = result
  267. switch event.type {
  268. case .tempBasal:
  269. result
  270. .append(
  271. contentsOf: self
  272. .processTempBasalEvent(event, existingTempBasalEntries: existingTempBasalEntries)
  273. )
  274. case .bolus:
  275. let bolusDoseEntry = DoseEntry(
  276. type: .bolus,
  277. startDate: event.timestamp,
  278. endDate: event.timestamp,
  279. value: Double(event.amount!),
  280. unit: .units,
  281. deliveredUnits: nil,
  282. syncIdentifier: event.id,
  283. scheduledBasalRate: nil,
  284. insulinType: self.apsManager.pumpManager?.status.insulinType ?? nil,
  285. automatic: event.isSMB ?? true,
  286. manuallyEntered: event.isExternal ?? false
  287. )
  288. result.append(bolusDoseEntry)
  289. default:
  290. break
  291. }
  292. return result
  293. }
  294. debug(.service, "TIDEPOOL DOSE ENTRIES: \(insulinDoseEvents)")
  295. let pumpEvents: [PersistedPumpEvent] = events.compactMap { event -> PersistedPumpEvent? in
  296. if let pumpEventType = event.type.mapEventTypeToPumpEventType() {
  297. let dose: DoseEntry? = switch pumpEventType {
  298. case .suspend:
  299. DoseEntry(suspendDate: event.timestamp, automatic: true)
  300. case .resume:
  301. DoseEntry(resumeDate: event.timestamp, automatic: true)
  302. default:
  303. nil
  304. }
  305. return PersistedPumpEvent(
  306. date: event.timestamp,
  307. persistedDate: event.timestamp,
  308. dose: dose,
  309. isUploaded: true,
  310. objectIDURL: URL(string: "x-coredata:///PumpEvent/\(event.id)")!,
  311. raw: event.id.data(using: .utf8),
  312. title: event.note,
  313. type: pumpEventType
  314. )
  315. } else {
  316. return nil
  317. }
  318. }
  319. self.processQueue.async {
  320. tidepoolService.uploadDoseData(created: insulinDoseEvents, deleted: []) { result in
  321. switch result {
  322. case let .failure(error):
  323. debug(.nightscout, "Error synchronizing dose data with Tidepool: \(String(describing: error))")
  324. case .success:
  325. debug(.nightscout, "Success synchronizing dose data. Upload to Tidepool complete.")
  326. Task {
  327. let insulinEvents = events.filter {
  328. $0.type == .tempBasal || $0.type == .tempBasalDuration || $0.type == .bolus
  329. }
  330. await self.updateInsulinAsUploaded(insulinEvents)
  331. }
  332. }
  333. }
  334. tidepoolService.uploadPumpEventData(pumpEvents) { result in
  335. switch result {
  336. case let .failure(error):
  337. debug(.nightscout, "Error synchronizing pump events data: \(String(describing: error))")
  338. case .success:
  339. debug(.nightscout, "Success synchronizing pump events data. Upload to Tidepool complete.")
  340. Task {
  341. let pumpEventType = events.map { $0.type.mapEventTypeToPumpEventType() }
  342. let pumpEvents = events.filter { _ in pumpEventType.contains(pumpEventType) }
  343. await self.updateInsulinAsUploaded(pumpEvents)
  344. }
  345. }
  346. }
  347. }
  348. }
  349. } catch {
  350. debug(.service, "Error fetching temp basal entries: \(error.localizedDescription)")
  351. }
  352. }
  353. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  354. await backgroundContext.perform {
  355. let ids = insulin.map(\.id) as NSArray
  356. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  357. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  358. do {
  359. let results = try self.backgroundContext.fetch(fetchRequest)
  360. for result in results {
  361. result.isUploadedToTidepool = true
  362. }
  363. guard self.backgroundContext.hasChanges else { return }
  364. try self.backgroundContext.save()
  365. } catch let error as NSError {
  366. debugPrint(
  367. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToTidepool: \(error.userInfo)"
  368. )
  369. }
  370. }
  371. }
  372. func deleteInsulin(withSyncId id: String, amount: Decimal, at: Date) {
  373. guard let tidepoolService = self.tidepoolService else { return }
  374. // must be an array here, because `tidepoolService.uploadDoseData` expects a `deleted` array
  375. let doseDataToDelete: [DoseEntry] = [DoseEntry(
  376. type: .bolus,
  377. startDate: at,
  378. value: Double(amount),
  379. unit: .units,
  380. syncIdentifier: id
  381. )]
  382. processQueue.async {
  383. tidepoolService.uploadDoseData(created: [], deleted: doseDataToDelete) { result in
  384. switch result {
  385. case let .failure(error):
  386. debug(.nightscout, "Error synchronizing Dose delete data: \(String(describing: error))")
  387. case .success:
  388. debug(.nightscout, "Success synchronizing Dose delete data")
  389. }
  390. }
  391. }
  392. }
  393. }
  394. /// Insulin Helper Functions
  395. extension BaseTidepoolManager {
  396. private func processTempBasalEvent(
  397. _ event: PumpHistoryEvent,
  398. existingTempBasalEntries: [PumpEventStored]
  399. ) -> [DoseEntry] {
  400. var insulinDoseEvents: [DoseEntry] = []
  401. backgroundContext.performAndWait {
  402. // Loop through the pump history events within the background context
  403. guard let duration = event.duration, let amount = event.amount,
  404. let currentBasalRate = self.getCurrentBasalRate()
  405. else {
  406. return
  407. }
  408. let value = (Decimal(duration) / 60.0) * amount
  409. // Find the corresponding temp basal entry in existingTempBasalEntries
  410. if let matchingEntryIndex = existingTempBasalEntries.firstIndex(where: { $0.timestamp == event.timestamp }) {
  411. // Check for a predecessor (the entry before the matching entry)
  412. let predecessorIndex = matchingEntryIndex - 1
  413. if predecessorIndex >= 0 {
  414. let predecessorEntry = existingTempBasalEntries[predecessorIndex]
  415. if let predecessorTimestamp = predecessorEntry.timestamp,
  416. let predecessorEntrySyncIdentifier = predecessorEntry.id
  417. {
  418. let predecessorEndDate = predecessorTimestamp
  419. .addingTimeInterval(TimeInterval(
  420. Int(predecessorEntry.tempBasal?.duration ?? 0) *
  421. 60
  422. )) // parse duration to minutes
  423. // If the predecessor's end date is later than the current event's start date, adjust it
  424. if predecessorEndDate > event.timestamp {
  425. let adjustedEndDate = event.timestamp
  426. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  427. let adjustedDeliveredUnits = (adjustedDuration / 3600) *
  428. Double(truncating: predecessorEntry.tempBasal?.rate ?? 0)
  429. // Create updated predecessor dose entry
  430. let updatedPredecessorEntry = DoseEntry(
  431. type: .tempBasal,
  432. startDate: predecessorTimestamp,
  433. endDate: adjustedEndDate,
  434. value: adjustedDeliveredUnits,
  435. unit: .units,
  436. deliveredUnits: adjustedDeliveredUnits,
  437. syncIdentifier: predecessorEntrySyncIdentifier,
  438. insulinType: self.apsManager.pumpManager?.status.insulinType ?? nil,
  439. automatic: true,
  440. manuallyEntered: false,
  441. isMutable: false
  442. )
  443. // Add the updated predecessor entry to the result
  444. insulinDoseEvents.append(updatedPredecessorEntry)
  445. }
  446. }
  447. }
  448. // Create a new dose entry for the current event
  449. let currentEndDate = event.timestamp.addingTimeInterval(TimeInterval(minutes: Double(duration)))
  450. let newDoseEntry = DoseEntry(
  451. type: .tempBasal,
  452. startDate: event.timestamp,
  453. endDate: currentEndDate,
  454. value: Double(value),
  455. unit: .units,
  456. deliveredUnits: Double(value),
  457. syncIdentifier: event.id,
  458. scheduledBasalRate: HKQuantity(
  459. unit: .internationalUnitsPerHour,
  460. doubleValue: Double(currentBasalRate.rate)
  461. ),
  462. insulinType: self.apsManager.pumpManager?.status.insulinType ?? nil,
  463. automatic: true,
  464. manuallyEntered: false,
  465. isMutable: false
  466. )
  467. // Add the new event entry to the result
  468. insulinDoseEvents.append(newDoseEntry)
  469. }
  470. }
  471. return insulinDoseEvents
  472. }
  473. private func getCurrentBasalRate() -> BasalProfileEntry? {
  474. let now = Date()
  475. let calendar = Calendar.current
  476. let dateFormatter = DateFormatter()
  477. dateFormatter.dateFormat = "HH:mm"
  478. dateFormatter.timeZone = TimeZone.current
  479. let basalEntries = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self)
  480. ?? [BasalProfileEntry](from: OpenAPS.defaults(for: OpenAPS.Settings.basalProfile))
  481. ?? []
  482. var currentRate: BasalProfileEntry = basalEntries[0]
  483. for (index, entry) in basalEntries.enumerated() {
  484. guard let entryTime = dateFormatter.date(from: entry.start) else {
  485. print("Invalid entry start time: \(entry.start)")
  486. continue
  487. }
  488. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  489. let entryStartTime = calendar.date(
  490. bySettingHour: entryComponents.hour!,
  491. minute: entryComponents.minute!,
  492. second: entryComponents.second!,
  493. of: now
  494. )!
  495. let entryEndTime: Date
  496. if index < basalEntries.count - 1,
  497. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  498. {
  499. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  500. entryEndTime = calendar.date(
  501. bySettingHour: nextEntryComponents.hour!,
  502. minute: nextEntryComponents.minute!,
  503. second: nextEntryComponents.second!,
  504. of: now
  505. )!
  506. } else {
  507. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  508. }
  509. if now >= entryStartTime, now < entryEndTime {
  510. currentRate = entry
  511. }
  512. }
  513. return currentRate
  514. }
  515. }
  516. /// Glucose Upload Functionality
  517. extension BaseTidepoolManager {
  518. func uploadGlucose() async {
  519. do {
  520. let glucose = try await glucoseStorage.getGlucoseNotYetUploadedToTidepool()
  521. uploadGlucose(glucose)
  522. let manualGlucose = try await glucoseStorage.getManualGlucoseNotYetUploadedToTidepool()
  523. uploadGlucose(manualGlucose)
  524. } catch {
  525. debug(.service, "Error fetching glucose data: \(error.localizedDescription)")
  526. }
  527. }
  528. func uploadGlucose(_ glucose: [StoredGlucoseSample]) {
  529. guard !glucose.isEmpty, let tidepoolService = self.tidepoolService else { return }
  530. let chunks = glucose.chunks(ofCount: tidepoolService.glucoseDataLimit ?? 100)
  531. processQueue.async {
  532. for chunk in chunks {
  533. tidepoolService.uploadGlucoseData(chunk) { result in
  534. switch result {
  535. case .success:
  536. debug(.nightscout, "Success synchronizing glucose data")
  537. // After successful upload, update the isUploadedToTidepool flag in Core Data
  538. Task {
  539. await self.updateGlucoseAsUploaded(glucose)
  540. }
  541. case let .failure(error):
  542. debug(.nightscout, "Error synchronizing glucose data: \(String(describing: error))")
  543. }
  544. }
  545. }
  546. }
  547. }
  548. private func updateGlucoseAsUploaded(_ glucose: [StoredGlucoseSample]) async {
  549. await backgroundContext.perform {
  550. let ids = glucose.map(\.syncIdentifier) as NSArray
  551. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  552. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  553. do {
  554. let results = try self.backgroundContext.fetch(fetchRequest)
  555. for result in results {
  556. result.isUploadedToTidepool = true
  557. }
  558. guard self.backgroundContext.hasChanges else { return }
  559. try self.backgroundContext.save()
  560. } catch let error as NSError {
  561. debugPrint(
  562. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToTidepool: \(error.userInfo)"
  563. )
  564. }
  565. }
  566. }
  567. }
  568. extension BaseTidepoolManager: StatefulPluggableDelegate {
  569. func pluginDidUpdateState(_: LoopKit.StatefulPluggable) {}
  570. func pluginWantsDeletion(_: LoopKit.StatefulPluggable) {
  571. tidepoolService = nil
  572. }
  573. }
  574. // Service extension for rawValue
  575. extension Service {
  576. typealias RawValue = [String: Any]
  577. var rawValue: RawValue {
  578. [
  579. "serviceIdentifier": pluginIdentifier,
  580. "state": rawState
  581. ]
  582. }
  583. }