TidepoolManager.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import Combine
  2. import Foundation
  3. import HealthKit
  4. import LoopKit
  5. import LoopKitUI
  6. import Swinject
  7. protocol TidepoolManager {
  8. func addTidepoolService(service: Service)
  9. func getTidepoolServiceUI() -> ServiceUI?
  10. func getTidepoolPluginHost() -> PluginHost?
  11. func deleteCarbs(at date: Date, isFPU: Bool?, fpuID: String?, syncID: String)
  12. func deleteInsulin(at date: Date)
  13. // func uploadStatus()
  14. func uploadGlucose(device: HKDevice?)
  15. func forceUploadData(device: HKDevice?)
  16. // func uploadPreferences(_ preferences: Preferences)
  17. // func uploadProfileAndSettings(_: Bool)
  18. }
  19. final class BaseTidepoolManager: TidepoolManager, Injectable {
  20. @Injected() private var broadcaster: Broadcaster!
  21. @Injected() private var pluginManager: PluginManager!
  22. @Injected() private var glucoseStorage: GlucoseStorage!
  23. @Injected() private var carbsStorage: CarbsStorage!
  24. @Injected() private var storage: FileStorage!
  25. @Injected() private var pumpHistoryStorage: PumpHistoryStorage!
  26. private let processQueue = DispatchQueue(label: "BaseNetworkManager.processQueue")
  27. private var tidepoolService: RemoteDataService? {
  28. didSet {
  29. if let tidepoolService = tidepoolService {
  30. rawTidepoolManager = tidepoolService.rawValue
  31. } else {
  32. rawTidepoolManager = nil
  33. }
  34. }
  35. }
  36. @PersistedProperty(key: "TidepoolState") var rawTidepoolManager: Service.RawValue?
  37. init(resolver: Resolver) {
  38. injectServices(resolver)
  39. loadTidepoolManager()
  40. subscribe()
  41. }
  42. /// load the Tidepool Remote Data Service if available
  43. fileprivate func loadTidepoolManager() {
  44. if let rawTidepoolManager = rawTidepoolManager {
  45. tidepoolService = tidepoolServiceFromRaw(rawTidepoolManager)
  46. tidepoolService?.serviceDelegate = self
  47. tidepoolService?.stateDelegate = self
  48. }
  49. }
  50. /// allows to acces to tidepoolService as a simple ServiceUI
  51. func getTidepoolServiceUI() -> ServiceUI? {
  52. if let tidepoolService = self.tidepoolService {
  53. return tidepoolService as! any ServiceUI as ServiceUI
  54. } else {
  55. return nil
  56. }
  57. }
  58. /// get the pluginHost of Tidepool
  59. func getTidepoolPluginHost() -> PluginHost? {
  60. self as PluginHost
  61. }
  62. func addTidepoolService(service: Service) {
  63. tidepoolService = service as! any RemoteDataService as RemoteDataService
  64. }
  65. /// load the Tidepool Remote Data Service from raw storage
  66. private func tidepoolServiceFromRaw(_ rawValue: [String: Any]) -> RemoteDataService? {
  67. guard let rawState = rawValue["state"] as? Service.RawStateValue,
  68. let serviceType = pluginManager.getServiceTypeByIdentifier("TidepoolService")
  69. else {
  70. return nil
  71. }
  72. if let service = serviceType.init(rawState: rawState) {
  73. return service as! any RemoteDataService as RemoteDataService
  74. } else { return nil }
  75. }
  76. private func subscribe() {
  77. broadcaster.register(PumpHistoryObserver.self, observer: self)
  78. broadcaster.register(CarbsObserver.self, observer: self)
  79. broadcaster.register(TempTargetsObserver.self, observer: self)
  80. }
  81. func sourceInfo() -> [String: Any]? {
  82. nil
  83. }
  84. func uploadCarbs() {
  85. let carbs: [CarbsEntry] = carbsStorage.recent()
  86. guard !carbs.isEmpty, let tidepoolService = self.tidepoolService else { return }
  87. processQueue.async {
  88. carbs.chunks(ofCount: tidepoolService.carbDataLimit ?? 100).forEach { chunk in
  89. let syncCarb: [SyncCarbObject] = Array(chunk).map {
  90. $0.convertSyncCarb()
  91. }
  92. tidepoolService.uploadCarbData(created: syncCarb, updated: [], deleted: []) { result in
  93. switch result {
  94. case let .failure(error):
  95. debug(.nightscout, "Error synchronizing carbs data: \(String(describing: error))")
  96. case .success:
  97. debug(.nightscout, "Success synchronizing carbs data:")
  98. }
  99. }
  100. }
  101. }
  102. }
  103. func deleteCarbs(at date: Date, isFPU: Bool?, fpuID: String?, syncID _: String) {
  104. guard let tidepoolService = self.tidepoolService else { return }
  105. processQueue.async {
  106. var carbsToDelete: [CarbsEntry] = []
  107. let allValues = self.storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  108. if let isFPU = isFPU, isFPU {
  109. guard let fpuID = fpuID else { return }
  110. carbsToDelete = allValues.filter { $0.fpuID == fpuID }.removeDublicates()
  111. } else {
  112. carbsToDelete = allValues.filter { $0.createdAt == date }.removeDublicates()
  113. }
  114. let syncCarb = carbsToDelete.map { d in
  115. d.convertSyncCarb(operation: .delete)
  116. }
  117. tidepoolService.uploadCarbData(created: [], updated: [], deleted: syncCarb) { result in
  118. switch result {
  119. case let .failure(error):
  120. debug(.nightscout, "Error synchronizing carbs data: \(String(describing: error))")
  121. case .success:
  122. debug(.nightscout, "Success synchronizing carbs data:")
  123. }
  124. }
  125. }
  126. }
  127. func deleteInsulin(at d: Date) {
  128. let allValues = storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self) ?? []
  129. guard !allValues.isEmpty, let tidepoolService = self.tidepoolService else { return }
  130. var doseDataToDelete: [DoseEntry] = []
  131. guard let entry = allValues.first(where: { $0.timestamp == d }) else {
  132. return
  133. }
  134. doseDataToDelete
  135. .append(DoseEntry(
  136. type: .bolus,
  137. startDate: entry.timestamp,
  138. value: Double(entry.amount!),
  139. unit: .units,
  140. syncIdentifier: entry.id
  141. ))
  142. processQueue.async {
  143. tidepoolService.uploadDoseData(created: [], deleted: doseDataToDelete) { result in
  144. switch result {
  145. case let .failure(error):
  146. debug(.nightscout, "Error synchronizing Dose delete data: \(String(describing: error))")
  147. case .success:
  148. debug(.nightscout, "Success synchronizing Dose delete data:")
  149. }
  150. }
  151. }
  152. }
  153. func uploadDose() {
  154. let events = pumpHistoryStorage.recent()
  155. guard !events.isEmpty, let tidepoolService = self.tidepoolService else { return }
  156. let eventsBasal = events.filter { $0.type == .tempBasal || $0.type == .tempBasalDuration }
  157. .sorted { $0.timestamp < $1.timestamp }
  158. let doseDataBasal: [DoseEntry] = eventsBasal.reduce([]) { result, event in
  159. var result = result
  160. switch event.type {
  161. case .tempBasal:
  162. // update the previous tempBasal with endtime = starttime of the last event
  163. if let last: DoseEntry = result.popLast() {
  164. let value = max(
  165. 0,
  166. Double(event.timestamp.timeIntervalSince1970 - last.startDate.timeIntervalSince1970) / 3600
  167. ) *
  168. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  169. result.append(DoseEntry(
  170. type: .tempBasal,
  171. startDate: last.startDate,
  172. endDate: event.timestamp,
  173. value: value,
  174. unit: last.unit,
  175. deliveredUnits: value,
  176. syncIdentifier: last.syncIdentifier,
  177. // scheduledBasalRate: last.scheduledBasalRate,
  178. insulinType: last.insulinType,
  179. automatic: last.automatic,
  180. manuallyEntered: last.manuallyEntered
  181. ))
  182. }
  183. result.append(DoseEntry(
  184. type: .tempBasal,
  185. startDate: event.timestamp,
  186. value: 0.0,
  187. unit: .units,
  188. syncIdentifier: event.id,
  189. scheduledBasalRate: HKQuantity(unit: .internationalUnitsPerHour, doubleValue: Double(event.rate!)),
  190. insulinType: nil,
  191. automatic: true,
  192. manuallyEntered: false,
  193. isMutable: true
  194. ))
  195. case .tempBasalDuration:
  196. if let last: DoseEntry = result.popLast(),
  197. last.type == .tempBasal,
  198. last.startDate == event.timestamp
  199. {
  200. let durationMin = event.durationMin ?? 0
  201. // result.append(last)
  202. let value = (Double(durationMin) / 60.0) *
  203. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  204. result.append(DoseEntry(
  205. type: .tempBasal,
  206. startDate: last.startDate,
  207. endDate: Calendar.current.date(byAdding: .minute, value: durationMin, to: last.startDate) ?? last
  208. .startDate,
  209. value: value,
  210. unit: last.unit,
  211. deliveredUnits: value,
  212. syncIdentifier: last.syncIdentifier,
  213. scheduledBasalRate: last.scheduledBasalRate,
  214. insulinType: last.insulinType,
  215. automatic: last.automatic,
  216. manuallyEntered: last.manuallyEntered
  217. ))
  218. }
  219. default: break
  220. }
  221. return result
  222. }
  223. let boluses: [DoseEntry] = events.compactMap { event -> DoseEntry? in
  224. switch event.type {
  225. case .bolus:
  226. return DoseEntry(
  227. type: .bolus,
  228. startDate: event.timestamp,
  229. endDate: event.timestamp,
  230. value: Double(event.amount!),
  231. unit: .units,
  232. deliveredUnits: nil,
  233. syncIdentifier: event.id,
  234. scheduledBasalRate: nil,
  235. insulinType: nil,
  236. automatic: true,
  237. manuallyEntered: false
  238. )
  239. default: return nil
  240. }
  241. }
  242. let pumpEvents: [PersistedPumpEvent] = events.compactMap { event -> PersistedPumpEvent? in
  243. if let pumpEventType = event.type.mapEventTypeToPumpEventType() {
  244. let dose: DoseEntry? = switch pumpEventType {
  245. case .suspend:
  246. DoseEntry(suspendDate: event.timestamp, automatic: true)
  247. case .resume:
  248. DoseEntry(resumeDate: event.timestamp, automatic: true)
  249. default:
  250. nil
  251. }
  252. return PersistedPumpEvent(
  253. date: event.timestamp,
  254. persistedDate: event.timestamp,
  255. dose: dose,
  256. isUploaded: true,
  257. objectIDURL: URL(string: "x-coredata:///PumpEvent/\(event.id)")!,
  258. raw: event.id.data(using: .utf8),
  259. title: event.note,
  260. type: pumpEventType
  261. )
  262. } else {
  263. return nil
  264. }
  265. }
  266. processQueue.async {
  267. tidepoolService.uploadDoseData(created: doseDataBasal + boluses, deleted: []) { result in
  268. switch result {
  269. case let .failure(error):
  270. debug(.nightscout, "Error synchronizing Dose data: \(String(describing: error))")
  271. case .success:
  272. debug(.nightscout, "Success synchronizing Dose data:")
  273. }
  274. }
  275. tidepoolService.uploadPumpEventData(pumpEvents) { result in
  276. switch result {
  277. case let .failure(error):
  278. debug(.nightscout, "Error synchronizing Pump Event data: \(String(describing: error))")
  279. case .success:
  280. debug(.nightscout, "Success synchronizing Pump Event data:")
  281. }
  282. }
  283. }
  284. }
  285. func uploadGlucose(device: HKDevice?) {
  286. let glucose: [BloodGlucose] = glucoseStorage.recent()
  287. guard !glucose.isEmpty, let tidepoolService = self.tidepoolService else { return }
  288. let glucoseWithoutCorrectID = glucose.filter { UUID(uuidString: $0._id) != nil }
  289. processQueue.async {
  290. glucoseWithoutCorrectID.chunks(ofCount: tidepoolService.glucoseDataLimit ?? 100)
  291. .forEach { chunk in
  292. // all glucose attached with the current device ;-(
  293. let chunkStoreGlucose = Array(chunk).map {
  294. $0.convertStoredGlucoseSample(device: device)
  295. }
  296. tidepoolService.uploadGlucoseData(chunkStoreGlucose) { result in
  297. switch result {
  298. case let .failure(error):
  299. debug(.nightscout, "Error synchronizing glucose data: \(String(describing: error))")
  300. // self.uploadFailed(key)
  301. case .success:
  302. debug(.nightscout, "Success synchronizing glucose data:")
  303. }
  304. }
  305. }
  306. }
  307. }
  308. /// force to uploads all data in Tidepool Service
  309. func forceUploadData(device: HKDevice?) {
  310. uploadDose()
  311. uploadCarbs()
  312. uploadGlucose(device: device)
  313. }
  314. }
  315. extension BaseTidepoolManager: PumpHistoryObserver {
  316. func pumpHistoryDidUpdate(_: [PumpHistoryEvent]) {
  317. uploadDose()
  318. }
  319. }
  320. extension BaseTidepoolManager: CarbsObserver {
  321. func carbsDidUpdate(_: [CarbsEntry]) {
  322. uploadCarbs()
  323. }
  324. }
  325. extension BaseTidepoolManager: TempTargetsObserver {
  326. func tempTargetsDidUpdate(_: [TempTarget]) {}
  327. }
  328. extension BaseTidepoolManager: ServiceDelegate {
  329. var hostIdentifier: String {
  330. "com.loopkit.Loop" // To check
  331. }
  332. var hostVersion: String {
  333. var semanticVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
  334. while semanticVersion.split(separator: ".").count < 3 {
  335. semanticVersion += ".0"
  336. }
  337. semanticVersion += "+\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String)"
  338. return semanticVersion
  339. }
  340. func issueAlert(_: LoopKit.Alert) {}
  341. func retractAlert(identifier _: LoopKit.Alert.Identifier) {}
  342. func enactRemoteOverride(name _: String, durationTime _: TimeInterval?, remoteAddress _: String) async throws {}
  343. func cancelRemoteOverride() async throws {}
  344. func deliverRemoteCarbs(
  345. amountInGrams _: Double,
  346. absorptionTime _: TimeInterval?,
  347. foodType _: String?,
  348. startDate _: Date?
  349. ) async throws {}
  350. func deliverRemoteBolus(amountInUnits _: Double) async throws {}
  351. }
  352. extension BaseTidepoolManager: StatefulPluggableDelegate {
  353. func pluginDidUpdateState(_: LoopKit.StatefulPluggable) {}
  354. func pluginWantsDeletion(_: LoopKit.StatefulPluggable) {
  355. tidepoolService = nil
  356. }
  357. }
  358. // Service extension for rawValue
  359. extension Service {
  360. typealias RawValue = [String: Any]
  361. var rawValue: RawValue {
  362. [
  363. "serviceIdentifier": pluginIdentifier,
  364. "state": rawState
  365. ]
  366. }
  367. }