TidepoolManager.swift 26 KB

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