DeviceStatusOpenAPS.swift 12 KB

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