TidepoolManager.swift 26 KB

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