ソースを参照

Update: Refactor timers into one extension class

Jon Fawcett 5 年 前
コミット
f7fa3b4660

+ 4 - 0
LoopFollow.xcodeproj/project.pbxproj

@@ -149,6 +149,7 @@
 		FC9788212485969B00A7906C /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FC97881F2485969B00A7906C /* Main.storyboard */; };
 		FC9788262485969C00A7906C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FC9788252485969C00A7906C /* Assets.xcassets */; };
 		FC9788292485969C00A7906C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FC9788272485969C00A7906C /* LaunchScreen.storyboard */; };
+		FCA2DDE62501095000254A8C /* Timers.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCA2DDE52501095000254A8C /* Timers.swift */; };
 		FCC0FAC224922A22003E610E /* DictionaryKeyPath.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC0FAC124922A22003E610E /* DictionaryKeyPath.swift */; };
 		FCC68850248935D800A0279D /* AlarmViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC6884F248935D800A0279D /* AlarmViewController.swift */; };
 		FCC6885C2489559400A0279D /* blank.wav in Resources */ = {isa = PBXBuildFile; fileRef = FCC6885B2489559400A0279D /* blank.wav */; };
@@ -314,6 +315,7 @@
 		FC9788202485969B00A7906C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
 		FC9788252485969C00A7906C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
 		FC9788282485969C00A7906C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+		FCA2DDE52501095000254A8C /* Timers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Timers.swift; sourceTree = "<group>"; };
 		FCC0FAC124922A22003E610E /* DictionaryKeyPath.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DictionaryKeyPath.swift; sourceTree = "<group>"; };
 		FCC6884F248935D800A0279D /* AlarmViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AlarmViewController.swift; sourceTree = "<group>"; };
 		FCC688592489554800A0279D /* BackgroundTaskAudio.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackgroundTaskAudio.swift; sourceTree = "<group>"; };
@@ -398,6 +400,7 @@
 				FC16A97E249969E2003D6245 /* Graphs.swift */,
 				FC1BDD2A24A22650001B652C /* Stats.swift */,
 				FC1BDD2C24A23204001B652C /* StatsView.swift */,
+				FCA2DDE52501095000254A8C /* Timers.swift */,
 			);
 			path = Controllers;
 			sourceTree = "<group>";
@@ -883,6 +886,7 @@
 				FCE537BC249A4D7D00F80BF8 /* carbBolusArrays.swift in Sources */,
 				FCD2A27D24C9D044009F7B7B /* Globals.swift in Sources */,
 				DDCF979A24C14DB4002C9752 /* WatchSettingsViewController.swift in Sources */,
+				FCA2DDE62501095000254A8C /* Timers.swift in Sources */,
 				FC16A98124996C07003D6245 /* DateTime.swift in Sources */,
 				FC3CAB022493B6220068A152 /* BackgroundTaskAudio.swift in Sources */,
 			);

+ 0 - 1
LoopFollow/Controllers/NightScout.swift

@@ -344,7 +344,6 @@ extension MainViewController {
                 return
             }
             self.updateBGGraph()
-            self.updateMinAgo()
             self.updateStats()
         }
         

+ 149 - 0
LoopFollow/Controllers/Timers.swift

