NightScout.swift 77 KB

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