BGData.swift 16 KB

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