DeviceStatusOpenAPS.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. LoopStatusLabel.text = "X"
  11. latestLoopStatusString = "X"
  12. } else {
  13. guard let enactedOrSuggested = lastLoopRecord["suggested"] as? [String: AnyObject] ?? lastLoopRecord["enacted"] as? [String: AnyObject] else {
  14. LoopStatusLabel.text = "↻"
  15. latestLoopStatusString = "↻"
  16. return
  17. }
  18. var updatedTime: TimeInterval?
  19. if let timestamp = 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. if let enactedISFValue = enactedOrSuggested["ISF"] as? Double {
  31. enactedISF = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: enactedISFValue)
  32. }
  33. if let profileISF = profileISF, let enactedISF = enactedISF, profileISF != enactedISF {
  34. infoManager.updateInfoData(type: .isf, firstValue: profileISF, secondValue: enactedISF, separator: .arrow)
  35. } else if let profileISF = profileISF {
  36. infoManager.updateInfoData(type: .isf, value: profileISF)
  37. }
  38. // Carb Ratio (CR)
  39. let profileCR = profileManager.currentCarbRatio()
  40. var enactedCR: Double?
  41. if let reasonString = enactedOrSuggested["reason"] as? String {
  42. let pattern = "CR: (\\d+(?:\\.\\d+)?)"
  43. if let regex = try? NSRegularExpression(pattern: pattern) {
  44. let nsString = reasonString as NSString
  45. if let match = regex.firstMatch(in: reasonString, range: NSRange(location: 0, length: nsString.length)) {
  46. let crString = nsString.substring(with: match.range(at: 1))
  47. enactedCR = Double(crString)
  48. }
  49. }
  50. }
  51. if let profileCR = profileCR, let enactedCR = enactedCR, profileCR != enactedCR {
  52. infoManager.updateInfoData(type: .carbRatio, value: profileCR, enactedValue: enactedCR, separator: .arrow)
  53. } else if let profileCR = profileCR {
  54. infoManager.updateInfoData(type: .carbRatio, value: profileCR)
  55. }
  56. // IOB
  57. if let iobMetric = InsulinMetric(from: lastLoopRecord["iob"], key: "iob") {
  58. infoManager.updateInfoData(type: .iob, value: iobMetric)
  59. latestIOB = iobMetric
  60. }
  61. // COB
  62. if let cobMetric = CarbMetric(from: enactedOrSuggested, key: "COB") {
  63. infoManager.updateInfoData(type: .cob, value: cobMetric)
  64. latestCOB = cobMetric
  65. } else if let reasonString = enactedOrSuggested["reason"] as? String {
  66. // Fallback: Extract COB from reason string
  67. let cobPattern = "COB: (\\d+(?:\\.\\d+)?)"
  68. if let cobRegex = try? NSRegularExpression(pattern: cobPattern),
  69. let cobMatch = cobRegex.firstMatch(in: reasonString, range: NSRange(location: 0, length: reasonString.utf16.count))
  70. {
  71. let cobValueString = (reasonString as NSString).substring(with: cobMatch.range(at: 1))
  72. if let cobValue = Double(cobValueString) {
  73. let tempDict: [String: AnyObject] = ["COB": cobValue as AnyObject]
  74. if let fallbackCobMetric = CarbMetric(from: tempDict, key: "COB") {
  75. infoManager.updateInfoData(type: .cob, value: fallbackCobMetric)
  76. latestCOB = fallbackCobMetric
  77. } else {
  78. print("Failed to create CarbMetric from extracted COB value: \(cobValue)")
  79. }
  80. } else {
  81. print("Invalid COB value extracted from reason string: \(cobValueString)")
  82. }
  83. } else {
  84. print("COB pattern not found in reason string.")
  85. }
  86. }
  87. // Autosens
  88. if let sens = enactedOrSuggested["sensitivityRatio"] as? Double {
  89. let formattedSens = String(format: "%.0f", sens * 100.0) + "%"
  90. infoManager.updateInfoData(type: .autosens, value: formattedSens)
  91. }
  92. // Recommended Bolus
  93. if let rec = InsulinMetric(from: lastLoopRecord, key: "recommendedBolus") {
  94. infoManager.updateInfoData(type: .recBolus, value: rec)
  95. Observable.shared.deviceRecBolus.value = rec.value
  96. } else {
  97. Observable.shared.deviceRecBolus.value = nil
  98. }
  99. // Eventual BG
  100. if let eventualBGValue = enactedOrSuggested["eventualBG"] as? Double {
  101. let eventualBGQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: eventualBGValue)
  102. PredictionLabel.text = Localizer.formatQuantity(eventualBGQuantity)
  103. }
  104. // Target
  105. let profileTargetHigh = profileManager.currentTargetHigh()
  106. var enactedTarget: HKQuantity?
  107. if let enactedTargetValue = enactedOrSuggested["current_target"] as? Double {
  108. var targetUnit = HKUnit.milligramsPerDeciliter
  109. if enactedTargetValue < 40 {
  110. targetUnit = .millimolesPerLiter
  111. }
  112. enactedTarget = HKQuantity(unit: targetUnit, doubleValue: enactedTargetValue)
  113. }
  114. if let profileTargetHigh = profileTargetHigh, let enactedTarget = enactedTarget {
  115. let profileTargetHighFormatted = Localizer.formatQuantity(profileTargetHigh)
  116. let enactedTargetFormatted = Localizer.formatQuantity(enactedTarget)
  117. // Compare formatted values to avoid issues with minor floating-point differences
  118. // Profile target could be in another unit than enacted target
  119. if profileTargetHighFormatted != enactedTargetFormatted {
  120. infoManager.updateInfoData(type: .target, firstValue: profileTargetHigh, secondValue: enactedTarget, separator: .arrow)
  121. } else {
  122. infoManager.updateInfoData(type: .target, value: profileTargetHigh)
  123. }
  124. }
  125. // TDD
  126. if let tddMetric = InsulinMetric(from: enactedOrSuggested, key: "TDD") {
  127. infoManager.updateInfoData(type: .tdd, value: tddMetric)
  128. }
  129. let predBGsData: [String: AnyObject]? = {
  130. if let enacted = lastLoopRecord["suggested"] as? [String: AnyObject],
  131. let predBGs = enacted["predBGs"] as? [String: AnyObject]
  132. {
  133. return predBGs
  134. } else if let suggested = lastLoopRecord["enacted"] as? [String: AnyObject],
  135. let predBGs = suggested["predBGs"] as? [String: AnyObject]
  136. {
  137. return predBGs
  138. }
  139. return nil
  140. }()
  141. let predictioncolor = UIColor.systemGray
  142. PredictionLabel.textColor = predictioncolor
  143. topPredictionBG = Storage.shared.minBGScale.value
  144. if let predbgdata = predBGsData {
  145. let predictionTypes: [(type: String, colorName: String, dataIndex: Int)] = [
  146. ("ZT", "ZT", 12),
  147. ("IOB", "Insulin", 13),
  148. ("COB", "LoopYellow", 14),
  149. ("UAM", "UAM", 15),
  150. ]
  151. var minPredBG = Double.infinity
  152. var maxPredBG = -Double.infinity
  153. for (type, colorName, dataIndex) in predictionTypes {
  154. var predictionData = [ShareGlucoseData]()
  155. if let graphdata = predbgdata[type] as? [Double] {
  156. var predictionTime = updatedTime ?? Date().timeIntervalSince1970
  157. let toLoad = Int(Storage.shared.predictionToLoad.value * 12)
  158. for i in 0 ... toLoad {
  159. if i < graphdata.count {
  160. let predictionValue = graphdata[i]
  161. minPredBG = min(minPredBG, predictionValue)
  162. maxPredBG = max(maxPredBG, predictionValue)
  163. let prediction = ShareGlucoseData(sgv: Int(round(predictionValue)), date: predictionTime, direction: "flat")
  164. predictionData.append(prediction)
  165. predictionTime += 300
  166. }
  167. }
  168. }
  169. let color = UIColor(named: colorName) ?? UIColor.systemPurple
  170. updatePredictionGraphGeneric(
  171. dataIndex: dataIndex,
  172. predictionData: predictionData,
  173. chartLabel: type,
  174. color: color
  175. )
  176. }
  177. if minPredBG != Double.infinity, maxPredBG != -Double.infinity {
  178. let value = "\(Localizer.toDisplayUnits(String(minPredBG)))/\(Localizer.toDisplayUnits(String(maxPredBG)))"
  179. infoManager.updateInfoData(type: .minMax, value: value)
  180. } else {
  181. infoManager.updateInfoData(type: .minMax, value: "N/A")
  182. }
  183. }
  184. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String: AnyObject] {
  185. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  186. var lastBGTime = updatedTime ?? Date().timeIntervalSince1970
  187. if bgData.count > 0 {
  188. lastBGTime = bgData[bgData.count - 1].date
  189. }
  190. if tempBasalTime > lastBGTime {
  191. LoopStatusLabel.text = "⏀"
  192. latestLoopStatusString = "⏀"
  193. } else {
  194. LoopStatusLabel.text = "↻"
  195. latestLoopStatusString = "↻"
  196. }
  197. }
  198. } else {
  199. LoopStatusLabel.text = "↻"
  200. latestLoopStatusString = "↻"
  201. }
  202. }
  203. }
  204. }