← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Health/SleepSummary.swift (3051B)

1import Foundation
2
3extension SleepHealth {
4    /// Asleep samples closer together than this are one session.
5    static let sessionGap: TimeInterval = 60 * 60
6
7    /// The longest sleep session in `samples`, from a single source.
8    ///
9    /// The iPhone and the Watch both record sleep, and their samples overlap,
10    /// so adding them up would count the night twice. The source with the
11    /// most time asleep is used on its own. Its asleep samples are split into
12    /// sessions where they're more than `sessionGap` apart, so a nap the
13    /// afternoon before isn't joined to the night, and the longest session is
14    /// the night.
15    init?(samples: [SleepSample]) {
16        let bySource = Dictionary(grouping: samples, by: \.source)
17        let best = bySource.values.max { a, b in
18            Self.asleep(in: a) < Self.asleep(in: b)
19        }
20        guard let best else { return nil }
21        let asleep = best.filter { $0.stage.isAsleep }.sorted { $0.start < $1.start }
22        var sessions: [[SleepSample]] = []
23        for sample in asleep {
24            if let last = sessions.last?.last, sample.start.timeIntervalSince(last.end) <= Self.sessionGap {
25                sessions[sessions.count - 1].append(sample)
26            } else {
27                sessions.append([sample])
28            }
29        }
30        guard let night = sessions.max(by: { Self.asleep(in: $0) < Self.asleep(in: $1) }),
31            let start = night.map(\.start).min(), let end = night.map(\.end).max()
32        else { return nil }
33        let span = start..<end
34        func total(_ stage: SleepSample.Stage) -> TimeInterval {
35            best.filter { $0.stage == stage }.reduce(0) { $0 + Self.overlap($1, span) }
36        }
37        let hasStages = night.contains { $0.stage != .asleep }
38        self.init(
39            start: start,
40            end: end,
41            asleep: Self.asleep(in: night),
42            core: hasStages ? total(.core) : nil,
43            deep: hasStages ? total(.deep) : nil,
44            rem: hasStages ? total(.rem) : nil,
45            awake: hasStages ? total(.awake) : nil)
46    }
47
48    /// Time asleep, with overlapping samples counted once.
49    private static func asleep(in samples: [SleepSample]) -> TimeInterval {
50        var total: TimeInterval = 0
51        var reach = Date.distantPast
52        for sample in samples.filter({ $0.stage.isAsleep }).sorted(by: { $0.start < $1.start }) {
53            let start = max(sample.start, reach)
54            if sample.end > start { total += sample.end.timeIntervalSince(start) }
55            reach = max(reach, sample.end)
56        }
57        return total
58    }
59
60    private static func overlap(_ sample: SleepSample, _ span: Range<Date>) -> TimeInterval {
61        let start = max(sample.start, span.lowerBound)
62        let end = min(sample.end, span.upperBound)
63        return max(0, end.timeIntervalSince(start))
64    }
65}
66
67extension SleepSample.Stage {
68    var isAsleep: Bool {
69        switch self {
70        case .asleep, .core, .deep, .rem: true
71        case .inBed, .awake: false
72        }
73    }
74}