AlarmManager.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. //
  2. // AlarmManager.swift
  3. // LoopFollow
  4. //
  5. // Created by Jonas Björkert on 2025-03-15.
  6. // Copyright © 2025 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UserNotifications
  10. class AlarmManager {
  11. static let shared = AlarmManager()
  12. private let evaluators: [AlarmType: AlarmCondition]
  13. private var lastBGAlarmTime: Date?
  14. private init(
  15. conditionTypes: [AlarmCondition.Type] = [
  16. BuildExpireCondition.self,
  17. LowBGCondition.self,
  18. HighBGCondition.self,
  19. FastDropCondition.self,
  20. NotLoopingCondition.self,
  21. OverrideStartCondition.self,
  22. OverrideEndCondition.self,
  23. TempTargetStartCondition.self,
  24. TempTargetEndCondition.self,
  25. RecBolusCondition.self,
  26. COBCondition.self,
  27. MissedReadingCondition.self,
  28. FastRiseCondition.self,
  29. TemporaryCondition.self,
  30. // TODO: add other condition types here
  31. ]
  32. ) {
  33. var dict = [AlarmType: AlarmCondition]()
  34. conditionTypes.forEach { dict[$0.type] = $0.init() }
  35. evaluators = dict
  36. }
  37. func checkAlarms(data: AlarmData) {
  38. let now = Date()
  39. let alarms = Storage.shared.alarms.value
  40. let sorted = alarms.sorted { lhs, rhs in
  41. // 1) type-level priority (hard-coded table in AlarmType)
  42. if lhs.type.priority != rhs.type.priority {
  43. return lhs.type.priority < rhs.type.priority
  44. }
  45. // 2) per-type “main value” ordering
  46. if lhs.type == rhs.type, // only makes sense within the same type
  47. let spec = lhs.type.sortSpec
  48. { // (direction, key extractor)
  49. let lv = spec.key(lhs)
  50. let rv = spec.key(rhs)
  51. switch spec.direction {
  52. case .ascending: // smaller ⇒ more urgent
  53. return (lv ?? Double.infinity) < (rv ?? Double.infinity)
  54. case .descending: // bigger ⇒ more urgent
  55. return (lv ?? -Double.infinity) > (rv ?? -Double.infinity)
  56. }
  57. }
  58. // 3) fallback – keep original insertion order
  59. return false
  60. }
  61. var skipType: AlarmType?
  62. let isLatestReadingRecent: Bool = {
  63. guard let last = data.bgReadings.last else { return false }
  64. return now.timeIntervalSince(last.date) <= 5 * 60
  65. }()
  66. for alarm in sorted {
  67. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  68. if alarm.type == skipType {
  69. continue
  70. }
  71. // If the alarm is based on bg values, and the value isnt recent, skip to next
  72. if alarm.type.isBGBased, !isLatestReadingRecent {
  73. continue
  74. }
  75. // If this is a bg-based alarm and we've already handled that same BG reading,
  76. // skip until we see a newer one.
  77. if alarm.type.isBGBased,
  78. let lastHandled = lastBGAlarmTime,
  79. let latestDate = data.bgReadings.last?.date,
  80. !(latestDate > lastHandled)
  81. {
  82. continue
  83. }
  84. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  85. // We still want other types af alarm to go off, so we continue here without breaking
  86. if let until = alarm.snoozedUntil, until > now {
  87. skipType = alarm.type
  88. continue
  89. }
  90. // Evaluate the alarm condition.
  91. guard let checker = evaluators[alarm.type],
  92. checker
  93. .shouldFire(
  94. alarm: alarm,
  95. data: data,
  96. now: now,
  97. config: Storage.shared.alarmConfiguration.value
  98. )
  99. else {
  100. // If this alarm is active, but no longer fulfill the requirements, stop it.
  101. // Continue evaluating other alarams
  102. if Observable.shared.currentAlarm.value == alarm.id {
  103. stopAlarm()
  104. }
  105. continue
  106. }
  107. // If this alarm is active, and still fulfill the requirements, let it be active
  108. // Break the loop, nothing else to do
  109. if Observable.shared.currentAlarm.value == alarm.id {
  110. break
  111. }
  112. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  113. Observable.shared.currentAlarm.value = alarm.id
  114. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  115. // Store the latest bg time so we don't use it again
  116. if alarm.type.isBGBased,
  117. let latestDate = data.bgReadings.last?.date
  118. {
  119. lastBGAlarmTime = latestDate
  120. }
  121. if alarm.type == .temporary {
  122. // turn it off and persist
  123. var list = Storage.shared.alarms.value
  124. if let idx = list.firstIndex(where: { $0.id == alarm.id }) {
  125. list[idx].isEnabled = false
  126. list[idx].snoozedUntil = nil
  127. Storage.shared.alarms.value = list
  128. }
  129. }
  130. break
  131. }
  132. }
  133. func performSnooze(_ snoozeUnits: Int? = nil) {
  134. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  135. var alarms = Storage.shared.alarms.value
  136. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  137. let alarm = alarms[idx]
  138. let units = snoozeUnits ?? alarm.snoozeDuration
  139. let snoozeSeconds = Double(units) * alarm.type.snoozeTimeUnit.seconds
  140. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  141. Storage.shared.alarms.value = alarms
  142. stopAlarm()
  143. }
  144. }
  145. func stopAlarm() {
  146. AlarmSound.stop()
  147. Observable.shared.currentAlarm.value = nil
  148. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  149. }
  150. }