-
Notifications
You must be signed in to change notification settings - Fork 10
Apple Health metrics: toothbrushing as sessions per day and as minutes per day #556
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
base: master
Are you sure you want to change the base?
Changes from all commits
4ac542b
c20ae28
2369317
dd45a19
41518a1
11144a3
6ee5cee
1695cc2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import Foundation | ||
| import HealthKit | ||
|
|
||
| /// tracks toothbrushing, in number of (decimal) minutes per day (daystamp) | ||
| class ToothbrushingDailyMinutesHealthKitMetric: CategoryHealthKitMetric { | ||
| private static let healthkitMetric = ["toothbrushing", "minutes-per-day"].joined(separator: "|") | ||
|
|
||
| init(humanText: String = "Teethbrushing (in minutes per day)", | ||
| databaseString: String = ToothbrushingDailyMinutesHealthKitMetric.healthkitMetric, | ||
| category: HealthKitCategory = .Other) { | ||
| super.init(humanText: humanText, | ||
| databaseString: databaseString, | ||
| category: category, | ||
| hkSampleType: HKObjectType.categoryType(forIdentifier: .toothbrushingEvent)!) | ||
| } | ||
|
|
||
| override func units(healthStore : HKHealthStore) async throws -> HKUnit { | ||
| HKUnit.second() | ||
| } | ||
|
|
||
| override func valueInAppropriateUnits(rawValue: Double) -> Double { | ||
| // raw seconds into minutes | ||
| rawValue / 60 | ||
| } | ||
|
|
||
| override func recentDataPoints(days: Int, deadline: Int, healthStore: HKHealthStore) async throws -> [any BeeDataPoint] { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rather than this, can probably just implement
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was implemented for the purpose of specifying the healthkitMetric in the comment and yes, converting seconds to minutes. |
||
| try await super.recentDataPoints(days: days, deadline: deadline, healthStore: healthStore) | ||
| .map { | ||
| NewDataPoint(requestid: $0.requestid, | ||
| daystamp: $0.daystamp, | ||
| value: $0.value, | ||
| comment: "Auto-entered via Apple Health (\(Self.healthkitMetric))") | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| // Part of BeeSwift. Copyright Beeminder | ||
|
|
||
| import Foundation | ||
| import HealthKit | ||
|
|
||
| /// tracks toothbrushing, in number of sessions per day (daystamp) | ||
| class ToothbrushingDailySessionsHealthKitMetric: CategoryHealthKitMetric { | ||
| private static let healthkitMetric = ["toothbrushing", "sessions-per-day"].joined(separator: "|") | ||
| private static let hkSampleType = HKObjectType.categoryType(forIdentifier: .toothbrushingEvent)! | ||
|
|
||
| init(humanText: String = "Teethbrushing (in sessions per day)", | ||
| databaseString: String = ToothbrushingDailySessionsHealthKitMetric.healthkitMetric, | ||
| category: HealthKitCategory = .Other) { | ||
| super.init(humanText: humanText, | ||
| databaseString: databaseString, | ||
| category: category, | ||
| hkSampleType: Self.hkSampleType) | ||
| } | ||
|
|
||
| override func units(healthStore : HKHealthStore) async throws -> HKUnit { | ||
| .count() | ||
| } | ||
|
|
||
| override func recentDataPoints(days: Int, deadline: Int, healthStore: HKHealthStore) async throws -> [any BeeDataPoint] { | ||
| let todayDaystamp = Daystamp.now(deadline: deadline) | ||
| let startDaystamp = todayDaystamp - days | ||
|
|
||
| let predicate = HKQuery.predicateForSamples(withStart: startDaystamp.start(deadline: deadline), | ||
| end: todayDaystamp.end(deadline: deadline)) | ||
|
|
||
| let samples = try await queryHealthStore(healthStore, predicate: predicate) | ||
|
|
||
| let dailyCounts = calculateDailyCounts(samples: samples) | ||
|
|
||
| let datapoints = makeDatapoints(dailyCounts: dailyCounts, deadline: deadline) | ||
|
|
||
| return datapoints | ||
| } | ||
|
|
||
| func queryHealthStore(_ healthStore: HKHealthStore, predicate: NSPredicate) async throws -> [HKCategorySample] { | ||
| try await withCheckedThrowingContinuation({ (continuation: CheckedContinuation<[HKSample], Error>) in | ||
| let query = HKSampleQuery(sampleType: sampleType(), | ||
| predicate: predicate, | ||
| limit: HKObjectQueryNoLimit, | ||
| sortDescriptors: [NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)], | ||
| resultsHandler: { (query, samples, error) in | ||
| if let error { | ||
| continuation.resume(throwing: error) | ||
| } else if let samples { | ||
| continuation.resume(returning: samples) | ||
| } else { | ||
| continuation.resume(throwing: HealthKitError("HKSampleQuery did not return samples")) | ||
| } | ||
| }) | ||
| healthStore.execute(query) | ||
| }) | ||
| .compactMap { $0 as? HKCategorySample } | ||
| } | ||
|
|
||
| func calculateDailyCounts(samples: [HKCategorySample]) -> [(Date, Int)] { | ||
| let calendar = Calendar.autoupdatingCurrent | ||
| let groupedByDay = Dictionary(grouping: samples, by: { sample in | ||
| calendar.startOfDay(for: sample.startDate) | ||
| }) | ||
|
|
||
| let dailyCounts = groupedByDay | ||
| .map { ($0, $1.count) } | ||
| .sorted { $0.0 < $1.0 } | ||
|
|
||
| return dailyCounts | ||
| } | ||
|
|
||
| func makeDatapoints(dailyCounts: [(Date, Int)], deadline: Int) -> [any BeeDataPoint] { | ||
| let datapoints = dailyCounts.map({ (date, numberOfEntries) in | ||
| let daystamp = Daystamp(fromDate: date, deadline: deadline) | ||
| let requestID = "apple-heath-" + daystamp.description | ||
|
|
||
| return NewDataPoint(requestid: requestID, | ||
| daystamp: daystamp, | ||
| value: NSNumber(value: numberOfEntries), | ||
| comment: "Auto-entered via Apple Health (\(Self.healthkitMetric))") | ||
| }) | ||
|
|
||
| return datapoints | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.