Kaynağa Gözat

Focus to the snooze tab

Jonas Björkert 1 yıl önce
ebeveyn
işleme
7b64fe4845

+ 10 - 10
LoopFollow/Alarm/AlarmManager.swift

@@ -12,16 +12,13 @@ class AlarmManager {
     static let shared = AlarmManager()
 
     private let evaluators: [AlarmType: AlarmCondition]
-    private let config: AlarmConfiguration
 
     private init(
-        config: AlarmConfiguration = .default,
         conditionTypes: [AlarmCondition.Type] = [
             BuildExpireCondition.self
-            // …add your other condition types here
+            // TODO: add other condition types here
         ]
     ) {
-        self.config = config
         var dict = [AlarmType: AlarmCondition]()
         conditionTypes.forEach { dict[$0.type] = $0.init() }
         evaluators = dict
@@ -62,18 +59,21 @@ class AlarmManager {
 
             // Evaluate the alarm condition.
             guard let checker = evaluators[alarm.type],
-                  checker.shouldFire(alarm: alarm, data: data, now: now, config: config)
+                  checker
+                .shouldFire(
+                    alarm: alarm,
+                    data: data,
+                    now: now,
+                    config: Storage.shared.alarmConfiguration.value
+                )
             else {
                 continue
             }
 
             // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
+            Observable.shared.currentAlarm.value = alarm.id
 
-            //TODO: a few things affecting the snoozed screen
-            Storage.shared.currentAlarm.value = alarm.id
-            //tabBarController?.selectedIndex = 2
-
-            alarm.trigger(config: config, now: now)
+            alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
             break
         }
     }

+ 21 - 21
LoopFollow/Controllers/AlarmSound.swift

@@ -112,21 +112,21 @@ class AlarmSound {
             //self.audioPlayer!.volume = (self.muted || (UserDefaultsRepository.fadeInTimeInterval.value > 0)) ? 0.0 : 1.0
             
             if !self.audioPlayer!.prepareToPlay() {
-                LogManager.shared.log(category: .general, message: "AlarmSound - audio player failed preparing to play")
+                LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
             }
             
             if self.audioPlayer!.play() {
                 if !self.isPlaying {
-                    LogManager.shared.log(category: .general, message: "AlarmSound - not playing after calling play")
-                    LogManager.shared.log(category: .general, message: "AlarmSound - rate value: \(self.audioPlayer!.rate)")
+                    LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
+                    LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(self.audioPlayer!.rate)")
                 }
             } else {
-                LogManager.shared.log(category: .general, message: "AlarmSound - audio player failed to play")
+                LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
             }
             
             
         } catch let error {
-            LogManager.shared.log(category: .general, message: "AlarmSound - unable to play sound; error: \(error)")
+            LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
         }
     }
     
@@ -156,16 +156,16 @@ class AlarmSound {
             //self.audioPlayer!.volume = (self.muted || (UserDefaultsRepository.fadeInTimeInterval.value > 0)) ? 0.0 : 1.0
             
             if !self.audioPlayer!.prepareToPlay() {
-                LogManager.shared.log(category: .general, message: "AlarmSound - audio player failed preparing to play")
+                LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
             }
             
             if self.audioPlayer!.play() {
                 if !self.isPlaying {
-                    LogManager.shared.log(category: .general, message: "AlarmSound - not playing after calling play")
-                    LogManager.shared.log(category: .general, message: "AlarmSound - rate value: \(self.audioPlayer!.rate)")
+                    LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
+                    LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(self.audioPlayer!.rate)")
                 }
             } else {
-                LogManager.shared.log(category: .general, message: "AlarmSound - audio player failed to play")
+                LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
             }
             
             
@@ -178,7 +178,7 @@ class AlarmSound {
                 MPVolumeView.setVolume(Storage.shared.alarmConfiguration.value.forcedOutputVolume)
             }
         } catch let error {
-            LogManager.shared.log(category: .general, message: "AlarmSound - unable to play sound; error: \(error)")
+            LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
         }
     }
     
