DeviceStatusOpenAPS.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. // LoopFollow
  2. // DeviceStatusOpenAPS.swift
  3. import Foundation
  4. import HealthKit
  5. extension MainViewController {
  6. func DeviceStatusOpenAPS(formatter: ISO8601DateFormatter, lastDeviceStatus: [String: AnyObject]?, lastLoopRecord: [String: AnyObject]) {
  7. Storage.shared.device.value = lastDeviceStatus?["device"] as? String ?? ""
  8. if lastLoopRecord["failureReason"] != nil {
  9. Observable.shared.loopStatusText.value = "X"
  10. latestLoopStatusString = "X"
  11. } else {
  12. guard let enactedOrSuggested = lastLoopRecord["suggested"] as? [String: AnyObject] ?? lastLoopRecord["enacted"] as? [String: AnyObject] else {
  13. Observable.shared.loopStatusText.value = "↻"
  14. latestLoopStatusString = "↻"
  15. return
  16. }
  17. var updatedTime: TimeInterval?
  18. if let timestamp = enactedOrSuggested["deliverAt"] as? String ?? enactedOrSuggested["timestamp"] as? String,
  19. let parsedTime = formatter.date(from: timestamp)?.timeIntervalSince1970
  20. {
  21. updatedTime = parsedTime
  22. let formattedTime = Localizer.formatTimestampToLocalString(parsedTime)
  23. infoManager.updateInfoData(type: .updated, value: formattedTime)
  24. Observable.shared.enactedOrSuggested.value = updatedTime
  25. }
  26. // ISF
  27. let profileISF = profileManager.currentISF()
  28. var enactedISF: HKQuantity?
  29. // Some uploaders (e.g. Trio Swift oref with dynamic ISF) report a
  30. // placeholder 0 in the structured ISF field; treat that as missing.
  31. if let enactedISFValue = enactedOrSuggested["ISF"] as? Double, enactedISFValue != 0 {
  32. enactedISF = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: enactedISFValue)
  33. }
  34. if let profileISF = profileISF, let enactedISF = enactedISF, profileISF != enactedISF {
  35. infoManager.updateInfoData(type: .isf, firstValue: profileISF, secondValue: enactedISF, separator: .arrow)
  36. Storage.shared.lastIsfMgdlPerU.value = enactedISF.doubleValue(for: .milligramsPerDeciliter)
  37. } else if let profileISF = profileISF {
  38. infoManager.updateInfoData(type: .isf, value: profileISF)
  39. Storage.shared.lastIsfMgdlPerU.value = profileISF.doubleValue(for: .milligramsPerDeciliter)
  40. }
  41. // Carb Ratio (CR)
  42. // Prefer the structured CR field; fall back to parsing it out of the
  43. // reason string for uploaders that don't expose it (a CR of 0 is never
  44. // valid, so it's treated as missing).
  45. let profileCR = profileManager.currentCarbRatio()
  46. var enactedCR: Double?
  47. if let structuredCR = enactedOrSuggested["CR"] as? Double, structuredCR != 0 {
  48. enactedCR = structuredCR
  49. } else if let reasonString = enactedOrSuggested["reason"] as? String {
  50. let pattern = "CR: (\\d+(?:\\.\\d+)?)"
  51. if let regex = try? NSRegularExpression(pattern: pattern) {
  52. let nsString = reasonString as NSString
  53. if let match = regex.firstMatch(in: reasonString, range: NSRange(location: 0, length: nsString.length)) {
  54. let crString = nsString.substring(with: match.range(at: 1))
  55. enactedCR = Double(crString)
  56. }
  57. }
  58. }
  59. if let profileCR = profileCR, let enactedCR = enactedCR, profileCR != enactedCR {
  60. infoManager.updateInfoData(type: .carbRatio, value: profileCR, enactedValue: enactedCR, separator: .arrow)
  61. Storage.shared.lastCarbRatio.value = enactedCR
  62. } else if let profileCR = profileCR {
  63. infoManager.updateInfoData(type: .carbRatio, value: profileCR)
  64. Storage.shared.lastCarbRatio.value = profileCR
  65. }
  66. // IOB
  67. if let iobMetric = InsulinMetric(from: lastLoopRecord["iob"], key: "iob") {
  68. infoManager.updateInfoData(type: .iob, value: iobMetric)
  69. latestIOB = iobMetric
  70. Observable.shared.iobText.value = iobMetric.formattedValue()
  71. }
  72. // COB
  73. if let cobMetric = CarbMetric(from: enactedOrSuggested, key: "COB") {
  74. infoManager.updateInfoData(type: .cob, value: cobMetric)
  75. latestCOB = cobMetric
  76. } else if let reasonString = enactedOrSuggested["reason"] as? String {
  77. // Fallback: Extract COB from reason string
  78. let cobPattern = "COB: (\\d+(?:\\.\\d+)?)"
  79. if let cobRegex = try? NSRegularExpression(pattern: cobPattern),
  80. let cobMatch = cobRegex.firstMatch(in: reasonString, range: NSRange(location: 0, length: reasonString.utf16.count))
  81. {
  82. let cobValueString = (reasonString as NSString).substring(with: cobMatch.range(at: 1))
  83. if let cobValue = Double(cobValueString) {
  84. let tempDict: [String: AnyObject] = ["COB": cobValue as AnyObject]
  85. if let fallbackCobMetric = CarbMetric(from: tempDict, key: "COB") {
  86. infoManager.updateInfoData(type: .cob, value: fallbackCobMetric)
  87. latestCOB = fallbackCobMetric
  88. } else {
  89. print("Failed to create CarbMetric from extracted COB value: \(cobValue)")
  90. }
  91. } else {
  92. print("Invalid COB value extracted from reason string: \(cobValueString)")
  93. }
  94. } else {
  95. print("COB pattern not found in reason string.")
  96. }
  97. }
  98. // Autosens
  99. if let sens = enactedOrSuggested["sensitivityRatio"] as? Double {
  100. let formattedSens = String(format: "%.0f", sens * 100.0) + "%"
  101. infoManager.updateInfoData(type: .autosens, value: formattedSens)
  102. Storage.shared.lastAutosens.value = sens
  103. }
  104. // Recommended Bolus
  105. if let rec = lastLoopRecord["recommendedBolus"] as? Double {
  106. infoManager.updateInfoData(type: .recBolus, value: InsulinFormatter.shared.string(rec))
  107. Observable.shared.deviceRecBolus.value = rec
  108. } else {
  109. infoManager.clearInfoData(type: .recBolus)
  110. Observable.shared.deviceRecBolus.value = nil
  111. }
  112. // Eventual BG
  113. if let eventualBGValue = enactedOrSuggested["eventualBG"] as? Double {
  114. let eventualBGQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: eventualBGValue)
  115. Observable.shared.predictionText.value = Localizer.formatQuantity(eventualBGQuantity)
  116. Storage.shared.projectedBgMgdl.value = eventualBGValue
  117. } else {
  118. Storage.shared.projectedBgMgdl.value = nil
  119. }
  120. // Target
  121. let profileTargetHigh = profileManager.currentTargetHigh()
  122. var enactedTarget: HKQuantity?
  123. if let enactedTargetValue = enactedOrSuggested["current_target"] as? Double {
  124. var targetUnit = HKUnit.milligramsPerDeciliter
  125. if enactedTargetValue < 40 {
  126. targetUnit = .millimolesPerLiter
  127. }
  128. enactedTarget = HKQuantity(unit: targetUnit, doubleValue: enactedTargetValue)
  129. }
  130. if let profileTargetHigh = profileTargetHigh, let enactedTarget = enactedTarget {
  131. let profileTargetHighFormatted = Localizer.formatQuantity(profileTargetHigh)
  132. let enactedTargetFormatted = Localizer.formatQuantity(enactedTarget)
  133. // Compare formatted values to avoid issues with minor floating-point differences
  134. // Profile target could be in another unit than enacted target
  135. if profileTargetHighFormatted != enactedTargetFormatted {
  136. infoManager.updateInfoData(type: .target, firstValue: profileTargetHigh, secondValue: enactedTarget, separator: .arrow)
  137. } else {
  138. infoManager.updateInfoData(type: .target, value: profileTargetHigh)
  139. }
  140. let effectiveMgdl = enactedTarget.doubleValue(for: .milligramsPerDeciliter)
  141. Storage.shared.lastTargetLowMgdl.value = effectiveMgdl
  142. Storage.shared.lastTargetHighMgdl.value = effectiveMgdl
  143. } else if let profileTargetHigh = profileTargetHigh {
  144. let profileMgdl = profileTargetHigh.doubleValue(for: .milligramsPerDeciliter)
  145. Storage.shared.lastTargetLowMgdl.value = profileMgdl
  146. Storage.shared.lastTargetHighMgdl.value = profileMgdl
  147. }
  148. // TDD
  149. if let tddMetric = InsulinMetric(from: enactedOrSuggested, key: "TDD")
  150. ?? InsulinMetric(from: lastLoopRecord["enacted"], key: "TDD")
  151. {
  152. infoManager.updateInfoData(type: .tdd, value: tddMetric)
  153. Storage.shared.lastTdd.value = tddMetric.value
  154. }
  155. let predBGsData: [String: AnyObject]? = {
  156. if let enacted = lastLoopRecord["suggested"] as? [String: AnyObject],
  157. let predBGs = enacted["predBGs"] as? [String: AnyObject]
  158. {
  159. return predBGs
  160. } else if let suggested = lastLoopRecord["enacted"] as? [String: AnyObject],
  161. let predBGs = suggested["predBGs"] as? [String: AnyObject]
  162. {
  163. return predBGs
  164. }
  165. return nil
  166. }()
  167. Observable.shared.predictionColor.value = .gray
  168. topPredictionBG = Storage.shared.minBGScale.value
  169. if let predbgdata = predBGsData {
  170. let toLoad = Int(Storage.shared.predictionToLoad.value * 12)
  171. var rawPredBGs = [String: [Double]]()
  172. var minPredBG = Double.infinity
  173. var maxPredBG = -Double.infinity
  174. for type in ["ZT", "IOB", "COB", "UAM"] {
  175. if let arr = predbgdata[type] as? [Double], !arr.isEmpty {
  176. rawPredBGs[type] = arr
  177. for i in 0 ... min(toLoad, arr.count - 1) {
  178. minPredBG = min(minPredBG, arr[i])
  179. maxPredBG = max(maxPredBG, arr[i])
  180. }
  181. }
  182. }
  183. openAPSPredBGs = rawPredBGs.isEmpty ? nil : rawPredBGs
  184. openAPSPredUpdatedTime = updatedTime
  185. if minPredBG != Double.infinity, maxPredBG != -Double.infinity {
  186. let value = "\(Localizer.toDisplayUnits(String(minPredBG)))/\(Localizer.toDisplayUnits(String(maxPredBG)))"
  187. infoManager.updateInfoData(type: .minMax, value: value)
  188. Storage.shared.lastMinBgMgdl.value = minPredBG
  189. Storage.shared.lastMaxBgMgdl.value = maxPredBG
  190. } else {
  191. infoManager.clearInfoData(type: .minMax)
  192. }
  193. updateOpenAPSPredictionDisplay()
  194. } else {
  195. openAPSPredBGs = nil
  196. openAPSPredUpdatedTime = nil
  197. }
  198. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String: AnyObject] {
  199. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  200. var lastBGTime = updatedTime ?? Date().timeIntervalSince1970
  201. if bgData.count > 0 {
  202. lastBGTime = bgData[bgData.count - 1].date
  203. }
  204. if tempBasalTime > lastBGTime {
  205. Observable.shared.loopStatusText.value = "⏀"
  206. latestLoopStatusString = "⏀"
  207. } else {
  208. Observable.shared.loopStatusText.value = "↻"
  209. latestLoopStatusString = "↻"
  210. }
  211. }
  212. } else {
  213. Observable.shared.loopStatusText.value = "↻"
  214. latestLoopStatusString = "↻"
  215. }
  216. // Live Activity storage
  217. Storage.shared.lastIOB.value = latestIOB?.value
  218. Storage.shared.lastCOB.value = latestCOB?.value
  219. }
  220. }
  221. }