-
Notifications
You must be signed in to change notification settings - Fork 493
Add HealthKit sensors to iOS app #4923
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bgoncal
merged 10 commits into
home-assistant:main
from
aero-oli:feature/apple-health-sensors
Jul 28, 2026
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
2664263
Add HealthKit sensors to iOS app
aero-oli 142d705
Address HealthKit sensor review feedback
aero-oli c33e9f4
Align HealthKit sensors with sensor settings
aero-oli f2c6170
Address HealthKit review feedback
aero-oli 8604c9e
Merge branch 'main' into feature/apple-health-sensors
bgoncal a014264
Align HealthKit permission with settings UI
aero-oli c722bae
Revert "Align HealthKit permission with settings UI"
aero-oli bd0c3df
Retrigger CI
aero-oli d46e29c
Merge branch 'main' into feature/apple-health-sensors
aero-oli 0965a80
Isolate HealthKit sensor tests
aero-oli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
130 changes: 130 additions & 0 deletions
130
Sources/Shared/API/Webhook/Sensors/HealthKitSensor.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| #if os(iOS) && !targetEnvironment(macCatalyst) | ||
| import Foundation | ||
| import PromiseKit | ||
|
|
||
| public final class HealthKitSensor: SensorProvider { | ||
| public enum Metric: CaseIterable, Codable { | ||
| case steps | ||
| case restingHeartRate | ||
|
|
||
| public var uniqueID: String { | ||
| switch self { | ||
| case .steps: return "health_steps" | ||
| case .restingHeartRate: return "health_resting_heart_rate" | ||
| } | ||
| } | ||
|
|
||
| public var name: String { | ||
| switch self { | ||
| case .steps: return "Health Steps" | ||
| case .restingHeartRate: return "Resting Heart Rate" | ||
| } | ||
| } | ||
|
|
||
| public var icon: String { | ||
| switch self { | ||
| case .steps: return "mdi:walk" | ||
| case .restingHeartRate: return "mdi:heart-pulse" | ||
| } | ||
| } | ||
|
|
||
| public var unit: String { | ||
| switch self { | ||
| case .steps: return "steps" | ||
| case .restingHeartRate: return "bpm" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public let request: SensorProviderRequest | ||
|
|
||
| public init(request: SensorProviderRequest) { | ||
| self.request = request | ||
| } | ||
|
|
||
| public static func isHealthSensor(uniqueID: String?) -> Bool { | ||
| guard let uniqueID else { return false } | ||
| return Metric.allCases.contains { $0.uniqueID == uniqueID } | ||
| } | ||
|
|
||
| public func sensors() -> Promise<[WebhookSensor]> { | ||
| guard Current.healthKitService.isAvailable() else { | ||
| return .value(Self.unavailableSensors()) | ||
| } | ||
|
|
||
| let start = Current.calendar().startOfDay(for: Current.date()) | ||
| let end = Current.date() | ||
| let restingHeartRateStart = Current.calendar().date(byAdding: .day, value: -7, to: end) ?? start | ||
| let (promise, seal) = Promise<[WebhookSensor]>.pending() | ||
|
|
||
| Task { | ||
| async let steps = value( | ||
| for: .steps, | ||
| start: start, | ||
| end: end, | ||
| restingHeartRateStart: restingHeartRateStart | ||
| ) | ||
| async let restingHeartRate = value( | ||
| for: .restingHeartRate, | ||
| start: start, | ||
| end: end, | ||
| restingHeartRateStart: restingHeartRateStart | ||
| ) | ||
|
|
||
| let values = await [steps, restingHeartRate].compactMap { $0 } | ||
| seal.fulfill(Self.sensors(from: values)) | ||
| } | ||
|
|
||
| return promise | ||
| } | ||
|
|
||
| private func value( | ||
| for metric: Metric, | ||
| start: Date, | ||
| end: Date, | ||
| restingHeartRateStart: Date | ||
| ) async -> HealthSensorValue? { | ||
| guard Current.sensors.isEnabled(uniqueID: metric.uniqueID) else { | ||
| return nil | ||
| } | ||
|
|
||
| switch metric { | ||
| case .steps: | ||
| let value = try? await Current.healthKitService.queryStepCount(start, end) | ||
| return HealthSensorValue(metric: metric, value: value.map(Double.init)) | ||
| case .restingHeartRate: | ||
| let value = try? await Current.healthKitService.queryLatestRestingHeartRate(restingHeartRateStart, end) | ||
| return HealthSensorValue(metric: metric, value: value) | ||
| } | ||
| } | ||
|
|
||
| private static func sensors(from values: [HealthSensorValue]) -> [WebhookSensor] { | ||
| Metric.allCases.map { metric in | ||
| let value = values.first(where: { $0.metric == metric })?.value | ||
| return sensor(metric: metric, value: value) | ||
| } | ||
| } | ||
|
|
||
| private static func unavailableSensors() -> [WebhookSensor] { | ||
| Metric.allCases.map { sensor(metric: $0, value: nil) } | ||
| } | ||
|
|
||
| private static func sensor(metric: Metric, value: Double?) -> WebhookSensor { | ||
| let state: Any | ||
| switch metric { | ||
| case .steps: | ||
| state = value.map { Int($0) } ?? "unavailable" | ||
| case .restingHeartRate: | ||
| state = value ?? "unavailable" | ||
| } | ||
|
|
||
| return WebhookSensor( | ||
| name: metric.name, | ||
| uniqueID: metric.uniqueID, | ||
| icon: metric.icon, | ||
| state: state, | ||
| unit: metric.unit | ||
| ) | ||
| } | ||
| } | ||
| #endif | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| #if os(iOS) && !targetEnvironment(macCatalyst) | ||
| import Foundation | ||
| import HealthKit | ||
|
|
||
| public struct HealthKitService { | ||
| public enum HealthKitServiceError: LocalizedError { | ||
| case unavailable | ||
|
|
||
| public var errorDescription: String? { | ||
| switch self { | ||
| case .unavailable: | ||
| return L10n.SettingsSensors.Health.Error.unavailable | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static let healthStore = HKHealthStore() | ||
|
|
||
| public var isAvailable: () -> Bool = { | ||
| HKHealthStore.isHealthDataAvailable() && !Current.isAppExtension | ||
| } | ||
|
|
||
| public var requestReadAuthorization: () async throws -> Void = { | ||
| guard HKHealthStore.isHealthDataAvailable(), !Current.isAppExtension else { | ||
| throw HealthKitServiceError.unavailable | ||
| } | ||
|
|
||
| try await healthStore.requestAuthorization( | ||
| toShare: Set<HKSampleType>(), | ||
| read: healthDataTypes() | ||
| ) | ||
| } | ||
|
|
||
| public var queryStepCount: (Date, Date) async throws -> Int? = { start, end in | ||
| guard HKHealthStore.isHealthDataAvailable(), !Current.isAppExtension, | ||
| let quantityType = HKObjectType.quantityType(forIdentifier: .stepCount) else { | ||
| return nil | ||
| } | ||
|
|
||
| let predicate = HKQuery.predicateForSamples(withStart: start, end: end) | ||
| return try await withCheckedThrowingContinuation { continuation in | ||
| let query = HKStatisticsQuery( | ||
| quantityType: quantityType, | ||
| quantitySamplePredicate: predicate, | ||
| options: .cumulativeSum | ||
| ) { _, statistics, error in | ||
| if let error { | ||
| continuation.resume(throwing: error) | ||
| } else { | ||
| let steps = statistics?.sumQuantity()?.doubleValue(for: .count()) | ||
| continuation.resume(returning: steps.map(Int.init)) | ||
| } | ||
| } | ||
| healthStore.execute(query) | ||
| } | ||
| } | ||
|
|
||
| public var queryLatestRestingHeartRate: (Date, Date) async throws -> Double? = { start, end in | ||
| guard HKHealthStore.isHealthDataAvailable(), !Current.isAppExtension, | ||
| let quantityType = HKObjectType.quantityType(forIdentifier: .restingHeartRate) else { | ||
| return nil | ||
| } | ||
|
|
||
| let predicate = HKQuery.predicateForSamples(withStart: start, end: end) | ||
| let sort = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) | ||
| return try await withCheckedThrowingContinuation { continuation in | ||
| let query = HKSampleQuery( | ||
| sampleType: quantityType, | ||
| predicate: predicate, | ||
| limit: 1, | ||
| sortDescriptors: [sort] | ||
| ) { _, samples, error in | ||
| if let error { | ||
| continuation.resume(throwing: error) | ||
| } else { | ||
| let sample = samples?.first as? HKQuantitySample | ||
| let unit = HKUnit.count().unitDivided(by: .minute()) | ||
| continuation.resume(returning: sample?.quantity.doubleValue(for: unit)) | ||
| } | ||
| } | ||
| healthStore.execute(query) | ||
| } | ||
| } | ||
|
|
||
| public init() {} | ||
|
|
||
| private static func healthDataTypes() -> Set<HKObjectType> { | ||
| Set([ | ||
| HKObjectType.quantityType(forIdentifier: .stepCount), | ||
| HKObjectType.quantityType(forIdentifier: .restingHeartRate), | ||
| ].compactMap { $0 }) | ||
| } | ||
| } | ||
| #endif |
13 changes: 13 additions & 0 deletions
13
Sources/Shared/API/Webhook/Sensors/HealthSensorValue.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| #if os(iOS) && !targetEnvironment(macCatalyst) | ||
| import Foundation | ||
|
|
||
| public struct HealthSensorValue: Codable, Equatable { | ||
| public let metric: HealthKitSensor.Metric | ||
| public let value: Double? | ||
|
|
||
| public init(metric: HealthKitSensor.Metric, value: Double?) { | ||
| self.metric = metric | ||
| self.value = value | ||
| } | ||
| } | ||
| #endif |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.