BGData.swift 13 KB

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