DeviceStatusOpenAPS.swift 14 KB

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