@@ -0,0 +1,149 @@
+//
+//  Timers.swift
+//  LoopFollow
+//
+//  Created by Jon Fawcett on 9/3/20.
+//  Copyright © 2020 Jon Fawcett. All rights reserved.
+//
+
+import Foundation
+import UIKit
+
+
+extension MainViewController {
+    
+    
+    
+    // min Ago Timer
+    func startMinAgoTimer(time: TimeInterval) {
+        minAgoTimer = Timer.scheduledTimer(timeInterval: time,
+                                           target: self,
+                                           selector: #selector(MainViewController.minAgoTimerDidEnd(_:)),
+                                           userInfo: nil,
+                                           repeats: true)
+    }
+    
+    // Updates Min Ago display
+    @objc func minAgoTimerDidEnd(_ timer:Timer) {
+        
+        // print("min ago timer ended")
+        if bgData.count > 0 {
+            let bgSeconds = bgData.last!.date
+            let now = Date().timeIntervalSince1970
+            let secondsAgo = now - bgSeconds
+            
+            // Update Min Ago Displays
+            let formatter = DateComponentsFormatter()
+            formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
+            
+            if secondsAgo < 270 {
+                formatter.allowedUnits = [ .minute] // Units to display in the formatted string
+            } else {
+                formatter.allowedUnits = [ .minute, .second] // Units to display in the formatted string
+            }
+            
+            
+            //formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
+            let formattedDuration = formatter.string(from: secondsAgo)
+            
+            MinAgoText.text = formattedDuration ?? ""
+            MinAgoText.text! += " min ago"
+            latestMinAgoString = formattedDuration ?? ""
+            latestMinAgoString += " min ago"
+            
+            guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
+            snoozer.MinAgoLabel.text = formattedDuration ?? ""
+            snoozer.MinAgoLabel.text! += " min ago"
+        } else {
+            MinAgoText.text = ""
+            latestMinAgoString = ""
+            
+            guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
+            snoozer.MinAgoLabel.text = ""
+        }
+        
+    }
+    
+    // Main Download Timer
+    func startTimer(time: TimeInterval) {
+        timer = Timer.scheduledTimer(timeInterval: time,
+                                     target: self,
+                                     selector: #selector(MainViewController.timerDidEnd(_:)),
+                                     userInfo: nil,
+                                     repeats: true)
+    }
+    
+    // Check for new data when timer ends
+    @objc func timerDidEnd(_ timer:Timer) {
+        nightscoutLoader()
+    }
+    
+    // Runs a 60 second timer when an alarm is snoozed
+    // Prevents the alarm from triggering again while saving the snooze time to settings
+    // End function needs nothing done
+    func startCheckAlarmTimer(time: TimeInterval = 60) {
+        
+        checkAlarmTimer = Timer.scheduledTimer(timeInterval: time,
+                                               target: self,
+                                               selector: #selector(MainViewController.checkAlarmTimerDidEnd(_:)),
+                                               userInfo: nil,
+                                               repeats: false)
+    }
+    
+    @objc func checkAlarmTimerDidEnd(_ timer:Timer) {
+    }
+    
+    // Cancel and reset the playing alarm if it has not been snoozed after 4 min 50 seconds.
+    // This allows the next BG reading to either start the timer going or not fire if the situation has been resolved
+    func startAlarmPlayingTimer(time: TimeInterval = 290) {
+        let alarmPlayingTimer = Timer.scheduledTimer(timeInterval: time,
+                                           target: self,
+                                           selector: #selector(MainViewController.alarmPlayingTimerDidEnd(_:)),
+                                           userInfo: nil,
+                                           repeats: false)
+    }
+    
+    @objc func alarmPlayingTimerDidEnd(_ timer:Timer) {
+        if AlarmSound.isPlaying {
+            stopAlarmAtNextReading()
+        }
+    }
+    
+    // NS Loader Timer
+    func startViewTimer(time: TimeInterval) {
+        viewTimer = Timer.scheduledTimer(timeInterval: time,
+                                         target: self,
+                                         selector: #selector(MainViewController.viewTimerDidEnd(_:)),
+                                         userInfo: nil,
+                                         repeats: false)
+        
+    }
+    
+    // This delays a few things to hopefully all all data to arrive.
+    @objc func viewTimerDidEnd(_ timer:Timer) {
+        if bgData.count > 0 {
+            self.checkAlarms(bgs: bgData)
+            //self.updateMinAgo()
+            // self.updateBadge(val: bgData[bgData.count - 1].sgv)
+            //self.viewUpdateNSBG()
+            if UserDefaultsRepository.writeCalendarEvent.value {
+                self.writeCalendar()
+            }
+        }
+    }
+    
+    // Timer to allow us to write min ago calendar entries but not update them every 30 seconds
+    func startCalTimer(time: TimeInterval) {
+        calTimer = Timer.scheduledTimer(timeInterval: time,
+                                        target: self,
+                                        selector: #selector(MainViewController.calTimerDidEnd(_:)),
+                                        userInfo: nil,
+                                        repeats: false)
+    }
+    
+    // Nothing should be done when this timer ends because it just blocks the calendar from writing when it's active
+    @objc func calTimerDidEnd(_ timer:Timer) {
+        
+    }
+    
+}

+ 9 - 70
LoopFollow/ViewControllers/MainViewController.swift

