Skip to content
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

Apple Health metrics: toothbrushing as sessions per day and as minutes per day #556

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions BeeKit/HeathKit/HealthKitConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ public enum HealthKitConfig {
QuantityHealthKitMetric(humanText: "Vitamin K", databaseString: "dietaryVitaminK", category: .Nutrition, hkQuantityTypeIdentifier: .dietaryVitaminK),
QuantityHealthKitMetric(humanText: "Water", databaseString: "water", category: .Nutrition, hkQuantityTypeIdentifier: .dietaryWater),

// Self care
ToothbrushingDailyMinutesHealthKitMetric.make(),
ToothbrushingDailySessionsHealthKitMetric.make(),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't want to have multiple top level metrics for the same underlying metric. There are lots of metrics where this could make sense, and the list risks getting far too long.
The way I think this should work:

  1. There is one metric for toothbrushing.
  2. On the preview/confirm page, there are additional settings to refine exactly how the metric is logged. These are stored using additional attributes on the autodata key on the goal. The preview updates as these settings are changed.
  3. For toothbrushing in particular, this should be either "Aggregate Total Daily Minutes", or reporting each toothbrushing session as a separate data point with its number of minutes. People can count sessions via adjusting aggday.

Note this will require some tweaks to the sync code to allow multiple data points per day to be synced correctly. A while back the app started including requestid with these points to help facilitate this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Customizing aggday is possible with a custom goal. A typical do more (hustler) goal type will have its how to aggregate the day set to sum.


// Sleep
TimeInBedHealthKitMetric(humanText: "Time in bed", databaseString: "timeInBed", category: .Sleep),
TimeAsleepHealthKitMetric(humanText: "Time asleep", databaseString: "timeAsleep", category: .Sleep),
Expand Down
1 change: 1 addition & 0 deletions BeeKit/HeathKit/HealthKitMetric.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public enum HealthKitCategory : String, CaseIterable {
case Heart = "Heart"
case Mindfulness = "Mindfulness"
case Nutrition = "Nutrition"
case SelfCare = "Self Care"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These categories map to the categorizations in the Health app. Toothbrushing is under "Other".

case Sleep = "Sleep"
case Other = "Other Data"
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
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: "|")

private init(humanText: String,
databaseString: String,
category: HealthKitCategory) {
super.init(humanText: humanText,
databaseString: databaseString,
category: category,
hkSampleType: HKObjectType.categoryType(forIdentifier: .toothbrushingEvent)!)
}

override func units(healthStore : HKHealthStore) async throws -> HKUnit {
HKUnit.second()
}

static func make() -> ToothbrushingDailyMinutesHealthKitMetric {
.init(humanText: "Teethbrushing (in seconds per day)",
databaseString: healthkitMetric,
category: HealthKitCategory.SelfCare)
}
krugerk marked this conversation as resolved.
Show resolved Hide resolved

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] {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than this, can probably just implement valueInAppropriateUnits

Copy link
Contributor Author

@krugerk krugerk Dec 19, 2024

Choose a reason for hiding this comment

The 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,75 @@
// 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 init(humanText: String,
databaseString: String,
category: HealthKitCategory) {
super.init(humanText: humanText,
databaseString: databaseString,
category: category,
hkSampleType: HKObjectType.categoryType(forIdentifier: .toothbrushingEvent)!)
}

override func units(healthStore : HKHealthStore) async throws -> HKUnit {
.count()
}

