BGData.swift 16 KB

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