@@ -74,6 +74,10 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
     // check every 30 Seconds whether new bgvalues should be retrieved
     let timeInterval: TimeInterval = 30.0
     
+    // Min Ago Timer
+    var minAgoTimer = Timer()
+    var minAgoTimeInterval: TimeInterval = 1.0
+    
     // View Delay Timer
     var viewTimer = Timer()
     let viewTimeInterval: TimeInterval = UserDefaultsRepository.viewRefreshDelay.value
@@ -202,6 +206,9 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
         if (UserDefaultsRepository.url.value != "" || (UserDefaultsRepository.shareUserName.value != "" && UserDefaultsRepository.sharePassword.value != "")) && firstGraphLoad {
             nightscoutLoader()
         }
+        
+        startMinAgoTimer(time: minAgoTimeInterval)
+        
     }
     
     override func viewWillAppear(_ animated: Bool) {
@@ -284,70 +291,6 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
         return cell
     }
     
-    
-    // NS Loader Timer
-    fileprivate func startTimer(time: TimeInterval) {
-        timer = Timer.scheduledTimer(timeInterval: time,
-                                     target: self,
-                                     selector: #selector(MainViewController.timerDidEnd(_:)),
-                                     userInfo: nil,
-                                     repeats: true)
-    }
-    
-    // Check Alarm Timer
-    func startCheckAlarmTimer(time: TimeInterval) {
-        
-        checkAlarmTimer = Timer.scheduledTimer(timeInterval: time,
-                                     target: self,
-                                     selector: #selector(MainViewController.checkAlarmTimerDidEnd(_:)),
-                                     userInfo: nil,
-                                     repeats: false)
-    }
-    
-    // NS Loader Timer
-     func startViewTimer(time: TimeInterval) {
-        viewTimer = Timer.scheduledTimer(timeInterval: time,
-                                     target: self,
-                                     selector: #selector(MainViewController.viewTimerDidEnd(_:)),
-                                     userInfo: nil,
-                                     repeats: false)
-        
-    }
-    
-    // Timer to allow us to write min ago calendar entries but not update them every 30 seconds
-    fileprivate func startCalTimer(time: TimeInterval) {
-        calTimer = Timer.scheduledTimer(timeInterval: time,
-                                     target: self,
-                                     selector: #selector(MainViewController.calTimerDidEnd(_:)),
-                                     userInfo: nil,
-                                     repeats: false)
-    }
-    
-    // Nothing should be done when this timer ends because it just blocks the alarms from firing when it's active
-    @objc func calTimerDidEnd(_ timer:Timer) {
-       // if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Calendar Timer Ended") }
-    }
-    
-    // This delays a few things to hopefully all all data to arrive.
-    @objc func viewTimerDidEnd(_ timer:Timer) {
-//        if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "View timer ended") }
-        if bgData.count > 0 {
-            self.checkAlarms(bgs: bgData)
-            self.updateMinAgo()
-            // self.updateBadge(val: bgData[bgData.count - 1].sgv)
-            //self.viewUpdateNSBG()
-            if UserDefaultsRepository.writeCalendarEvent.value {
-                self.writeCalendar()
-            }
-        }
-    }
-    
-    
-    // Nothing should be done when this timer ends because it just blocks the alarms from firing when it's active
-    @objc func checkAlarmTimerDidEnd(_ timer:Timer) {
-//        if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Check alarm timer ended") }
-    }
-    
     @objc func appMovedToBackground() {
         // Allow screen to turn off
         UIApplication.shared.isIdleTimerDisabled = false;
@@ -363,6 +306,7 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
             let refresh = UserDefaultsRepository.backgroundRefreshFrequency.value * 60
             startTimer(time: TimeInterval(refresh))
         }
+        
     }
 
     @objc func appCameToForeground() {
@@ -384,12 +328,7 @@ class MainViewController: UIViewController, UITableViewDataSource, ChartViewDele
         showHideNSDetails()
     }
     
-    // Check for new data when timer ends
-    @objc func timerDidEnd(_ timer:Timer) {
-//        if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Main timer ended") }
-        updateMinAgo()
-        nightscoutLoader()
-    }
+    
 
     //update Min Ago Text. We need to call this separately because it updates between readings
     func updateMinAgo(){