Timers.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //
  2. // Timers.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 9/3/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension MainViewController {
  11. func restartAllTimers() {
  12. if !bgTimer.isValid { startBGTimer(time: 2) }
  13. if !profileTimer.isValid { startProfileTimer(time: 3) }
  14. if !deviceStatusTimer.isValid { startDeviceStatusTimer(time: 4) }
  15. if !treatmentsTimer.isValid { startTreatmentsTimer(time: 5) }
  16. if !minAgoTimer.isValid { startMinAgoTimer(time: minAgoTimeInterval) }
  17. if !calendarTimer.isValid { startCalendarTimer(time: 15) }
  18. if !alarmTimer.isValid { startAlarmTimer(time: 30) }
  19. }
  20. func invalidateTimers() {
  21. bgTimer.invalidate()
  22. profileTimer.invalidate()
  23. deviceStatusTimer.invalidate()
  24. treatmentsTimer.invalidate()
  25. minAgoTimer.invalidate()
  26. calendarTimer.invalidate()
  27. alarmTimer.invalidate()
  28. }
  29. // min Ago Timer
  30. func startMinAgoTimer(time: TimeInterval) {
  31. minAgoTimer = Timer.scheduledTimer(timeInterval: time,
  32. target: self,
  33. selector: #selector(MainViewController.minAgoTimerDidEnd(_:)),
  34. userInfo: nil,
  35. repeats: true)
  36. }
  37. @objc func minAgoTimerDidEnd(_ timer: Timer) {
  38. if bgData.count > 0 {
  39. let bgSeconds = bgData.last!.date
  40. let now = Date().timeIntervalSince1970
  41. let secondsAgo = now - bgSeconds
  42. // Update Min Ago Displays
  43. let formatter = DateComponentsFormatter()
  44. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  45. if secondsAgo >= 720 { // 720 seconds = 12 minutes
  46. formatter.allowedUnits = [.minute] // Only show minutes after 12 minutes have passed
  47. } else if secondsAgo < 270 { // Less than 4.5 minutes
  48. formatter.allowedUnits = [.minute] // Show only minutes if less than 4.5 minutes
  49. } else {
  50. formatter.allowedUnits = [.minute, .second] // Show minutes and seconds otherwise
  51. }
  52. let formattedDuration = formatter.string(from: secondsAgo) ?? ""
  53. let minAgoDisplayText = formattedDuration + " min ago"
  54. MinAgoText.text = minAgoDisplayText
  55. latestMinAgoString = minAgoDisplayText
  56. if let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController {
  57. snoozer.MinAgoLabel.text = minAgoDisplayText
  58. let bgLabelText = snoozer.BGLabel.attributedText?.string ?? ""
  59. let bgLabelAttributes = snoozer.BGLabel.attributedText?.attributes(at: 0, effectiveRange: nil) ?? [:]
  60. let attributeString = NSMutableAttributedString(string: bgLabelText, attributes: bgLabelAttributes)
  61. // Apply strikethrough in system red if more than 12 minutes old
  62. if secondsAgo >= 720 { // 720 seconds = 12 minutes
  63. attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributeString.length))
  64. attributeString.addAttribute(NSAttributedString.Key.strikethroughColor, value: UIColor.systemRed, range: NSRange(location: 0, length: attributeString.length))
  65. }
  66. snoozer.BGLabel.attributedText = attributeString
  67. }
  68. } else {
  69. MinAgoText.text = ""
  70. latestMinAgoString = ""
  71. if let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController {
  72. snoozer.MinAgoLabel.text = ""
  73. }
  74. }
  75. }
  76. // Runs a 60 second timer when an alarm is snoozed
  77. // Prevents the alarm from triggering again while saving the snooze time to settings
  78. // End function needs nothing done
  79. func startGraphNowTimer(time: TimeInterval = 60) {
  80. graphNowTimer = Timer.scheduledTimer(timeInterval: time,
  81. target: self,
  82. selector: #selector(MainViewController.graphNowTimerDidEnd(_:)),
  83. userInfo: nil,
  84. repeats: true)
  85. }
  86. @objc func graphNowTimerDidEnd(_ timer:Timer) {
  87. createVerticalLines()
  88. }
  89. // Runs a 60 second timer when an alarm is snoozed
  90. // Prevents the alarm from triggering again while saving the snooze time to settings
  91. // End function needs nothing done
  92. func startCheckAlarmTimer(time: TimeInterval = 60) {
  93. checkAlarmTimer = Timer.scheduledTimer(timeInterval: time,
  94. target: self,
  95. selector: #selector(MainViewController.checkAlarmTimerDidEnd(_:)),
  96. userInfo: nil,
  97. repeats: false)
  98. }
  99. @objc func checkAlarmTimerDidEnd(_ timer:Timer) {
  100. }
  101. // BG Timer
  102. // Runs to 5:10 after last reading timestamp
  103. // Failed or no reading re-attempts after 10 second delay
  104. // Changes to 30 second increments after 7:00
  105. // Changes to 1 minute increments after 10:00
  106. // Changes to 5 minute increments after 20:00 stale data
  107. func startBGTimer(time: TimeInterval = 60 * 5) {
  108. bgTimer = Timer.scheduledTimer(timeInterval: time,
  109. target: self,
  110. selector: #selector(MainViewController.bgTimerDidEnd(_:)),
  111. userInfo: nil,
  112. repeats: false)
  113. }
  114. @objc func bgTimerDidEnd(_ timer:Timer) {
  115. // reset timer to 1 minute if settings aren't entered
  116. if UserDefaultsRepository.shareUserName.value == "" && UserDefaultsRepository.sharePassword.value == "" && UserDefaultsRepository.url.value == "" {
  117. startBGTimer(time: 60)
  118. return
  119. }
  120. if UserDefaultsRepository.shareUserName.value != "" && UserDefaultsRepository.sharePassword.value != "" {
  121. webLoadDexShare()
  122. } else {
  123. webLoadNSBGData()
  124. }
  125. }
  126. // Device Status Timer
  127. // Runs to 5:10 after last reading timestamp
  128. // Failed or no update re-attempts after 10 second delay
  129. // Changes to 30 second increments after 7:00
  130. // Changes to 1 minute increments after 10:00
  131. // Changes to 5 minute increments after 20:00 stale data
  132. func startDeviceStatusTimer(time: TimeInterval = 60 * 5) {
  133. deviceStatusTimer = Timer.scheduledTimer(timeInterval: time,
  134. target: self,
  135. selector: #selector(MainViewController.deviceStatusTimerDidEnd(_:)),
  136. userInfo: nil,
  137. repeats: false)
  138. }
  139. @objc func deviceStatusTimerDidEnd(_ timer:Timer) {
  140. // reset timer to 1 minute if settings aren't entered
  141. if UserDefaultsRepository.url.value == "" || !UserDefaultsRepository.loopUser.value {
  142. startDeviceStatusTimer(time: 60)
  143. return
  144. }
  145. if UserDefaultsRepository.url.value != "" {
  146. webLoadNSDeviceStatus()
  147. }
  148. }
  149. // Treatments Timer
  150. // Runs on 2 minute intervals
  151. // Pauses with stale BG data
  152. func startTreatmentsTimer(time: TimeInterval = 60 * 2) {
  153. treatmentsTimer = Timer.scheduledTimer(timeInterval: time,
  154. target: self,
  155. selector: #selector(MainViewController.treatmentsTimerDidEnd(_:)),
  156. userInfo: nil,
  157. repeats: false)
  158. }
  159. @objc func treatmentsTimerDidEnd(_ timer:Timer) {
  160. // reset timer to 1 minute if settings aren't entered
  161. if UserDefaultsRepository.url.value == "" || !UserDefaultsRepository.loopUser.value {
  162. startTreatmentsTimer(time: 60)
  163. return
  164. }
  165. if UserDefaultsRepository.url.value != "" && UserDefaultsRepository.downloadTreatments.value {
  166. WebLoadNSTreatments()
  167. }
  168. startTreatmentsTimer()
  169. }
  170. // Profile Timer
  171. // Runs on 10 minute intervals
  172. // Pauses with stale BG data
  173. func startProfileTimer(time: TimeInterval = 60 * 10) {
  174. profileTimer = Timer.scheduledTimer(timeInterval: time,
  175. target: self,
  176. selector: #selector(MainViewController.profileTimerDidEnd(_:)),
  177. userInfo: nil,
  178. repeats: false)
  179. }
  180. @objc func profileTimerDidEnd(_ timer:Timer) {
  181. // reset timer to 1 minute if settings aren't entered
  182. if UserDefaultsRepository.url.value == "" || !UserDefaultsRepository.loopUser.value {
  183. startProfileTimer(time: 60)
  184. return
  185. }
  186. if !isStaleData() && UserDefaultsRepository.url.value != "" {
  187. webLoadNSProfile()
  188. startProfileTimer()
  189. }
  190. }
  191. // Cancel and reset the playing alarm if it has not been snoozed after 4 min 50 seconds.
  192. // This allows the next BG reading to either start the timer going or not fire if the situation has been resolved
  193. func startAlarmPlayingTimer(time: TimeInterval = 290) {
  194. let alarmPlayingTimer = Timer.scheduledTimer(timeInterval: time,
  195. target: self,
  196. selector: #selector(MainViewController.alarmPlayingTimerDidEnd(_:)),
  197. userInfo: nil,
  198. repeats: false)
  199. }
  200. @objc func alarmPlayingTimerDidEnd(_ timer:Timer) {
  201. if AlarmSound.isPlaying {
  202. stopAlarmAtNextReading()
  203. }
  204. }
  205. // Alarm Timer
  206. // Run the alarm checker every 15 seconds
  207. func startAlarmTimer(time: TimeInterval) {
  208. alarmTimer = Timer.scheduledTimer(timeInterval: time,
  209. target: self,
  210. selector: #selector(MainViewController.alarmTimerDidEnd(_:)),
  211. userInfo: nil,
  212. repeats: true)
  213. }
  214. @objc func alarmTimerDidEnd(_ timer:Timer) {
  215. if bgData.count > 0 {
  216. self.checkAlarms(bgs: bgData)
  217. }
  218. if overrideGraphData.count > 0 {
  219. self.checkOverrideAlarms()
  220. }
  221. }
  222. // Calendar Timer
  223. // Run the calendar writer every 30 seconds
  224. func startCalendarTimer(time: TimeInterval) {
  225. calendarTimer = Timer.scheduledTimer(timeInterval: time,
  226. target: self,
  227. selector: #selector(MainViewController.calendarTimerDidEnd(_:)),
  228. userInfo: nil,
  229. repeats: true)
  230. }
  231. @objc func calendarTimerDidEnd(_ timer:Timer) {
  232. if UserDefaultsRepository.writeCalendarEvent.value && UserDefaultsRepository.calendarIdentifier.value != "" {
  233. self.writeCalendar()
  234. }
  235. }
  236. // Timer to allow us to write min ago calendar entries but not update them every 30 seconds
  237. func startCalTimer(time: TimeInterval) {
  238. calTimer = Timer.scheduledTimer(timeInterval: time,
  239. target: self,
  240. selector: #selector(MainViewController.calTimerDidEnd(_:)),
  241. userInfo: nil,
  242. repeats: false)
  243. }
  244. // Nothing should be done when this timer ends because it just blocks the calendar from writing when it's active
  245. @objc func calTimerDidEnd(_ timer:Timer) {
  246. }
  247. }