AlarmManager.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // LoopFollow
  2. // AlarmManager.swift
  3. // Created by Jonas Björkert.
  4. import Foundation
  5. import UserNotifications
  6. class AlarmManager {
  7. static let shared = AlarmManager()
  8. private let evaluators: [AlarmType: AlarmCondition]
  9. private var lastBGAlarmTime: Date?
  10. private init(
  11. conditionTypes: [AlarmCondition.Type] = [
  12. BuildExpireCondition.self,
  13. LowBGCondition.self,
  14. HighBGCondition.self,
  15. FastDropCondition.self,
  16. NotLoopingCondition.self,
  17. OverrideStartCondition.self,
  18. OverrideEndCondition.self,
  19. TempTargetStartCondition.self,
  20. TempTargetEndCondition.self,
  21. RecBolusCondition.self,
  22. COBCondition.self,
  23. MissedReadingCondition.self,
  24. FastRiseCondition.self,
  25. TemporaryCondition.self,
  26. SensorAgeCondition.self,
  27. PumpChangeCondition.self,
  28. PumpVolumeCondition.self,
  29. IOBCondition.self,
  30. BatteryCondition.self,
  31. BatteryDropCondition.self,
  32. ]
  33. ) {
  34. var dict = [AlarmType: AlarmCondition]()
  35. conditionTypes.forEach { dict[$0.type] = $0.init() }
  36. evaluators = dict
  37. }
  38. func checkAlarms(data: AlarmData) {
  39. let now = Date()
  40. var alarmTriggered = false
  41. let config = Storage.shared.alarmConfiguration.value
  42. // Honor the "Snooze All" setting. If active, stop any current alarm and exit.
  43. if let snoozeUntil = config.snoozeUntil, snoozeUntil > now {
  44. if Observable.shared.currentAlarm.value != nil {
  45. stopAlarm()
  46. }
  47. return
  48. }
  49. let alarms = Storage.shared.alarms.value
  50. let sorted = alarms.sorted(by: Alarm.byPriorityThenSpec)
  51. var skipType: AlarmType?
  52. let isLatestReadingRecent: Bool = {
  53. guard let last = data.bgReadings.last else { return false }
  54. return now.timeIntervalSince(last.date) <= 5 * 60
  55. }()
  56. for alarm in sorted {
  57. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  58. if alarm.type == skipType {
  59. continue
  60. }
  61. // If the alarm is based on bg values, and the value isnt recent, skip to next
  62. if alarm.type.isBGBased, !isLatestReadingRecent {
  63. continue
  64. }
  65. // If this is a bg-based alarm and we've already handled that same BG reading,
  66. // skip until we see a newer one.
  67. if alarm.type.isBGBased,
  68. let lastHandled = lastBGAlarmTime,
  69. let latestDate = data.bgReadings.last?.date,
  70. !(latestDate > lastHandled)
  71. {
  72. continue
  73. }
  74. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  75. // We still want other types af alarm to go off, so we continue here without breaking
  76. if let until = alarm.snoozedUntil, until > now {
  77. skipType = alarm.type
  78. continue
  79. }
  80. // Evaluate the alarm condition.
  81. guard let checker = evaluators[alarm.type],
  82. checker
  83. .shouldFire(
  84. alarm: alarm,
  85. data: data,
  86. now: now,
  87. config: Storage.shared.alarmConfiguration.value
  88. )
  89. else {
  90. // If this alarm is active, but no longer fulfill the requirements, stop it.
  91. // Continue evaluating other alarams
  92. if Observable.shared.currentAlarm.value == alarm.id {
  93. stopAlarm()
  94. }
  95. continue
  96. }
  97. // If this alarm is active, and still fulfill the requirements, let it be active
  98. // Break the loop, nothing else to do
  99. if Observable.shared.currentAlarm.value == alarm.id {
  100. break
  101. }
  102. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  103. Observable.shared.currentAlarm.value = alarm.id
  104. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  105. // Store the latest bg time so we don't use it again
  106. if alarm.type.isBGBased,
  107. let latestDate = data.bgReadings.last?.date
  108. {
  109. lastBGAlarmTime = latestDate
  110. }
  111. if alarm.type == .temporary {
  112. // turn it off and persist
  113. var list = Storage.shared.alarms.value
  114. if let idx = list.firstIndex(where: { $0.id == alarm.id }) {
  115. list[idx].isEnabled = false
  116. list[idx].snoozedUntil = nil
  117. Storage.shared.alarms.value = list
  118. }
  119. }
  120. alarmTriggered = true
  121. break
  122. }
  123. if isLatestReadingRecent, Storage.shared.persistentNotification.value, !alarmTriggered, let latestDate = data.bgReadings.last?.date, latestDate > Storage.shared.persistentNotificationLastBGTime.value {
  124. sendNotification(title: "Latest BG")
  125. Storage.shared.persistentNotificationLastBGTime.value = now
  126. }
  127. }
  128. func performSnooze(_ snoozeUnits: Int? = nil) {
  129. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  130. var alarms = Storage.shared.alarms.value
  131. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  132. let alarm = alarms[idx]
  133. let units = snoozeUnits ?? alarm.snoozeDuration
  134. if units > 0 {
  135. let snoozeSeconds = Double(units) * alarm.type.snoozeTimeUnit.seconds
  136. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  137. Storage.shared.alarms.value = alarms
  138. }
  139. stopAlarm()
  140. }
  141. }
  142. func stopAlarm() {
  143. AlarmSound.stop()
  144. Observable.shared.currentAlarm.value = nil
  145. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  146. }
  147. func sendNotification(title: String, actionTitle: String? = nil) {
  148. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  149. let content = UNMutableNotificationContent()
  150. content.title = title
  151. content.subtitle += Observable.shared.bgText.value + " "
  152. content.subtitle += Observable.shared.directionText.value + " "
  153. content.subtitle += Observable.shared.deltaText.value
  154. content.categoryIdentifier = "category"
  155. content.sound = .default
  156. let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  157. let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
  158. UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  159. if let actionTitle = actionTitle {
  160. let action = UNNotificationAction(identifier: "snooze", title: actionTitle, options: [])
  161. let category = UNNotificationCategory(identifier: "category", actions: [action], intentIdentifiers: [], options: [])
  162. UNUserNotificationCenter.current().setNotificationCategories([category])
  163. }
  164. }
  165. }