TidepoolManager.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. uploadDose(await pumpHistoryStorage.getPumpHistoryNotYetUploadedToTidepool())
  232. }
  233. func uploadDose(_ events: [PumpHistoryEvent]) {
  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 existingTempBasalEntries: [PumpEventStored] = CoreDataStack.shared.fetchEntities(
  237. ofType: PumpEventStored.self,
  238. onContext: backgroundContext,
  239. predicate: NSPredicate.pumpHistoryLast24h,
  240. key: "timestamp",
  241. ascending: true,
  242. batchSize: 50
  243. ).filter { $0.tempBasal != nil }
  244. var insulinDoseEvents: [DoseEntry] = events.reduce([]) { result, event in
  245. var result = result
  246. switch event.type {
  247. case .tempBasal:
  248. result
  249. .append(contentsOf: self.processTempBasalEvent(event, existingTempBasalEntries: existingTempBasalEntries))
  250. case .bolus:
  251. let bolusDoseEntry = DoseEntry(
  252. type: .bolus,
  253. startDate: event.timestamp,
  254. endDate: event.timestamp,
  255. value: Double(event.amount!),
  256. unit: .units,
  257. deliveredUnits: nil,
  258. syncIdentifier: event.id,
  259. scheduledBasalRate: nil,
  260. insulinType: apsManager.pumpManager?.status.insulinType ?? nil,
  261. automatic: event.isSMB ?? true,
  262. manuallyEntered: event.isExternal ?? false
  263. )
  264. result.append(bolusDoseEntry)
  265. default:
  266. break
  267. }
  268. return result
  269. }
  270. debug(.service, "TIDEPOOL DOSE ENTRIES: \(insulinDoseEvents)")
  271. let pumpEvents: [PersistedPumpEvent] = events.compactMap { event -> PersistedPumpEvent? in
  272. if let pumpEventType = event.type.mapEventTypeToPumpEventType() {
  273. let dose: DoseEntry? = switch pumpEventType {
  274. case .suspend:
  275. DoseEntry(suspendDate: event.timestamp, automatic: true)
  276. case .resume:
  277. DoseEntry(resumeDate: event.timestamp, automatic: true)
  278. default:
  279. nil
  280. }
  281. return PersistedPumpEvent(
  282. date: event.timestamp,
  283. persistedDate: event.timestamp,
  284. dose: dose,
  285. isUploaded: true,
  286. objectIDURL: URL(string: "x-coredata:///PumpEvent/\(event.id)")!,
  287. raw: event.id.data(using: .utf8),
  288. title: event.note,
  289. type: pumpEventType
  290. )
  291. } else {
  292. return nil
  293. }
  294. }
  295. processQueue.async {
  296. tidepoolService.uploadDoseData(created: insulinDoseEvents, deleted: []) { result in
  297. switch result {
  298. case let .failure(error):
  299. debug(.nightscout, "Error synchronizing dose data with Tidepool: \(String(describing: error))")
  300. case .success:
  301. debug(.nightscout, "Success synchronizing dose data. Upload to Tidepool complete.")
  302. // After successful upload, update the isUploadedToTidepool flag in Core Data
  303. Task {
  304. let insulinEvents = events.filter {
  305. $0.type == .tempBasal || $0.type == .tempBasalDuration || $0.type == .bolus
  306. }
  307. await self.updateInsulinAsUploaded(insulinEvents)
  308. }
  309. }
  310. }
  311. tidepoolService.uploadPumpEventData(pumpEvents) { result in
  312. switch result {
  313. case let .failure(error):
  314. debug(.nightscout, "Error synchronizing pump events data: \(String(describing: error))")
  315. case .success:
  316. debug(.nightscout, "Success synchronizing pump events data. Upload to Tidepool complete.")
  317. // After successful upload, update the isUploadedToTidepool flag in Core Data
  318. Task {
  319. let pumpEventType = events.map { $0.type.mapEventTypeToPumpEventType() }
  320. let pumpEvents = events.filter { _ in pumpEventType.contains(pumpEventType) }
  321. await self.updateInsulinAsUploaded(pumpEvents)
  322. }
  323. }
  324. }
  325. }
  326. }
  327. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  328. await backgroundContext.perform {
  329. let ids = insulin.map(\.id) as NSArray
  330. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  331. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  332. do {
  333. let results = try self.backgroundContext.fetch(fetchRequest)
  334. for result in results {
  335. result.isUploadedToTidepool = true
  336. }
  337. guard self.backgroundContext.hasChanges else { return }
  338. try self.backgroundContext.save()
  339. } catch let error as NSError {
  340. debugPrint(
  341. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToTidepool: \(error.userInfo)"
  342. )
  343. }
  344. }
  345. }
  346. func deleteInsulin(withSyncId id: String, amount: Decimal, at: Date) {
  347. guard let tidepoolService = self.tidepoolService else { return }
  348. // must be an array here, because `tidepoolService.uploadDoseData` expects a `deleted` array
  349. let doseDataToDelete: [DoseEntry] = [DoseEntry(
  350. type: .bolus,
  351. startDate: at,
  352. value: Double(amount),
  353. unit: .units,
  354. syncIdentifier: id
  355. )]
  356. processQueue.async {
  357. tidepoolService.uploadDoseData(created: [], deleted: doseDataToDelete) { result in
  358. switch result {
  359. case let .failure(error):
  360. debug(.nightscout, "Error synchronizing Dose delete data: \(String(describing: error))")
  361. case .success:
  362. debug(.nightscout, "Success synchronizing Dose delete data")
  363. }
  364. }
  365. }
  366. }
  367. }
  368. /// Insulin Helper Functions
  369. extension BaseTidepoolManager {
  370. private func processTempBasalEvent(_ event: PumpHistoryEvent, existingTempBasalEntries: [PumpEventStored]) -> [DoseEntry] {
  371. var insulinDoseEvents: [DoseEntry] = []
  372. // Loop through the pump history events
  373. guard let duration = event.duration, let amount = event.amount,
  374. let currentBasalRate = getCurrentBasalRate()
  375. else {
  376. return []
  377. }
  378. let value = (Decimal(duration) / 60.0) * amount
  379. // Find the corresponding temp basal entry in existingTempBasalEntries
  380. if let matchingEntryIndex = existingTempBasalEntries.firstIndex(where: { $0.timestamp == event.timestamp }) {
  381. // Check for a predecessor (the entry before the matching entry)
  382. let predecessorIndex = matchingEntryIndex - 1
  383. if predecessorIndex >= 0 {
  384. let predecessorEntry = existingTempBasalEntries[predecessorIndex]
  385. if let predecessorTimestamp = predecessorEntry.timestamp,
  386. let predecessorEntrySyncIdentifier = predecessorEntry.id
  387. {
  388. let predecessorEndDate = predecessorTimestamp
  389. .addingTimeInterval(TimeInterval(
  390. Int(predecessorEntry.tempBasal?.duration ?? 0) *
  391. 60
  392. )) // parse duration to minutes
  393. // If the predecessor's end date is later than the current event's start date, adjust it
  394. if predecessorEndDate > event.timestamp {
  395. let adjustedEndDate = event.timestamp
  396. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  397. let adjustedDeliveredUnits = (adjustedDuration / 3600) *
  398. Double(truncating: predecessorEntry.tempBasal?.rate ?? 0)
  399. // Create updated predecessor dose entry
  400. let updatedPredecessorEntry = DoseEntry(
  401. type: .tempBasal,
  402. startDate: predecessorTimestamp,
  403. endDate: adjustedEndDate,
  404. value: adjustedDeliveredUnits,
  405. unit: .units,
  406. deliveredUnits: adjustedDeliveredUnits,
  407. syncIdentifier: predecessorEntrySyncIdentifier,
  408. insulinType: apsManager.pumpManager?.status.insulinType ?? nil,
  409. automatic: true,
  410. manuallyEntered: false,
  411. isMutable: false
  412. )
  413. // Add the updated predecessor entry to the result
  414. insulinDoseEvents.append(updatedPredecessorEntry)
  415. }
  416. }
  417. }
  418. // Create a new dose entry for the current event
  419. let currentEndDate = event.timestamp.addingTimeInterval(TimeInterval(minutes: Double(duration)))
  420. let newDoseEntry = DoseEntry(
  421. type: .tempBasal,
  422. startDate: event.timestamp,
  423. endDate: currentEndDate,
  424. value: Double(value),
  425. unit: .units,
  426. deliveredUnits: Double(value),
  427. syncIdentifier: event.id,
  428. scheduledBasalRate: HKQuantity(
  429. unit: .internationalUnitsPerHour,
  430. doubleValue: Double(currentBasalRate.rate)
  431. ),
  432. insulinType: apsManager.pumpManager?.status.insulinType ?? nil,
  433. automatic: true,
  434. manuallyEntered: false,
  435. isMutable: false
  436. )
  437. // Add the new event entry to the result
  438. insulinDoseEvents.append(newDoseEntry)
  439. }
  440. return insulinDoseEvents
  441. }
  442. private func getCurrentBasalRate() -> BasalProfileEntry? {
  443. let now = Date()
  444. let calendar = Calendar.current
  445. let dateFormatter = DateFormatter()
  446. dateFormatter.dateFormat = "HH:mm:ss"
  447. dateFormatter.timeZone = TimeZone.current
  448. let basalEntries = storage.retrieve(OpenAPS.Settings.basalProfile, as: [BasalProfileEntry].self)
  449. ?? [BasalProfileEntry](from: OpenAPS.defaults(for: OpenAPS.Settings.basalProfile))
  450. ?? []
  451. var currentRate: BasalProfileEntry = basalEntries[0]
  452. for (index, entry) in basalEntries.enumerated() {
  453. guard let entryTime = dateFormatter.date(from: entry.start) else {
  454. print("Invalid entry start time: \(entry.start)")
  455. continue
  456. }
  457. let entryComponents = calendar.dateComponents([.hour, .minute, .second], from: entryTime)
  458. let entryStartTime = calendar.date(
  459. bySettingHour: entryComponents.hour!,
  460. minute: entryComponents.minute!,
  461. second: entryComponents.second!,
  462. of: now
  463. )!
  464. let entryEndTime: Date
  465. if index < basalEntries.count - 1,
  466. let nextEntryTime = dateFormatter.date(from: basalEntries[index + 1].start)
  467. {
  468. let nextEntryComponents = calendar.dateComponents([.hour, .minute, .second], from: nextEntryTime)
  469. entryEndTime = calendar.date(
  470. bySettingHour: nextEntryComponents.hour!,
  471. minute: nextEntryComponents.minute!,
  472. second: nextEntryComponents.second!,
  473. of: now
  474. )!
  475. } else {
  476. entryEndTime = calendar.date(byAdding: .day, value: 1, to: entryStartTime)!
  477. }
  478. if now >= entryStartTime, now < entryEndTime {
  479. currentRate = entry
  480. }
  481. }
  482. return currentRate
  483. }
  484. }
  485. /// Glucose Upload Functionality
  486. extension BaseTidepoolManager {
  487. func uploadGlucose() async {
  488. uploadGlucose(await glucoseStorage.getGlucoseNotYetUploadedToTidepool())
  489. uploadGlucose(
  490. await glucoseStorage
  491. .getManualGlucoseNotYetUploadedToTidepool()
  492. )
  493. }
  494. func uploadGlucose(_ glucose: [StoredGlucoseSample]) {
  495. guard !glucose.isEmpty, let tidepoolService = self.tidepoolService else { return }
  496. let chunks = glucose.chunks(ofCount: tidepoolService.glucoseDataLimit ?? 100)
  497. processQueue.async {
  498. for chunk in chunks {
  499. tidepoolService.uploadGlucoseData(chunk) { result in
  500. switch result {
  501. case .success:
  502. debug(.nightscout, "Success synchronizing glucose data")
  503. // After successful upload, update the isUploadedToTidepool flag in Core Data
  504. Task {
  505. await self.updateGlucoseAsUploaded(glucose)
  506. }
  507. case let .failure(error):
  508. debug(.nightscout, "Error synchronizing glucose data: \(String(describing: error))")
  509. }
  510. }
  511. }
  512. }
  513. }
  514. private func updateGlucoseAsUploaded(_ glucose: [StoredGlucoseSample]) async {
  515. await backgroundContext.perform {
  516. let ids = glucose.map(\.syncIdentifier) as NSArray
  517. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  518. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  519. do {
  520. let results = try self.backgroundContext.fetch(fetchRequest)
  521. for result in results {
  522. result.isUploadedToTidepool = true
  523. }
  524. guard self.backgroundContext.hasChanges else { return }
  525. try self.backgroundContext.save()
  526. } catch let error as NSError {
  527. debugPrint(
  528. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToTidepool: \(error.userInfo)"
  529. )
  530. }
  531. }
  532. }
  533. }
  534. extension BaseTidepoolManager: StatefulPluggableDelegate {
  535. func pluginDidUpdateState(_: LoopKit.StatefulPluggable) {}
  536. func pluginWantsDeletion(_: LoopKit.StatefulPluggable) {
  537. tidepoolService = nil
  538. }
  539. }
  540. // Service extension for rawValue
  541. extension Service {
  542. typealias RawValue = [String: Any]
  543. var rawValue: RawValue {
  544. [
  545. "serviceIdentifier": pluginIdentifier,
  546. "state": rawState
  547. ]
  548. }
  549. }