Carbs.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import Foundation
  2. struct Carbs {
  3. static func carbRatioLookup(carbRatio: CarbRatios, now: Date = Date()) -> Decimal? {
  4. // Get last schedule as default
  5. guard let lastSchedule = carbRatio.schedule.last else { return nil }
  6. var currentRatio = lastSchedule.ratio
  7. // Find matching schedule for current time
  8. do {
  9. for (curr, next) in zip(carbRatio.schedule, carbRatio.schedule.dropFirst()) {
  10. if try now.isMinutesFromMidnightWithinRange(lowerBound: curr.offset, upperBound: next.offset) {
  11. currentRatio = curr.ratio
  12. break
  13. }
  14. }
  15. } catch {
  16. return nil
  17. }
  18. // Check for invalid values
  19. if currentRatio < 3 || currentRatio > 150 {
  20. warning(.openAPS, "Warning: carbRatio of \(currentRatio) out of bounds.")
  21. return nil
  22. }
  23. // Convert exchanges to grams
  24. switch carbRatio.units {
  25. case .exchanges:
  26. return 12 / currentRatio
  27. case .grams:
  28. return currentRatio
  29. }
  30. }
  31. }