DeviceStatusOpenAPS.swift 12 KB

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