DeviceStatusOpenAPS.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. // Insulin Required
  109. if let insulinReqMetric = InsulinMetric(from: enactedOrSuggested, key: "insulinReq") {
  110. infoManager.updateInfoData(type: .recBolus, value: insulinReqMetric)
  111. Observable.shared.deviceRecBolus.value = insulinReqMetric.value
  112. } else {
  113. Observable.shared.deviceRecBolus.value = 0
  114. }
  115. // Autosens
  116. if let sens = enactedOrSuggested["sensitivityRatio"] as? Double {
  117. let formattedSens = String(format: "%.0f", sens * 100.0) + "%"
  118. infoManager.updateInfoData(type: .autosens, value: formattedSens)
  119. }
  120. // Eventual BG
  121. if let eventualBGValue = enactedOrSuggested["eventualBG"] as? Double {
  122. let eventualBGQuantity = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: eventualBGValue)
  123. PredictionLabel.text = Localizer.formatQuantity(eventualBGQuantity)
  124. }
  125. // Target
  126. let profileTargetHigh = profileManager.currentTargetHigh()
  127. var enactedTarget: HKQuantity?
  128. if let enactedTargetValue = enactedOrSuggested["current_target"] as? Double {
  129. var targetUnit = HKUnit.milligramsPerDeciliter
  130. if enactedTargetValue < 40 {
  131. targetUnit = .millimolesPerLiter
  132. }
  133. enactedTarget = HKQuantity(unit: targetUnit, doubleValue: enactedTargetValue)
  134. }
  135. if let profileTargetHigh = profileTargetHigh, let enactedTarget = enactedTarget {
  136. let profileTargetHighFormatted = Localizer.formatQuantity(profileTargetHigh)
  137. let enactedTargetFormatted = Localizer.formatQuantity(enactedTarget)
  138. // Compare formatted values to avoid issues with minor floating-point differences
  139. // Profile target could be in another unit than enacted target
  140. if profileTargetHighFormatted != enactedTargetFormatted {
  141. infoManager.updateInfoData(type: .target, firstValue: profileTargetHigh, secondValue: enactedTarget, separator: .arrow)
  142. } else {
  143. infoManager.updateInfoData(type: .target, value: profileTargetHigh)
  144. }
  145. }
  146. // TDD
  147. if let tddMetric = InsulinMetric(from: enactedOrSuggested, key: "TDD") {
  148. infoManager.updateInfoData(type: .tdd, value: tddMetric)
  149. }
  150. let predBGsData: [String: AnyObject]? = {
  151. if let enacted = lastLoopRecord["suggested"] as? [String: AnyObject],
  152. let predBGs = enacted["predBGs"] as? [String: AnyObject]
  153. {
  154. return predBGs
  155. } else if let suggested = lastLoopRecord["enacted"] as? [String: AnyObject],
  156. let predBGs = suggested["predBGs"] as? [String: AnyObject]
  157. {
  158. return predBGs
  159. }
  160. return nil
  161. }()
  162. let predictioncolor = UIColor.systemGray
  163. PredictionLabel.textColor = predictioncolor
  164. topPredictionBG = Storage.shared.minBGScale.value
  165. if let predbgdata = predBGsData {
  166. let predictionTypes: [(type: String, colorName: String, dataIndex: Int)] = [
  167. ("ZT", "ZT", 12),
  168. ("IOB", "Insulin", 13),
  169. ("COB", "LoopYellow", 14),
  170. ("UAM", "UAM", 15),
  171. ]
  172. var minPredBG = Double.infinity
  173. var maxPredBG = -Double.infinity
  174. for (type, colorName, dataIndex) in predictionTypes {
  175. var predictionData = [ShareGlucoseData]()
  176. if let graphdata = predbgdata[type] as? [Double] {
  177. var predictionTime = updatedTime ?? Date().timeIntervalSince1970
  178. let toLoad = Int(Storage.shared.predictionToLoad.value * 12)
  179. for i in 0 ... toLoad {
  180. if i < graphdata.count {
  181. let predictionValue = graphdata[i]
  182. minPredBG = min(minPredBG, predictionValue)
  183. maxPredBG = max(maxPredBG, predictionValue)
  184. let prediction = ShareGlucoseData(sgv: Int(round(predictionValue)), date: predictionTime, direction: "flat")
  185. predictionData.append(prediction)
  186. predictionTime += 300
  187. }
  188. }
  189. }
  190. let color = UIColor(named: colorName) ?? UIColor.systemPurple
  191. updatePredictionGraphGeneric(
  192. dataIndex: dataIndex,
  193. predictionData: predictionData,
  194. chartLabel: type,
  195. color: color
  196. )
  197. }
  198. if minPredBG != Double.infinity, maxPredBG != -Double.infinity {
  199. let value = "\(Localizer.toDisplayUnits(String(minPredBG)))/\(Localizer.toDisplayUnits(String(maxPredBG)))"
  200. infoManager.updateInfoData(type: .minMax, value: value)
  201. } else {
  202. infoManager.updateInfoData(type: .minMax, value: "N/A")
  203. }
  204. }
  205. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String: AnyObject] {
  206. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  207. var lastBGTime = updatedTime ?? Date().timeIntervalSince1970
  208. if bgData.count > 0 {
  209. lastBGTime = bgData[bgData.count - 1].date
  210. }
  211. if tempBasalTime > lastBGTime, !wasEnacted {
  212. LoopStatusLabel.text = "⏀"
  213. latestLoopStatusString = "⏀"
  214. } else {
  215. LoopStatusLabel.text = "↻"
  216. latestLoopStatusString = "↻"
  217. }
  218. }
  219. } else {
  220. LoopStatusLabel.text = "↻"
  221. latestLoopStatusString = "↻"
  222. }
  223. }
  224. }
  225. }