@@ -205,16 +205,16 @@ class AlarmSound {
             
             
             if !self.audioPlayer!.prepareToPlay() {
-                LogManager.shared.log(category: .general, message: "Terminate AlarmSound - audio player failed preparing to play")
+                LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed preparing to play")
             }
             
             if self.audioPlayer!.play() {
                 if !self.isPlaying {
-                    LogManager.shared.log(category: .general, message: "Terminate AlarmSound - not playing after calling play")
-                    LogManager.shared.log(category: .general, message: "Terminate AlarmSound - rate value: \(self.audioPlayer!.rate)")
+                    LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - not playing after calling play")
+                    LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - rate value: \(self.audioPlayer!.rate)")
                 }
             } else {
-                LogManager.shared.log(category: .general, message: "Terminate AlarmSound - audio player failed to play")
+                LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed to play")
             }
             
             
@@ -222,7 +222,7 @@ class AlarmSound {
            
             
         } catch let error {
-            LogManager.shared.log(category: .general, message: "Terminate AlarmSound - unable to play sound; error: \(error)")
+            LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - unable to play sound; error: \(error)")
         }
     }
 
@@ -249,7 +249,7 @@ class AlarmSound {
             try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
             try AVAudioSession.sharedInstance().setActive(true)
         } catch {
-            LogManager.shared.log(category: .general, message: "Enable audio error: \(error)")
+            LogManager.shared.log(category: .alarm, message: "Enable audio error: \(error)")
         }
     }
 }
@@ -258,15 +258,15 @@ class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate {
 
     /* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
     func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
-        LogManager.shared.log(category: .general, message: "AlarmRule - audioPlayerDidFinishPlaying (\(flag))", isDebug: true)
+        LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDidFinishPlaying (\(flag))", isDebug: true)
     }
     
     /* if an error occurs while decoding it will be reported to the delegate. */
     func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
         if let error = error {
-            LogManager.shared.log(category: .general, message: "AlarmRule - audioPlayerDecodeErrorDidOccur: \(error)")
+            LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur: \(error)")
         } else {
-            LogManager.shared.log(category: .general, message: "AlarmRule - audioPlayerDecodeErrorDidOccur")
+            LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur")
         }
     }
     
