TidepoolManager.swift 26 KB

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