HealthKitManager.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import HealthKit
  5. import LoopKit
  6. import LoopKitUI
  7. import Swinject
  8. protocol HealthKitManager {
  9. /// Check all needed permissions
  10. /// Return false if one or more permissions are deny or not choosen
  11. var hasGrantedFullWritePermissions: Bool { get }
  12. /// Check availability to save data of BG type to Health store
  13. func hasGlucoseWritePermission() -> Bool
  14. /// Requests user to give permissions on using HealthKit
  15. func requestPermission() async throws -> Bool
  16. /// Checks whether permissions are granted for Trio to write to Health
  17. func checkWriteToHealthPermissions(objectTypeToHealthStore: HKObjectType) -> Bool
  18. /// Save blood glucose to Health store
  19. func uploadGlucose() async
  20. /// Save carbs to Health store
  21. func uploadCarbs() async
  22. /// Save Insulin to Health store
  23. func uploadInsulin() async
  24. /// Delete glucose with syncID
  25. func deleteGlucose(syncID: String) async
  26. /// delete carbs with syncID
  27. func deleteMealData(byID id: String, sampleType: HKSampleType) async
  28. /// delete insulin with syncID
  29. func deleteInsulin(syncID: String) async
  30. }
  31. public enum AppleHealthConfig {
  32. // unwraped HKObjects
  33. static var writePermissions: Set<HKSampleType> {
  34. Set([healthBGObject, healthCarbObject, healthFatObject, healthProteinObject, healthInsulinObject].compactMap { $0 }) }
  35. // link to object in HealthKit
  36. static let healthBGObject = HKObjectType.quantityType(forIdentifier: .bloodGlucose)
  37. static let healthCarbObject = HKObjectType.quantityType(forIdentifier: .dietaryCarbohydrates)
  38. static let healthFatObject = HKObjectType.quantityType(forIdentifier: .dietaryFatTotal)
  39. static let healthProteinObject = HKObjectType.quantityType(forIdentifier: .dietaryProtein)
  40. static let healthInsulinObject = HKObjectType.quantityType(forIdentifier: .insulinDelivery)
  41. // MetaDataKey of Trio data in HealthStore
  42. static let TrioMetaDataKey = "TrioMetaDataKey"
  43. }
  44. final class BaseHealthKitManager: HealthKitManager, Injectable {
  45. @Injected() private var glucoseStorage: GlucoseStorage!
  46. @Injected() private var healthKitStore: HKHealthStore!
  47. @Injected() private var settingsManager: SettingsManager!
  48. @Injected() private var broadcaster: Broadcaster!
  49. @Injected() var carbsStorage: CarbsStorage!
  50. @Injected() var pumpHistoryStorage: PumpHistoryStorage!
  51. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  52. private var coreDataPublisher: AnyPublisher<Set<NSManagedObject>, Never>?
  53. private var subscriptions = Set<AnyCancellable>()
  54. var isAvailableOnCurrentDevice: Bool {
  55. HKHealthStore.isHealthDataAvailable()
  56. }
  57. init(resolver: Resolver) {
  58. injectServices(resolver)
  59. coreDataPublisher =
  60. changedObjectsOnManagedObjectContextDidSavePublisher()
  61. .receive(on: DispatchQueue.global(qos: .background))
  62. .share()
  63. .eraseToAnyPublisher()
  64. registerHandlers()
  65. Task { [weak self] in
  66. guard let self = self else { return }
  67. await self.uploadInsulin()
  68. }
  69. guard isAvailableOnCurrentDevice,
  70. AppleHealthConfig.healthBGObject != nil else { return }
  71. debug(.service, "HealthKitManager did create")
  72. }
  73. private func registerHandlers() {
  74. coreDataPublisher?.filterByEntityName("PumpEventStored").sink { [weak self] _ in
  75. guard let self = self else { return }
  76. Task { [weak self] in
  77. guard let self = self else { return }
  78. await self.uploadInsulin()
  79. }
  80. }.store(in: &subscriptions)
  81. coreDataPublisher?.filterByEntityName("CarbEntryStored").sink { [weak self] _ in
  82. guard let self = self else { return }
  83. Task { [weak self] in
  84. guard let self = self else { return }
  85. await self.uploadCarbs()
  86. }
  87. }.store(in: &subscriptions)
  88. }
  89. func checkWriteToHealthPermissions(objectTypeToHealthStore: HKObjectType) -> Bool {
  90. healthKitStore.authorizationStatus(for: objectTypeToHealthStore) == .sharingAuthorized
  91. }
  92. var hasGrantedFullWritePermissions: Bool {
  93. Set(AppleHealthConfig.writePermissions.map { healthKitStore.authorizationStatus(for: $0) })
  94. .intersection([.sharingDenied, .notDetermined])
  95. .isEmpty
  96. }
  97. func hasGlucoseWritePermission() -> Bool {
  98. AppleHealthConfig.healthBGObject.map { checkWriteToHealthPermissions(objectTypeToHealthStore: $0) } ?? false
  99. }
  100. func requestPermission() async throws -> Bool {
  101. guard isAvailableOnCurrentDevice else {
  102. throw HKError.notAvailableOnCurrentDevice
  103. }
  104. return try await withCheckedThrowingContinuation { continuation in
  105. healthKitStore.requestAuthorization(
  106. toShare: AppleHealthConfig.writePermissions,
  107. read: nil
  108. ) { status, error in
  109. if let error = error {
  110. continuation.resume(throwing: error)
  111. } else {
  112. continuation.resume(returning: status)
  113. }
  114. }
  115. }
  116. }
  117. // Glucose Upload
  118. func uploadGlucose() async {
  119. await uploadGlucose(glucoseStorage.getGlucoseNotYetUploadedToHealth())
  120. await uploadGlucose(glucoseStorage.getManualGlucoseNotYetUploadedToHealth())
  121. }
  122. func uploadGlucose(_ glucose: [BloodGlucose]) async {
  123. guard settingsManager.settings.useAppleHealth,
  124. let sampleType = AppleHealthConfig.healthBGObject,
  125. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  126. glucose.isNotEmpty
  127. else { return }
  128. do {
  129. // Create HealthKit samples from all the passed glucose values
  130. let glucoseSamples = glucose.compactMap { glucoseSample -> HKQuantitySample? in
  131. guard let glucoseValue = glucoseSample.glucose else { return nil }
  132. return HKQuantitySample(
  133. type: sampleType,
  134. quantity: HKQuantity(unit: .milligramsPerDeciliter, doubleValue: Double(glucoseValue)),
  135. start: glucoseSample.dateString,
  136. end: glucoseSample.dateString,
  137. metadata: [
  138. HKMetadataKeyExternalUUID: glucoseSample.id,
  139. HKMetadataKeySyncIdentifier: glucoseSample.id,
  140. HKMetadataKeySyncVersion: 1,
  141. AppleHealthConfig.TrioMetaDataKey: UUID().uuidString
  142. ]
  143. )
  144. }
  145. guard glucoseSamples.isNotEmpty else {
  146. debug(.service, "No glucose samples available for upload.")
  147. return
  148. }
  149. // Attempt to save the blood glucose samples to Apple Health
  150. try await healthKitStore.save(glucoseSamples)
  151. debug(.service, "Successfully stored \(glucoseSamples.count) blood glucose samples in HealthKit.")
  152. // After successful upload, update the isUploadedToHealth flag in Core Data
  153. await updateGlucoseAsUploaded(glucose)
  154. } catch {
  155. debug(.service, "Failed to upload glucose samples to HealthKit: \(error.localizedDescription)")
  156. }
  157. }
  158. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  159. await backgroundContext.perform {
  160. let ids = glucose.map(\.id) as NSArray
  161. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  162. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  163. do {
  164. let results = try self.backgroundContext.fetch(fetchRequest)
  165. for result in results {
  166. result.isUploadedToHealth = true
  167. }
  168. guard self.backgroundContext.hasChanges else { return }
  169. try self.backgroundContext.save()
  170. } catch let error as NSError {
  171. debugPrint(
  172. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  173. )
  174. }
  175. }
  176. }
  177. // Carbs Upload
  178. func uploadCarbs() async {
  179. await uploadCarbs(carbsStorage.getCarbsNotYetUploadedToHealth())
  180. }
  181. func uploadCarbs(_ carbs: [CarbsEntry]) async {
  182. guard settingsManager.settings.useAppleHealth,
  183. let carbSampleType = AppleHealthConfig.healthCarbObject,
  184. let fatSampleType = AppleHealthConfig.healthFatObject,
  185. let proteinSampleType = AppleHealthConfig.healthProteinObject,
  186. checkWriteToHealthPermissions(objectTypeToHealthStore: carbSampleType),
  187. carbs.isNotEmpty
  188. else { return }
  189. do {
  190. var samples: [HKQuantitySample] = []
  191. // Create HealthKit samples for carbs, fat, and protein
  192. for allSamples in carbs {
  193. guard let id = allSamples.id else { continue }
  194. let fpuID = allSamples.fpuID ?? id
  195. let startDate = allSamples.actualDate ?? Date()
  196. // Carbs Sample
  197. let carbValue = allSamples.carbs
  198. let carbSample = HKQuantitySample(
  199. type: carbSampleType,
  200. quantity: HKQuantity(unit: .gram(), doubleValue: Double(carbValue)),
  201. start: startDate,
  202. end: startDate,
  203. metadata: [
  204. HKMetadataKeyExternalUUID: id,
  205. HKMetadataKeySyncIdentifier: id,
  206. HKMetadataKeySyncVersion: 1,
  207. AppleHealthConfig.TrioMetaDataKey: UUID().uuidString
  208. ]
  209. )
  210. samples.append(carbSample)
  211. // Fat Sample (if available)
  212. if let fatValue = allSamples.fat {
  213. let fatSample = HKQuantitySample(
  214. type: fatSampleType,
  215. quantity: HKQuantity(unit: .gram(), doubleValue: Double(fatValue)),
  216. start: startDate,
  217. end: startDate,
  218. metadata: [
  219. HKMetadataKeyExternalUUID: fpuID,
  220. HKMetadataKeySyncIdentifier: fpuID,
  221. HKMetadataKeySyncVersion: 1,
  222. AppleHealthConfig.TrioMetaDataKey: UUID().uuidString
  223. ]
  224. )
  225. samples.append(fatSample)
  226. }
  227. // Protein Sample (if available)
  228. if let proteinValue = allSamples.protein {
  229. let proteinSample = HKQuantitySample(
  230. type: proteinSampleType,
  231. quantity: HKQuantity(unit: .gram(), doubleValue: Double(proteinValue)),
  232. start: startDate,
  233. end: startDate,
  234. metadata: [
  235. HKMetadataKeyExternalUUID: fpuID,
  236. HKMetadataKeySyncIdentifier: fpuID,
  237. HKMetadataKeySyncVersion: 1,
  238. AppleHealthConfig.TrioMetaDataKey: UUID().uuidString
  239. ]
  240. )
  241. samples.append(proteinSample)
  242. }
  243. }
  244. // Attempt to save the samples to Apple Health
  245. guard samples.isNotEmpty else {
  246. debug(.service, "No samples available for upload.")
  247. return
  248. }
  249. try await healthKitStore.save(samples)
  250. debug(.service, "Successfully stored \(samples.count) carb samples in HealthKit.")
  251. // After successful upload, update the isUploadedToHealth flag in Core Data
  252. await updateCarbsAsUploaded(carbs)
  253. } catch {
  254. debug(.service, "Failed to upload carb samples to HealthKit: \(error.localizedDescription)")
  255. }
  256. }
  257. private func updateCarbsAsUploaded(_ carbs: [CarbsEntry]) async {
  258. await backgroundContext.perform {
  259. let ids = carbs.map(\.id) as NSArray
  260. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  261. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  262. do {
  263. let results = try self.backgroundContext.fetch(fetchRequest)
  264. for result in results {
  265. result.isUploadedToHealth = true
  266. }
  267. guard self.backgroundContext.hasChanges else { return }
  268. try self.backgroundContext.save()
  269. } catch let error as NSError {
  270. debugPrint(
  271. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  272. )
  273. }
  274. }
  275. }
  276. // Insulin Upload
  277. func uploadInsulin() async {
  278. await uploadInsulin(pumpHistoryStorage.getPumpHistoryNotYetUploadedToHealth())
  279. }
  280. func uploadInsulin(_ insulin: [PumpHistoryEvent]) async {
  281. guard settingsManager.settings.useAppleHealth,
  282. let sampleType = AppleHealthConfig.healthInsulinObject,
  283. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType),
  284. insulin.isNotEmpty
  285. else { return }
  286. // Fetch existing temp basal entries from Core Data
  287. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  288. ofType: PumpEventStored.self,
  289. onContext: backgroundContext,
  290. predicate: NSCompoundPredicate(andPredicateWithSubpredicates: [
  291. NSPredicate.pumpHistoryLast24h,
  292. NSPredicate(format: "tempBasal != nil")
  293. ]),
  294. key: "timestamp",
  295. ascending: true,
  296. batchSize: 50
  297. )
  298. var processedEvents: [PumpHistoryEvent] = []
  299. await backgroundContext.perform {
  300. guard let existingTempBasalEntries = results as? [PumpEventStored] else { return }
  301. for event in insulin {
  302. switch event.type {
  303. case .tempBasal:
  304. let tempBasalEvents = self.processTempBasalEvent(
  305. event,
  306. existingTempBasalEntries: existingTempBasalEntries
  307. )
  308. processedEvents.append(contentsOf: tempBasalEvents)
  309. case .bolus:
  310. processedEvents.append(event)
  311. default:
  312. break
  313. }
  314. }
  315. }
  316. // Create HKQuantitySamples for all processed events
  317. do {
  318. let insulinSamples = processedEvents.compactMap { processedEvent -> HKQuantitySample? in
  319. guard let insulinValue = processedEvent.amount else { return nil }
  320. let deliveryReason: HKInsulinDeliveryReason
  321. switch processedEvent.type {
  322. case .bolus:
  323. deliveryReason = .bolus
  324. case .tempBasal:
  325. deliveryReason = .basal
  326. default:
  327. return nil
  328. }
  329. // adjust end date based on duration
  330. let endDate = processedEvent.timestamp
  331. .addingTimeInterval(TimeInterval(minutes: Double(processedEvent.duration ?? 0)))
  332. return HKQuantitySample(
  333. type: sampleType,
  334. quantity: HKQuantity(unit: .internationalUnit(), doubleValue: Double(insulinValue)),
  335. start: processedEvent.timestamp,
  336. end: endDate,
  337. metadata: [
  338. HKMetadataKeyExternalUUID: processedEvent.id,
  339. HKMetadataKeySyncIdentifier: processedEvent.id,
  340. HKMetadataKeySyncVersion: 1,
  341. HKMetadataKeyInsulinDeliveryReason: deliveryReason.rawValue,
  342. AppleHealthConfig.TrioMetaDataKey: UUID().uuidString
  343. ]
  344. )
  345. }
  346. guard insulinSamples.isNotEmpty else {
  347. debug(.service, "No insulin samples available for upload.")
  348. return
  349. }
  350. try await healthKitStore.save(insulinSamples)
  351. debug(.service, "Successfully stored \(insulinSamples.count) insulin samples in HealthKit.")
  352. await updateInsulinAsUploaded(processedEvents)
  353. } catch {
  354. debug(.service, "Failed to upload insulin samples to HealthKit: \(error.localizedDescription)")
  355. }
  356. }
  357. private func processTempBasalEvent(
  358. _ event: PumpHistoryEvent,
  359. existingTempBasalEntries: [PumpEventStored]
  360. ) -> [PumpHistoryEvent] {
  361. var processedTempBasalEvents: [PumpHistoryEvent] = []
  362. backgroundContext.performAndWait {
  363. guard let duration = event.duration, let amount = event.amount else { return }
  364. let value = (Decimal(duration) / 60.0) * amount
  365. if let matchingEntryIndex = existingTempBasalEntries.firstIndex(where: { $0.timestamp == event.timestamp }) {
  366. let predecessorIndex = matchingEntryIndex - 1
  367. if predecessorIndex >= 0 {
  368. let predecessorEntry = existingTempBasalEntries[predecessorIndex]
  369. if let predecessorTimestamp = predecessorEntry.timestamp {
  370. let predecessorEndDate = predecessorTimestamp
  371. .addingTimeInterval(TimeInterval(Int(predecessorEntry.tempBasal?.duration ?? 0) * 60))
  372. if predecessorEndDate > event.timestamp {
  373. let adjustedEndDate = event.timestamp
  374. let adjustedDuration = adjustedEndDate.timeIntervalSince(predecessorTimestamp)
  375. let adjustedPumpHistoryEvent = PumpHistoryEvent(
  376. id: UUID().uuidString,
  377. type: .tempBasal,
  378. timestamp: predecessorTimestamp,
  379. amount: Decimal(adjustedDuration / 3600) * amount,
  380. duration: Int(adjustedDuration / 60)
  381. )
  382. processedTempBasalEvents.append(adjustedPumpHistoryEvent)
  383. }
  384. }
  385. }
  386. let newPumpHistoryEvent = PumpHistoryEvent(
  387. id: UUID().uuidString,
  388. type: .tempBasal,
  389. timestamp: event.timestamp,
  390. amount: value,
  391. duration: event.duration
  392. )
  393. processedTempBasalEvents.append(newPumpHistoryEvent)
  394. }
  395. }
  396. return processedTempBasalEvents
  397. }
  398. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  399. await backgroundContext.perform {
  400. let ids = insulin.map(\.id) as NSArray
  401. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  402. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  403. do {
  404. let results = try self.backgroundContext.fetch(fetchRequest)
  405. for result in results {
  406. result.isUploadedToHealth = true
  407. }
  408. guard self.backgroundContext.hasChanges else { return }
  409. try self.backgroundContext.save()
  410. } catch let error as NSError {
  411. debugPrint(
  412. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  413. )
  414. }
  415. }
  416. }
  417. // Delete Glucose/Carbs/Insulin
  418. func deleteGlucose(syncID: String) async {
  419. guard settingsManager.settings.useAppleHealth,
  420. let sampleType = AppleHealthConfig.healthBGObject,
  421. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  422. else { return }
  423. let predicate = HKQuery.predicateForObjects(
  424. withMetadataKey: HKMetadataKeySyncIdentifier,
  425. operatorType: .equalTo,
  426. value: syncID
  427. )
  428. do {
  429. try await deleteObjects(of: sampleType, predicate: predicate)
  430. debug(.service, "Successfully deleted glucose sample with syncID: \(syncID)")
  431. } catch {
  432. warning(.service, "Failed to delete glucose sample with syncID: \(syncID)", error: error)
  433. }
  434. }
  435. func deleteMealData(byID id: String, sampleType: HKSampleType) async {
  436. guard settingsManager.settings.useAppleHealth else { return }
  437. let predicate = HKQuery.predicateForObjects(
  438. withMetadataKey: HKMetadataKeySyncIdentifier,
  439. operatorType: .equalTo,
  440. value: id
  441. )
  442. do {
  443. try await deleteObjects(of: sampleType, predicate: predicate)
  444. debug(.service, "Successfully deleted \(sampleType) with syncID: \(id)")
  445. } catch {
  446. warning(.service, "Failed to delete carbs sample with syncID: \(id)", error: error)
  447. }
  448. }
  449. func deleteInsulin(syncID: String) async {
  450. guard settingsManager.settings.useAppleHealth,
  451. let sampleType = AppleHealthConfig.healthInsulinObject,
  452. checkWriteToHealthPermissions(objectTypeToHealthStore: sampleType)
  453. else {
  454. debug(.service, "HealthKit permissions are not available for insulin deletion.")
  455. return
  456. }
  457. let predicate = HKQuery.predicateForObjects(
  458. withMetadataKey: HKMetadataKeySyncIdentifier,
  459. operatorType: .equalTo,
  460. value: syncID
  461. )
  462. do {
  463. try await deleteObjects(of: sampleType, predicate: predicate)
  464. debug(.service, "Successfully deleted insulin sample with syncID: \(syncID)")
  465. } catch {
  466. warning(.service, "Failed to delete insulin sample with syncID: \(syncID)", error: error)
  467. }
  468. }
  469. private func deleteObjects(of sampleType: HKSampleType, predicate: NSPredicate) async throws {
  470. try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
  471. healthKitStore.deleteObjects(of: sampleType, predicate: predicate) { success, _, error in
  472. if let error = error {
  473. continuation.resume(throwing: error)
  474. } else if success {
  475. continuation.resume(returning: ())
  476. }
  477. }
  478. }
  479. }
  480. }
  481. enum HealthKitPermissionRequestStatus {
  482. case needRequest
  483. case didRequest
  484. }
  485. enum HKError: Error {
  486. // HealthKit work only iPhone (not on iPad)
  487. case notAvailableOnCurrentDevice
  488. // Some data can be not available on current iOS-device
  489. case dataNotAvailable
  490. }
  491. private struct InsulinBolus {
  492. var id: String
  493. var amount: Decimal
  494. var date: Date
  495. }
  496. private struct InsulinBasal {
  497. var id: String
  498. var amount: Decimal
  499. var startDelivery: Date
  500. var endDelivery: Date
  501. }