ShareClientExtension.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // ShareClientExtension.swift
  3. // LoopFollow
  4. //
  5. // Created by Jose Paredes on 7/13/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import ShareClient
  10. public struct ShareGlucoseData: Codable {
  11. var sgv: Int
  12. var date: TimeInterval
  13. var direction: String?
  14. enum CodingKeys: String, CodingKey {
  15. case sgv
  16. case date
  17. case direction
  18. }
  19. public init(from decoder: Decoder) throws {
  20. let container = try decoder.container(keyedBy: CodingKeys.self)
  21. if let sgvAsDouble = try? container.decode(Double.self, forKey: .sgv) {
  22. sgv = Int(sgvAsDouble.rounded())
  23. } else if let sgvAsInt = try? container.decode(Int.self, forKey: .sgv) {
  24. sgv = sgvAsInt
  25. } else {
  26. throw DecodingError.dataCorruptedError(forKey: .sgv, in: container, debugDescription: "Expected to decode an Integer or Double.")
  27. }
  28. // Decode the other properties
  29. date = try container.decode(TimeInterval.self, forKey: .date)
  30. direction = try container.decodeIfPresent(String.self, forKey: .direction)
  31. }
  32. public init(sgv: Int, date: TimeInterval, direction: String?) {
  33. self.sgv = sgv
  34. self.date = date
  35. self.direction = direction
  36. }
  37. }
  38. private var TrendTable: [String] = [
  39. "NONE", // 0
  40. "DoubleUp", // 1
  41. "SingleUp", // 2
  42. "FortyFiveUp", // 3
  43. "Flat", // 4
  44. "FortyFiveDown", // 5
  45. "SingleDown", // 6
  46. "DoubleDown", // 7
  47. "NOT COMPUTABLE", // 8
  48. "RATE OUT OF RANGE" // 9
  49. ]
  50. // TODO: probably better to make this an inherited class rather than an extension
  51. extension ShareClient {
  52. public func fetchData(_ entries: Int, callback: @escaping (ShareError?, [ShareGlucoseData]?) -> Void) {
  53. self.fetchLast(entries) { (error, result) -> () in
  54. guard error == nil || result != nil else {
  55. return callback(error, nil)
  56. }
  57. // parse data to conanical form
  58. var shareData = [ShareGlucoseData]()
  59. for i in 0..<result!.count {
  60. var trend = Int(result![i].trend)
  61. if(trend < 0 || trend > TrendTable.count-1) {
  62. trend = 0
  63. }
  64. let newShareData = ShareGlucoseData(
  65. sgv: Int(result![i].glucose),
  66. date: result![i].timestamp.timeIntervalSince1970,
  67. direction: TrendTable[trend]
  68. )
  69. shareData.append(newShareData)
  70. }
  71. callback(nil,shareData)
  72. }
  73. }
  74. }