BGData.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // LoopFollow
  2. // BGData.swift
  3. // Created by Jonas Björkert on 2023-10-05.
  4. import Foundation
  5. import UIKit
  6. extension MainViewController {
  7. // Dex Share Web Call
  8. func webLoadDexShare() {
  9. // Dexcom Share only returns 24 hrs of data as of now
  10. // Requesting more just for consistency with NS
  11. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  12. let count = graphHours * 12
  13. dexShare?.fetchData(count) { err, result in
  14. if let error = err {
  15. LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)", limitIdentifier: "Error fetching Dexcom data")
  16. self.webLoadNSBGData()
  17. return
  18. }
  19. guard let data = result else {
  20. LogManager.shared.log(category: .dexcom, message: "Received nil data from Dexcom", limitIdentifier: "Received nil data from Dexcom")
  21. self.webLoadNSBGData()
  22. return
  23. }
  24. // If Dex data is old, load from NS instead
  25. let latestDate = data[0].date
  26. let now = dateTimeUtils.getNowTimeIntervalUTC()
  27. if (latestDate + 330) < now, IsNightscoutEnabled() {
  28. LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead", limitIdentifier: "Dexcom data is old, loading from NS instead")
  29. self.webLoadNSBGData()
  30. return
  31. }
  32. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  33. if graphHours > 24, IsNightscoutEnabled() {
  34. self.webLoadNSBGData(dexData: data)
  35. } else {
  36. self.ProcessDexBGData(data: data, sourceName: "Dexcom")
  37. }
  38. }
  39. }
  40. // NS BG Data Web call
  41. func webLoadNSBGData(dexData: [ShareGlucoseData] = []) {
  42. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  43. if !IsNightscoutEnabled() {
  44. return
  45. }
  46. var parameters: [String: String] = [:]
  47. let utcISODateFormatter = ISO8601DateFormatter()
  48. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  49. parameters["count"] = "\(UserDefaultsRepository.downloadDays.value * 2 * 24 * 60 / 5)"
  50. parameters["find[dateString][$gte]"] = utcISODateFormatter.string(from: date)
  51. // Exclude 'cal' entries
  52. parameters["find[type][$ne]"] = "cal"
  53. NightscoutUtils.executeRequest(eventType: .sgv, parameters: parameters) { (result: Result<[ShareGlucoseData], Error>) in
  54. switch result {
  55. case let .success(entriesResponse):
  56. var nsData = entriesResponse
  57. DispatchQueue.main.async {
  58. // transform NS data to look like Dex data
  59. for i in 0 ..< nsData.count {
  60. // convert the NS timestamp to seconds instead of milliseconds
  61. nsData[i].date /= 1000
  62. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  63. }
  64. var nsData2: [ShareGlucoseData] = []
  65. var lastAddedTime = Double.infinity
  66. var lastAddedSGV: Int?
  67. let minInterval: Double = 30
  68. for reading in nsData {
  69. if (lastAddedSGV == nil || lastAddedSGV != reading.sgv) || (lastAddedTime - reading.date >= minInterval) {
  70. nsData2.append(reading)
  71. lastAddedTime = reading.date
  72. lastAddedSGV = reading.sgv
  73. }
  74. }
  75. // merge NS and Dex data if needed; use recent Dex data and older NS data
  76. var sourceName = "Nightscout"
  77. if !dexData.isEmpty {
  78. let oldestDexDate = dexData[dexData.count - 1].date
  79. var itemsToRemove = 0
  80. while itemsToRemove < nsData2.count, nsData2[itemsToRemove].date >= oldestDexDate {
  81. itemsToRemove += 1
  82. }
  83. nsData2.removeFirst(itemsToRemove)
  84. nsData2 = dexData + nsData2
  85. sourceName = "Dexcom"
  86. }
  87. // trigger the processor for the data after downloading.
  88. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  89. }
  90. case let .failure(error):
  91. LogManager.shared.log(category: .nightscout, message: "Failed to fetch bg data: \(error)", limitIdentifier: "Failed to fetch bg data")
  92. DispatchQueue.main.async {
  93. TaskScheduler.shared.rescheduleTask(
  94. id: .fetchBG,
  95. to: Date().addingTimeInterval(10)
  96. )
  97. }
  98. // if we have Dex data, use it
  99. if !dexData.isEmpty {
  100. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  101. }
  102. return
  103. }
  104. }
  105. }
  106. /// Processes incoming BG data.
  107. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String) {
  108. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  109. guard !data.isEmpty else {
  110. LogManager.shared.log(category: .nightscout, message: "No bg data received. Skipping processing.", limitIdentifier: "No bg data received. Skipping processing.")
  111. return
  112. }
  113. let latestReading = data[0]
  114. let sensorTimestamp = latestReading.date
  115. let now = dateTimeUtils.getNowTimeIntervalUTC()
  116. // secondsAgo is how old the newest reading is
  117. let secondsAgo = now - sensorTimestamp
  118. // Compute the current sensor schedule offset
  119. let currentOffset = CycleHelper.cycleOffset(for: sensorTimestamp, interval: 5 * 60)
  120. if Storage.shared.sensorScheduleOffset.value != currentOffset {
  121. Storage.shared.sensorScheduleOffset.value = currentOffset
  122. LogManager.shared.log(category: .nightscout,
  123. message: "Sensor schedule offset: \(currentOffset) seconds.",
  124. isDebug: true)
  125. }
  126. // Determine the next polling delay.
  127. var delayToSchedule: Double = 0
  128. DispatchQueue.main.async {
  129. // Fallback scheduling for older readings.
  130. if secondsAgo >= (20 * 60) {
  131. delayToSchedule = 5 * 60
  132. LogManager.shared.log(category: .nightscout,
  133. message: "Reading is very old (\(secondsAgo) sec). Scheduling next fetch in 5 minutes.",
  134. isDebug: true)
  135. } else if secondsAgo >= (10 * 60) {
  136. delayToSchedule = 60
  137. LogManager.shared.log(category: .nightscout,
  138. message: "Reading is moderately old (\(secondsAgo) sec). Scheduling next fetch in 60 seconds.",
  139. isDebug: true)
  140. } else if secondsAgo >= (7 * 60) {
  141. delayToSchedule = 30
  142. LogManager.shared.log(category: .nightscout,
  143. message: "Reading is a bit old (\(secondsAgo) sec). Scheduling next fetch in 30 seconds.",
  144. isDebug: true)
  145. } else if secondsAgo >= (5 * 60) {
  146. delayToSchedule = 5
  147. LogManager.shared.log(category: .nightscout,
  148. message: "Reading is close to 5 minutes old (\(secondsAgo) sec). Scheduling next fetch in 5 seconds.",
  149. isDebug: true)
  150. } else {
  151. delayToSchedule = 300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value)
  152. LogManager.shared.log(category: .nightscout,
  153. message: "Fresh reading. Scheduling next fetch in \(delayToSchedule) seconds.",
  154. isDebug: true)
  155. }
  156. TaskScheduler.shared.rescheduleTask(id: .fetchBG, to: Date().addingTimeInterval(delayToSchedule))
  157. // Evaluate speak conditions if there is a previous value.
  158. if data.count > 1 {
  159. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  160. }
  161. }
  162. // Process data for graph display.
  163. bgData.removeAll()
  164. for i in 0 ..< data.count {
  165. let readingTimestamp = data[data.count - 1 - i].date
  166. if readingTimestamp >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  167. let sgvValue = data[data.count - 1 - i].sgv
  168. // Skip outlier values (e.g. first reading of a new sensor might be abnormally high).
  169. if sgvValue > 600 {
  170. LogManager.shared.log(category: .nightscout,
  171. message: "Skipping reading with sgv \(sgvValue) as it exceeds threshold.",
  172. isDebug: true)
  173. continue
  174. }
  175. let reading = ShareGlucoseData(sgv: sgvValue, date: readingTimestamp, direction: data[data.count - 1 - i].direction)
  176. bgData.append(reading)
  177. }
  178. }
  179. LogManager.shared.log(category: .nightscout,
  180. message: "Graph data updated with \(bgData.count) entries.",
  181. isDebug: true)
  182. viewUpdateNSBG(sourceName: sourceName)
  183. }
  184. func updateServerText(with serverText: String? = nil) {
  185. if UserDefaultsRepository.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  186. self.serverText.text = displayName
  187. } else if let serverText = serverText {
  188. self.serverText.text = serverText
  189. }
  190. }
  191. // NS BG Data Front end updater
  192. func viewUpdateNSBG(sourceName: String) {
  193. DispatchQueue.main.async {
  194. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  195. let entries = self.bgData
  196. if entries.count < 2 { return } // Protect index out of bounds
  197. self.updateBGGraph()
  198. self.updateStats()
  199. let latestEntryIndex = entries.count - 1
  200. let latestBG = entries[latestEntryIndex].sgv
  201. let priorBG = entries[latestEntryIndex - 1].sgv
  202. let deltaBG = latestBG - priorBG
  203. let lastBGTime = entries[latestEntryIndex].date
  204. let deltaTime = (TimeInterval(Date().timeIntervalSince1970) - lastBGTime) / 60
  205. self.updateServerText(with: sourceName)
  206. // Set BGText with the latest BG value
  207. self.setBGTextColor()
  208. Observable.shared.bgText.value = Localizer
  209. .toDisplayUnits(String(latestBG))
  210. // Direction handling
  211. if let directionBG = entries[latestEntryIndex].direction {
  212. Observable.shared.directionText.value = self.bgDirectionGraphic(directionBG)
  213. } else {
  214. Observable.shared.directionText.value = ""
  215. }
  216. // Delta handling
  217. if deltaBG < 0 {
  218. Observable.shared.deltaText.value = Localizer.toDisplayUnits(String(deltaBG))
  219. } else {
  220. Observable.shared.deltaText.value = "+" + Localizer.toDisplayUnits(String(deltaBG))
  221. }
  222. // Stale
  223. Observable.shared.bgStale.value = deltaTime >= 12
  224. // Apply strikethrough to BGText based on the staleness of the data
  225. // Also clear badge if bgvalue is stale
  226. let bgTextStr = self.BGText.text ?? ""
  227. let attributeString = NSMutableAttributedString(string: bgTextStr)
  228. attributeString.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributeString.length))
  229. if Observable.shared.bgStale.value { // Data is stale
  230. attributeString.addAttribute(.strikethroughColor, value: UIColor.systemRed, range: NSRange(location: 0, length: attributeString.length))
  231. self.updateBadge(val: 0)
  232. } else { // Data is fresh
  233. attributeString.addAttribute(.strikethroughColor, value: UIColor.clear, range: NSRange(location: 0, length: attributeString.length))
  234. self.updateBadge(val: latestBG)
  235. }
  236. self.BGText.attributedText = attributeString
  237. // Update contact
  238. if Storage.shared.contactEnabled.value {
  239. self.contactImageUpdater
  240. .updateContactImage(
  241. bgValue: bgTextStr,
  242. trend: Observable.shared.directionText.value,
  243. delta: Observable.shared.deltaText.value,
  244. stale: Observable.shared.bgStale.value
  245. )
  246. }
  247. }
  248. }
  249. }