NightScout.swift 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  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 Cage Struct
  12. struct cageData: Codable {
  13. var created_at: String
  14. }
  15. //NS Basal Profile Struct
  16. struct basalProfileStruct: Codable {
  17. var value: Double
  18. var time: String
  19. var timeAsSeconds: Double
  20. }
  21. //NS Basal Data Struct
  22. struct basalGraphStruct: Codable {
  23. var basalRate: Double
  24. var date: TimeInterval
  25. }
  26. //NS Bolus Data Struct
  27. struct bolusGraphStruct: Codable {
  28. var value: Double
  29. var date: TimeInterval
  30. var sgv: Int
  31. }
  32. //NS Bolus Data Struct
  33. struct carbGraphStruct: Codable {
  34. var value: Double
  35. var date: TimeInterval
  36. var sgv: Int
  37. var absorptionTime: Int
  38. }
  39. func isStaleData() -> Bool {
  40. if bgData.count > 0 {
  41. let now = dateTimeUtils.getNowTimeIntervalUTC()
  42. let lastReadingTime = bgData.last!.date
  43. let secondsAgo = now - lastReadingTime
  44. if secondsAgo >= 20*60 {
  45. return true
  46. } else {
  47. return false
  48. }
  49. } else {
  50. return false
  51. }
  52. }
  53. // Dex Share Web Call
  54. func webLoadDexShare(onlyPullLastRecord: Bool = false) {
  55. var count = 288
  56. if onlyPullLastRecord { count = 1 }
  57. dexShare?.fetchData(count) { (err, result) -> () in
  58. // TODO: add error checking
  59. if(err == nil) {
  60. var data = result!
  61. self.ProcessNSBGData(data: data, onlyPullLastRecord: onlyPullLastRecord)
  62. } else {
  63. // If we get an error, immediately try to pull NS BG Data
  64. self.webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  65. if globalVariables.dexVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  66. globalVariables.dexVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  67. DispatchQueue.main.async {
  68. //self.sendNotification(title: "Dexcom Share Error", body: "Please double check user name and password, internet connection, and sharing status.")
  69. }
  70. }
  71. }
  72. }
  73. }
  74. // NS BG Data Web call
  75. func webLoadNSBGData(onlyPullLastRecord: Bool = false) {
  76. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: BG") }
  77. // Set the count= in the url either to pull 24 hours or only the last record
  78. var points = "1"
  79. if !onlyPullLastRecord {
  80. points = String(self.graphHours * 12 + 1)
  81. }
  82. // URL processor
  83. var urlBGDataPath: String = UserDefaultsRepository.url.value + "/api/v1/entries/sgv.json?"
  84. if token == "" {
  85. urlBGDataPath = urlBGDataPath + "count=" + points
  86. } else {
  87. urlBGDataPath = urlBGDataPath + "token=" + token + "&count=" + points
  88. }
  89. guard let urlBGData = URL(string: urlBGDataPath) else {
  90. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  91. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  92. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  93. }
  94. DispatchQueue.main.async {
  95. if self.bgTimer.isValid {
  96. self.bgTimer.invalidate()
  97. }
  98. self.startBGTimer(time: 10)
  99. }
  100. return
  101. }
  102. var request = URLRequest(url: urlBGData)
  103. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  104. // Downloader
  105. let getBGTask = URLSession.shared.dataTask(with: request) { data, response, error in
  106. guard error == nil else {
  107. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  108. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  109. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  110. }
  111. DispatchQueue.main.async {
  112. if self.bgTimer.isValid {
  113. self.bgTimer.invalidate()
  114. }
  115. self.startBGTimer(time: 10)
  116. }
  117. return
  118. }
  119. guard let data = data else {
  120. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  121. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  122. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  123. }
  124. DispatchQueue.main.async {
  125. if self.bgTimer.isValid {
  126. self.bgTimer.invalidate()
  127. }
  128. self.startBGTimer(time: 10)
  129. }
  130. return
  131. }
  132. let decoder = JSONDecoder()
  133. let entriesResponse = try? decoder.decode([ShareGlucoseData].self, from: data)
  134. if let entriesResponse = entriesResponse {
  135. DispatchQueue.main.async {
  136. // trigger the processor for the data after downloading.
  137. self.ProcessNSBGData(data: entriesResponse, onlyPullLastRecord: onlyPullLastRecord, isNS: true)
  138. }
  139. } else {
  140. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  141. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  142. //self.sendNotification(title: "Nightscout Failure", 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. return
  151. }
  152. }
  153. getBGTask.resume()
  154. }
  155. // NS BG Data Response processor
  156. func ProcessNSBGData(data: [ShareGlucoseData], onlyPullLastRecord: Bool, isNS: Bool = false){
  157. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG") }
  158. var pullDate = data[data.count - 1].date
  159. if isNS {
  160. pullDate = data[data.count - 1].date / 1000
  161. pullDate.round(FloatingPointRoundingRule.toNearestOrEven)
  162. }
  163. var latestDate = data[0].date
  164. if isNS {
  165. latestDate = data[0].date / 1000
  166. latestDate.round(FloatingPointRoundingRule.toNearestOrEven)
  167. }
  168. let now = dateTimeUtils.getNowTimeIntervalUTC()
  169. if !isNS && (latestDate + 330) < now {
  170. webLoadNSBGData(onlyPullLastRecord: onlyPullLastRecord)
  171. print("dex didn't load, triggered NS attempt")
  172. return
  173. }
  174. // Start the BG timer based on the reading
  175. let secondsAgo = now - latestDate
  176. DispatchQueue.main.async {
  177. // if reading is overdue over: 20:00, re-attempt every 5 minutes
  178. if secondsAgo >= (20 * 60) {
  179. self.startBGTimer(time: (5 * 60))
  180. print("##### started 5 minute bg timer")
  181. self.sendNotification(title: "BG Timer", body: "5 Minutes")
  182. // if the reading is overdue: 10:00-19:59, re-attempt every minute
  183. } else if secondsAgo >= (10 * 60) {
  184. self.startBGTimer(time: 60)
  185. print("##### started 1 minute bg timer")
  186. self.sendNotification(title: "BG Timer", body: "1 Minute")
  187. // if the reading is overdue: 7:00-9:59, re-attempt every 30 seconds
  188. } else if secondsAgo >= (7 * 60) {
  189. self.startBGTimer(time: 30)
  190. print("##### started 30 second bg timer")
  191. self.sendNotification(title: "BG Timer", body: "30 Seconds")
  192. // if the reading is overdue: 5:00-6:59 re-attempt every 10 seconds
  193. } else if secondsAgo >= (5 * 60) {
  194. self.startBGTimer(time: 10)
  195. print("##### started 10 second bg timer")
  196. self.sendNotification(title: "BG Timer", body: "10 Seconds")
  197. // We have a current reading. Set timer to 5:10 from last reading
  198. } else {
  199. self.startBGTimer(time: 310 - secondsAgo)
  200. let timerVal = 310 - secondsAgo
  201. print("##### started 5:10 bg timer: \(timerVal)")
  202. }
  203. }
  204. // 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
  205. if !onlyPullLastRecord {
  206. bgData.removeAll()
  207. } else if bgData[bgData.count - 1].date != pullDate {
  208. bgData.removeFirst()
  209. if data.count > 0 && UserDefaultsRepository.speakBG.value {
  210. speakBG(sgv: data[data.count - 1].sgv)
  211. }
  212. } else {
  213. if data.count > 0 {
  214. self.updateBadge(val: data[data.count - 1].sgv)
  215. }
  216. return
  217. }
  218. // 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.
  219. for i in 0..<data.count{
  220. var dateString = data[data.count - 1 - i].date
  221. if isNS {
  222. dateString = data[data.count - 1 - i].date / 1000
  223. dateString.round(FloatingPointRoundingRule.toNearestOrEven)
  224. }
  225. if dateString >= dateTimeUtils.getTimeInterval24HoursAgo() {
  226. let reading = ShareGlucoseData(sgv: data[data.count - 1 - i].sgv, date: dateString, direction: data[data.count - 1 - i].direction)
  227. bgData.append(reading)
  228. }
  229. }
  230. viewUpdateNSBG(isNS: isNS)
  231. }
  232. // NS BG Data Front end updater
  233. func viewUpdateNSBG (isNS: Bool) {
  234. DispatchQueue.main.async {
  235. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Display: BG") }
  236. guard let snoozer = self.tabBarController!.viewControllers?[2] as? SnoozeViewController else { return }
  237. let entries = self.bgData
  238. if entries.count > 0 {
  239. let latestEntryi = entries.count - 1
  240. let latestBG = entries[latestEntryi].sgv
  241. let priorBG = entries[latestEntryi - 1].sgv
  242. let deltaBG = latestBG - priorBG as Int
  243. let lastBGTime = entries[latestEntryi].date
  244. let deltaTime = (TimeInterval(Date().timeIntervalSince1970)-lastBGTime) / 60
  245. var userUnit = " mg/dL"
  246. if self.mmol {
  247. userUnit = " mmol/L"
  248. }
  249. // TODO: remove testing feature to color code arrow based on NS vs Dex
  250. if isNS {
  251. self.serverText.text = "Nightscout"
  252. } else {
  253. self.serverText.text = "Dexcom"
  254. }
  255. self.BGText.text = bgUnits.toDisplayUnits(String(latestBG))
  256. snoozer.BGLabel.text = bgUnits.toDisplayUnits(String(latestBG))
  257. self.setBGTextColor()
  258. if let directionBG = entries[latestEntryi].direction {
  259. self.DirectionText.text = self.bgDirectionGraphic(directionBG)
  260. snoozer.DirectionLabel.text = self.bgDirectionGraphic(directionBG)
  261. self.latestDirectionString = self.bgDirectionGraphic(directionBG)
  262. }
  263. else
  264. {
  265. self.DirectionText.text = ""
  266. snoozer.DirectionLabel.text = ""
  267. self.latestDirectionString = ""
  268. }
  269. if deltaBG < 0 {
  270. self.DeltaText.text = bgUnits.toDisplayUnits(String(deltaBG))
  271. snoozer.DeltaLabel.text = bgUnits.toDisplayUnits(String(deltaBG))
  272. self.latestDeltaString = String(deltaBG)
  273. }
  274. else
  275. {
  276. self.DeltaText.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  277. snoozer.DeltaLabel.text = "+" + bgUnits.toDisplayUnits(String(deltaBG))
  278. self.latestDeltaString = "+" + String(deltaBG)
  279. }
  280. self.updateBadge(val: latestBG)
  281. }
  282. else
  283. {
  284. return
  285. }
  286. self.updateBGGraph()
  287. self.updateStats()
  288. }
  289. }
  290. // NS Device Status Web Call
  291. func webLoadNSDeviceStatus() {
  292. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: device status") }
  293. let urlUser = UserDefaultsRepository.url.value
  294. // NS Api is not working to find by greater than date
  295. var urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288"
  296. if token != "" {
  297. urlStringDeviceStatus = urlUser + "/api/v1/devicestatus.json?count=288&token=" + token
  298. }
  299. let escapedAddress = urlStringDeviceStatus.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  300. guard let urlDeviceStatus = URL(string: escapedAddress!) else {
  301. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  302. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  303. //self.sendNotification(title: "Nightscout Failure", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  304. }
  305. DispatchQueue.main.async {
  306. if self.deviceStatusTimer.isValid {
  307. self.deviceStatusTimer.invalidate()
  308. }
  309. self.startDeviceStatusTimer(time: 10)
  310. }
  311. return
  312. }
  313. var requestDeviceStatus = URLRequest(url: urlDeviceStatus)
  314. requestDeviceStatus.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  315. let deviceStatusTask = URLSession.shared.dataTask(with: requestDeviceStatus) { data, response, error in
  316. guard error == nil else {
  317. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  318. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  319. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  320. }
  321. DispatchQueue.main.async {
  322. if self.deviceStatusTimer.isValid {
  323. self.deviceStatusTimer.invalidate()
  324. }
  325. self.startDeviceStatusTimer(time: 10)
  326. }
  327. return
  328. }
  329. guard let data = data else {
  330. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  331. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  332. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  333. }
  334. DispatchQueue.main.async {
  335. if self.deviceStatusTimer.isValid {
  336. self.deviceStatusTimer.invalidate()
  337. }
  338. self.startDeviceStatusTimer(time: 10)
  339. }
  340. return
  341. }
  342. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  343. if let json = json {
  344. DispatchQueue.main.async {
  345. self.updateDeviceStatusDisplay(jsonDeviceStatus: json)
  346. }
  347. } else {
  348. if globalVariables.nsVerifiedAlert < dateTimeUtils.getNowTimeIntervalUTC() + 300 {
  349. globalVariables.nsVerifiedAlert = dateTimeUtils.getNowTimeIntervalUTC()
  350. //self.sendNotification(title: "Nightscout Error", body: "Please double check url, token, and internet connection. This may also indicate a temporary Nightscout issue")
  351. }
  352. DispatchQueue.main.async {
  353. if self.deviceStatusTimer.isValid {
  354. self.deviceStatusTimer.invalidate()
  355. }
  356. self.startDeviceStatusTimer(time: 10)
  357. }
  358. return
  359. }
  360. }
  361. deviceStatusTask.resume()
  362. }
  363. // NS Device Status Response Processor
  364. func updateDeviceStatusDisplay(jsonDeviceStatus: [[String:AnyObject]]) {
  365. self.clearLastInfoData(index: 0)
  366. self.clearLastInfoData(index: 1)
  367. self.clearLastInfoData(index: 3)
  368. self.clearLastInfoData(index: 4)
  369. self.clearLastInfoData(index: 5)
  370. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: device status") }
  371. if jsonDeviceStatus.count == 0 {
  372. return
  373. }
  374. //Process the current data first
  375. let lastDeviceStatus = jsonDeviceStatus[0] as [String : AnyObject]?
  376. //pump and uploader
  377. let formatter = ISO8601DateFormatter()
  378. formatter.formatOptions = [.withFullDate,
  379. .withTime,
  380. .withDashSeparatorInDate,
  381. .withColonSeparatorInTime]
  382. if let lastPumpRecord = lastDeviceStatus?["pump"] as! [String : AnyObject]? {
  383. if let lastPumpTime = formatter.date(from: (lastPumpRecord["clock"] as! String))?.timeIntervalSince1970 {
  384. if let reservoirData = lastPumpRecord["reservoir"] as? Double {
  385. tableData[5].value = String(format:"%.0f", reservoirData) + "U"
  386. } else {
  387. tableData[5].value = "50+U"
  388. }
  389. if let uploader = lastDeviceStatus?["uploader"] as? [String:AnyObject] {
  390. let upbat = uploader["battery"] as! Double
  391. tableData[4].value = String(format:"%.0f", upbat) + "%"
  392. }
  393. }
  394. }
  395. // Loop
  396. if let lastLoopRecord = lastDeviceStatus?["loop"] as! [String : AnyObject]? {
  397. //print("Loop: \(lastLoopRecord)")
  398. if let lastLoopTime = formatter.date(from: (lastLoopRecord["timestamp"] as! String))?.timeIntervalSince1970 {
  399. UserDefaultsRepository.alertLastLoopTime.value = lastLoopTime
  400. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastLoopTime: " + String(lastLoopTime)) }
  401. if let failure = lastLoopRecord["failureReason"] {
  402. LoopStatusLabel.text = "X"
  403. latestLoopStatusString = "X"
  404. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop Failure: X") }
  405. } else {
  406. var wasEnacted = false
  407. if let enacted = lastLoopRecord["enacted"] as? [String:AnyObject] {
  408. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Loop: Was Enacted") }
  409. wasEnacted = true
  410. if let lastTempBasal = enacted["rate"] as? Double {
  411. }
  412. }
  413. if let iobdata = lastLoopRecord["iob"] as? [String:AnyObject] {
  414. tableData[0].value = String(format:"%.2f", (iobdata["iob"] as! Double))
  415. latestIOB = String(format:"%.2f", (iobdata["iob"] as! Double))
  416. }
  417. if let cobdata = lastLoopRecord["cob"] as? [String:AnyObject] {
  418. tableData[1].value = String(format:"%.0f", cobdata["cob"] as! Double)
  419. latestCOB = String(format:"%.0f", cobdata["cob"] as! Double)
  420. }
  421. if let predictdata = lastLoopRecord["predicted"] as? [String:AnyObject] {
  422. let prediction = predictdata["values"] as! [Int]
  423. PredictionLabel.text = bgUnits.toDisplayUnits(String(Int(prediction.last!)))
  424. PredictionLabel.textColor = UIColor.systemPurple
  425. if UserDefaultsRepository.downloadPrediction.value && latestLoopTime < lastLoopTime {
  426. predictionData.removeAll()
  427. var predictionTime = lastLoopTime
  428. let toLoad = Int(UserDefaultsRepository.predictionToLoad.value * 12)
  429. var i = 0
  430. while i <= toLoad {
  431. if i < prediction.count {
  432. let prediction = ShareGlucoseData(sgv: prediction[i], date: predictionTime, direction: "flat")
  433. predictionData.append(prediction)
  434. predictionTime += 300
  435. }
  436. i += 1
  437. }
  438. }
  439. let predMin = prediction.min()
  440. let predMax = prediction.max()
  441. tableData[9].value = bgUnits.toDisplayUnits(String(predMin!)) + "/" + bgUnits.toDisplayUnits(String(predMax!))
  442. if UserDefaultsRepository.graphPrediction.value {
  443. updatePredictionGraph()
  444. }
  445. }
  446. if let recBolus = lastLoopRecord["recommendedBolus"] as? Double {
  447. tableData[8].value = String(format:"%.2fU", recBolus)
  448. }
  449. if let loopStatus = lastLoopRecord["recommendedTempBasal"] as? [String:AnyObject] {
  450. if let tempBasalTime = formatter.date(from: (loopStatus["timestamp"] as! String))?.timeIntervalSince1970 {
  451. var lastBGTime = lastLoopTime
  452. if bgData.count > 0 {
  453. lastBGTime = bgData[bgData.count - 1].date
  454. }
  455. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "tempBasalTime: " + String(tempBasalTime)) }
  456. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "lastBGTime: " + String(lastBGTime)) }
  457. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "wasEnacted: " + String(wasEnacted)) }
  458. if tempBasalTime > lastBGTime && !wasEnacted {
  459. LoopStatusLabel.text = "⏀"
  460. latestLoopStatusString = "⏀"
  461. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Open Loop: recommended temp. temp time > bg time, was not enacted") }
  462. } else {
  463. LoopStatusLabel.text = "↻"
  464. latestLoopStatusString = "↻"
  465. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: recommended temp, but temp time is < bg time and/or was enacted") }
  466. }
  467. }
  468. } else {
  469. LoopStatusLabel.text = "↻"
  470. latestLoopStatusString = "↻"
  471. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Looping: no recommended temp") }
  472. }
  473. }
  474. if ((TimeInterval(Date().timeIntervalSince1970) - lastLoopTime) / 60) > 15 {
  475. LoopStatusLabel.text = "⚠"
  476. latestLoopStatusString = "⚠"
  477. }
  478. latestLoopTime = lastLoopTime
  479. } // end lastLoopTime
  480. } // end lastLoop Record
  481. var oText = "" as String
  482. currentOverride = 1.0
  483. if let lastOverride = lastDeviceStatus?["override"] as! [String : AnyObject]? {
  484. if let lastOverrideTime = formatter.date(from: (lastOverride["timestamp"] as! String))?.timeIntervalSince1970 {
  485. }
  486. if lastOverride["active"] as! Bool {
  487. let lastCorrection = lastOverride["currentCorrectionRange"] as! [String: AnyObject]
  488. if let multiplier = lastOverride["multiplier"] as? Double {
  489. currentOverride = multiplier
  490. oText += String(format: "%.0f%%", (multiplier * 100))
  491. }
  492. else
  493. {
  494. oText += String(format:"%.0f%%", 100)
  495. }
  496. oText += " ("
  497. let minValue = lastCorrection["minValue"] as! Double
  498. let maxValue = lastCorrection["maxValue"] as! Double
  499. oText += bgUnits.toDisplayUnits(String(minValue)) + "-" + bgUnits.toDisplayUnits(String(maxValue)) + ")"
  500. tableData[3].value = oText
  501. }
  502. }
  503. infoTable.reloadData()
  504. // Process Override Data
  505. overrideData.removeAll()
  506. for i in 0..<jsonDeviceStatus.count {
  507. let deviceStatus = jsonDeviceStatus[i] as [String : AnyObject]?
  508. if let override = deviceStatus?["override"] as! [String : AnyObject]? {
  509. let formatter = ISO8601DateFormatter()
  510. formatter.formatOptions = [.withFullDate,
  511. .withTime,
  512. .withDashSeparatorInDate,
  513. .withColonSeparatorInTime]
  514. if let timestamp = formatter.date(from: (override["timestamp"] as! String))?.timeIntervalSince1970 {
  515. if timestamp > dateTimeUtils.getTimeInterval24HoursAgo() {
  516. if let isActive = override["active"] as? Bool {
  517. if isActive {
  518. if let multiplier = override["multiplier"] as? Double {
  519. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: Int(UserDefaultsRepository.overrideDisplayLocation.value))
  520. overrideData.append(override)
  521. }
  522. } else {
  523. let multiplier = 1.0 as Double
  524. let override = DataStructs.overrideGraphStruct(value: multiplier, date: timestamp, sgv: Int(UserDefaultsRepository.overrideDisplayLocation.value))
  525. overrideData.append(override)
  526. }
  527. }
  528. }
  529. }
  530. }
  531. }
  532. overrideData.reverse()
  533. //updateOverrideGraph()
  534. checkOverrideAlarms()
  535. // Start the timer based on the timestamp
  536. let now = dateTimeUtils.getNowTimeIntervalUTC()
  537. let secondsAgo = now - latestLoopTime
  538. DispatchQueue.main.async {
  539. // if Loop is overdue over: 20:00, re-attempt every 5 minutes
  540. if secondsAgo >= (20 * 60) {
  541. self.startDeviceStatusTimer(time: (5 * 60))
  542. print("started 5 minute device status timer")
  543. // if the Loop is overdue: 10:00-19:59, re-attempt every minute
  544. } else if secondsAgo >= (10 * 60) {
  545. self.startDeviceStatusTimer(time: 60)
  546. print("started 1 minute device status timer")
  547. // if the Loop is overdue: 7:00-9:59, re-attempt every 30 seconds
  548. } else if secondsAgo >= (7 * 60) {
  549. self.startDeviceStatusTimer(time: 30)
  550. print("started 30 second device status timer")
  551. // if the Loop is overdue: 5:00-6:59 re-attempt every 10 seconds
  552. } else if secondsAgo >= (5 * 60) {
  553. self.startDeviceStatusTimer(time: 10)
  554. print("started 10 second device status timer")
  555. // We have a current Loop. Set timer to 5:10 from last reading
  556. } else {
  557. self.startDeviceStatusTimer(time: 310 - secondsAgo)
  558. let timerVal = 310 - secondsAgo
  559. print("started 5:10 device status timer: \(timerVal)")
  560. }
  561. }
  562. }
  563. // NS Cage Web Call
  564. func webLoadNSCage() {
  565. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: CAGE") }
  566. let urlUser = UserDefaultsRepository.url.value
  567. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Site%20Change&count=1"
  568. if token != "" {
  569. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Site%20Change&count=1"
  570. }
  571. guard let urlData = URL(string: urlString) else {
  572. return
  573. }
  574. var request = URLRequest(url: urlData)
  575. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  576. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  577. guard error == nil else {
  578. return
  579. }
  580. guard let data = data else {
  581. return
  582. }
  583. let decoder = JSONDecoder()
  584. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  585. if let entriesResponse = entriesResponse {
  586. DispatchQueue.main.async {
  587. self.updateCage(data: entriesResponse)
  588. }
  589. } else {
  590. return
  591. }
  592. }
  593. task.resume()
  594. }
  595. // NS Cage Response Processor
  596. func updateCage(data: [cageData]) {
  597. self.clearLastInfoData(index: 7)
  598. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: CAGE") }
  599. if data.count == 0 {
  600. return
  601. }
  602. let lastCageString = data[0].created_at
  603. let formatter = ISO8601DateFormatter()
  604. formatter.formatOptions = [.withFullDate,
  605. .withTime,
  606. .withDashSeparatorInDate,
  607. .withColonSeparatorInTime]
  608. UserDefaultsRepository.alertCageInsertTime.value = formatter.date(from: (lastCageString))?.timeIntervalSince1970 as! TimeInterval
  609. if let cageTime = formatter.date(from: (lastCageString))?.timeIntervalSince1970 {
  610. let now = dateTimeUtils.getNowTimeIntervalUTC()
  611. let secondsAgo = now - cageTime
  612. //let days = 24 * 60 * 60
  613. let formatter = DateComponentsFormatter()
  614. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  615. formatter.allowedUnits = [ .day, .hour ] // Units to display in the formatted string
  616. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  617. let formattedDuration = formatter.string(from: secondsAgo)
  618. tableData[7].value = formattedDuration ?? ""
  619. }
  620. infoTable.reloadData()
  621. }
  622. // NS Sage Web Call
  623. func webLoadNSSage() {
  624. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: SAGE") }
  625. let lastDateString = dateTimeUtils.nowMinus10DaysTimeInterval()
  626. let urlUser = UserDefaultsRepository.url.value
  627. var urlString = urlUser + "/api/v1/treatments.json?find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  628. if token != "" {
  629. urlString = urlUser + "/api/v1/treatments.json?token=" + token + "&find[eventType]=Sensor%20Start&find[created_at][$gte]=" + lastDateString + "&count=1"
  630. }
  631. guard let urlData = URL(string: urlString) else {
  632. return
  633. }
  634. var request = URLRequest(url: urlData)
  635. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  636. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  637. guard error == nil else {
  638. return
  639. }
  640. guard let data = data else {
  641. return
  642. }
  643. let decoder = JSONDecoder()
  644. let entriesResponse = try? decoder.decode([cageData].self, from: data)
  645. if let entriesResponse = entriesResponse {
  646. DispatchQueue.main.async {
  647. self.updateSage(data: entriesResponse)
  648. }
  649. } else {
  650. return
  651. }
  652. }
  653. task.resume()
  654. }
  655. // NS Sage Response Processor
  656. func updateSage(data: [cageData]) {
  657. self.clearLastInfoData(index: 6)
  658. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process/Display: SAGE") }
  659. if data.count == 0 {
  660. return
  661. }
  662. var lastSageString = data[0].created_at
  663. let formatter = ISO8601DateFormatter()
  664. formatter.formatOptions = [.withFullDate,
  665. .withTime,
  666. .withDashSeparatorInDate,
  667. .withColonSeparatorInTime]
  668. UserDefaultsRepository.alertSageInsertTime.value = formatter.date(from: (lastSageString))?.timeIntervalSince1970 as! TimeInterval
  669. if let sageTime = formatter.date(from: (lastSageString as! String))?.timeIntervalSince1970 {
  670. let now = dateTimeUtils.getNowTimeIntervalUTC()
  671. let secondsAgo = now - sageTime
  672. let days = 24 * 60 * 60
  673. let formatter = DateComponentsFormatter()
  674. formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale
  675. formatter.allowedUnits = [ .day, .hour] // Units to display in the formatted string
  676. formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale
  677. let formattedDuration = formatter.string(from: secondsAgo)
  678. tableData[6].value = formattedDuration ?? ""
  679. }
  680. infoTable.reloadData()
  681. }
  682. // NS Profile Web Call
  683. func webLoadNSProfile() {
  684. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: profile") }
  685. let urlUser = UserDefaultsRepository.url.value
  686. var urlString = urlUser + "/api/v1/profile/current.json"
  687. if token != "" {
  688. urlString = urlUser + "/api/v1/profile/current.json?token=" + token
  689. }
  690. let escapedAddress = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
  691. guard let url = URL(string: escapedAddress!) else {
  692. return
  693. }
  694. var request = URLRequest(url: url)
  695. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  696. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  697. guard error == nil else {
  698. return
  699. }
  700. guard let data = data else {
  701. return
  702. }
  703. let json = try? JSONSerialization.jsonObject(with: data) as! Dictionary<String, Any>
  704. if let json = json {
  705. DispatchQueue.main.async {
  706. self.updateProfile(jsonDeviceStatus: json)
  707. }
  708. } else {
  709. return
  710. }
  711. }
  712. task.resume()
  713. }
  714. // NS Profile Response Processor
  715. func updateProfile(jsonDeviceStatus: Dictionary<String, Any>) {
  716. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: profile") }
  717. if jsonDeviceStatus.count == 0 {
  718. return
  719. }
  720. if jsonDeviceStatus[keyPath: "message"] != nil { return }
  721. let basal = try jsonDeviceStatus[keyPath: "store.Default.basal"] as! NSArray
  722. basalProfile.removeAll()
  723. for i in 0..<basal.count {
  724. let dict = basal[i] as! Dictionary<String, Any>
  725. do {
  726. let thisValue = try dict[keyPath: "value"] as! Double
  727. let thisTime = dict[keyPath: "time"] as! String
  728. let thisTimeAsSeconds = dict[keyPath: "timeAsSeconds"] as! Double
  729. let entry = basalProfileStruct(value: thisValue, time: thisTime, timeAsSeconds: thisTimeAsSeconds)
  730. basalProfile.append(entry)
  731. } catch {
  732. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: profile wrapped in quotes") }
  733. }
  734. }
  735. // Don't process the basal or draw the graph until after the BG has been fully processeed and drawn
  736. if firstGraphLoad { return }
  737. // Make temporary array with all values of yesterday and today
  738. let yesterdayStart = dateTimeUtils.getTimeIntervalMidnightYesterday()
  739. let todayStart = dateTimeUtils.getTimeIntervalMidnightToday()
  740. var basal2Day: [DataStructs.basal2DayProfile] = []
  741. // Run twice to add in order yesterday then today.
  742. for p in 0..<basalProfile.count {
  743. let start = yesterdayStart + basalProfile[p].timeAsSeconds
  744. var end = yesterdayStart
  745. // set the endings 1 second before the next one starts
  746. if p < basalProfile.count - 1 {
  747. end = yesterdayStart + basalProfile[p + 1].timeAsSeconds - 1
  748. } else {
  749. // set the end 1 second before midnight
  750. end = yesterdayStart + 86399
  751. }
  752. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  753. basal2Day.append(entry)
  754. }
  755. for p in 0..<basalProfile.count {
  756. let start = todayStart + basalProfile[p].timeAsSeconds
  757. var end = todayStart
  758. // set the endings 1 second before the next one starts
  759. if p < basalProfile.count - 1 {
  760. end = todayStart + basalProfile[p + 1].timeAsSeconds - 1
  761. } else {
  762. // set the end 1 second before midnight
  763. end = todayStart + 86399
  764. }
  765. let entry = DataStructs.basal2DayProfile(basalRate: basalProfile[p].value, startDate: start, endDate: end)
  766. basal2Day.append(entry)
  767. }
  768. let now = dateTimeUtils.nowMinus24HoursTimeInterval()
  769. var firstPass = true
  770. basalScheduleData.removeAll()
  771. for i in 0..<basal2Day.count {
  772. var timeYesterday = dateTimeUtils.getTimeInterval24HoursAgo()
  773. // This processed everything after the first one.
  774. if firstPass == false
  775. && basal2Day[i].startDate <= dateTimeUtils.getNowTimeIntervalUTC() {
  776. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: basal2Day[i].startDate)
  777. basalScheduleData.append(startDot)
  778. var endDate = basal2Day[i].endDate
  779. // if it's the last one in the profile or date is greater than now, set it to 30 minutes from now
  780. if i == basal2Day.count - 1 || endDate > dateTimeUtils.getNowTimeIntervalUTC() {
  781. endDate = Double(dateTimeUtils.getNowTimeIntervalUTC() + (30 * 60))
  782. }
  783. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  784. basalScheduleData.append(endDot)
  785. }
  786. // we need to manually set the first one
  787. // Check that this is the first one and there are no existing entries
  788. if firstPass == true {
  789. // check that the timestamp is > the current entry and < the next entry
  790. if timeYesterday >= basal2Day[i].startDate && timeYesterday < basal2Day[i].endDate {
  791. // Set the start time to match the BG start
  792. let startDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: Double(dateTimeUtils.getTimeInterval24HoursAgo() + (60 * 5)))
  793. basalScheduleData.append(startDot)
  794. // set the enddot where the next one will start
  795. var endDate = basal2Day[i].endDate
  796. let endDot = basalGraphStruct(basalRate: basal2Day[i].basalRate, date: endDate)
  797. basalScheduleData.append(endDot)
  798. firstPass = false
  799. }
  800. }
  801. }
  802. if UserDefaultsRepository.graphBasal.value {
  803. updateBasalScheduledGraph()
  804. }
  805. }
  806. // NS Treatments Web Call
  807. // Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
  808. func WebLoadNSTreatments() {
  809. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Download: Treatments") }
  810. if !UserDefaultsRepository.downloadTreatments.value { return }
  811. let yesterdayString = dateTimeUtils.nowMinus24HoursTimeInterval()
  812. var urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?find[created_at][$gte]=" + yesterdayString
  813. if token != "" {
  814. urlString = UserDefaultsRepository.url.value + "/api/v1/treatments.json?token=" + token + "&find[created_at][$gte]=" + yesterdayString
  815. }
  816. guard let urlData = URL(string: urlString) else {
  817. return
  818. }
  819. var request = URLRequest(url: urlData)
  820. request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
  821. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  822. guard error == nil else {
  823. return
  824. }
  825. guard let data = data else {
  826. return
  827. }
  828. let json = try? (JSONSerialization.jsonObject(with: data) as? [[String:AnyObject]])
  829. if let json = json {
  830. DispatchQueue.main.async {
  831. self.updateTreatments(entries: json)
  832. }
  833. } else {
  834. return
  835. }
  836. }
  837. task.resume()
  838. }
  839. // Process and split out treatments to individual tasks
  840. func updateTreatments(entries: [[String:AnyObject]]) {
  841. var tempBasal: [[String:AnyObject]] = []
  842. var bolus: [[String:AnyObject]] = []
  843. var carbs: [[String:AnyObject]] = []
  844. var temporaryOverride: [[String:AnyObject]] = []
  845. var note: [[String:AnyObject]] = []
  846. var bgCheck: [[String:AnyObject]] = []
  847. var suspendPump: [[String:AnyObject]] = []
  848. var resumePump: [[String:AnyObject]] = []
  849. var pumpSiteChange: [[String:AnyObject]] = []
  850. var cgmSensorStart: [[String:AnyObject]] = []
  851. for i in 0..<entries.count {
  852. let entry = entries[i] as [String : AnyObject]?
  853. switch entry?["eventType"] as! String {
  854. case "Temp Basal":
  855. tempBasal.append(entry!)
  856. case "Correction Bolus":
  857. bolus.append(entry!)
  858. case "Meal Bolus":
  859. carbs.append(entry!)
  860. case "Temporary Override":
  861. temporaryOverride.append(entry!)
  862. case "Note":
  863. note.append(entry!)
  864. print("Note: \(String(describing: entry))")
  865. case "BG Check":
  866. bgCheck.append(entry!)
  867. case "Suspend Pump":
  868. suspendPump.append(entry!)
  869. case "Resume Pump":
  870. resumePump.append(entry!)
  871. case "Pump Site Change":
  872. pumpSiteChange.append(entry!)
  873. case "CGM Sensor Start":
  874. cgmSensorStart.append(entry!)
  875. default:
  876. print("No Match: \(String(describing: entry))")
  877. }
  878. }
  879. // end of for loop
  880. if tempBasal.count > 0 { processNSBasals(entries: tempBasal)}
  881. if bolus.count > 0 { processNSBolus(entries: bolus)}
  882. if carbs.count > 0 { processNSCarbs(entries: carbs)}
  883. if bgCheck.count > 0 { processNSBGCheck(entries: bgCheck)}
  884. if temporaryOverride.count > 0 { processNSOverrides(entries: temporaryOverride)}
  885. }
  886. // NS Temp Basal Response Processor
  887. func processNSBasals(entries: [[String:AnyObject]]) {
  888. self.clearLastInfoData(index: 2)
  889. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Basal") }
  890. // due to temp basal durations, we're going to destroy the array and load everything each cycle for the time being.
  891. basalData.removeAll()
  892. var lastEndDot = 0.0
  893. var tempArray = entries
  894. tempArray.reverse()
  895. for i in 0..<tempArray.count {
  896. let currentEntry = tempArray[i] as [String : AnyObject]?
  897. var basalDate: String
  898. if currentEntry?["timestamp"] != nil {
  899. basalDate = currentEntry?["timestamp"] as! String
  900. } else if currentEntry?["created_at"] != nil {
  901. basalDate = currentEntry?["created_at"] as! String
  902. } else {
  903. return
  904. }
  905. var strippedZone = String(basalDate.dropLast())
  906. strippedZone = strippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  907. let dateFormatter = DateFormatter()
  908. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  909. dateFormatter.locale = Locale(identifier: "en_US")
  910. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  911. let dateString = dateFormatter.date(from: strippedZone)
  912. let dateTimeStamp = dateString!.timeIntervalSince1970
  913. guard let basalRate = currentEntry?["absolute"] as? Double else {
  914. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Basal entry")}
  915. continue
  916. }
  917. let midnightTime = dateTimeUtils.getTimeIntervalMidnightToday()
  918. // Setting end dots
  919. var duration = 0.0
  920. do {
  921. duration = try currentEntry?["duration"] as! Double
  922. } catch {
  923. print("No Duration Found")
  924. }
  925. // 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
  926. if i > 0 {
  927. let priorEntry = tempArray[i - 1] as [String : AnyObject]?
  928. var priorBasalDate: String
  929. if priorEntry?["timestamp"] != nil {
  930. priorBasalDate = priorEntry?["timestamp"] as! String
  931. } else if currentEntry?["created_at"] != nil {
  932. priorBasalDate = priorEntry?["created_at"] as! String
  933. } else {
  934. continue
  935. }
  936. var priorStrippedZone = String(priorBasalDate.dropLast())
  937. priorStrippedZone = priorStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  938. let priorDateFormatter = DateFormatter()
  939. priorDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  940. priorDateFormatter.locale = Locale(identifier: "en_US")
  941. priorDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  942. let priorDateString = dateFormatter.date(from: priorStrippedZone)
  943. let priorDateTimeStamp = priorDateString!.timeIntervalSince1970
  944. let priorDuration = priorEntry?["duration"] as! Double
  945. // 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
  946. if Double( dateTimeStamp - priorDateTimeStamp ) > Double( (priorDuration * 60) + 15 ) {
  947. var scheduled = 0.0
  948. // cycle through basal profiles.
  949. // TODO figure out how to deal with profile changes that happen mid-gap
  950. for b in 0..<self.basalProfile.count {
  951. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  952. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  953. // check the prior temp ending to the profile seconds from midnight
  954. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeYesterday {
  955. scheduled = basalProfile[b].value
  956. }
  957. if (priorDateTimeStamp + (priorDuration * 60)) >= scheduleTimeToday {
  958. scheduled = basalProfile[b].value
  959. }
  960. // This will iterate through from midnight on and set it for the highest matching one.
  961. }
  962. // Make the starting dot at the last ending dot
  963. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(priorDateTimeStamp + (priorDuration * 60)))
  964. basalData.append(startDot)
  965. //if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Basal: Scheduled " + String(scheduled) + " " + String(dateTimeStamp)) }
  966. // Make the ending dot at the new starting dot
  967. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(dateTimeStamp))
  968. basalData.append(endDot)
  969. }
  970. }
  971. // Make the starting dot
  972. let startDot = basalGraphStruct(basalRate: basalRate, date: Double(dateTimeStamp))
  973. basalData.append(startDot)
  974. // Make the ending dot
  975. // If it's the last one and has no duration, extend it for 30 minutes past the start. Otherwise set ending at duration
  976. // duration is already set to 0 if there is no duration set on it.
  977. //if i == tempArray.count - 1 && dateTimeStamp + duration <= dateTimeUtils.getNowTimeIntervalUTC() {
  978. if i == tempArray.count - 1 && duration == 0.0 {
  979. lastEndDot = dateTimeStamp + (30 * 60)
  980. latestBasal = String(format:"%.2f", basalRate)
  981. } else {
  982. lastEndDot = dateTimeStamp + (duration * 60)
  983. latestBasal = String(format:"%.2f", basalRate)
  984. }
  985. // Double check for overlaps of incorrectly ended TBRs and sent it to end when the next one starts if it finds a discrepancy
  986. if i < tempArray.count - 1 {
  987. let nextEntry = tempArray[i + 1] as [String : AnyObject]?
  988. var nextBasalDate: String
  989. if nextEntry?["timestamp"] != nil {
  990. nextBasalDate = nextEntry?["timestamp"] as! String
  991. } else if currentEntry?["created_at"] != nil {
  992. nextBasalDate = nextEntry?["created_at"] as! String
  993. } else {
  994. continue
  995. }
  996. var nextStrippedZone = String(nextBasalDate.dropLast())
  997. nextStrippedZone = nextStrippedZone.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
  998. let nextDateFormatter = DateFormatter()
  999. nextDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1000. nextDateFormatter.locale = Locale(identifier: "en_US")
  1001. nextDateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1002. let nextDateString = dateFormatter.date(from: nextStrippedZone)
  1003. let nextDateTimeStamp = nextDateString!.timeIntervalSince1970
  1004. if nextDateTimeStamp < (dateTimeStamp + (duration * 60)) {
  1005. lastEndDot = nextDateTimeStamp
  1006. }
  1007. }
  1008. let endDot = basalGraphStruct(basalRate: basalRate, date: Double(lastEndDot))
  1009. basalData.append(endDot)
  1010. }
  1011. // If last basal was prior to right now, we need to create one last scheduled entry
  1012. if lastEndDot <= dateTimeUtils.getNowTimeIntervalUTC() {
  1013. var scheduled = 0.0
  1014. // cycle through basal profiles.
  1015. // TODO figure out how to deal with profile changes that happen mid-gap
  1016. for b in 0..<self.basalProfile.count {
  1017. let scheduleTimeYesterday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightYesterday()
  1018. let scheduleTimeToday = self.basalProfile[b].timeAsSeconds + dateTimeUtils.getTimeIntervalMidnightToday()
  1019. // check the prior temp ending to the profile seconds from midnight
  1020. print("yesterday " + String(scheduleTimeYesterday))
  1021. print("today " + String(scheduleTimeToday))
  1022. if lastEndDot >= scheduleTimeToday {
  1023. scheduled = basalProfile[b].value
  1024. }
  1025. }
  1026. latestBasal = String(format:"%.2f", scheduled)
  1027. // Make the starting dot at the last ending dot
  1028. let startDot = basalGraphStruct(basalRate: scheduled, date: Double(lastEndDot))
  1029. basalData.append(startDot)
  1030. // Make the ending dot 10 minutes after now
  1031. let endDot = basalGraphStruct(basalRate: scheduled, date: Double(Date().timeIntervalSince1970 + (60 * 10)))
  1032. basalData.append(endDot)
  1033. }
  1034. tableData[2].value = latestBasal
  1035. infoTable.reloadData()
  1036. if UserDefaultsRepository.graphBasal.value {
  1037. updateBasalGraph()
  1038. }
  1039. infoTable.reloadData()
  1040. }
  1041. // NS Meal Bolus Response Processor
  1042. func processNSBolus(entries: [[String:AnyObject]]) {
  1043. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Bolus") }
  1044. // because it's a small array, we're going to destroy and reload every time.
  1045. bolusData.removeAll()
  1046. var lastFoundIndex = 0
  1047. for i in 0..<entries.count {
  1048. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1049. var bolusDate: String
  1050. if currentEntry?["timestamp"] != nil {
  1051. bolusDate = currentEntry?["timestamp"] as! String
  1052. } else if currentEntry?["created_at"] != nil {
  1053. bolusDate = currentEntry?["created_at"] as! String
  1054. } else {
  1055. return
  1056. }
  1057. // fix to remove millisecond (after period in timestamp) for FreeAPS users
  1058. var strippedZone = String(bolusDate.dropLast())
  1059. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1060. let dateFormatter = DateFormatter()
  1061. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1062. dateFormatter.locale = Locale(identifier: "en_US")
  1063. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1064. let dateString = dateFormatter.date(from: strippedZone)
  1065. let dateTimeStamp = dateString!.timeIntervalSince1970
  1066. do {
  1067. let bolus = try currentEntry?["insulin"] as! Double
  1068. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1069. lastFoundIndex = sgv.foundIndex
  1070. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1071. // Make the dot
  1072. let dot = bolusGraphStruct(value: bolus, date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1073. bolusData.append(dot)
  1074. }
  1075. } catch {
  1076. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Bolus") }
  1077. }
  1078. }
  1079. if UserDefaultsRepository.graphBolus.value {
  1080. updateBolusGraph()
  1081. }
  1082. }
  1083. // NS Carb Bolus Response Processor
  1084. func processNSCarbs(entries: [[String:AnyObject]]) {
  1085. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Carbs") }
  1086. // because it's a small array, we're going to destroy and reload every time.
  1087. carbData.removeAll()
  1088. var lastFoundIndex = 0
  1089. for i in 0..<entries.count {
  1090. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1091. var carbDate: String
  1092. if currentEntry?["timestamp"] != nil {
  1093. carbDate = currentEntry?["timestamp"] as! String
  1094. } else if currentEntry?["created_at"] != nil {
  1095. carbDate = currentEntry?["created_at"] as! String
  1096. } else {
  1097. return
  1098. }
  1099. let absorptionTime = currentEntry?["absorptionTime"] as? Int ?? 0
  1100. // Fix for FreeAPS milliseconds in timestamp
  1101. var strippedZone = String(carbDate.dropLast())
  1102. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1103. let dateFormatter = DateFormatter()
  1104. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1105. dateFormatter.locale = Locale(identifier: "en_US")
  1106. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1107. let dateString = dateFormatter.date(from: strippedZone)
  1108. let dateTimeStamp = dateString!.timeIntervalSince1970
  1109. guard let carbs = currentEntry?["carbs"] as? Double else {
  1110. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Null Carb entry")}
  1111. break
  1112. }
  1113. let sgv = findNearestBGbyTime(needle: dateTimeStamp, haystack: bgData, startingIndex: lastFoundIndex)
  1114. lastFoundIndex = sgv.foundIndex
  1115. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1116. // Make the dot
  1117. let dot = carbGraphStruct(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv), absorptionTime: absorptionTime)
  1118. carbData.append(dot)
  1119. }
  1120. }
  1121. if UserDefaultsRepository.graphCarbs.value {
  1122. updateCarbGraph()
  1123. }
  1124. }
  1125. // NS BG Check Response Processor
  1126. func processNSBGCheck(entries: [[String:AnyObject]]) {
  1127. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: BG Check") }
  1128. // because it's a small array, we're going to destroy and reload every time.
  1129. bgCheckData.removeAll()
  1130. for i in 0..<entries.count {
  1131. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1132. var date: String
  1133. if currentEntry?["timestamp"] != nil {
  1134. date = currentEntry?["timestamp"] as! String
  1135. } else if currentEntry?["created_at"] != nil {
  1136. date = currentEntry?["created_at"] as! String
  1137. } else {
  1138. return
  1139. }
  1140. // Fix for FreeAPS milliseconds in timestamp
  1141. var strippedZone = String(date.dropLast())
  1142. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1143. let dateFormatter = DateFormatter()
  1144. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1145. dateFormatter.locale = Locale(identifier: "en_US")
  1146. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1147. let dateString = dateFormatter.date(from: strippedZone)
  1148. let dateTimeStamp = dateString!.timeIntervalSince1970
  1149. guard let sgv = currentEntry?["glucose"] as? Int else {
  1150. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "ERROR: Non-Int Glucose entry")}
  1151. continue
  1152. }
  1153. if dateTimeStamp < (dateTimeUtils.getNowTimeIntervalUTC() + (60 * 60)) {
  1154. // Make the dot
  1155. //let dot = ShareGlucoseData(value: Double(carbs), date: Double(dateTimeStamp), sgv: Int(sgv.sgv))
  1156. let dot = ShareGlucoseData(sgv: sgv, date: Double(dateTimeStamp), direction: "")
  1157. bgCheckData.append(dot)
  1158. }
  1159. }
  1160. if UserDefaultsRepository.graphCarbs.value {
  1161. updateBGCheckGraph()
  1162. }
  1163. }
  1164. // NS Override Response Processor
  1165. func processNSOverrides(entries: [[String:AnyObject]]) {
  1166. if UserDefaultsRepository.debugLog.value { self.writeDebugLog(value: "Process: Overrides") }
  1167. // because it's a small array, we're going to destroy and reload every time.
  1168. overrideGraphData.removeAll()
  1169. for i in 0..<entries.count {
  1170. let currentEntry = entries[entries.count - 1 - i] as [String : AnyObject]?
  1171. var date: String
  1172. if currentEntry?["timestamp"] != nil {
  1173. date = currentEntry?["timestamp"] as! String
  1174. } else if currentEntry?["created_at"] != nil {
  1175. date = currentEntry?["created_at"] as! String
  1176. } else {
  1177. return
  1178. }
  1179. // Fix for FreeAPS milliseconds in timestamp
  1180. var strippedZone = String(date.dropLast())
  1181. strippedZone = strippedZone.components(separatedBy: ".")[0]
  1182. let dateFormatter = DateFormatter()
  1183. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
  1184. dateFormatter.locale = Locale(identifier: "en_US")
  1185. dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  1186. let dateString = dateFormatter.date(from: strippedZone)
  1187. var dateTimeStamp = dateString!.timeIntervalSince1970
  1188. if dateTimeStamp < dateTimeUtils.getTimeInterval24HoursAgo() {
  1189. dateTimeStamp = dateTimeUtils.getTimeInterval24HoursAgo()
  1190. }
  1191. guard let multipler = currentEntry?["insulinNeedsScaleFactor"] as? Double else { continue }
  1192. var duration: Double = 5.0
  1193. if let durationType = currentEntry?["durationType"] as? String {
  1194. duration = dateTimeUtils.getNowTimeIntervalUTC() - dateTimeStamp + (60 * 60)
  1195. } else {
  1196. duration = (currentEntry?["duration"] as? Double)!
  1197. duration = duration * 60
  1198. }
  1199. guard let enteredBy = currentEntry?["enteredBy"] as? String else { continue }
  1200. guard let reason = currentEntry?["reason"] as? String else { continue }
  1201. var range: [Int] = []
  1202. if let ranges = currentEntry?["correctionRange"] as? [Int] {
  1203. if ranges.count == 2 {
  1204. guard let low = ranges[0] as? Int else { continue }
  1205. guard let high = ranges[1] as? Int else { continue }
  1206. range.append(low)
  1207. range.append(high)
  1208. }
  1209. }
  1210. let endDate = dateTimeStamp + (duration)
  1211. let dot = DataStructs.overrideStruct(insulNeedsScaleFactor: multipler, date: dateTimeStamp, endDate: endDate, duration: duration, correctionRange: range, enteredBy: enteredBy, reason: reason, sgv: -20)
  1212. overrideGraphData.append(dot)
  1213. }
  1214. updateOverrideGraph()
  1215. }
  1216. }