@@ -274,14 +274,14 @@ class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate {
     
     /* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
     func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
-        LogManager.shared.log(category: .general, message: "AlarmRule - audioPlayerBeginInterruption")
+        LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerBeginInterruption")
     }
     
     
     /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
     /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
     func audioPlayerEndInterruption(_ player: AVAudioPlayer, withOptions flags: Int) {
-        LogManager.shared.log(category: .general, message: "AlarmRule - audioPlayerEndInterruption withOptions: \(flags)")
+        LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerEndInterruption withOptions: \(flags)")
     }
 }
 

+ 2 - 0
LoopFollow/Storage/Observable.swift

@@ -28,5 +28,7 @@ class Observable {
     var directionText = ObservableValue<String>(default: "-")
     var deltaText = ObservableValue<String>(default: "+0")
 
+    var currentAlarm = ObservableValue<UUID?>(default: nil)
+
     private init() {}
 }

+ 0 - 1
LoopFollow/Storage/Storage.swift

@@ -55,7 +55,6 @@ class Storage {
         key: "alarmConfiguration",
         defaultValue: .default
     )
-    var currentAlarm = StorageValue<UUID?>(key: "currentAlarm", defaultValue: nil)
 
     static let shared = Storage()
     private init() { }

+ 1 - 1
LoopFollow/Task/AlarmTask.swift

@@ -23,7 +23,7 @@ extension MainViewController {
             //TODO: Fyll på med mer alarmData
             //TODO: gör det möjligt att köra med fejkad data.
             let alarmData = AlarmData(
-                expireDate: Storage.shared.expirationDate.value
+                expireDate: .distantPast // Storage.shared.expirationDate.value
             )
 
             LogManager.shared.log(category: .alarm, message: "Checking alarms based on \(alarmData)", isDebug: true)

+ 2 - 2
LoopFollow/Task/TaskScheduler.swift

@@ -48,7 +48,7 @@ class TaskScheduler {
 
     func rescheduleTask(id: TaskID, to newRunDate: Date) {
         let timeString = self.formatTime(newRunDate)
-        LogManager.shared.log(category: .taskScheduler, message: "Reschedule Task \(id): next run = \(timeString)", isDebug: true)
+        //LogManager.shared.log(category: .taskScheduler, message: "Reschedule Task \(id): next run = \(timeString)", isDebug: true)
 
         queue.async {
             guard var existingTask = self.tasks[id] else { return }
@@ -118,7 +118,7 @@ class TaskScheduler {
             updatedTask.nextRun = .distantFuture
             tasks[taskID] = updatedTask
 
-            LogManager.shared.log(category: .taskScheduler, message: "Executing task \(taskID)", isDebug: true)
+            //LogManager.shared.log(category: .taskScheduler, message: "Executing Task \(taskID)", isDebug: true)
 
             DispatchQueue.main.async {
                 task.action()

+ 9 - 0
LoopFollow/ViewControllers/MainViewController.swift

@@ -235,6 +235,15 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
                 self?.DeltaText.text = newValue
             }
             .store(in: &cancellables)
+
+        /// When an alarm is triggered, go to the snoozer tab
+        Observable.shared.currentAlarm.$value
+            .receive(on: DispatchQueue.main)
+            .compactMap { $0 } /// Ignore nil
+            .sink { [weak self] _ in
+                self?.tabBarController?.selectedIndex = 2
+            }
+            .store(in: &cancellables)
     }
 
     deinit {

+ 0 - 68
LoopFollowTests/AlwaysTrueCondition.swift

@@ -8,71 +8,3 @@
 
 import XCTest
 @testable import LoopFollow
-/*
-struct AlwaysTrueCondition: AlarmCondition {
-    static let type: AlarmType = .low
-    init() {}
-    func evaluate(alarm: Alarm, data: AlarmData) -> Bool { true }
-}
-
-final class CommonAlarmGuardsTests: XCTestCase {
-    var now: Date!
-    var config: AlarmConfiguration!
-    var context: AlarmContext!
-    var alarm: Alarm!
-    var data: AlarmData!
-    var cond: AlwaysTrueCondition!
-
-    override func setUp() {
-        super.setUp()
-        now = Date()
-        config = .default
-        context = AlarmContext(now: now, config: config)
-
-        alarm = Alarm(type: .low)
-        alarm.name = "test"
-        alarm.isEnabled = true
-        alarm.snoozedUntil = nil
-        alarm.playSoundOption = .always
-        alarm.activeOption = .always
-        alarm.snoozeDuration = 0
-
-        data = AlarmData(expireDate: nil)
-        cond = AlwaysTrueCondition()
-    }
-
-    func testMuteUntil() {
-        config.muteUntil = now.addingTimeInterval(60)
-        context = AlarmContext(now: now, config: config)
-        XCTAssertFalse(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-
-    func testDisabledAlarm() {
-        alarm.isEnabled = false
-        XCTAssertFalse(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-
-    func testSnoozedAlarm() {
-        alarm.snoozedUntil = now.addingTimeInterval(60)
-        XCTAssertFalse(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-
-    func testRespectsNightFlag() {
-        let night = Calendar.current.date(bySettingHour: 23, minute: 0, second: 0, of: now)!
-        alarm.activeOption = .day // alarm should be inactive at night
-        context = AlarmContext(now: night, config: config)
-        XCTAssertFalse(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-
-    func testRespectsDayFlag() {
-        let day = Calendar.current.date(bySettingHour: 9, minute: 0, second: 0, of: now)!
-        alarm.activeOption = .night // alarm should be inactive during day
-        context = AlarmContext(now: day, config: config)
-        XCTAssertFalse(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-
-    func testAllGuardsPass() {
-        XCTAssertTrue(cond.shouldFire(alarm: alarm, data: data, context: context))
-    }
-}
-*/