BGData.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. // LoopFollow
  2. // BGData.swift
  3. import Foundation
  4. import UIKit
  5. extension MainViewController {
  6. /// Number of days of BG history to request from the source. One extra day is
  7. /// added when the "Show Yesterday's BG" overlay is enabled (Nightscout only),
  8. /// so the overlay can display the same clock time from the day before.
  9. var bgFetchDays: Int {
  10. let extraDay = (Storage.shared.showYesterdayLine.value && IsNightscoutEnabled()) ? 1 : 0
  11. return Storage.shared.downloadDays.value + extraDay
  12. }
  13. // Dex Share Web Call
  14. func webLoadDexShare() {
  15. // Dexcom Share only returns 24 hrs of data as of now
  16. // Requesting more just for consistency with NS
  17. let graphHours = 24 * bgFetchDays
  18. let count = graphHours * 12
  19. dexShare?.fetchData(count) { err, result in
  20. if let error = err {
  21. LogManager.shared.log(category: .dexcom, message: "Error fetching Dexcom data: \(error.localizedDescription)", limitIdentifier: "Error fetching Dexcom data")
  22. BannerManager.shared.reportDexcomFailure(error, nightscoutFallback: IsNightscoutEnabled())
  23. self.webLoadNSBGData()
  24. return
  25. }
  26. guard let data = result, !data.isEmpty else {
  27. LogManager.shared.log(category: .dexcom, message: "Received empty data array from Dexcom", limitIdentifier: "Received empty data array from Dexcom")
  28. self.webLoadNSBGData()
  29. return
  30. }
  31. BannerManager.shared.clear(.dexcom)
  32. // If Dex data is old, load from NS instead
  33. let latestDate = data[0].date
  34. let now = dateTimeUtils.getNowTimeIntervalUTC()
  35. if (latestDate + 330) < now, IsNightscoutEnabled() {
  36. LogManager.shared.log(category: .dexcom, message: "Dexcom data is old, loading from NS instead", limitIdentifier: "Dexcom data is old, loading from NS instead")
  37. self.webLoadNSBGData()
  38. return
  39. }
  40. // Dexcom Share can return duplicate readings when multiple uploaders
  41. // write to the same Dexcom account. Dedup before any further use.
  42. let dedupedData = self.deduplicateBGReadings(data)
  43. // Supplement with NS if Dex data doesn't cover the full requested window.
  44. let dexCutoff = dateTimeUtils.getNowTimeIntervalUTC() - Double(graphHours) * 3600
  45. let dexCoversFull = dedupedData.last.map { $0.date <= dexCutoff } ?? false
  46. if !dexCoversFull, IsNightscoutEnabled() {
  47. self.webLoadNSBGData(dexData: dedupedData)
  48. } else {
  49. self.ProcessDexBGData(data: dedupedData, sourceName: "Dexcom")
  50. }
  51. }
  52. }
  53. // NS BG Data Web call
  54. func webLoadNSBGData(dexData: [ShareGlucoseData] = []) {
  55. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  56. if !IsNightscoutEnabled() {
  57. BannerManager.shared.clear(.nightscout)
  58. Storage.shared.lastBGChecked.value = Date()
  59. return
  60. }
  61. var parameters: [String: String] = [:]
  62. let date = Calendar.current.date(byAdding: .day, value: -1 * bgFetchDays, to: Date())!
  63. parameters["count"] = "\(bgFetchDays * globalVariables.maxExpectedUploaders * 24 * 60 / 5)"
  64. parameters["find[date][$gte]"] = "\(Int(date.timeIntervalSince1970 * 1000))"
  65. // Exclude 'cal' entries
  66. parameters["find[type][$ne]"] = "cal"
  67. NightscoutUtils.executeRequest(eventType: .sgv, parameters: parameters) { (result: Result<[ShareGlucoseData], Error>) in
  68. switch result {
  69. case let .success(entriesResponse):
  70. BannerManager.shared.clear(.nightscout)
  71. var nsData = entriesResponse
  72. DispatchQueue.main.async {
  73. // transform NS data to look like Dex data
  74. for i in 0 ..< nsData.count {
  75. // convert the NS timestamp to seconds instead of milliseconds
  76. nsData[i].date /= 1000
  77. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  78. }
  79. var nsData2 = self.deduplicateBGReadings(nsData)
  80. // merge NS and Dex data if needed; use recent Dex data and older NS data
  81. var sourceName = "Nightscout"
  82. if !dexData.isEmpty {
  83. let oldestDexDate = dexData[dexData.count - 1].date
  84. var itemsToRemove = 0
  85. while itemsToRemove < nsData2.count, nsData2[itemsToRemove].date >= oldestDexDate {
  86. itemsToRemove += 1
  87. }
  88. nsData2.removeFirst(itemsToRemove)
  89. nsData2 = dexData + nsData2
  90. sourceName = "Dexcom"
  91. }
  92. // trigger the processor for the data after downloading.
  93. self.ProcessDexBGData(data: nsData2, sourceName: sourceName)
  94. }
  95. case let .failure(error):
  96. LogManager.shared.log(category: .nightscout, message: "Failed to fetch bg data: \(error)", limitIdentifier: "Failed to fetch bg data")
  97. BannerManager.shared.reportNightscoutFetchFailure(error)
  98. DispatchQueue.main.async {
  99. TaskScheduler.shared.rescheduleTask(
  100. id: .fetchBG,
  101. to: Date().addingTimeInterval(10)
  102. )
  103. }
  104. // if we have Dex data, use it
  105. if !dexData.isEmpty {
  106. self.ProcessDexBGData(data: dexData, sourceName: "Dexcom")
  107. } else {
  108. Storage.shared.lastBGChecked.value = Date()
  109. }
  110. return
  111. }
  112. }
  113. }
  114. /// Removes consecutive duplicate readings (same SGV within 30 s). Expects newest-first input.
  115. func deduplicateBGReadings(_ readings: [ShareGlucoseData]) -> [ShareGlucoseData] {
  116. var result: [ShareGlucoseData] = []
  117. var lastTime = Double.infinity
  118. var lastSGV: Int?
  119. for reading in readings {
  120. if lastSGV == nil || lastSGV != reading.sgv || lastTime - reading.date >= 30 {
  121. result.append(reading)
  122. lastTime = reading.date
  123. lastSGV = reading.sgv
  124. }
  125. }
  126. return result
  127. }
  128. /// Processes incoming BG data.
  129. func ProcessDexBGData(data: [ShareGlucoseData], sourceName: String) {
  130. let graphHours = 24 * Storage.shared.downloadDays.value
  131. guard !data.isEmpty else {
  132. LogManager.shared.log(category: .nightscout, message: "No bg data received. Skipping processing.", limitIdentifier: "No bg data received. Skipping processing.")
  133. Storage.shared.lastBGChecked.value = Date()
  134. return
  135. }
  136. let latestReading = data[0]
  137. let sensorTimestamp = latestReading.date
  138. let now = dateTimeUtils.getNowTimeIntervalUTC()
  139. // secondsAgo is how old the newest reading is
  140. let secondsAgo = now - sensorTimestamp
  141. // Compute the current sensor schedule offset
  142. let currentOffset = CycleHelper.cycleOffset(for: sensorTimestamp, interval: 5 * 60)
  143. if Storage.shared.sensorScheduleOffset.value != currentOffset {
  144. Storage.shared.sensorScheduleOffset.value = currentOffset
  145. LogManager.shared.log(category: .nightscout,
  146. message: "Sensor schedule offset: \(currentOffset) seconds.",
  147. isDebug: true)
  148. }
  149. // Determine the next polling delay.
  150. var delayToSchedule: Double = 0
  151. DispatchQueue.main.async {
  152. // Fallback scheduling for older readings.
  153. if secondsAgo >= (20 * 60) {
  154. delayToSchedule = 5 * 60
  155. LogManager.shared.log(category: .nightscout,
  156. message: "Reading is very old (\(secondsAgo) sec). Scheduling next fetch in 5 minutes.",
  157. isDebug: true)
  158. } else if secondsAgo >= (10 * 60) {
  159. delayToSchedule = 60
  160. LogManager.shared.log(category: .nightscout,
  161. message: "Reading is moderately old (\(secondsAgo) sec). Scheduling next fetch in 60 seconds.",
  162. isDebug: true)
  163. } else if secondsAgo >= (7 * 60) {
  164. delayToSchedule = 30
  165. LogManager.shared.log(category: .nightscout,
  166. message: "Reading is a bit old (\(secondsAgo) sec). Scheduling next fetch in 30 seconds.",
  167. isDebug: true)
  168. } else if secondsAgo >= (5 * 60) {
  169. delayToSchedule = 5
  170. LogManager.shared.log(category: .nightscout,
  171. message: "Reading is close to 5 minutes old (\(secondsAgo) sec). Scheduling next fetch in 5 seconds.",
  172. isDebug: true)
  173. } else {
  174. delayToSchedule = 300 - secondsAgo + Double(Storage.shared.bgUpdateDelay.value)
  175. LogManager.shared.log(category: .nightscout,
  176. message: "Fresh reading. Scheduling next fetch in \(delayToSchedule) seconds.",
  177. isDebug: true)
  178. TaskScheduler.shared.rescheduleTask(id: .alarmCheck, to: Date().addingTimeInterval(3))
  179. }
  180. if NightscoutSocketManager.shared.connectionState == .authenticated {
  181. delayToSchedule = max(delayToSchedule * 3, 60)
  182. }
  183. TaskScheduler.shared.rescheduleTask(id: .fetchBG, to: Date().addingTimeInterval(delayToSchedule))
  184. // Evaluate speak conditions if there is a previous value.
  185. if data.count > 1 {
  186. self.evaluateSpeakConditions(currentValue: data[0].sgv, previousValue: data[1].sgv)
  187. }
  188. }
  189. // Process data for graph display.
  190. bgData.removeAll()
  191. for i in 0 ..< data.count {
  192. let readingTimestamp = data[data.count - 1 - i].date
  193. if readingTimestamp >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  194. let sgvValue = data[data.count - 1 - i].sgv
  195. // Skip outlier values (e.g. first reading of a new sensor might be abnormally high).
  196. if sgvValue > 600 {
  197. LogManager.shared.log(category: .nightscout,
  198. message: "Skipping reading with sgv \(sgvValue) as it exceeds threshold.",
  199. isDebug: true)
  200. continue
  201. }
  202. let reading = ShareGlucoseData(sgv: sgvValue, date: readingTimestamp, direction: data[data.count - 1 - i].direction)
  203. bgData.append(reading)
  204. }
  205. }
  206. LogManager.shared.log(category: .nightscout,
  207. message: "Graph data updated with \(bgData.count) entries.",
  208. isDebug: true)
  209. // Build the optional "yesterday" comparison overlay. Every fetched reading is
  210. // shifted +24h so it lines up with the same clock time today; the extra day of
  211. // history pulled by bgFetchDays provides the portion that falls inside the
  212. // visible window. The overlay is capped to "now + hours of prediction" so it
  213. // never extends further into the future than the prediction line.
  214. yesterdayBGData.removeAll()
  215. if Storage.shared.showYesterdayLine.value, IsNightscoutEnabled() {
  216. let cutoff = dateTimeUtils.getTimeIntervalNHoursAgo(N: 24 * bgFetchDays)
  217. let futureLimit = dateTimeUtils.getNowTimeIntervalUTC() + Storage.shared.predictionToLoad.value * 3600
  218. for i in 0 ..< data.count {
  219. let reading = data[data.count - 1 - i]
  220. guard reading.date >= cutoff, reading.sgv <= 600 else { continue }
  221. let shiftedDate = reading.date + 24 * 60 * 60
  222. guard shiftedDate <= futureLimit else { continue }
  223. yesterdayBGData.append(ShareGlucoseData(sgv: reading.sgv,
  224. date: shiftedDate,
  225. direction: reading.direction))
  226. }
  227. }
  228. viewUpdateNSBG(sourceName: sourceName)
  229. }
  230. func updateServerText(with serverText: String? = nil) {
  231. if Storage.shared.showDisplayName.value, let displayName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
  232. Observable.shared.serverText.value = displayName
  233. } else if let serverText = serverText {
  234. Observable.shared.serverText.value = serverText
  235. }
  236. }
  237. // NS BG Data Front end updater
  238. func viewUpdateNSBG(sourceName: String) {
  239. DispatchQueue.main.async {
  240. TaskScheduler.shared.rescheduleTask(id: .minAgoUpdate, to: Date())
  241. let entries = self.bgData
  242. if entries.count < 2 { // Protect index out of bounds
  243. Storage.shared.lastBGChecked.value = Date()
  244. return
  245. }
  246. self.updateBGGraph()
  247. self.updateStats()
  248. let latestEntryIndex = entries.count - 1
  249. let latestBG = entries[latestEntryIndex].sgv
  250. let priorBG = entries[latestEntryIndex - 1].sgv
  251. let deltaBG = latestBG - priorBG
  252. let lastBGTime = entries[latestEntryIndex].date
  253. self.updateServerText(with: sourceName)
  254. // Set BGText with the latest BG value
  255. self.updateBGTextAppearance()
  256. if latestBG <= globalVariables.minDisplayGlucose {
  257. Observable.shared.bgText.value = "LOW"
  258. } else if latestBG >= globalVariables.maxDisplayGlucose {
  259. Observable.shared.bgText.value = "HIGH"
  260. } else {
  261. Observable.shared.bgText.value = Localizer.toDisplayUnits(String(latestBG))
  262. }
  263. Observable.shared.bg.value = latestBG
  264. // Direction handling
  265. if let directionBG = entries[latestEntryIndex].direction {
  266. Observable.shared.directionText.value = self.bgDirectionGraphic(directionBG)
  267. } else {
  268. Observable.shared.directionText.value = ""
  269. }
  270. // Delta handling
  271. if deltaBG < 0 {
  272. Observable.shared.deltaText.value = Localizer.toDisplayUnits(String(deltaBG))
  273. } else {
  274. Observable.shared.deltaText.value = "+" + Localizer.toDisplayUnits(String(deltaBG))
  275. }
  276. // Live Activity storage
  277. Storage.shared.lastBgReadingTimeSeconds.value = lastBGTime
  278. Storage.shared.lastDeltaMgdl.value = Double(deltaBG)
  279. Storage.shared.lastTrendCode.value = entries[latestEntryIndex].direction
  280. // Mark BG data as loaded for initial loading state
  281. self.markDataLoaded("bg")
  282. // Live Activity update
  283. #if !targetEnvironment(macCatalyst)
  284. LiveActivityManager.shared.refreshFromCurrentState(reason: "bg")
  285. #endif
  286. // Update contact
  287. if Storage.shared.contactEnabled.value {
  288. self.contactImageUpdater
  289. .updateContactImage(
  290. bgValue: Observable.shared.bgText.value,
  291. trend: Observable.shared.directionText.value,
  292. delta: Observable.shared.deltaText.value,
  293. iob: Observable.shared.iobText.value,
  294. stale: Observable.shared.bgStale.value
  295. )
  296. }
  297. Storage.shared.lastBGChecked.value = Date()
  298. }
  299. }
  300. }