NightScout.swift 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. //
  12. // //NS BG Struct
  13. // struct sgvData: Codable {
  14. // var sgv: Int
  15. // var date: TimeInterval
  16. // var direction: String?
  17. // }
  18. //NS Cage Struct
  19. struct cageData: Codable {
  20. var created_at: String
  21. }
  22. //NS Basal Profile Struct
  23. struct basalProfileStruct: Codable {
  24. var value: Double
  25. var time: String
  26. var timeAsSeconds: Double
  27. }
  28. //NS Basal Data Struct
  29. struct basalGraphStruct: Codable {
  30. var basalRate: Double
  31. var date: TimeInterval
  32. }
  33. //NS Bolus Data Struct
  34. struct bolusCarbGraphStruct: Codable {
  35. var value: Double
  36. var date: TimeInterval
  37. var sgv: Int
  38. }
  39. // Main loader for all data
  40. func nightscoutLoader(forceLoad: Bool = false) {
  41. var needsLoaded: Bool = false
  42. var staleData: Bool = false
  43. var onlyPullLastRecord = false
  44. // If we have existing data and it's within 5 minutes, we aren't going to do a BG network call
  45. // if we have stale BG data 10 min or older, we're only going to attempt to pull BG and Loop status
  46. // to not have a full refresh every 15 seconds. The remaining data will start pulling again on the
  47. // next BG reading that comes in.
  48. if bgData.count > 0 {
  49. let now = NSDate().timeIntervalSince1970
  50. let lastReadingTime = bgData[bgData.count - 1].date
  51. let secondsAgo = now - lastReadingTime
  52. if secondsAgo >= 5*60 {
  53. needsLoaded = true
  54. if secondsAgo < 10*60 {
  55. onlyPullLastRecord = true
  56. } else {
  57. staleData = true
  58. }
  59. }
  60. } else {
  61. needsLoaded = true
  62. }
  63. if forceLoad { needsLoaded = true}
  64. // Only update if we don't have a current reading or forced to load
  65. if needsLoaded {
  66. self.clearLastInfoData()
  67. webLoadNSDeviceStatus()
  68. webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  69. if !staleData {
  70. webLoadNSProfile()
  71. if UserDefaultsRepository.downloadBasal.value {
  72. WebLoadNSTempBasals()
  73. }
  74. if UserDefaultsRepository.downloadBolus.value {
  75. webLoadNSBoluses()
  76. }
  77. if UserDefaultsRepository.downloadCarbs.value {
  78. webLoadNSCarbs()
  79. }
  80. webLoadNSCage()
  81. webLoadNSSage()
  82. }
  83. // Give the alarms and calendar 15 seconds delay to allow time for data to compile
  84. // if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Start view timer") }
  85. self.startViewTimer(time: viewTimeInterval)
  86. } else {
  87. // Things to do if we already have data and don't need a network call
  88. // Leaving all downloads off for right now.
  89. /*
  90. webLoadNSDeviceStatus()
  91. if UserDefaultsRepository.downloadBolus.value {
  92. webLoadNSBoluses()
  93. }
  94. if UserDefaultsRepository.downloadCarbs.value {
  95. webLoadNSCarbs()
  96. }*/
  97. if bgData.count > 0 {
  98. self.checkAlarms(bgs: bgData)
  99. }
  100. }
  101. }
  102. // NS BG Data Web call
  103. func webLoadNSBGData(onlyPullLastRecord: Bool = false) {
  104. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  105. // Set the count= in the url either to pull 24 hours or only the last record
  106. var points = "1"
  107. if !onlyPullLastRecord {
  108. points = String(self.graphHours * 12 + 1)
  109. }
  110. // URL processor
  111. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  112. if token == "" {
  113. urlBGDataPath = urlBGDataPath + "count=" + points
  114. } else {
  115. urlBGDataPath = urlBGDataPath + "token=" + token + "&count=" + points
  116. }
  117. guard let urlBGData = URL(string: urlBGDataPath) else {
  118. return
  119. }
  120. var request = URLRequest(url: urlBGData)
  121. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  122. // Downloader
  123. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  124. guard error == nil else {
  125. return
  126. }
  127. guard let data = data else {
  128. return
  129. }
  130. let decoder = JSONDecoder()
  131. let entriesResponse = try? decoder.decode([DataStructs.sgvData].self, from: data)
  132. if let entriesResponse = entriesResponse {
  133. DispatchQueue.main.async {
  134. // trigger the processor for the data after downloading.
  135. self.ProcessNSBGData(data: entriesResponse, onlyPullLastRecord: onlyPullLastRecord)
  136. }
  137. } else {
  138. return
  139. }
  140. }
  141. getBGTask.resume()
  142. }
  143. // NS BG Data Response processor
  144. func ProcessNSBGData(data: [DataStructs.sgvData], onlyPullLastRecord: Bool){
  145. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  146. var pullDate = data[data.count - 1].date / 1000
  147. pullDate.round(FloatingPointRoundingRule.toNearestOrEven)
  148. // 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
  149. if !onlyPullLastRecord {
  150. bgData.removeAll()
  151. } else if bgData[bgData.count - 1].date != pullDate {
  152. bgData.removeFirst()
  153. if data.count > 0 && UserDefaultsRepository.speakBG.value {
  154. speakBG(sgv: data[data.count - 1].sgv)
  155. }
  156. } else {
  157. if data.count > 0 {
  158. self.updateBadge(val: data[data.count - 1].sgv)
  159. }
  160. // self.viewUpdateNSBG()
  161. return
  162. }
  163. // loop through the data so we can reverse the order to oldest first for the graph and convert the NS timestamp to seconds instead of milliseconds. Makes date comparisons easier for everything else.
  164. for i in 0..<data.count{
  165. var dateString = data[data.count - 1 - i].date / 1000
  166. dateString.round(FloatingPointRoundingRule.toNearestOrEven)
  167. if dateString >= dateTimeUtils.getTimeInterval24HoursAgo() {
  168. let reading = DataStructs.sgvData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  169. bgData.append(reading)
  170. }
  171. }
  172. viewUpdateNSBG()
  173. }
  174. // NS BG Data Front end updater
  175. func viewUpdateNSBG () {
  176. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Display: BG") }
  177. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  178. let entries = bgData
  179. if entries.count > 0 {
  180. let latestEntryi = entries.count - 1
  181. let latestBG = entries[latestEntryi].sgv
  182. let priorBG = entries[latestEntryi - 1].sgv
  183. let deltaBG = latestBG - priorBG as Int
  184. let lastBGTime = entries[latestEntryi].date
  185. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  186. var userUnit = " mg/dL"
  187. if mmol {
  188. userUnit = " mmol/L"
  189. }
  190. BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  191. snoozer.BGLabel.text = bgUnits.toDisplayUnits(String(latestBG))
  192. setBGTextColor()
  193. if let directionBG = entries[latestEntryi].direction {
  194. DirectionText.text = bgDirectionGraphic(directionBG)
  195. snoozer.DirectionLabel.text = bgDirectionGraphic(directionBG)
  196. latestDirectionString = bgDirectionGraphic(directionBG)
  197. }
  198. else
  199. {
  200. DirectionText.text = ""
  201. snoozer.DirectionLabel.text = ""
  202. latestDirectionString = ""
  203. }
  204. if deltaBG < 0 {
  205. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  206. snoozer.DeltaLabel.text = bgUnits.toDisplayUnits(String(deltaBG))
  207. latestDeltaString = String(deltaBG)
  208. }
  209. else
  210. {
  211. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  212. snoozer.DeltaLabel.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  213. latestDeltaString = "+" + String(deltaBG)
  214. }
  215. self.updateBadge(val: latestBG)
  216. }
  217. else
  218. {
  219. return
  220. }
  221. updateBGGraph()
  222. updateMinAgo()
  223. updateStats()
  224. }
  225. // NS Device Status Web Call
  226. func webLoadNSDeviceStatus() {
  227. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  228. let urlUser = UserDefaultsRepository.url.value
  229. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=1"
  230. if token != "" {
  231. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?token=" + token + "&count=1"
  232. }
  233. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  234. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  235. return
  236. }
  237. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  238. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  239. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  240. guard error == nil else {
  241. return
  242. }
  243. guard let data = data else {
  244. return
  245. }
  246. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  247. if let json = json {
  248. DispatchQueue.main.async {
  249. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  250. }
  251. } else {
  252. return
  253. } }
  254. deviceStatusTask.resume()
  255. }
  256. // NS Device Status Response Processor
  257. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  258. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  259. if jsonDeviceStatus.count == 0 {
  260. return
  261. }
  262. //only grabbing one record since ns sorts by {created_at : -1}
  263. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  264. //pump and uploader
  265. let formatter = ISO8601DateFormatter()
  266. formatter.formatOptions = [.withFullDate,
  267. .withTime,
  268. .withDashSeparatorInDate,
  269. .withColonSeparatorInTime]
  270. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  271. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  272. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  273. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  274. } else {
  275. tableData[5].value = "50+U"
  276. }
  277. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  278. let upbat = uploader["battery"] as! Double
  279. tableData[4].value = String(format:"%.0f", upbat) + "%"
  280. }
  281. }
  282. }
  283. // Loop
  284. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  285. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  286. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  287. latestLoopTime = lastLoopTime
  288. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  289. if let failure = lastLoopRecord["failureReason"] {
  290. LoopStatusLabel.text = "X"
  291. latestLoopStatusString = "X"
  292. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  293. } else {
  294. var wasEnacted = false
  295. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  296. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  297. wasEnacted = true
  298. if let lastTempBasal = enacted["rate"] as? Double {
  299. // tableData[2].value = String(format:"%.1f", lastTempBasal)
  300. }
  301. }
  302. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  303. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  304. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  305. }
  306. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  307. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  308. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  309. }
  310. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  311. let prediction = predictdata["values"] as! [Double]
  312. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  313. PredictionLabel.textColor = UIColor.systemPurple
  314. predictionData.removeAll()
  315. if UserDefaultsRepository.downloadPrediction.value {
  316. var i = 1
  317. while i <= 12 {
  318. predictionData.append(prediction[i])
  319. i += 1
  320. }
  321. }
  322. }
  323. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  324. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  325. var lastBGTime = lastLoopTime
  326. if bgData.count > 0 {
  327. lastBGTime = bgData[bgData.count - 1].date
  328. }
  329. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  330. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  331. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  332. if tempBasalTime > lastBGTime && !wasEnacted {
  333. LoopStatusLabel.text = "⏀"
  334. latestLoopStatusString = "⏀"
  335. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  336. } else {
  337. LoopStatusLabel.text = "↻"
  338. latestLoopStatusString = "↻"
  339. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  340. }
  341. }
  342. } else {
  343. LoopStatusLabel.text = "↻"
  344. latestLoopStatusString = "↻"
  345. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  346. }
  347. }
  348. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  349. LoopStatusLabel.text = "⚠"
  350. latestLoopStatusString = "⚠"
  351. }
  352. } // end lastLoopTime
  353. } // end lastLoop Record
  354. var oText = "" as String
  355. currentOverride = 1.0
  356. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  357. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  358. }
  359. if lastOverride["active"] as! Bool {
  360. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  361. if let multiplier = lastOverride["multiplier"] as? Double {
  362. currentOverride = multiplier
  363. oText += String(format:"%.1f", multiplier*100)
  364. }
  365. else
  366. {
  367. oText += String(format:"%.1f", 100)
  368. }
  369. oText += "% ("
  370. let minValue = lastCorrection["minValue"] as! Double
  371. let maxValue = lastCorrection["maxValue"] as! Double
  372. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  373. tableData[3].value = oText
  374. }
  375. }
  376. infoTable.reloadData()
  377. }
  378. // NS Cage Web Call
  379. func webLoadNSCage() {
  380. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  381. let urlUser = UserDefaultsRepository.url.value
  382. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  383. if token != "" {
  384. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  385. }
  386. guard let urlData = URL(string: urlString) else {
  387. return
  388. }
  389. var request = URLRequest(url: urlData)
  390. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  391. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  392. guard error == nil else {
  393. return
  394. }
  395. guard let data = data else {
  396. return
  397. }
  398. let decoder = JSONDecoder()
  399. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  400. if let entriesResponse = entriesResponse {
  401. DispatchQueue.main.async {
  402. self.updateCage(data: entriesResponse)
  403. }
  404. } else {
  405. return
  406. }
  407. }
  408. task.resume()
  409. }
  410. // NS Cage Response Processor
  411. func updateCage(data: [cageData]) {
  412. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  413. if data.count == 0 {
  414. return
  415. }
  416. let lastCageString = data[0].created_at
  417. let formatter = ISO8601DateFormatter()
  418. formatter.formatOptions = [.withFullDate,
  419. .withTime,
  420. .withDashSeparatorInDate,
  421. .withColonSeparatorInTime]
  422. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  423. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  424. let now = NSDate().timeIntervalSince1970
  425. let secondsAgo = now - cageTime
  426. //let days = 24 * 60 * 60
  427. let formatter = DateComponentsFormatter()
  428. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  429. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  430. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  431. let formattedDuration = formatter.string(from: secondsAgo)
  432. tableData[7].value = formattedDuration ?? ""
  433. }
  434. infoTable.reloadData()
  435. }
  436. // NS Sage Web Call
  437. func webLoadNSSage() {
  438. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  439. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  440. let urlUser = UserDefaultsRepository.url.value
  441. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  442. if token != "" {
  443. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  444. }
  445. guard let urlData = URL(string: urlString) else {
  446. return
  447. }
  448. var request = URLRequest(url: urlData)
  449. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  450. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  451. guard error == nil else {
  452. return
  453. }
  454. guard let data = data else {
  455. return
  456. }
  457. let decoder = JSONDecoder()
  458. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  459. if let entriesResponse = entriesResponse {
  460. DispatchQueue.main.async {
  461. self.updateSage(data: entriesResponse)
  462. }
  463. } else {
  464. return
  465. }
  466. }
  467. task.resume()
  468. }
  469. // NS Sage Response Processor
  470. func updateSage(data: [cageData]) {
  471. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  472. if data.count == 0 {
  473. return
  474. }
  475. var lastSageString = data[0].created_at
  476. let formatter = ISO8601DateFormatter()
  477. formatter.formatOptions = [.withFullDate,
  478. .withTime,
  479. .withDashSeparatorInDate,
  480. .withColonSeparatorInTime]
  481. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  482. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  483. let now = NSDate().timeIntervalSince1970
  484. let secondsAgo = now - sageTime
  485. let days = 24 * 60 * 60
  486. let formatter = DateComponentsFormatter()
  487. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  488. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  489. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  490. let formattedDuration = formatter.string(from: secondsAgo)
  491. tableData[6].value = formattedDuration ?? ""
  492. }
  493. infoTable.reloadData()
  494. }
  495. // NS Profile Web Call
  496. func webLoadNSProfile() {
  497. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  498. let urlUser = UserDefaultsRepository.url.value
  499. var urlString = urlUser + "/api/v1/profile/current.json"
  500. if token != "" {
  501. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  502. }
  503. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  504. guard let url = URL(string: escapedAddress!) else {
  505. return
  506. }
  507. var request = URLRequest(url: url)
  508. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  509. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  510. guard error == nil else {
  511. return
  512. }
  513. guard let data = data else {
  514. return
  515. }
  516. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  517. if let json = json {
  518. DispatchQueue.main.async {
  519. self.updateProfile(jsonDeviceStatus: json)
  520. }
  521. } else {
  522. return
  523. }
  524. }
  525. task.resume()
  526. }
  527. // NS Profile Response Processor
  528. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  529. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  530. if jsonDeviceStatus.count == 0 {
  531. return
  532. }
  533. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  534. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  535. for i in 0..<basal.count {
  536. let dict = basal[i] as! Dictionary<String, Any>
  537. do {
  538. let thisValue = try dict[keyPath: "value"] as! Double
  539. let thisTime = dict[keyPath: "time"] as! String
  540. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  541. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  542. basalProfile.append(entry)
  543. } catch {
  544. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  545. }
  546. }
  547. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  548. if firstGraphLoad { return }
  549. // Make temporary array with all values of yesterday and today
  550. let yesterdayStart = dateTimeUtils.getTimeIntervalMidnightYesterday()
  551. let todayStart = dateTimeUtils.getTimeIntervalMidnightToday()
  552. basalScheduleData.removeAll()
  553. var basal2Day: [DataStructs.basal2DayProfile] = []
  554. // Run twice to add in order yesterday then today.
  555. for p in 0..<basalProfile.count {
  556. let start = yesterdayStart + basalProfile[p].timeAsSeconds
  557. var end = yesterdayStart
  558. // set the endings 1 second before the next one starts
  559. if p < basalProfile.count - 1 {
  560. end = yesterdayStart + basalProfile[p + 1].timeAsSeconds - 1
  561. } else {
  562. // set the end 1 second before midnight
  563. end = yesterdayStart + 86399
  564. }
  565. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  566. basal2Day.append(entry)
  567. }
  568. for p in 0..<basalProfile.count {
  569. let start = todayStart + basalProfile[p].timeAsSeconds
  570. var end = todayStart
  571. // set the endings 1 second before the next one starts
  572. if p < basalProfile.count - 1 {
  573. end = todayStart + basalProfile[p + 1].timeAsSeconds - 1
  574. } else {
  575. // set the end 1 second before midnight
  576. end = todayStart + 86399
  577. }
  578. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  579. basal2Day.append(entry)
  580. }
  581. let now = dateTimeUtils.nowMinus24HoursTimeInterval()
  582. for i in 0..<basal2Day.count {
  583. var timeYesterday = dateTimeUtils.getTimeInterval24HoursAgo()
  584. // we need to manually set the first one
  585. // Check that this is the first one and there are no existing entries
  586. if basalScheduleData.count == 0 {
  587. // check that the timestamp is > the current entry and < the next entry
  588. if timeYesterday >= basal2Day[i].startDate && timeYesterday < basal2Day[i].endDate {
  589. // Set the start time to match the BG start
  590. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: Double(dateTimeUtils.getNowTimeIntervalUTC() + (60 * 10)))
  591. basalScheduleData.append(startDot)
  592. // set the enddot where the next one will start
  593. var endDate = basal2Day[i].endDate
  594. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  595. basalScheduleData.append(endDot)
  596. }
  597. }
  598. // process the rest after the first line segment of 2 dots
  599. // check if it's > 24 hours ago an <= 30 minutes from now.
  600. if basalScheduleData.count > 1
  601. && basal2Day[i].startDate < dateTimeUtils.getNowTimeIntervalUTC() + ( 60 * 30 ) {
  602. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: basal2Day[i].startDate)
  603. basalScheduleData.append(startDot)
  604. var endDate = basal2Day[i].endDate
  605. // if it's the last one in the profile or date is greater than now, set it to the last BG dot
  606. if i == basal2Day.count - 1 || endDate > dateTimeUtils.getNowTimeIntervalUTC() {
  607. endDate = Double(dateTimeUtils.getNowTimeIntervalUTC())
  608. }
  609. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  610. basalScheduleData.append(endDot)
  611. }
  612. }
  613. if UserDefaultsRepository.graphBasal.value {
  614. updateBasalScheduledGraph()
  615. }
  616. }
  617. // NS Temp Basal Web Call
  618. func WebLoadNSTempBasals() {
  619. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Basal") }
  620. if !UserDefaultsRepository.downloadBasal.value { return }
  621. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  622. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  623. if token != "" {
  624. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[eventType][$eq]=Temp%20Basal&find[created_at][$gte]=" + yesterdayString
  625. }
  626. guard let urlData = URL(string: urlString) else {
  627. return
  628. }
  629. var request = URLRequest(url: urlData)
  630. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  631. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  632. guard error == nil else {
  633. return
  634. }
  635. guard let data = data else {
  636. return
  637. }
  638. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  639. if let json = json {
  640. DispatchQueue.main.async {
  641. self.updateBasals(entries: json)
  642. }
  643. } else {
  644. return
  645. }
  646. }
  647. task.resume()
  648. }
  649. // NS Temp Basal Response Processor
  650. func updateBasals(entries: [[String:AnyObject]]) {
  651. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  652. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  653. basalData.removeAll()
  654. var lastEndDot = 0.0
  655. var tempArray = entries
  656. tempArray.reverse()
  657. for i in 0..<tempArray.count {
  658. let currentEntry = tempArray[i] as [String : AnyObject]?
  659. var basalDate: String
  660. if currentEntry?["timestamp"] != nil {
  661. basalDate = currentEntry?["timestamp"] as! String
  662. } else if currentEntry?["created_at"] != nil {
  663. basalDate = currentEntry?["created_at"] as! String
  664. } else {
  665. return
  666. }
  667. let strippedZone = String(basalDate.dropLast())
  668. let dateFormatter = DateFormatter()
  669. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  670. dateFormatter.locale = Locale(identifier: "en_US")
  671. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  672. let dateString = dateFormatter.date(from: strippedZone)
  673. let dateTimeStamp = dateString!.timeIntervalSince1970
  674. let basalRate = currentEntry?["absolute"] as! Double
  675. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  676. // Setting end dots
  677. var duration = 0.0
  678. do {
  679. duration = try currentEntry?["duration"] as! Double
  680. } catch {
  681. print("No Duration Found")
  682. }
  683. // 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
  684. if i > 0 {
  685. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  686. let priorBasalDate = priorEntry?["timestamp"] as! String
  687. let priorStrippedZone = String(priorBasalDate.dropLast())
  688. let priorDateFormatter = DateFormatter()
  689. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  690. priorDateFormatter.locale = Locale(identifier: "en_US")
  691. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  692. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  693. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  694. let priorDuration = priorEntry?["duration"] as! Double
  695. // 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
  696. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  697. var scheduled = 0.0
  698. // cycle through basal profiles.
  699. // TODO figure out how to deal with profile changes that happen mid-gap
  700. for b in 0..<self.basalProfile.count {
  701. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  702. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  703. // check the prior temp ending to the profile seconds from midnight
  704. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  705. scheduled = basalProfile[b].value
  706. }
  707. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  708. scheduled = basalProfile[b].value
  709. }
  710. // This will iterate through from midnight on and set it for the highest matching one.
  711. }
  712. // Make the starting dot at the last ending dot
  713. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  714. basalData.append(startDot)
  715. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  716. // Make the ending dot at the new starting dot
  717. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  718. basalData.append(endDot)
  719. }
  720. }
  721. // Make the starting dot
  722. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  723. basalData.append(startDot)
  724. // Make the ending dot
  725. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  726. // duration is already set to 0 if there is no duration set on it.
  727. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  728. if i == tempArray.count - 1 && duration == 0.0 {
  729. lastEndDot = dateTimeStamp + (30 * 60)
  730. latestBasal = String(format:"%.2f", basalRate)
  731. } else {
  732. lastEndDot = dateTimeStamp + (duration * 60)
  733. latestBasal = String(format:"%.2f", basalRate)
  734. }
  735. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  736. if i < tempArray.count - 1 {
  737. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  738. let nextBasalDate = nextEntry?["timestamp"] as! String
  739. let nextStrippedZone = String(nextBasalDate.dropLast())
  740. let nextDateFormatter = DateFormatter()
  741. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  742. nextDateFormatter.locale = Locale(identifier: "en_US")
  743. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  744. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  745. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  746. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  747. lastEndDot = nextDateTimeStamp
  748. }
  749. }
  750. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  751. basalData.append(endDot)
  752. }
  753. // If last basal was prior to right now, we need to create one last scheduled entry
  754. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  755. var scheduled = 0.0
  756. // cycle through basal profiles.
  757. // TODO figure out how to deal with profile changes that happen mid-gap
  758. for b in 0..<self.basalProfile.count {
  759. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  760. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  761. // check the prior temp ending to the profile seconds from midnight
  762. print("yesterday " + String(scheduleTimeYesterday))
  763. print("today " + String(scheduleTimeToday))
  764. if lastEndDot >= scheduleTimeToday {
  765. scheduled = basalProfile[b].value
  766. }
  767. }
  768. latestBasal = String(format:"%.2f", scheduled)
  769. // Make the starting dot at the last ending dot
  770. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  771. basalData.append(startDot)
  772. // Make the ending dot 10 minutes after now
  773. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  774. basalData.append(endDot)
  775. }
  776. tableData[2].value = latestBasal
  777. if UserDefaultsRepository.graphBasal.value {
  778. updateBasalGraph()
  779. }
  780. }
  781. // NS Bolus Web Call
  782. func webLoadNSBoluses(){
  783. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Bolus") }
  784. if !UserDefaultsRepository.downloadBolus.value { return }
  785. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  786. let urlUser = UserDefaultsRepository.url.value
  787. var searchString = "find[eventType]=Correction%20Bolus&find[created_at][$gte]=" + yesterdayString
  788. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  789. if token == "" {
  790. urlDataPath = urlDataPath + searchString
  791. }
  792. else
  793. {
  794. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  795. }
  796. guard let urlData = URL(string: urlDataPath) else {
  797. return
  798. }
  799. var request = URLRequest(url: urlData)
  800. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  801. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  802. guard error == nil else {
  803. return
  804. }
  805. guard let data = data else {
  806. return
  807. }
  808. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  809. if let json = json {
  810. DispatchQueue.main.async {
  811. self.processNSBolus(entries: json)
  812. }
  813. } else {
  814. return
  815. }
  816. }
  817. task.resume()
  818. }
  819. // NS Meal Bolus Response Processor
  820. func processNSBolus(entries: [[String:AnyObject]]) {
  821. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  822. // because it's a small array, we're going to destroy and reload every time.
  823. bolusData.removeAll()
  824. var lastFoundIndex = 0
  825. for i in 0..<entries.count {
  826. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  827. var bolusDate: String
  828. if currentEntry?["timestamp"] != nil {
  829. bolusDate = currentEntry?["timestamp"] as! String
  830. } else if currentEntry?["created_at"] != nil {
  831. bolusDate = currentEntry?["created_at"] as! String
  832. } else {
  833. return
  834. }
  835. let strippedZone = String(bolusDate.dropLast())
  836. let dateFormatter = DateFormatter()
  837. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  838. dateFormatter.locale = Locale(identifier: "en_US")
  839. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  840. let dateString = dateFormatter.date(from: strippedZone)
  841. let dateTimeStamp = dateString!.timeIntervalSince1970
  842. do {
  843. let bolus = try currentEntry?["insulin"] as! Double
  844. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  845. lastFoundIndex = sgv.foundIndex
  846. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  847. // Make the dot
  848. let dot = bolusCarbGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  849. bolusData.append(dot)
  850. }
  851. } catch {
  852. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  853. }
  854. }
  855. if UserDefaultsRepository.graphBolus.value {
  856. updateBolusGraph()
  857. }
  858. }
  859. // NS Carb Web Call
  860. func webLoadNSCarbs(){
  861. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Carbs") }
  862. if !UserDefaultsRepository.downloadCarbs.value { return }
  863. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  864. let urlUser = UserDefaultsRepository.url.value
  865. var searchString = "find[eventType]=Meal%20Bolus&find[created_at][$gte]=" + yesterdayString
  866. var urlDataPath: String = urlUser + "/api/v1/treatments.json?"
  867. if token == "" {
  868. urlDataPath = urlDataPath + searchString
  869. }
  870. else
  871. {
  872. urlDataPath = urlDataPath + "token=" + token + "&" + searchString
  873. }
  874. guard let urlData = URL(string: urlDataPath) else {
  875. return
  876. }
  877. var request = URLRequest(url: urlData)
  878. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  879. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  880. guard error == nil else {
  881. return
  882. }
  883. guard let data = data else {
  884. return
  885. }
  886. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  887. if let json = json {
  888. DispatchQueue.main.async {
  889. self.processNSCarbs(entries: json)
  890. }
  891. } else {
  892. return
  893. }
  894. }
  895. task.resume()
  896. }
  897. // NS Carb Bolus Response Processor
  898. func processNSCarbs(entries: [[String:AnyObject]]) {
  899. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  900. // because it's a small array, we're going to destroy and reload every time.
  901. carbData.removeAll()
  902. var lastFoundIndex = 0
  903. for i in 0..<entries.count {
  904. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  905. var carbDate: String
  906. if currentEntry?["timestamp"] != nil {
  907. carbDate = currentEntry?["timestamp"] as! String
  908. } else if currentEntry?["created_at"] != nil {
  909. carbDate = currentEntry?["created_at"] as! String
  910. } else {
  911. return
  912. }
  913. let strippedZone = String(carbDate.dropLast())
  914. let dateFormatter = DateFormatter()
  915. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  916. dateFormatter.locale = Locale(identifier: "en_US")
  917. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  918. let dateString = dateFormatter.date(from: strippedZone)
  919. let dateTimeStamp = dateString!.timeIntervalSince1970
  920. do {
  921. let carbs = try currentEntry?["carbs"] as! Double
  922. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  923. lastFoundIndex = sgv.foundIndex
  924. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  925. // Make the dot
  926. let dot = bolusCarbGraphStruct(value: carbs, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  927. carbData.append(dot)
  928. }
  929. } catch {
  930. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry") }
  931. }
  932. }
  933. if UserDefaultsRepository.graphCarbs.value {
  934. updateCarbGraph()
  935. }
  936. }
  937. }