static func make() -> ToothbrushingDailySessionsHealthKitMetric {
.init(humanText: "Teethbrushing (in sessions per day)",
databaseString: healthkitMetric,
category: HealthKitCategory.SelfCare)
}

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 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 }

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 }

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
}
}
16 changes: 16 additions & 0 deletions BeeSwift.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
objects = {

/* Begin PBXBuildFile section */
9B1DCA5B2D10EA76006A64D9 /* ToothbrushingDailyMinutesHealthKitMetric.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B1DCA5A2D10EA76006A64D9 /* ToothbrushingDailyMinutesHealthKitMetric.swift */; };
9B7D44662D12C304003B62B1 /* ToothbrushingDailySessionsHealthKitMetric.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B7D44652D12C304003B62B1 /* ToothbrushingDailySessionsHealthKitMetric.swift */; };
9B8CA57D24B120CA009C86C2 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 9B8CA57C24B120CA009C86C2 /* LaunchScreen.storyboard */; };
A10D4E931B07948500A72D29 /* DatapointsTableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10D4E921B07948500A72D29 /* DatapointsTableView.swift */; };
A10DC2DF207BFCBA00FB7B3A /* RemoveHKMetricViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A10DC2DE207BFCBA00FB7B3A /* RemoveHKMetricViewController.swift */; };
Expand Down Expand Up @@ -217,6 +219,8 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
9B1DCA5A2D10EA76006A64D9 /* ToothbrushingDailyMinutesHealthKitMetric.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToothbrushingDailyMinutesHealthKitMetric.swift; sourceTree = "<group>"; };
9B7D44652D12C304003B62B1 /* ToothbrushingDailySessionsHealthKitMetric.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ToothbrushingDailySessionsHealthKitMetric.swift; sourceTree = "<group>"; };
9B8CA57C24B120CA009C86C2 /* LaunchScreen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = "<group>"; };
A10D4E921B07948500A72D29 /* DatapointsTableView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatapointsTableView.swift; sourceTree = "<group>"; };
A10DC2DE207BFCBA00FB7B3A /* RemoveHKMetricViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoveHKMetricViewController.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -409,6 +413,15 @@
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
9B7D44642D12C2F3003B62B1 /* Toothbrushing */ = {
isa = PBXGroup;
children = (
9B7D44652D12C304003B62B1 /* ToothbrushingDailySessionsHealthKitMetric.swift */,
9B1DCA5A2D10EA76006A64D9 /* ToothbrushingDailyMinutesHealthKitMetric.swift */,
);
path = Toothbrushing;
sourceTree = "<group>";
};
A106AD8B1AF1F62800C434E8 /* Managers */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -622,6 +635,7 @@
E4E6426E290E27CB004F3EA9 /* HeathKit */ = {
isa = PBXGroup;
children = (
9B7D44642D12C2F3003B62B1 /* Toothbrushing */,
A1E618FF1E86980900D8ED93 /* HealthKitConfig.swift */,
E4E642832910C442004F3EA9 /* CategoryHealthKitMetric.swift */,
E4E642872910D055004F3EA9 /* MindfulSessionHealthKitMetric.swift */,
Expand Down Expand Up @@ -1073,6 +1087,7 @@
E45470282B60E24500EE648B /* Daystamp.swift in Sources */,
E458C8042AD11BC3000DCA5C /* SignedRequestManager.swift in Sources */,
E458C8162AD11CA2000DCA5C /* HealthKitError.swift in Sources */,
9B1DCA5B2D10EA76006A64D9 /* ToothbrushingDailyMinutesHealthKitMetric.swift in Sources */,
E458C81E2AD11D05000DCA5C /* DateUtils.swift in Sources */,
E4B0A33128C194C900055EA7 /* AddDataIntents.intentdefinition in Sources */,
E458C8132AD11C94000DCA5C /* HealthKitMetric.swift in Sources */,
Expand Down Expand Up @@ -1104,6 +1119,7 @@
E46071012B451FA400305DB4 /* BeeminderModel.xcdatamodeld in Sources */,
E458C80D2AD11C64000DCA5C /* Crypto.swift in Sources */,
E458C8012AD11BB3000DCA5C /* RequestManager.swift in Sources */,
9B7D44662D12C304003B62B1 /* ToothbrushingDailySessionsHealthKitMetric.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
2 changes: 1 addition & 1 deletion BeeSwift/Settings/RemoveHKMetricViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class RemoveHKMetricViewController: UIViewController {
attrString.append(NSMutableAttributedString(string: "\(self.goal.slug)\n",
attributes: [NSAttributedString.Key.font: UIFont.beeminder.defaultBoldFont]))

attrString.append(NSMutableAttributedString(string: "This goal obtains its data from Apple Health (\(self.goal.humanizedAutodata!)). You can disconnect the goal with the button below.",
attrString.append(NSMutableAttributedString(string: "This goal obtains its data from Apple Health (\(self.goal.humanizedAutodata ?? self.goal.healthKitMetric ?? "unknown metric")). You can disconnect the goal with the button below.",
krugerk marked this conversation as resolved.
Show resolved Hide resolved
attributes: [NSAttributedString.Key.font: UIFont.beeminder.defaultFontLight.withSize(Constants.defaultFontSize)]))
return attrString
}()
Expand Down
Loading