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

Fix calculation for meditation minutes #453

Merged
merged 1 commit into from
Apr 29, 2024
Merged
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
42 changes: 40 additions & 2 deletions BeeKit/HeathKit/MindfulSessionHealthKitMetric.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,46 @@ class MindfulSessionHealthKitMetric : CategoryHealthKitMetric {
super.init(humanText: humanText, databaseString: databaseString, category: category, hkSampleType: HKObjectType.categoryType(forIdentifier: .mindfulSession)!)
}

override func valueInAppropriateUnits(rawValue: Double) -> Double {
return rawValue / minuteInSeconds
override func hkDatapointValueForSamples(samples: [HKSample], startOfDate: Date) -> Double {
let endOfDate = startOfDate.addingTimeInterval(24 * 60 * 60)

let orderedSamples = samples.sorted(by: { $0.startDate < $1.startDate })

var spanStart: Optional<Date> = nil
var spanEnd: Optional<Date> = nil
var totalSeconds = 0.0

for sample in orderedSamples {
if sample.hasUndeterminedDuration {
continue
}

let sampleStart = max(sample.startDate, startOfDate)
let sampleEnd = min(sample.endDate, endOfDate)

if let start = spanStart, let end = spanEnd {
// There is an existing span to examine
if sampleStart <= end {
// If the sample overlaps with the current span, extend the span
spanEnd = max(end, sampleEnd)
} else {
// Otherwise, add the span to the total and start a new span
totalSeconds += end.timeIntervalSince(start)
spanStart = sampleStart
spanEnd = sampleEnd
}
} else {
// No prior span, start with this one
spanStart = sampleStart
spanEnd = sampleEnd
}
}
if let end = spanEnd {
totalSeconds += end.timeIntervalSince(spanStart!)
}

let totalMinutes = totalSeconds / minuteInSeconds
return totalMinutes.rounded()
}

override func units(healthStore : HKHealthStore) async throws -> HKUnit {
Expand Down