Repository Public License
1// ORIX Alarm2// File: App/Features/Nightstand/NightstandSession.swift3// Description: Drives one Nightstand session: wake timeline, soundscape level, screen-awake and brightness handling, compressed demo.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import UIKit910/// State of the bedside screen. Everything it changes on the device (idle timer, brightness, battery monitoring,11/// audio) is restored by `end()`.12@Observable13final class NightstandSession {14 typealias Snapshot = ProgressiveWakeTimeline.Snapshot1516 /// Compressed demo: a short night, the whole lead window in forty seconds, then the "alarm" moment.17 enum Demo {18 static let idle: TimeInterval = 419 static let lead: TimeInterval = 4020 static let alarm: TimeInterval = 1021 }2223 private(set) var alarm: AlarmDefinition?24 private(set) var timeline: ProgressiveWakeTimeline?25 private(set) var snapshot = Snapshot.idle26 private(set) var isDemo = false27 private(set) var batteryState = UIDevice.BatteryState.unknown28 /// Hardware volume (0...1) as last read. The app cannot change it.29 private(set) var deviceVolume = 1.030 var soundEnabled = true { didSet { if oldValue != soundEnabled { applyAudio(ramp: 1) } } }31 /// Opt-in: raise the screen brightness along with the sunrise. The previous brightness is restored on exit.32 var raisesBrightness = UserDefaults.standard.bool(forKey: NightstandSession.brightnessKey) {33 didSet {34 UserDefaults.standard.set(raisesBrightness, forKey: Self.brightnessKey)35 if raisesBrightness { applyBrightness() } else { restoreBrightness() }36 }37 }3839 static let brightnessKey = "nightstand.raisesBrightness"4041 @ObservationIgnored private var now: () -> Date = { .now }42 @ObservationIgnored private var nextFireDate: () -> Date? = { nil }43 @ObservationIgnored private var isActive = false44 @ObservationIgnored private var savedIdleTimerDisabled = false45 @ObservationIgnored private var savedBatteryMonitoring = false46 @ObservationIgnored private var savedBrightness: CGFloat?47 @ObservationIgnored private var demoAlarmPreviewed = false4849 /// Seconds between two `tick()` calls: fine-grained in the demo, once a second otherwise.50 var tickInterval: TimeInterval { isDemo ? 0.25 : 1 }51 var soundscape: SoundAsset? { alarm.map { SoundCatalog.soundscape($0.scenario.progressive.soundscapeID) } }52 /// True when the alarm has a progressive wake to play (always true in the demo).53 var hasProgressiveWake: Bool { (timeline?.lead ?? 0) > 0 }54 var fireDate: Date? { timeline?.fireDate }5556 // MARK: Lifecycle5758 func begin(alarm: AlarmDefinition, now: @escaping () -> Date, nextFireDate: @escaping () -> Date?) {59 guard !isActive else { return }60 isActive = true61 self.alarm = alarm; self.now = now; self.nextFireDate = nextFireDate62 savedIdleTimerDisabled = UIApplication.shared.isIdleTimerDisabled63 UIApplication.shared.isIdleTimerDisabled = true // keep the screen on while this view is visible64 savedBatteryMonitoring = UIDevice.current.isBatteryMonitoringEnabled65 UIDevice.current.isBatteryMonitoringEnabled = true66 // SwiftUI may tear the cover down and bring it back (another cover settling, a scene change): a demo that was67 // running starts over instead of silently turning into the real countdown.68 if isDemo { startDemo() } else { armForNextOccurrence(); tick() }69 }7071 func end() {72 guard isActive else { return }73 isActive = false74 UIApplication.shared.isIdleTimerDisabled = savedIdleTimerDisabled75 UIDevice.current.isBatteryMonitoringEnabled = savedBatteryMonitoring76 restoreBrightness()77 SoundPlayer.shared.stopSoundscape(fade: 0.6)78 if demoAlarmPreviewed { SoundPlayer.shared.stopPreview() }79 }8081 /// The app left the foreground: give the screen back as we found it. Audio is handled by the system (no background mode).82 func suspend() {83 guard isActive else { return }84 restoreBrightness()85 }8687 func resume() {88 guard isActive else { return }89 UIApplication.shared.isIdleTimerDisabled = true90 tick()91 SoundPlayer.shared.resumeSoundscapeIfNeeded()92 }9394 // MARK: Demo9596 func startDemo() {97 guard let alarm else { return }98 var progressive = alarm.scenario.progressive99 progressive.isEnabled = true100 stopDemoAudio()101 isDemo = true102 timeline = ProgressiveWakeTimeline(fireDate: Date().addingTimeInterval(Demo.idle + Demo.lead), progressive: progressive,103 leadOverride: Demo.lead, mainAlarmDuration: Demo.alarm)104 tick()105 }106107 func stopDemo() {108 guard isDemo else { return }109 stopDemoAudio()110 isDemo = false111 restoreBrightness()112 armForNextOccurrence()113 tick()114 }115116 private func stopDemoAudio() {117 SoundPlayer.shared.stopSoundscape(fade: 0.4)118 if demoAlarmPreviewed { SoundPlayer.shared.stopPreview(); demoAlarmPreviewed = false }119 }120121 private func armForNextOccurrence() {122 guard let alarm else { return }123 timeline = nextFireDate().map { ProgressiveWakeTimeline(fireDate: $0, progressive: alarm.scenario.progressive) }124 }125126 // MARK: Tick127128 func tick() {129 guard isActive, let alarm else { return }130 batteryState = UIDevice.current.batteryState131 deviceVolume = SoundPlayer.shared.deviceVolume132 guard let timeline else {133 snapshot = Snapshot.idle134 return135 }136 // The demo runs on the real clock; a real night uses the model's clock (injectable in tests).137 snapshot = timeline.snapshot(at: isDemo ? Date() : now())138 applyAudio(ramp: tickInterval * 1.5)139 applyBrightness()140 if isDemo {141 // In the demo nothing rings for real: preview the alarm sound at the "fire" moment to show the hand-over.142 if snapshot.stage == .mainAlarm, !demoAlarmPreviewed, soundEnabled {143 demoAlarmPreviewed = true144 if SoundPlayer.shared.previewingID != alarm.soundID { SoundPlayer.shared.togglePreview(alarmSoundID: alarm.soundID) }145 } else if snapshot.stage == .finished, demoAlarmPreviewed {146 SoundPlayer.shared.stopPreview(); demoAlarmPreviewed = false147 }148 } else if snapshot.stage == .finished, let next = nextFireDate(), next > timeline.fireDate {149 // A repeating alarm: once this morning is over, get ready for the next occurrence.150 armForNextOccurrence()151 }152 }153154 private func applyAudio(ramp: TimeInterval) {155 guard isActive, let id = soundscape?.id else { return }156 let player = SoundPlayer.shared157 let inLead = snapshot.stage == .preparation || snapshot.stage == .gentleWake158 if inLead, soundEnabled {159 player.setSoundscape(id: id)160 player.setIntensity(snapshot.audioIntensity, ramp: ramp)161 } else if player.soundscapeID != nil {162 // Outside the lead window, or muted: fade out. At the fire time the system alarm takes over.163 player.stopSoundscape(fade: inLead ? 0.6 : 2)164 }165 }166167 // MARK: Brightness168169 private var screen: UIScreen? { UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.screen }.first }170171 /// Raises the brightness with the sunrise, never below what the user had, and only when the option is on.172 private func applyBrightness() {173 guard isActive, raisesBrightness, let screen else { return }174 let light = snapshot.sunriseProgress175 guard light > 0 else { return restoreBrightness() }176 if savedBrightness == nil { savedBrightness = screen.brightness }177 let base = savedBrightness ?? screen.brightness178 screen.brightness = base + (1 - base) * light179 }180181 private func restoreBrightness() {182 guard let saved = savedBrightness else { return }183 screen?.brightness = saved184 savedBrightness = nil185 }186}187