TidepoolManager.swift 25 KB

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