DeviceStatusOpenAPS.swift 12 KB

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