NightScout.swift 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008
  1. //
  2. // NightScout.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 6/16/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension MainViewController {
  11. //NS Carbs Struct
  12. struct carbsData: Codable {
  13. var carbs: Double?
  14. }
  15. //NS Cage Struct
  16. struct cageData: Codable {
  17. var created_at: String
  18. }
  19. //NS Basal Profile Struct
  20. struct basalProfileStruct: Codable {
  21. var value: Double
  22. var time: String
  23. var timeAsSeconds: Double
  24. }
  25. //NS Basal Data Struct
  26. struct basalGraphStruct: Codable {
  27. var basalRate: Double
  28. var date: TimeInterval
  29. }
  30. //NS Bolus Data Struct
  31. struct bolusGraphStruct: Codable {
  32. var value: Double
  33. var date: TimeInterval
  34. var sgv: Int
  35. }
  36. //NS Bolus Data Struct
  37. struct carbGraphStruct: Codable {
  38. var value: Double
  39. var date: TimeInterval
  40. var sgv: Int
  41. var absorptionTime: Int
  42. }
  43. func isStaleData() -> Bool {
  44. if bgData.count > 0 {
  45. let now = dateTimeUtils.getNowTimeIntervalUTC()
  46. let lastReadingTime = bgData.last!.date
  47. let secondsAgo = now - lastReadingTime
  48. if secondsAgo >= 20*60 {
  49. return true
  50. } else {
  51. return false
  52. }
  53. } else {
  54. return false
  55. }
  56. }
  57. // Dex Share Web Call
  58. func webLoadDexShare(onlyPullLastRecord: Bool = false) {
  59. // Dexcom Share only returns 24 hrs of data as of now
  60. // Requesting more just for consistency with NS
  61. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  62. var count = graphHours * 12
  63. if onlyPullLastRecord { count = 1 }
  64. dexShare?.fetchData(count) { (err, result) -> () in
  65. // TODO: add error checking
  66. if(err == nil) {
  67. var data = result!
  68. // If Dex data is old, load from NS instead
  69. let latestDate = data[0].date
  70. let now = dateTimeUtils.getNowTimeIntervalUTC()
  71. if (latestDate + 330) < now && UserDefaultsRepository.url.value != "" {
  72. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  73. print("dex didn't load, triggered NS attempt")
  74. return
  75. }
  76. // Dexcom only returns 24 hrs of data. If we need more, call NS.
  77. if graphHours > 24 && !onlyPullLastRecord && UserDefaultsRepository.url.value != "" {
  78. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord, dexData: data)
  79. } else {
  80. self.ProcessDexBGData(data: data, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  81. }
  82. } else {
  83. // If we get an error, immediately try to pull NS BG Data
  84. if UserDefaultsRepository.url.value != "" {
  85. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  86. }
  87. if globalVariables.dexVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  88. globalVariables.dexVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  89. DispatchQueue.main.async {
  90. //self.sendNotification(title: "Dexcom Share Error", body: "Please double check user name and password, internet connection, and sharing status.")
  91. }
  92. }
  93. }
  94. }
  95. }
  96. // NS BG Data Web call
  97. func webLoadNSBGData(onlyPullLastRecord: Bool = false, dexData: [ShareGlucoseData] = []) {
  98. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  99. // This kicks it out in the instance where dexcom fails but they aren't using NS &&
  100. if UserDefaultsRepository.url.value == "" {
  101. self.startBGTimer(time: 10)
  102. return
  103. }
  104. // URL processor
  105. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  106. if onlyPullLastRecord {
  107. urlBGDataPath = urlBGDataPath + "count=1"
  108. } else {
  109. //Fetch entries for the time period of "downloadDays"
  110. let utcISODateFormatter = ISO8601DateFormatter()
  111. let date = Calendar.current.date(byAdding: .day, value: -1 * UserDefaultsRepository.downloadDays.value, to: Date())!
  112. urlBGDataPath = urlBGDataPath + "count=1000&find[dateString][$gte]=" + utcISODateFormatter.string(from: date)
  113. }
  114. if !token.isEmpty {
  115. urlBGDataPath = urlBGDataPath + "&token=" + token
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. // if we have Dex data, use it
  119. if !dexData.isEmpty {
  120. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  121. return
  122. }
  123. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  124. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  125. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  126. }
  127. DispatchQueue.main.async {
  128. if self.bgTimer.isValid {
  129. self.bgTimer.invalidate()
  130. }
  131. self.startBGTimer(time: 10)
  132. }
  133. return
  134. }
  135. var request = URLRequest(url: urlBGData)
  136. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  137. // Downloader
  138. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  139. guard error == nil else {
  140. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  141. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  142. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  143. }
  144. DispatchQueue.main.async {
  145. if self.bgTimer.isValid {
  146. self.bgTimer.invalidate()
  147. }
  148. self.startBGTimer(time: 10)
  149. }
  150. // if we have Dex data, use it
  151. if !dexData.isEmpty {
  152. self.ProcessDexBGData(data: dexData, onlyPullLastRecord: onlyPullLastRecord, sourceName: "Dexcom")
  153. }
  154. return
  155. }
  156. guard let data = data else {
  157. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  158. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  159. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  160. }
  161. DispatchQueue.main.async {
  162. if self.bgTimer.isValid {
  163. self.bgTimer.invalidate()
  164. }
  165. self.startBGTimer(time: 10)
  166. }
  167. return
  168. }
  169. var entriesResponse: [ShareGlucoseData]?
  170. let decoder = JSONDecoder()
  171. do {
  172. entriesResponse = try decoder.decode([ShareGlucoseData].self, from: data)
  173. } catch let DecodingError.dataCorrupted(context) {
  174. print("Data corrupted: \(context)")
  175. } catch let DecodingError.keyNotFound(key, context) {
  176. print("Key '\(key)' not found: \(context.debugDescription)")
  177. print("codingPath: \(context.codingPath)")
  178. } catch let DecodingError.valueNotFound(value, context) {
  179. print("Value '\(value)' not found: \(context.debugDescription)")
  180. print("codingPath: \(context.codingPath)")
  181. } catch let DecodingError.typeMismatch(type, context) {
  182. print("Type '\(type)' mismatch: \(context.debugDescription)")
  183. print("codingPath: \(context.codingPath)")
  184. } catch {
  185. print("Error decoding JSON: \(error)")
  186. }
  187. if var nsData = entriesResponse {
  188. DispatchQueue.main.async {
  189. // transform NS data to look like Dex data
  190. for i in 0..<nsData.count {
  191. // convert the NS timestamp to seconds instead of milliseconds
  192. nsData[i].date /= 1000
  193. nsData[i].date.round(FloatingPointRoundingRule.toNearestOrEven)
  194. }
  195. print(nsData.count)
  196. //Avoid duplicate entries messing up the graph, only use one reading per 5 minutes.
  197. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  198. let points = graphHours * 12 + 1
  199. var nsData2 = [ShareGlucoseData]()
  200. let timestamp = Date().timeIntervalSince1970
  201. for i in 0..<points {
  202. //Starting with "now" and then step 5 minutes back in time
  203. let target = timestamp - Double(i) * 60 * 5
  204. //Find the reading closest to the target, but not too far away
  205. let closest = nsData.filter{ abs($0.date - target) < 3 * 60 }.min { abs($0.date - target) < abs($1.date - target) }
  206. //If a reading is found, add it to the new array
  207. if let item = closest {
  208. nsData2.append(item)
  209. }
  210. }
  211. print(nsData2.count)
  212. // merge NS and Dex data if needed; use recent Dex data and older NS data
  213. var sourceName = "Nightscout"
  214. if !dexData.isEmpty {
  215. let oldestDexDate = dexData[dexData.count - 1].date
  216. var itemsToRemove = 0
  217. while itemsToRemove < nsData2.count && nsData2[itemsToRemove].date >= oldestDexDate {
  218. itemsToRemove += 1
  219. }
  220. nsData2.removeFirst(itemsToRemove)
  221. nsData2 = dexData + nsData2
  222. sourceName = "Dexcom"
  223. }
  224. // trigger the processor for the data after downloading.
  225. self.ProcessDexBGData(data: nsData2, onlyPullLastRecord: onlyPullLastRecord, sourceName: sourceName)
  226. }
  227. } else {
  228. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  229. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  230. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  231. }
  232. DispatchQueue.main.async {
  233. if self.bgTimer.isValid {
  234. self.bgTimer.invalidate()
  235. }
  236. self.startBGTimer(time: 10)
  237. }
  238. return
  239. }
  240. }
  241. getBGTask.resume()
  242. }
  243. // Dexcom BG Data Response processor
  244. func ProcessDexBGData(data: [ShareGlucoseData], onlyPullLastRecord: Bool, sourceName: String){
  245. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  246. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  247. let pullDate = data[data.count - 1].date
  248. let latestDate = data[0].date
  249. let now = dateTimeUtils.getNowTimeIntervalUTC()
  250. // Start the BG timer based on the reading
  251. let secondsAgo = now - latestDate
  252. DispatchQueue.main.async {
  253. // if reading is overdue over: 20:00, re-attempt every 5 minutes
  254. if secondsAgo >= (20 * 60) {
  255. self.startBGTimer(time: (5 * 60))
  256. print("##### started 5 minute bg timer")
  257. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  258. } else if secondsAgo >= (10 * 60) {
  259. self.startBGTimer(time: 60)
  260. print("##### started 1 minute bg timer")
  261. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  262. } else if secondsAgo >= (7 * 60) {
  263. self.startBGTimer(time: 30)
  264. print("##### started 30 second bg timer")
  265. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  266. } else if secondsAgo >= (5 * 60) {
  267. self.startBGTimer(time: 10)
  268. print("##### started 10 second bg timer")
  269. // We have a current reading. Set timer to 5:10 from last reading
  270. } else {
  271. self.startBGTimer(time: 300 - secondsAgo + Double(UserDefaultsRepository.bgUpdateDelay.value))
  272. let timerVal = 310 - secondsAgo
  273. print("##### started 5:10 bg timer: \(timerVal)")
  274. self.updateBadge(val: data[0].sgv)
  275. if UserDefaultsRepository.speakBG.value {
  276. self.speakBG(currentValue: data[0].sgv, previousValue: data[1].sgv)
  277. }
  278. }
  279. }
  280. // If we already have data, we're going to pop it to the end and remove the first. If we have old or no data, we'll destroy the whole array and start over. This is simpler than determining how far back we need to get new data from in case Dex back-filled readings
  281. if !onlyPullLastRecord {
  282. bgData.removeAll()
  283. } else if bgData[bgData.count - 1].date != pullDate {
  284. bgData.removeFirst()
  285. } else {
  286. return
  287. }
  288. // loop through the data so we can reverse the order to oldest first for the graph
  289. for i in 0..<data.count {
  290. let dateString = data[data.count - 1 - i].date
  291. if dateString >= dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  292. let sgvValue = data[data.count - 1 - i].sgv
  293. // Skip the current iteration if the sgv value is over 600
  294. // First time a user starts a G7, they get a value of 4000
  295. if sgvValue > 600 {
  296. continue
  297. }
  298. let reading = ShareGlucoseData(sgv: sgvValue, date: dateString, direction: data[data.count - 1 - i].direction)
  299. bgData.append(reading)
  300. }
  301. }
  302. viewUpdateNSBG(sourceName: sourceName)
  303. }
  304. // NS BG Data Front end updater
  305. func viewUpdateNSBG (sourceName: String) {
  306. DispatchQueue.main.async {
  307. if UserDefaultsRepository.debugLog.value {
  308. self.writeDebugLog(value: "Display: BG")
  309. self.writeDebugLog(value: "Num BG: " + self.bgData.count.description)
  310. }
  311. let entries = self.bgData
  312. if entries.count < 1 { return }
  313. self.updateBGGraph()
  314. self.updateStats()
  315. let latestEntryi = entries.count - 1
  316. let latestBG = entries[latestEntryi].sgv
  317. let priorBG = entries[latestEntryi - 1].sgv
  318. let deltaBG = latestBG - priorBG as Int
  319. let lastBGTime = entries[latestEntryi].date
  320. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  321. var userUnit = " mg/dL"
  322. if self.mmol {
  323. userUnit = " mmol/L"
  324. }
  325. self.serverText.text = sourceName
  326. var snoozerBG = ""
  327. var snoozerDirection = ""
  328. var snoozerDelta = ""
  329. self.BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  330. snoozerBG = bgUnits.toDisplayUnits(String(latestBG))
  331. self.setBGTextColor()
  332. if let directionBG = entries[latestEntryi].direction {
  333. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  334. snoozerDirection = self.bgDirectionGraphic(directionBG)
  335. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  336. }
  337. else
  338. {
  339. self.DirectionText.text = ""
  340. snoozerDirection = ""
  341. self.latestDirectionString = ""
  342. }
  343. if deltaBG < 0 {
  344. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  345. snoozerDelta = bgUnits.toDisplayUnits(String(deltaBG))
  346. self.latestDeltaString = String(deltaBG)
  347. }
  348. else
  349. {
  350. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  351. snoozerDelta = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  352. self.latestDeltaString = "+" + String(deltaBG)
  353. }
  354. // Snoozer Display
  355. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  356. snoozer.BGLabel.text = snoozerBG
  357. snoozer.DirectionLabel.text = snoozerDirection
  358. snoozer.DeltaLabel.text = snoozerDelta
  359. }
  360. }
  361. // NS Device Status Web Call
  362. func webLoadNSDeviceStatus() {
  363. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  364. let urlUser = UserDefaultsRepository.url.value
  365. // NS Api is not working to find by greater than date
  366. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288"
  367. if token != "" {
  368. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288&token=" + token
  369. }
  370. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  371. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  372. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  373. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  374. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  375. }
  376. DispatchQueue.main.async {
  377. if self.deviceStatusTimer.isValid {
  378. self.deviceStatusTimer.invalidate()
  379. }
  380. self.startDeviceStatusTimer(time: 10)
  381. }
  382. return
  383. }
  384. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  385. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  386. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  387. guard error == nil else {
  388. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  389. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  390. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  391. }
  392. DispatchQueue.main.async {
  393. if self.deviceStatusTimer.isValid {
  394. self.deviceStatusTimer.invalidate()
  395. }
  396. self.startDeviceStatusTimer(time: 10)
  397. }
  398. return
  399. }
  400. guard let data = data else {
  401. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  402. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  403. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  404. }
  405. DispatchQueue.main.async {
  406. if self.deviceStatusTimer.isValid {
  407. self.deviceStatusTimer.invalidate()
  408. }
  409. self.startDeviceStatusTimer(time: 10)
  410. }
  411. return
  412. }
  413. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  414. if let json = json {
  415. DispatchQueue.main.async {
  416. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  417. }
  418. } else {
  419. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  420. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  421. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  422. }
  423. DispatchQueue.main.async {
  424. if self.deviceStatusTimer.isValid {
  425. self.deviceStatusTimer.invalidate()
  426. }
  427. self.startDeviceStatusTimer(time: 10)
  428. }
  429. return
  430. }
  431. }
  432. deviceStatusTask.resume()
  433. }
  434. // NS Device Status Response Processor
  435. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  436. self.clearLastInfoData(index: 0)
  437. self.clearLastInfoData(index: 1)
  438. self.clearLastInfoData(index: 3)
  439. self.clearLastInfoData(index: 4)
  440. self.clearLastInfoData(index: 5)
  441. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  442. if jsonDeviceStatus.count == 0 {
  443. return
  444. }
  445. //Process the current data first
  446. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  447. //pump and uploader
  448. let formatter = ISO8601DateFormatter()
  449. formatter.formatOptions = [.withFullDate,
  450. .withTime,
  451. .withDashSeparatorInDate,
  452. .withColonSeparatorInTime]
  453. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  454. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  455. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  456. latestPumpVolume = reservoirData
  457. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  458. } else {
  459. latestPumpVolume = 50.0
  460. tableData[5].value = "50+U"
  461. }
  462. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  463. let upbat = uploader["battery"] as! Double
  464. tableData[4].value = String(format:"%.0f", upbat) + "%"
  465. UserDefaultsRepository.deviceBatteryLevel.value = upbat
  466. }
  467. }
  468. }
  469. // Loop
  470. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  471. //print("Loop: \(lastLoopRecord)")
  472. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  473. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  474. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  475. if let failure = lastLoopRecord["failureReason"] {
  476. LoopStatusLabel.text = "X"
  477. latestLoopStatusString = "X"
  478. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  479. } else {
  480. var wasEnacted = false
  481. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  482. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  483. wasEnacted = true
  484. if let lastTempBasal = enacted["rate"] as? Double {
  485. }
  486. }
  487. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  488. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  489. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  490. }
  491. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  492. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  493. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  494. }
  495. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  496. let prediction = predictdata["values"] as! [Double]
  497. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  498. PredictionLabel.textColor = UIColor.systemPurple
  499. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  500. predictionData.removeAll()
  501. var predictionTime = lastLoopTime
  502. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  503. var i = 0
  504. while i <= toLoad {
  505. if i < prediction.count {
  506. let sgvValue = Int(round(prediction[i]))
  507. // Skip values higher than 600
  508. if sgvValue <= 600 {
  509. let prediction = ShareGlucoseData(sgv: sgvValue, date: predictionTime, direction: "flat")
  510. predictionData.append(prediction)
  511. }
  512. predictionTime += 300
  513. }
  514. i += 1
  515. }
  516. let predMin = prediction.min()
  517. let predMax = prediction.max()
  518. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  519. updatePredictionGraph()
  520. }
  521. }
  522. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  523. tableData[8].value = String(format:"%.2fU", recBolus)
  524. }
  525. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  526. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  527. var lastBGTime = lastLoopTime
  528. if bgData.count > 0 {
  529. lastBGTime = bgData[bgData.count - 1].date
  530. }
  531. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  532. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  533. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  534. if tempBasalTime > lastBGTime && !wasEnacted {
  535. LoopStatusLabel.text = "⏀"
  536. latestLoopStatusString = "⏀"
  537. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  538. } else {
  539. LoopStatusLabel.text = "↻"
  540. latestLoopStatusString = "↻"
  541. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  542. }
  543. }
  544. } else {
  545. LoopStatusLabel.text = "↻"
  546. latestLoopStatusString = "↻"
  547. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  548. }
  549. }
  550. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  551. LoopStatusLabel.text = "⚠"
  552. latestLoopStatusString = "⚠"
  553. }
  554. latestLoopTime = lastLoopTime
  555. } // end lastLoopTime
  556. } // end lastLoop Record
  557. if let lastLoopRecord = lastDeviceStatus?["openaps"] as! [String : AnyObject]? {
  558. if let lastLoopTime = formatter.date(from: (lastDeviceStatus?["created_at"] as! String))?.timeIntervalSince1970 {
  559. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  560. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  561. if let failure = lastLoopRecord["failureReason"] {
  562. LoopStatusLabel.text = "X"
  563. latestLoopStatusString = "X"
  564. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  565. } else {
  566. var wasEnacted = false
  567. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  568. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  569. wasEnacted = true
  570. if let lastTempBasal = enacted["rate"] as? Double {
  571. }
  572. }
  573. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  574. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  575. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  576. }
  577. if let cobdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  578. tableData[1].value = String(format:"%.1f", cobdata["COB"] as! Double)
  579. latestCOB = String(format:"%.1f", cobdata["COB"] as! Double)
  580. }
  581. if let recbolusdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  582. tableData[8].value = String(format:"%.2fU", recbolusdata["insulinReq"] as! Double)
  583. }
  584. if let autosensdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  585. let sens = autosensdata["sensitivityRatio"] as! Double * 100.0
  586. tableData[11].value = String(format:"%.0f", sens) + "%"
  587. }
  588. //Picks COB prediction if available, else UAM, else IOB, else ZT
  589. //Ideal is to predict all 4 in Loop Follow but this is a quick start
  590. var graphtype = ""
  591. var predictioncolor = UIColor.systemGray
  592. PredictionLabel.textColor = predictioncolor
  593. if let enactdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  594. if let predbgdata = enactdata["predBGs"] as? [String:AnyObject] {
  595. if predbgdata["COB"] != nil {
  596. graphtype="COB"
  597. predictioncolor = UIColor.systemYellow
  598. PredictionLabel.textColor = predictioncolor
  599. }
  600. else if predbgdata["UAM"] != nil {
  601. graphtype="UAM"
  602. predictioncolor = UIColor.systemOrange
  603. PredictionLabel.textColor = predictioncolor
  604. }
  605. else if predbgdata["IOB"] != nil {
  606. graphtype="IOB"
  607. predictioncolor = UIColor.systemBlue
  608. PredictionLabel.textColor = predictioncolor
  609. }
  610. else {
  611. graphtype="ZT"
  612. predictioncolor = UIColor.systemGreen
  613. PredictionLabel.textColor = predictioncolor
  614. }
  615. let graphdata = predbgdata[graphtype] as! [Double]
  616. if let eventualdata = lastLoopRecord["enacted"] as? [String:AnyObject] {
  617. PredictionLabel.text = String(format:"%.0f", eventualdata["eventualBG"] as! Double)
  618. }
  619. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  620. predictionData.removeAll()
  621. var predictionTime = lastLoopTime
  622. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  623. var i = 0
  624. while i <= toLoad {
  625. if i < graphdata.count {
  626. let prediction = ShareGlucoseData(sgv: Int(round(graphdata[i])), date: predictionTime, direction: "flat")
  627. predictionData.append(prediction)
  628. predictionTime += 300
  629. }
  630. i += 1
  631. }
  632. }
  633. let predMin = graphdata.min()
  634. let predMax = graphdata.max()
  635. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  636. updatePredictionGraph(color: predictioncolor)
  637. }
  638. }
  639. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  640. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  641. var lastBGTime = lastLoopTime
  642. if bgData.count > 0 {
  643. lastBGTime = bgData[bgData.count - 1].date
  644. }
  645. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  646. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  647. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  648. if tempBasalTime > lastBGTime && !wasEnacted {
  649. LoopStatusLabel.text = "⏀"
  650. latestLoopStatusString = "⏀"
  651. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  652. } else {
  653. LoopStatusLabel.text = "↻"
  654. latestLoopStatusString = "↻"
  655. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  656. }
  657. }
  658. } else {
  659. LoopStatusLabel.text = "↻"
  660. latestLoopStatusString = "↻"
  661. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  662. }
  663. }
  664. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  665. LoopStatusLabel.text = "⚠"
  666. latestLoopStatusString = "⚠"
  667. }
  668. latestLoopTime = lastLoopTime
  669. }
  670. }
  671. var oText = "" as String
  672. currentOverride = 1.0
  673. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  674. if lastOverride["active"] as! Bool {
  675. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  676. if let multiplier = lastOverride["multiplier"] as? Double {
  677. currentOverride = multiplier
  678. oText += String(format: "%.0f%%", (multiplier * 100))
  679. }
  680. else
  681. {
  682. oText += "100%"
  683. }
  684. oText += " ("
  685. let minValue = lastCorrection["minValue"] as! Double
  686. let maxValue = lastCorrection["maxValue"] as! Double
  687. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  688. tableData[3].value = oText
  689. }
  690. }
  691. infoTable.reloadData()
  692. // Start the timer based on the timestamp
  693. let now = dateTimeUtils.getNowTimeIntervalUTC()
  694. let secondsAgo = now - latestLoopTime
  695. DispatchQueue.main.async {
  696. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  697. if secondsAgo >= (20 * 60) {
  698. self.startDeviceStatusTimer(time: (5 * 60))
  699. print("started 5 minute device status timer")
  700. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  701. } else if secondsAgo >= (10 * 60) {
  702. self.startDeviceStatusTimer(time: 60)
  703. print("started 1 minute device status timer")
  704. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  705. } else if secondsAgo >= (7 * 60) {
  706. self.startDeviceStatusTimer(time: 30)
  707. print("started 30 second device status timer")
  708. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  709. } else if secondsAgo >= (5 * 60) {
  710. self.startDeviceStatusTimer(time: 10)
  711. print("started 10 second device status timer")
  712. // We have a current Loop. Set timer to 5:10 from last reading
  713. } else {
  714. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  715. let timerVal = 310 - secondsAgo
  716. print("started 5:10 device status timer: \(timerVal)")
  717. }
  718. }
  719. }
  720. // NS Carbs Today Web Call
  721. func webLoadNSCarbsToday() {
  722. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs Today") }
  723. let urlUser = UserDefaultsRepository.url.value
  724. let now = Date()
  725. let timeZone = TimeZone.current
  726. var calendar = Calendar(identifier: .gregorian)
  727. calendar.timeZone = timeZone
  728. var dateComponents = calendar.dateComponents(in: timeZone, from: now)
  729. dateComponents.hour = 0
  730. dateComponents.minute = 0
  731. dateComponents.second = 0
  732. guard let date = dateComponents.date else { fatalError("Invalid date components") }
  733. let dateFormatter = DateFormatter()
  734. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
  735. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  736. let utcDateString = dateFormatter.string(from: date)
  737. var urlString = urlUser + "/api/v1/treatments.json?count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  738. if token != "" {
  739. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&count=1000&find[eventType]=Carb+Correction&find[timestamp][$gte]=" + utcDateString
  740. }
  741. guard let urlData = URL(string: urlString) else {
  742. return
  743. }
  744. var request = URLRequest(url: urlData)
  745. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  746. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  747. guard error == nil else {
  748. return
  749. }
  750. guard let data = data else {
  751. return
  752. }
  753. let decoder = JSONDecoder()
  754. let entriesResponse = try? decoder.decode([carbsData].self, from: data)
  755. if let entriesResponse = entriesResponse {
  756. DispatchQueue.main.async {
  757. self.updateCarbsToday(data: entriesResponse)
  758. }
  759. } else {
  760. return
  761. }
  762. }
  763. task.resume()
  764. }
  765. // NS CarbsToday Response Processor
  766. func updateCarbsToday(data: [carbsData]) {
  767. self.clearLastInfoData(index: 10)
  768. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: carbs") }
  769. if data.count == 0 {
  770. return
  771. }
  772. let totalCarbs = data.reduce(0.0) { $0 + ($1.carbs ?? 0.0) }
  773. let resultString = String(format: "%.0f", totalCarbs)
  774. tableData[10].value = resultString
  775. infoTable.reloadData()
  776. }
  777. // NS Cage Web Call
  778. func webLoadNSCage() {
  779. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  780. let urlUser = UserDefaultsRepository.url.value
  781. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  782. if token != "" {
  783. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  784. }
  785. guard let urlData = URL(string: urlString) else {
  786. return
  787. }
  788. var request = URLRequest(url: urlData)
  789. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  790. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  791. guard error == nil else {
  792. return
  793. }
  794. guard let data = data else {
  795. return
  796. }
  797. let decoder = JSONDecoder()
  798. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  799. if let entriesResponse = entriesResponse {
  800. DispatchQueue.main.async {
  801. self.updateCage(data: entriesResponse)
  802. }
  803. } else {
  804. return
  805. }
  806. }
  807. task.resume()
  808. }
  809. // NS Cage Response Processor
  810. func updateCage(data: [cageData]) {
  811. self.clearLastInfoData(index: 7)
  812. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  813. if data.count == 0 {
  814. return
  815. }
  816. let lastCageString = data[0].created_at
  817. let formatter = ISO8601DateFormatter()
  818. formatter.formatOptions = [.withFullDate,
  819. .withTime,
  820. .withDashSeparatorInDate,
  821. .withColonSeparatorInTime]
  822. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  823. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  824. let now = dateTimeUtils.getNowTimeIntervalUTC()
  825. let secondsAgo = now - cageTime
  826. //let days = 24 * 60 * 60
  827. let formatter = DateComponentsFormatter()
  828. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  829. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  830. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  831. let formattedDuration = formatter.string(from: secondsAgo)
  832. tableData[7].value = formattedDuration ?? ""
  833. }
  834. infoTable.reloadData()
  835. }
  836. // NS Sage Web Call
  837. func webLoadNSSage() {
  838. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  839. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  840. let urlUser = UserDefaultsRepository.url.value
  841. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  842. if token != "" {
  843. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  844. }
  845. guard let urlData = URL(string: urlString) else {
  846. return
  847. }
  848. var request = URLRequest(url: urlData)
  849. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  850. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  851. guard error == nil else {
  852. return
  853. }
  854. guard let data = data else {
  855. return
  856. }
  857. let decoder = JSONDecoder()
  858. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  859. if let entriesResponse = entriesResponse {
  860. DispatchQueue.main.async {
  861. self.updateSage(data: entriesResponse)
  862. }
  863. } else {
  864. return
  865. }
  866. }
  867. task.resume()
  868. }
  869. // NS Sage Response Processor
  870. func updateSage(data: [cageData]) {
  871. self.clearLastInfoData(index: 6)
  872. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  873. if data.count == 0 {
  874. return
  875. }
  876. var lastSageString = data[0].created_at
  877. let formatter = ISO8601DateFormatter()
  878. formatter.formatOptions = [.withFullDate,
  879. .withTime,
  880. .withDashSeparatorInDate,
  881. .withColonSeparatorInTime]
  882. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  883. if UserDefaultsRepository.alertAutoSnoozeCGMStart.value && (dateTimeUtils.getNowTimeIntervalUTC() - UserDefaultsRepository.alertSageInsertTime.value < 7200){
  884. let snoozeTime = Date(timeIntervalSince1970: UserDefaultsRepository.alertSageInsertTime.value + 7200)
  885. UserDefaultsRepository.alertSnoozeAllTime.value = snoozeTime
  886. UserDefaultsRepository.alertSnoozeAllIsSnoozed.value = true
  887. guard let alarms = self.tabBarController!.viewControllers?[1] as? AlarmViewController else { return }
  888. alarms.reloadIsSnoozed(key: "alertSnoozeAllIsSnoozed", value: true)
  889. alarms.reloadSnoozeTime(key: "alertSnoozeAllTime", setNil: false, value: snoozeTime)
  890. }
  891. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  892. let now = dateTimeUtils.getNowTimeIntervalUTC()
  893. let secondsAgo = now - sageTime
  894. let days = 24 * 60 * 60
  895. let formatter = DateComponentsFormatter()
  896. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  897. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  898. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  899. let formattedDuration = formatter.string(from: secondsAgo)
  900. tableData[6].value = formattedDuration ?? ""
  901. }
  902. infoTable.reloadData()
  903. }
  904. // NS Profile Web Call
  905. func webLoadNSProfile() {
  906. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  907. let urlUser = UserDefaultsRepository.url.value
  908. var urlString = urlUser + "/api/v1/profile/current.json"
  909. if token != "" {
  910. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  911. }
  912. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  913. guard let url = URL(string: escapedAddress!) else {
  914. return
  915. }
  916. var request = URLRequest(url: url)
  917. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  918. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  919. guard error == nil else {
  920. return
  921. }
  922. guard let data = data else {
  923. return
  924. }
  925. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  926. if let json = json {
  927. DispatchQueue.main.async {
  928. self.updateProfile(jsonDeviceStatus: json)
  929. }
  930. } else {
  931. return
  932. }
  933. }
  934. task.resume()
  935. }
  936. // NS Profile Response Processor
  937. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  938. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  939. if jsonDeviceStatus.count == 0 {
  940. return
  941. }
  942. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  943. if let basal = jsonDeviceStatus[keyPath: "store.default.basal"] as? NSArray ?? jsonDeviceStatus[keyPath: "store.Default.basal"] as? NSArray {
  944. basalProfile.removeAll()
  945. for i in 0..<basal.count {
  946. let dict = basal[i] as! Dictionary<String, Any>
  947. do {
  948. let thisValue = try dict[keyPath: "value"] as! Double
  949. let thisTime = dict[keyPath: "time"] as! String
  950. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  951. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  952. basalProfile.append(entry)
  953. } catch {
  954. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  955. }
  956. }
  957. }
  958. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  959. if firstGraphLoad { return }
  960. var basalSegments: [DataStructs.basalProfileSegment] = []
  961. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  962. // Build scheduled basal segments from right to left by
  963. // moving pointers to the current midnight and current basal
  964. var midnight = dateTimeUtils.getTimeIntervalMidnightToday()
  965. var basalProfileIndex = basalProfile.count - 1
  966. var start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  967. var end = dateTimeUtils.getNowTimeIntervalUTC()
  968. // Move back until we're in the graph range
  969. while start > end {
  970. basalProfileIndex -= 1
  971. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  972. }
  973. // Add records while they're still within the graph
  974. let graphStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  975. while end >= graphStart {
  976. let entry = DataStructs.basalProfileSegment(
  977. basalRate: basalProfile[basalProfileIndex].value, startDate: start, endDate: end)
  978. basalSegments.append(entry)
  979. basalProfileIndex -= 1
  980. if basalProfileIndex < 0 {
  981. basalProfileIndex = basalProfile.count - 1
  982. midnight = midnight.advanced(by: -24*60*60)
  983. }
  984. end = start - 1
  985. start = midnight + basalProfile[basalProfileIndex].timeAsSeconds
  986. }
  987. // reverse the result to get chronological order
  988. basalSegments.reverse()
  989. var firstPass = true
  990. // Runs the scheduled basal to the end of the prediction line
  991. var predictionEndTime = dateTimeUtils.getNowTimeIntervalUTC() + (3600 * UserDefaultsRepository.predictionToLoad.value)
  992. basalScheduleData.removeAll()
  993. for i in 0..<basalSegments.count {
  994. let timeStart = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  995. // This processed everything after the first one.
  996. if firstPass == false
  997. && basalSegments[i].startDate <= predictionEndTime {
  998. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: basalSegments[i].startDate)
  999. basalScheduleData.append(startDot)
  1000. var endDate = basalSegments[i].endDate
  1001. // if it's the last one needed, set it to end at the prediction end time
  1002. if endDate > predictionEndTime || i == basalSegments.count - 1 {
  1003. endDate = Double(predictionEndTime)
  1004. }
  1005. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  1006. basalScheduleData.append(endDot)
  1007. }
  1008. // we need to manually set the first one
  1009. // Check that this is the first one and there are no existing entries
  1010. if firstPass == true {
  1011. // check that the timestamp is > the current entry and < the next entry
  1012. if timeStart >= basalSegments[i].startDate && timeStart < basalSegments[i].endDate {
  1013. // Set the start time to match the BG start
  1014. let startDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: Double(timeStart + (60 * 5)))
  1015. basalScheduleData.append(startDot)
  1016. // set the enddot where the next one will start
  1017. var endDate = basalSegments[i].endDate
  1018. let endDot = basalGraphStruct(basalRate: basalSegments[i].basalRate, date: endDate)
  1019. basalScheduleData.append(endDot)
  1020. firstPass = false
  1021. }
  1022. }
  1023. }
  1024. if UserDefaultsRepository.graphBasal.value {
  1025. updateBasalScheduledGraph()
  1026. }
  1027. }
  1028. // NS Treatments Web Call
  1029. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  1030. func WebLoadNSTreatments() {
  1031. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  1032. if !UserDefaultsRepository.downloadTreatments.value { return }
  1033. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1034. let startTimeString = dateTimeUtils.nowMinusNHoursTimeInterval(N: graphHours)
  1035. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + startTimeString
  1036. if token != "" {
  1037. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + startTimeString
  1038. }
  1039. guard let urlData = URL(string: urlString) else {
  1040. return
  1041. }
  1042. var request = URLRequest(url: urlData)
  1043. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  1044. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  1045. guard error == nil else {
  1046. return
  1047. }
  1048. guard let data = data else {
  1049. return
  1050. }
  1051. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  1052. if let json = json {
  1053. DispatchQueue.main.async {
  1054. self.updateTreatments(entries: json)
  1055. }
  1056. } else {
  1057. return
  1058. }
  1059. }
  1060. task.resume()
  1061. }
  1062. // Process and split out treatments to individual tasks
  1063. func updateTreatments(entries: [[String:AnyObject]]) {
  1064. var tempBasal: [[String:AnyObject]] = []
  1065. var bolus: [[String:AnyObject]] = []
  1066. var carbs: [[String:AnyObject]] = []
  1067. var temporaryOverride: [[String:AnyObject]] = []
  1068. var note: [[String:AnyObject]] = []
  1069. var bgCheck: [[String:AnyObject]] = []
  1070. var suspendPump: [[String:AnyObject]] = []
  1071. var resumePump: [[String:AnyObject]] = []
  1072. var pumpSiteChange: [[String:AnyObject]] = []
  1073. var cgmSensorStart: [[String:AnyObject]] = []
  1074. for i in 0..<entries.count {
  1075. let entry = entries[i] as [String : AnyObject]?
  1076. switch entry?["eventType"] as! String {
  1077. case "Temp Basal":
  1078. tempBasal.append(entry!)
  1079. case "Correction Bolus":
  1080. bolus.append(entry!)
  1081. case "Bolus":
  1082. bolus.append(entry!)
  1083. case "Meal Bolus":
  1084. carbs.append(entry!)
  1085. bolus.append(entry!)
  1086. case "Carb Correction":
  1087. carbs.append(entry!)
  1088. case "Temporary Override":
  1089. temporaryOverride.append(entry!)
  1090. case "Temporary Target":
  1091. temporaryOverride.append(entry!)
  1092. case "Note":
  1093. note.append(entry!)
  1094. print("Note: \(String(describing: entry))")
  1095. case "BG Check":
  1096. bgCheck.append(entry!)
  1097. case "Suspend Pump":
  1098. suspendPump.append(entry!)
  1099. case "Resume Pump":
  1100. resumePump.append(entry!)
  1101. case "Pump Site Change":
  1102. pumpSiteChange.append(entry!)
  1103. case "Sensor Start":
  1104. cgmSensorStart.append(entry!)
  1105. default:
  1106. print("No Match: \(String(describing: entry))")
  1107. }
  1108. }
  1109. // end of for loop
  1110. if tempBasal.count > 0 {
  1111. processNSBasals(entries: tempBasal)
  1112. } else {
  1113. if basalData.count < 0 {
  1114. clearOldTempBasal()
  1115. }
  1116. }
  1117. if bolus.count > 0 {
  1118. processNSBolus(entries: bolus)
  1119. } else {
  1120. if bolusData.count > 0 {
  1121. clearOldBolus()
  1122. }
  1123. }
  1124. if carbs.count > 0 {
  1125. processNSCarbs(entries: carbs)
  1126. } else {
  1127. if carbData.count > 0 {
  1128. clearOldCarb()
  1129. }
  1130. }
  1131. if bgCheck.count > 0 {
  1132. processNSBGCheck(entries: bgCheck)
  1133. } else {
  1134. if bgCheckData.count > 0 {
  1135. clearOldBGCheck()
  1136. }
  1137. }
  1138. if temporaryOverride.count > 0 {
  1139. processNSOverrides(entries: temporaryOverride)
  1140. } else {
  1141. if overrideGraphData.count > 0 {
  1142. clearOldOverride()
  1143. }
  1144. }
  1145. if suspendPump.count > 0 {
  1146. processSuspendPump(entries: suspendPump)
  1147. } else {
  1148. if suspendGraphData.count > 0 {
  1149. clearOldSuspend()
  1150. }
  1151. }
  1152. if resumePump.count > 0 {
  1153. processResumePump(entries: resumePump)
  1154. } else {
  1155. if resumeGraphData.count > 0 {
  1156. clearOldResume()
  1157. }
  1158. }
  1159. if cgmSensorStart.count > 0 {
  1160. processSensorStart(entries: cgmSensorStart)
  1161. } else {
  1162. if sensorStartGraphData.count > 0 {
  1163. clearOldSensor()
  1164. }
  1165. }
  1166. if note.count > 0 {
  1167. processNotes(entries: note)
  1168. } else {
  1169. if noteGraphData.count > 0 {
  1170. clearOldNotes()
  1171. }
  1172. }
  1173. }
  1174. func clearOldTempBasal()
  1175. {
  1176. basalData.removeAll()
  1177. updateBasalGraph()
  1178. }
  1179. func clearOldBolus()
  1180. {
  1181. bolusData.removeAll()
  1182. updateBolusGraph()
  1183. }
  1184. func clearOldCarb()
  1185. {
  1186. carbData.removeAll()
  1187. updateCarbGraph()
  1188. }
  1189. func clearOldBGCheck()
  1190. {
  1191. bgCheckData.removeAll()
  1192. updateBGCheckGraph()
  1193. }
  1194. func clearOldOverride()
  1195. {
  1196. overrideGraphData.removeAll()
  1197. updateOverrideGraph()
  1198. }
  1199. func clearOldSuspend()
  1200. {
  1201. suspendGraphData.removeAll()
  1202. updateSuspendGraph()
  1203. }
  1204. func clearOldResume()
  1205. {
  1206. resumeGraphData.removeAll()
  1207. updateResumeGraph()
  1208. }
  1209. func clearOldSensor()
  1210. {
  1211. sensorStartGraphData.removeAll()
  1212. updateSensorStart()
  1213. }
  1214. func clearOldNotes()
  1215. {
  1216. noteGraphData.removeAll()
  1217. updateNotes()
  1218. }
  1219. // NS Temp Basal Response Processor
  1220. func processNSBasals(entries: [[String:AnyObject]]) {
  1221. self.clearLastInfoData(index: 2)
  1222. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  1223. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  1224. basalData.removeAll()
  1225. var lastEndDot = 0.0
  1226. var tempArray = entries
  1227. tempArray.reverse()
  1228. for i in 0..<tempArray.count {
  1229. let currentEntry = tempArray[i] as [String : AnyObject]?
  1230. var basalDate: String
  1231. if currentEntry?["timestamp"] != nil {
  1232. basalDate = currentEntry?["timestamp"] as! String
  1233. } else if currentEntry?["created_at"] != nil {
  1234. basalDate = currentEntry?["created_at"] as! String
  1235. } else {
  1236. continue
  1237. }
  1238. var strippedZone = String(basalDate.dropLast())
  1239. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1240. let dateFormatter = DateFormatter()
  1241. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1242. dateFormatter.locale = Locale(identifier: "en_US")
  1243. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1244. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1245. let dateTimeStamp = dateString.timeIntervalSince1970
  1246. guard let basalRate = currentEntry?["absolute"] as? Double else {
  1247. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  1248. continue
  1249. }
  1250. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  1251. // Setting end dots
  1252. var duration = 0.0
  1253. do {
  1254. duration = try currentEntry?["duration"] as! Double
  1255. } catch {
  1256. print("No Duration Found")
  1257. }
  1258. // This adds scheduled basal wherever there is a break between temps. can't check the prior ending on the first item. it is 24 hours old, so it isn't important for display anyway
  1259. if i > 0 {
  1260. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  1261. var priorBasalDate: String
  1262. if priorEntry?["timestamp"] != nil {
  1263. priorBasalDate = priorEntry?["timestamp"] as! String
  1264. } else if currentEntry?["created_at"] != nil {
  1265. priorBasalDate = priorEntry?["created_at"] as! String
  1266. } else {
  1267. continue
  1268. }
  1269. var priorStrippedZone = String(priorBasalDate.dropLast())
  1270. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1271. let priorDateFormatter = DateFormatter()
  1272. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1273. priorDateFormatter.locale = Locale(identifier: "en_US")
  1274. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1275. guard let priorDateString = dateFormatter.date(from: priorStrippedZone) else { continue }
  1276. let priorDateTimeStamp = priorDateString.timeIntervalSince1970
  1277. let priorDuration = priorEntry?["duration"] as? Double ?? 0.0
  1278. // if difference between time stamps is greater than the duration of the last entry, there is a gap. Give a 15 second leeway on the timestamp
  1279. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  1280. var scheduled = 0.0
  1281. var midGap = false
  1282. var midGapTime: TimeInterval = 0
  1283. var midGapValue: Double = 0
  1284. // cycle through basal profiles.
  1285. // TODO figure out how to deal with profile changes that happen mid-gap
  1286. for b in 0..<self.basalScheduleData.count {
  1287. if (priorDateTimeStamp + (priorDuration * 60)) >= basalScheduleData[b].date {
  1288. scheduled = basalScheduleData[b].basalRate
  1289. // deal with mid-gap scheduled basal change
  1290. // don't do it on the last scheudled basal entry
  1291. if b < self.basalScheduleData.count - 1 {
  1292. if dateTimeStamp > self.basalScheduleData[b + 1].date {
  1293. // midGap = true
  1294. // TODO: finish this to handle mid-gap items without crashing from overlapping entries
  1295. midGapTime = self.basalScheduleData[b + 1].date
  1296. midGapValue = self.basalScheduleData[b + 1].basalRate
  1297. }
  1298. }
  1299. }
  1300. }
  1301. // Make the starting dot at the last ending dot
  1302. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  1303. basalData.append(startDot)
  1304. if midGap {
  1305. // Make the ending dot at the new scheduled basal
  1306. let endDot1 = basalGraphStruct(basalRate: scheduled, date: Double(midGapTime))
  1307. basalData.append(endDot1)
  1308. // Make the starting dot at the scheduled Time
  1309. let startDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(midGapTime))
  1310. basalData.append(startDot2)
  1311. // Make the ending dot at the new basal value
  1312. let endDot2 = basalGraphStruct(basalRate: midGapValue, date: Double(dateTimeStamp))
  1313. basalData.append(endDot2)
  1314. } else {
  1315. // Make the ending dot at the new starting dot
  1316. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  1317. basalData.append(endDot)
  1318. }
  1319. }
  1320. }
  1321. // Make the starting dot
  1322. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  1323. basalData.append(startDot)
  1324. // Make the ending dot
  1325. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  1326. // duration is already set to 0 if there is no duration set on it.
  1327. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  1328. if i == tempArray.count - 1 && duration == 0.0 {
  1329. lastEndDot = dateTimeStamp + (30 * 60)
  1330. latestBasal = String(format:"%.2f", basalRate)
  1331. } else {
  1332. lastEndDot = dateTimeStamp + (duration * 60)
  1333. latestBasal = String(format:"%.2f", basalRate)
  1334. }
  1335. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  1336. if i < tempArray.count - 1 {
  1337. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  1338. var nextBasalDate: String
  1339. if nextEntry?["timestamp"] != nil {
  1340. nextBasalDate = nextEntry?["timestamp"] as! String
  1341. } else if currentEntry?["created_at"] != nil {
  1342. nextBasalDate = nextEntry?["created_at"] as! String
  1343. } else {
  1344. continue
  1345. }
  1346. var nextStrippedZone = String(nextBasalDate.dropLast())
  1347. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  1348. let nextDateFormatter = DateFormatter()
  1349. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1350. nextDateFormatter.locale = Locale(identifier: "en_US")
  1351. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1352. guard let nextDateString = dateFormatter.date(from: nextStrippedZone) else { continue }
  1353. let nextDateTimeStamp = nextDateString.timeIntervalSince1970
  1354. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1355. lastEndDot = nextDateTimeStamp
  1356. }
  1357. }
  1358. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1359. basalData.append(endDot)
  1360. }
  1361. // If last basal was prior to right now, we need to create one last scheduled entry
  1362. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1363. var scheduled = 0.0
  1364. // cycle through basal profiles.
  1365. // TODO figure out how to deal with profile changes that happen mid-gap
  1366. for b in 0..<self.basalProfile.count {
  1367. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1368. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1369. // check the prior temp ending to the profile seconds from midnight
  1370. print("yesterday " + String(scheduleTimeYesterday))
  1371. print("today " + String(scheduleTimeToday))
  1372. if lastEndDot >= scheduleTimeToday {
  1373. scheduled = basalProfile[b].value
  1374. }
  1375. }
  1376. latestBasal = String(format:"%.2f", scheduled)
  1377. // Make the starting dot at the last ending dot
  1378. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1379. basalData.append(startDot)
  1380. // Make the ending dot 10 minutes after now
  1381. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1382. basalData.append(endDot)
  1383. }
  1384. tableData[2].value = latestBasal
  1385. infoTable.reloadData()
  1386. if UserDefaultsRepository.graphBasal.value {
  1387. updateBasalGraph()
  1388. }
  1389. infoTable.reloadData()
  1390. }
  1391. // NS Meal Bolus Response Processor
  1392. func processNSBolus(entries: [[String:AnyObject]]) {
  1393. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1394. // because it's a small array, we're going to destroy and reload every time.
  1395. bolusData.removeAll()
  1396. var lastFoundIndex = 0
  1397. for i in 0..<entries.count {
  1398. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1399. var bolusDate: String
  1400. if currentEntry?["timestamp"] != nil {
  1401. bolusDate = currentEntry?["timestamp"] as! String
  1402. } else if currentEntry?["created_at"] != nil {
  1403. bolusDate = currentEntry?["created_at"] as! String
  1404. } else {
  1405. continue
  1406. }
  1407. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1408. var strippedZone = String(bolusDate.dropLast())
  1409. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1410. let dateFormatter = DateFormatter()
  1411. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1412. dateFormatter.locale = Locale(identifier: "en_US")
  1413. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1414. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1415. let dateTimeStamp = dateString.timeIntervalSince1970
  1416. guard let bolus = currentEntry?["insulin"] as? Double else { continue }
  1417. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1418. lastFoundIndex = sgv.foundIndex
  1419. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1420. // Make the dot
  1421. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv + 20))
  1422. bolusData.append(dot)
  1423. }
  1424. }
  1425. if UserDefaultsRepository.graphBolus.value {
  1426. updateBolusGraph()
  1427. }
  1428. }
  1429. // NS Carb Bolus Response Processor
  1430. func processNSCarbs(entries: [[String:AnyObject]]) {
  1431. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1432. // because it's a small array, we're going to destroy and reload every time.
  1433. carbData.removeAll()
  1434. var lastFoundIndex = 0
  1435. var lastFoundBolus = 0
  1436. for i in 0..<entries.count {
  1437. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1438. var carbDate: String
  1439. if currentEntry?["timestamp"] != nil {
  1440. carbDate = currentEntry?["timestamp"] as! String
  1441. } else if currentEntry?["created_at"] != nil {
  1442. carbDate = currentEntry?["created_at"] as! String
  1443. } else {
  1444. continue
  1445. }
  1446. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1447. // Fix for FreeAPS milliseconds in timestamp
  1448. var strippedZone = String(carbDate.dropLast())
  1449. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1450. let dateFormatter = DateFormatter()
  1451. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1452. dateFormatter.locale = Locale(identifier: "en_US")
  1453. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1454. guard let dateString = dateFormatter.date(from: strippedZone) else { continue }
  1455. var dateTimeStamp = dateString.timeIntervalSince1970
  1456. guard let carbs = currentEntry?["carbs"] as? Double else {
  1457. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1458. continue
  1459. }
  1460. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1461. lastFoundIndex = sgv.foundIndex
  1462. var offset = -50
  1463. if sgv.sgv < Double(topBG - 100) {
  1464. let bolusTime = findNearestBolusbyTime(timeWithin: 300, needle: dateTimeStamp, haystack: bolusData, startingIndex: lastFoundBolus)
  1465. lastFoundBolus = bolusTime.foundIndex
  1466. if bolusTime.offset {
  1467. offset = 70
  1468. } else {
  1469. offset = 20
  1470. }
  1471. }
  1472. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1473. // Make the dot
  1474. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv + Double(offset)), absorptionTime: absorptionTime)
  1475. carbData.append(dot)
  1476. }
  1477. }
  1478. if UserDefaultsRepository.graphCarbs.value {
  1479. updateCarbGraph()
  1480. }
  1481. }
  1482. // NS Suspend Pump Response Processor
  1483. func processSuspendPump(entries: [[String:AnyObject]]) {
  1484. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Suspend Pump") }
  1485. // because it's a small array, we're going to destroy and reload every time.
  1486. suspendGraphData.removeAll()
  1487. var lastFoundIndex = 0
  1488. for i in 0..<entries.count {
  1489. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1490. var date: String
  1491. if currentEntry?["timestamp"] != nil {
  1492. date = currentEntry?["timestamp"] as! String
  1493. } else if currentEntry?["created_at"] != nil {
  1494. date = currentEntry?["created_at"] as! String
  1495. } else {
  1496. return
  1497. }
  1498. // Fix for FreeAPS milliseconds in timestamp
  1499. var strippedZone = String(date.dropLast())
  1500. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1501. let dateFormatter = DateFormatter()
  1502. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1503. dateFormatter.locale = Locale(identifier: "en_US")
  1504. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1505. let dateString = dateFormatter.date(from: strippedZone)
  1506. let dateTimeStamp = dateString!.timeIntervalSince1970
  1507. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1508. lastFoundIndex = sgv.foundIndex
  1509. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1510. // Make the dot
  1511. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1512. suspendGraphData.append(dot)
  1513. }
  1514. }
  1515. if UserDefaultsRepository.graphOtherTreatments.value {
  1516. updateSuspendGraph()
  1517. }
  1518. }
  1519. // NS Resume Pump Response Processor
  1520. func processResumePump(entries: [[String:AnyObject]]) {
  1521. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Resume Pump") }
  1522. // because it's a small array, we're going to destroy and reload every time.
  1523. resumeGraphData.removeAll()
  1524. var lastFoundIndex = 0
  1525. for i in 0..<entries.count {
  1526. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1527. var date: String
  1528. if currentEntry?["timestamp"] != nil {
  1529. date = currentEntry?["timestamp"] as! String
  1530. } else if currentEntry?["created_at"] != nil {
  1531. date = currentEntry?["created_at"] as! String
  1532. } else {
  1533. return
  1534. }
  1535. // Fix for FreeAPS milliseconds in timestamp
  1536. var strippedZone = String(date.dropLast())
  1537. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1538. let dateFormatter = DateFormatter()
  1539. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1540. dateFormatter.locale = Locale(identifier: "en_US")
  1541. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1542. let dateString = dateFormatter.date(from: strippedZone)
  1543. let dateTimeStamp = dateString!.timeIntervalSince1970
  1544. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1545. lastFoundIndex = sgv.foundIndex
  1546. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1547. // Make the dot
  1548. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1549. resumeGraphData.append(dot)
  1550. }
  1551. }
  1552. if UserDefaultsRepository.graphOtherTreatments.value {
  1553. updateResumeGraph()
  1554. }
  1555. }
  1556. // NS Sensor Start Response Processor
  1557. func processSensorStart(entries: [[String:AnyObject]]) {
  1558. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Sensor Start") }
  1559. // because it's a small array, we're going to destroy and reload every time.
  1560. sensorStartGraphData.removeAll()
  1561. var lastFoundIndex = 0
  1562. for i in 0..<entries.count {
  1563. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1564. var date: String
  1565. if currentEntry?["timestamp"] != nil {
  1566. date = currentEntry?["timestamp"] as! String
  1567. } else if currentEntry?["created_at"] != nil {
  1568. date = currentEntry?["created_at"] as! String
  1569. } else {
  1570. return
  1571. }
  1572. // Fix for FreeAPS milliseconds in timestamp
  1573. var strippedZone = String(date.dropLast())
  1574. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1575. let dateFormatter = DateFormatter()
  1576. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1577. dateFormatter.locale = Locale(identifier: "en_US")
  1578. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1579. let dateString = dateFormatter.date(from: strippedZone)
  1580. let dateTimeStamp = dateString!.timeIntervalSince1970
  1581. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1582. lastFoundIndex = sgv.foundIndex
  1583. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1584. // Make the dot
  1585. let dot = DataStructs.timestampOnlyStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1586. sensorStartGraphData.append(dot)
  1587. }
  1588. }
  1589. if UserDefaultsRepository.graphOtherTreatments.value {
  1590. updateSensorStart()
  1591. }
  1592. }
  1593. // NS Note Response Processor
  1594. func processNotes(entries: [[String:AnyObject]]) {
  1595. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Notes") }
  1596. // because it's a small array, we're going to destroy and reload every time.
  1597. noteGraphData.removeAll()
  1598. var lastFoundIndex = 0
  1599. for i in 0..<entries.count {
  1600. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1601. var date: String
  1602. if currentEntry?["timestamp"] != nil {
  1603. date = currentEntry?["timestamp"] as! String
  1604. } else if currentEntry?["created_at"] != nil {
  1605. date = currentEntry?["created_at"] as! String
  1606. } else {
  1607. return
  1608. }
  1609. // Fix for FreeAPS milliseconds in timestamp
  1610. var strippedZone = String(date.dropLast())
  1611. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1612. let dateFormatter = DateFormatter()
  1613. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1614. dateFormatter.locale = Locale(identifier: "en_US")
  1615. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1616. let dateString = dateFormatter.date(from: strippedZone)
  1617. let dateTimeStamp = dateString!.timeIntervalSince1970
  1618. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1619. lastFoundIndex = sgv.foundIndex
  1620. guard let thisNote = currentEntry?["notes"] as? String else { continue }
  1621. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1622. // Make the dot
  1623. let dot = DataStructs.noteStruct(date: Double(dateTimeStamp), sgv: Int(sgv.sgv), note: thisNote)
  1624. noteGraphData.append(dot)
  1625. }
  1626. }
  1627. if UserDefaultsRepository.graphOtherTreatments.value {
  1628. updateNotes()
  1629. }
  1630. }
  1631. // NS BG Check Response Processor
  1632. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1633. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1634. // because it's a small array, we're going to destroy and reload every time.
  1635. bgCheckData.removeAll()
  1636. for i in 0..<entries.count {
  1637. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1638. var date: String
  1639. if currentEntry?["timestamp"] != nil {
  1640. date = currentEntry?["timestamp"] as! String
  1641. } else if currentEntry?["created_at"] != nil {
  1642. date = currentEntry?["created_at"] as! String
  1643. } else {
  1644. return
  1645. }
  1646. // Fix for FreeAPS milliseconds in timestamp
  1647. var strippedZone = String(date.dropLast())
  1648. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1649. let dateFormatter = DateFormatter()
  1650. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1651. dateFormatter.locale = Locale(identifier: "en_US")
  1652. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1653. let dateString = dateFormatter.date(from: strippedZone)
  1654. let dateTimeStamp = dateString!.timeIntervalSince1970
  1655. guard let sgv = currentEntry?["glucose"] as? Int else {
  1656. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1657. continue
  1658. }
  1659. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1660. // Make the dot
  1661. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1662. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1663. bgCheckData.append(dot)
  1664. }
  1665. }
  1666. if UserDefaultsRepository.graphOtherTreatments.value {
  1667. updateBGCheckGraph()
  1668. }
  1669. }
  1670. // NS Override Response Processor
  1671. func processNSOverrides(entries: [[String:AnyObject]]) {
  1672. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1673. // because it's a small array, we're going to destroy and reload every time.
  1674. overrideGraphData.removeAll()
  1675. for i in 0..<entries.count {
  1676. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1677. var date: String
  1678. if currentEntry?["timestamp"] != nil {
  1679. date = currentEntry?["timestamp"] as! String
  1680. } else if currentEntry?["created_at"] != nil {
  1681. date = currentEntry?["created_at"] as! String
  1682. } else {
  1683. return
  1684. }
  1685. // Fix for FreeAPS milliseconds in timestamp
  1686. var strippedZone = String(date.dropLast())
  1687. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1688. let dateFormatter = DateFormatter()
  1689. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1690. dateFormatter.locale = Locale(identifier: "en_US")
  1691. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1692. let dateString = dateFormatter.date(from: strippedZone)
  1693. var dateTimeStamp = dateString!.timeIntervalSince1970
  1694. let graphHours = 24 * UserDefaultsRepository.downloadDays.value
  1695. if dateTimeStamp < dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours) {
  1696. dateTimeStamp = dateTimeUtils.getTimeIntervalNHoursAgo(N: graphHours)
  1697. }
  1698. var multiplier: Double = 1.0
  1699. if currentEntry?["insulinNeedsScaleFactor"] != nil {
  1700. multiplier = currentEntry?["insulinNeedsScaleFactor"] as! Double
  1701. }
  1702. var duration: Double = 5.0
  1703. if let durationType = currentEntry?["durationType"] as? String {
  1704. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1705. } else {
  1706. duration = (currentEntry?["duration"] as? Double)!
  1707. duration = duration * 60
  1708. }
  1709. // Skip overrides that aren't 5 minutes long. This prevents overlapping that causes bars to not display.
  1710. if duration < 300 { continue }
  1711. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1712. guard let reason = currentEntry?["reason"] as? String else { continue }
  1713. var range: [Int] = []
  1714. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1715. if ranges.count == 2 {
  1716. guard let low = ranges[0] as? Int else { continue }
  1717. guard let high = ranges[1] as? Int else { continue }
  1718. range.append(low)
  1719. range.append(high)
  1720. }
  1721. } else {
  1722. guard let low = currentEntry?["targetBottom"] as? Int else { continue }
  1723. guard let high = currentEntry?["targetTop"] as? Int else { continue }
  1724. range.append(low)
  1725. range.append(high)
  1726. }
  1727. let endDate = dateTimeStamp + (duration)
  1728. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multiplier, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1729. overrideGraphData.append(dot)
  1730. }
  1731. if UserDefaultsRepository.graphOtherTreatments.value {
  1732. updateOverrideGraph()
  1733. }
  1734. }
  1735. }