CycleHelper.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // LoopFollow
  2. // CycleHelper.swift
  3. import Foundation
  4. enum CycleHelper {
  5. /// Returns a positive modulus value (always between 0 and modulus).
  6. static func positiveModulo(_ value: TimeInterval, modulus: TimeInterval) -> TimeInterval {
  7. let remainder = value.truncatingRemainder(dividingBy: modulus)
  8. return remainder < 0 ? remainder + modulus : remainder
  9. }
  10. /// Calculates the cycle offset for a given date relative to midnight.
  11. /// The offset is the number of seconds into the cycle (i.e., date mod interval).
  12. static func cycleOffset(for date: Date, interval: TimeInterval) -> TimeInterval {
  13. let calendar = Calendar.current
  14. let startOfDay = calendar.startOfDay(for: date)
  15. let secondsSinceMidnight = date.timeIntervalSince(startOfDay)
  16. return secondsSinceMidnight.truncatingRemainder(dividingBy: interval)
  17. }
  18. /// Same as above, but takes a timestamp (seconds since 1970) instead of a Date.
  19. static func cycleOffset(for timestamp: TimeInterval, interval: TimeInterval) -> TimeInterval {
  20. let date = Date(timeIntervalSince1970: timestamp)
  21. return cycleOffset(for: date, interval: interval)
  22. }
  23. /// Computes the delay experienced when using a heartbeat device to read a sensor value.
  24. /// The calculation is based on a sensor reference (Date) and sensor interval.
  25. /// All calculations assume midnight as the base reference.
  26. static func computeDelay(sensorReference: Date,
  27. sensorInterval: TimeInterval,
  28. heartbeatLast: Date,
  29. heartbeatInterval: TimeInterval) -> TimeInterval
  30. {
  31. let sensorOffset = cycleOffset(for: sensorReference, interval: sensorInterval)
  32. let hbOffset = cycleOffset(for: heartbeatLast, interval: heartbeatInterval)
  33. return positiveModulo(hbOffset - sensorOffset, modulus: heartbeatInterval)
  34. }
  35. /// Overloaded version of computeDelay where the sensor cycle offset is already known.
  36. static func computeDelay(sensorOffset: TimeInterval,
  37. heartbeatLast: Date,
  38. heartbeatInterval: TimeInterval) -> TimeInterval
  39. {
  40. let hbOffset = cycleOffset(for: heartbeatLast, interval: heartbeatInterval)
  41. return positiveModulo(hbOffset - sensorOffset, modulus: heartbeatInterval)
  42. }
  43. }