AlarmManager.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. // TODO: add other condition types here
  22. ]
  23. ) {
  24. var dict = [AlarmType: AlarmCondition]()
  25. conditionTypes.forEach { dict[$0.type] = $0.init() }
  26. evaluators = dict
  27. }
  28. func checkAlarms(data: AlarmData) {
  29. let now = Date()
  30. let alarms = Storage.shared.alarms.value
  31. let sorted = alarms.sorted { lhs, rhs in
  32. // 1) by type priority
  33. if lhs.type.priority != rhs.type.priority {
  34. return lhs.type.priority < rhs.type.priority
  35. }
  36. // 2) by “main” value for that type
  37. if let asc = lhs.type.thresholdSortAscending {
  38. // pick the right field:
  39. let leftVal: Double
  40. let rightVal: Double
  41. switch lhs.type {
  42. // TODO: Make a alarm type setting of this, sortedBy or something like that
  43. case .fastDrop, .fastRise:
  44. // sort on the per-reading delta
  45. leftVal = lhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  46. rightVal = rhs.delta ?? (asc ? Double.infinity : -Double.infinity)
  47. default:
  48. // sort on the BG limit threshold
  49. leftVal = lhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  50. rightVal = rhs.threshold ?? (asc ? Double.infinity : -Double.infinity)
  51. }
  52. return asc ? (leftVal < rightVal) : (leftVal > rightVal)
  53. }
  54. // 3) fallback
  55. return false
  56. }
  57. var skipType: AlarmType?
  58. let isLatestReadingRecent: Bool = {
  59. guard let last = data.bgReadings.last else { return false }
  60. return now.timeIntervalSince(last.date) <= 5 * 60
  61. }()
  62. for alarm in sorted {
  63. // If there is already an active (snoozed) alarm of this type, skip to next [type]
  64. if alarm.type == skipType {
  65. continue
  66. }
  67. // If the alarm is based on bg values, and the value isnt recent, skip to next
  68. if alarm.type.isBGBased, !isLatestReadingRecent {
  69. continue
  70. }
  71. // If this is a bg-based alarm and we've already handled that same BG reading,
  72. // skip until we see a newer one.
  73. if alarm.type.isBGBased,
  74. let lastHandled = lastBGAlarmTime,
  75. let latestDate = data.bgReadings.last?.date,
  76. !(latestDate > lastHandled)
  77. {
  78. continue
  79. }
  80. // If the alarm itself is snoozed skip it, and skip lower‑priority alarms of the same type.
  81. // We still want other types af alarm to go off, so we continue here without breaking
  82. if let until = alarm.snoozedUntil, until > now {
  83. skipType = alarm.type
  84. continue
  85. }
  86. // Evaluate the alarm condition.
  87. guard let checker = evaluators[alarm.type],
  88. checker
  89. .shouldFire(
  90. alarm: alarm,
  91. data: data,
  92. now: now,
  93. config: Storage.shared.alarmConfiguration.value
  94. )
  95. else {
  96. // If this alarm is active, but no longer fulfill the requirements, stop it.
  97. // Continue evaluating other alarams
  98. if Observable.shared.currentAlarm.value == alarm.id {
  99. stopAlarm()
  100. }
  101. continue
  102. }
  103. // If this alarm is active, and still fulfill the requirements, let it be active
  104. // Break the loop, nothing else to do
  105. if Observable.shared.currentAlarm.value == alarm.id {
  106. break
  107. }
  108. // Fire the alarm and break the loop; we only allow one alarm per evaluation tick.
  109. Observable.shared.currentAlarm.value = alarm.id
  110. alarm.trigger(config: Storage.shared.alarmConfiguration.value, now: now)
  111. // Store the latest bg time so we don't use it again
  112. if alarm.type.isBGBased,
  113. let latestDate = data.bgReadings.last?.date
  114. {
  115. lastBGAlarmTime = latestDate
  116. }
  117. break
  118. }
  119. }
  120. func performSnooze(_ snoozeUnits: Int? = nil) {
  121. guard let alarmID = Observable.shared.currentAlarm.value else { return }
  122. var alarms = Storage.shared.alarms.value
  123. if let idx = alarms.firstIndex(where: { $0.id == alarmID }) {
  124. let alarm = alarms[idx]
  125. let units = snoozeUnits ?? alarm.snoozeDuration
  126. let snoozeSeconds = Double(units) * alarm.type.timeUnit.seconds
  127. alarms[idx].snoozedUntil = Date().addingTimeInterval(snoozeSeconds)
  128. Storage.shared.alarms.value = alarms
  129. stopAlarm()
  130. }
  131. }
  132. func stopAlarm() {
  133. AlarmSound.stop()
  134. Observable.shared.currentAlarm.value = nil
  135. UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
  136. }
  137. }