TidepoolManager.swift 25 KB

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