NightScout.swift 78 KB

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