NightScout.swift 82 KB

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