TidepoolManager.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import HealthKit
  5. import LoopKit
  6. import LoopKitUI
  7. import Swinject
  8. protocol TidepoolManager {
  9. func addTidepoolService(service: Service)
  10. func getTidepoolServiceUI() -> ServiceUI?
  11. func getTidepoolPluginHost() -> PluginHost?
  12. func uploadCarbs() async
  13. func deleteCarbs(at date: Date, isFPU: Bool?, fpuID: String?, syncID: String)
  14. func uploadInsulin() async
  15. func deleteInsulin(at date: Date)
  16. func uploadGlucose(device: HKDevice?) async
  17. func forceTidepoolDataUpload(device: HKDevice?)
  18. }
  19. final class BaseTidepoolManager: TidepoolManager, Injectable, CarbsStoredDelegate, PumpHistoryDelegate {
  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. private var backgroundContext = CoreDataStack.shared.newTaskContext()
  37. func carbsStorageHasUpdatedCarbs(_: BaseCarbsStorage) {
  38. Task.detached { [weak self] in
  39. guard let self = self else { return }
  40. await self.uploadCarbs()
  41. }
  42. }
  43. func pumpHistoryHasUpdated(_: BasePumpHistoryStorage) {
  44. Task.detached { [weak self] in
  45. guard let self = self else { return }
  46. await self.uploadInsulin()
  47. }
  48. }
  49. @PersistedProperty(key: "TidepoolState") var rawTidepoolManager: Service.RawValue?
  50. init(resolver: Resolver) {
  51. injectServices(resolver)
  52. loadTidepoolManager()
  53. pumpHistoryStorage.delegate = self
  54. carbsStorage.delegate = self
  55. subscribe()
  56. }
  57. /// load the Tidepool Remote Data Service if available
  58. fileprivate func loadTidepoolManager() {
  59. if let rawTidepoolManager = rawTidepoolManager {
  60. tidepoolService = tidepoolServiceFromRaw(rawTidepoolManager)
  61. tidepoolService?.serviceDelegate = self
  62. tidepoolService?.stateDelegate = self
  63. }
  64. }
  65. /// allows access to tidepoolService as a simple ServiceUI
  66. func getTidepoolServiceUI() -> ServiceUI? {
  67. if let tidepoolService = self.tidepoolService {
  68. return tidepoolService as! any ServiceUI as ServiceUI
  69. } else {
  70. return nil
  71. }
  72. }
  73. /// get the pluginHost of Tidepool
  74. func getTidepoolPluginHost() -> PluginHost? {
  75. self as PluginHost
  76. }
  77. func addTidepoolService(service: Service) {
  78. tidepoolService = service as! any RemoteDataService as RemoteDataService
  79. }
  80. /// load the Tidepool Remote Data Service from raw storage
  81. private func tidepoolServiceFromRaw(_ rawValue: [String: Any]) -> RemoteDataService? {
  82. guard let rawState = rawValue["state"] as? Service.RawStateValue,
  83. let serviceType = pluginManager.getServiceTypeByIdentifier("TidepoolService")
  84. else {
  85. return nil
  86. }
  87. if let service = serviceType.init(rawState: rawState) {
  88. return service as! any RemoteDataService as RemoteDataService
  89. } else { return nil }
  90. }
  91. private func subscribe() {
  92. broadcaster.register(TempTargetsObserver.self, observer: self)
  93. }
  94. func sourceInfo() -> [String: Any]? {
  95. nil
  96. }
  97. func uploadCarbs() async {
  98. uploadCarbs(await carbsStorage.getCarbsNotYetUploadedToHealth())
  99. }
  100. func uploadCarbs(_ carbs: [CarbsEntry]) {
  101. guard !carbs.isEmpty, let tidepoolService = self.tidepoolService else { return }
  102. processQueue.async {
  103. carbs.chunks(ofCount: tidepoolService.carbDataLimit ?? 100).forEach { chunk in
  104. let syncCarb: [SyncCarbObject] = Array(chunk).map {
  105. $0.convertSyncCarb()
  106. }
  107. tidepoolService.uploadCarbData(created: syncCarb, updated: [], deleted: []) { result in
  108. switch result {
  109. case let .failure(error):
  110. debug(.nightscout, "Error synchronizing carbs data: \(String(describing: error))")
  111. case .success:
  112. debug(.nightscout, "Success synchronizing carbs data:")
  113. // After successful upload, update the isUploadedToTidepool flag in Core Data
  114. Task {
  115. await self.updateCarbsAsUploaded(carbs)
  116. }
  117. }
  118. }
  119. }
  120. }
  121. }
  122. private func updateCarbsAsUploaded(_ carbs: [CarbsEntry]) async {
  123. await backgroundContext.perform {
  124. let ids = carbs.map(\.id) as NSArray
  125. let fetchRequest: NSFetchRequest<CarbEntryStored> = CarbEntryStored.fetchRequest()
  126. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  127. do {
  128. let results = try self.backgroundContext.fetch(fetchRequest)
  129. for result in results {
  130. result.isUploadedToHealth = true
  131. }
  132. guard self.backgroundContext.hasChanges else { return }
  133. try self.backgroundContext.save()
  134. } catch let error as NSError {
  135. debugPrint(
  136. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  137. )
  138. }
  139. }
  140. }
  141. func deleteCarbs(at date: Date, isFPU: Bool?, fpuID: String?, syncID _: String) {
  142. guard let tidepoolService = self.tidepoolService else { return }
  143. processQueue.async {
  144. var carbsToDelete: [CarbsEntry] = []
  145. let allValues = self.storage.retrieve(OpenAPS.Monitor.carbHistory, as: [CarbsEntry].self) ?? []
  146. if let isFPU = isFPU, isFPU {
  147. guard let fpuID = fpuID else { return }
  148. carbsToDelete = allValues.filter { $0.fpuID == fpuID }.removeDublicates()
  149. } else {
  150. carbsToDelete = allValues.filter { $0.createdAt == date }.removeDublicates()
  151. }
  152. let syncCarb = carbsToDelete.map { d in
  153. d.convertSyncCarb(operation: .delete)
  154. }
  155. tidepoolService.uploadCarbData(created: [], updated: [], deleted: syncCarb) { result in
  156. switch result {
  157. case let .failure(error):
  158. debug(.nightscout, "Error synchronizing carbs data: \(String(describing: error))")
  159. case .success:
  160. debug(.nightscout, "Success synchronizing carbs data:")
  161. }
  162. }
  163. }
  164. }
  165. func uploadInsulin() async {
  166. uploadDose(await pumpHistoryStorage.getPumpHistoryNotYetUploadedToTidepool())
  167. }
  168. func uploadDose(_ events: [PumpHistoryEvent]) {
  169. guard !events.isEmpty, let tidepoolService = self.tidepoolService else { return }
  170. let eventsBasal = events.filter { $0.type == .tempBasal || $0.type == .tempBasalDuration }
  171. .sorted { $0.timestamp < $1.timestamp }
  172. let doseDataBasal: [DoseEntry] = eventsBasal.reduce([]) { result, event in
  173. var result = result
  174. switch event.type {
  175. case .tempBasal:
  176. // update the previous tempBasal with endtime = starttime of the last event
  177. if let last: DoseEntry = result.popLast() {
  178. let value = max(
  179. 0,
  180. Double(event.timestamp.timeIntervalSince1970 - last.startDate.timeIntervalSince1970) / 3600
  181. ) *
  182. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  183. result.append(DoseEntry(
  184. type: .tempBasal,
  185. startDate: last.startDate,
  186. endDate: event.timestamp,
  187. value: value,
  188. unit: last.unit,
  189. deliveredUnits: value,
  190. syncIdentifier: last.syncIdentifier,
  191. insulinType: last.insulinType,
  192. automatic: last.automatic,
  193. manuallyEntered: last.manuallyEntered
  194. ))
  195. }
  196. result.append(DoseEntry(
  197. type: .tempBasal,
  198. startDate: event.timestamp,
  199. value: 0.0,
  200. unit: .units,
  201. syncIdentifier: event.id,
  202. scheduledBasalRate: HKQuantity(unit: .internationalUnitsPerHour, doubleValue: Double(event.amount!)),
  203. insulinType: nil,
  204. automatic: true,
  205. manuallyEntered: false,
  206. isMutable: true
  207. ))
  208. case .tempBasalDuration:
  209. if let last: DoseEntry = result.popLast(),
  210. last.type == .tempBasal,
  211. last.startDate == event.timestamp
  212. {
  213. let durationMin = event.durationMin ?? 0
  214. // result.append(last)
  215. let value = (Double(durationMin) / 60.0) *
  216. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  217. result.append(DoseEntry(
  218. type: .tempBasal,
  219. startDate: last.startDate,
  220. endDate: Calendar.current.date(byAdding: .minute, value: durationMin, to: last.startDate) ?? last
  221. .startDate,
  222. value: value,
  223. unit: last.unit,
  224. deliveredUnits: value,
  225. syncIdentifier: last.syncIdentifier,
  226. scheduledBasalRate: last.scheduledBasalRate,
  227. insulinType: last.insulinType,
  228. automatic: last.automatic,
  229. manuallyEntered: last.manuallyEntered
  230. ))
  231. }
  232. default: break
  233. }
  234. return result
  235. }
  236. let boluses: [DoseEntry] = events.compactMap { event -> DoseEntry? in
  237. switch event.type {
  238. case .bolus:
  239. return DoseEntry(
  240. type: .bolus,
  241. startDate: event.timestamp,
  242. endDate: event.timestamp,
  243. value: Double(event.amount!),
  244. unit: .units,
  245. deliveredUnits: nil,
  246. syncIdentifier: event.id,
  247. scheduledBasalRate: nil,
  248. insulinType: nil,
  249. automatic: event.isSMB ?? true,
  250. manuallyEntered: event.isExternal ?? false
  251. )
  252. default: return nil
  253. }
  254. }
  255. let pumpEvents: [PersistedPumpEvent] = events.compactMap { event -> PersistedPumpEvent? in
  256. if let pumpEventType = event.type.mapEventTypeToPumpEventType() {
  257. let dose: DoseEntry? = switch pumpEventType {
  258. case .suspend:
  259. DoseEntry(suspendDate: event.timestamp, automatic: true)
  260. case .resume:
  261. DoseEntry(resumeDate: event.timestamp, automatic: true)
  262. default:
  263. nil
  264. }
  265. return PersistedPumpEvent(
  266. date: event.timestamp,
  267. persistedDate: event.timestamp,
  268. dose: dose,
  269. isUploaded: true,
  270. objectIDURL: URL(string: "x-coredata:///PumpEvent/\(event.id)")!,
  271. raw: event.id.data(using: .utf8),
  272. title: event.note,
  273. type: pumpEventType
  274. )
  275. } else {
  276. return nil
  277. }
  278. }
  279. processQueue.async {
  280. tidepoolService.uploadDoseData(created: doseDataBasal + boluses, deleted: []) { result in
  281. switch result {
  282. case let .failure(error):
  283. debug(.nightscout, "Error synchronizing Dose data: \(String(describing: error))")
  284. case .success:
  285. debug(.nightscout, "Success synchronizing Dose data:")
  286. // After successful upload, update the isUploadedToTidepool flag in Core Data
  287. Task {
  288. let insulinEvents = events
  289. .filter {
  290. $0.type == .tempBasal || $0.type == .tempBasalDuration || $0.type == .bolus
  291. }
  292. await self.updateInsulinAsUploaded(insulinEvents)
  293. }
  294. }
  295. }
  296. tidepoolService.uploadPumpEventData(pumpEvents) { result in
  297. switch result {
  298. case let .failure(error):
  299. debug(.nightscout, "Error synchronizing Pump Event data: \(String(describing: error))")
  300. case .success:
  301. debug(.nightscout, "Success synchronizing Pump Event data:")
  302. // After successful upload, update the isUploadedToTidepool flag in Core Data
  303. Task {
  304. let pumpEventType = events.map({ $0.type.mapEventTypeToPumpEventType()
  305. })
  306. let pumpEvents = events.filter { _ in pumpEventType.contains(pumpEventType) }
  307. await self.updateInsulinAsUploaded(pumpEvents)
  308. }
  309. }
  310. }
  311. }
  312. }
  313. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  314. await backgroundContext.perform {
  315. let ids = insulin.map(\.id) as NSArray
  316. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  317. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  318. do {
  319. let results = try self.backgroundContext.fetch(fetchRequest)
  320. for result in results {
  321. result.isUploadedToHealth = true
  322. }
  323. guard self.backgroundContext.hasChanges else { return }
  324. try self.backgroundContext.save()
  325. } catch let error as NSError {
  326. debugPrint(
  327. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  328. )
  329. }
  330. }
  331. }
  332. func deleteInsulin(at d: Date) {
  333. let allValues = storage.retrieve(OpenAPS.Monitor.pumpHistory, as: [PumpHistoryEvent].self) ?? []
  334. guard !allValues.isEmpty, let tidepoolService = self.tidepoolService else { return }
  335. var doseDataToDelete: [DoseEntry] = []
  336. guard let entry = allValues.first(where: { $0.timestamp == d }) else {
  337. return
  338. }
  339. doseDataToDelete
  340. .append(DoseEntry(
  341. type: .bolus,
  342. startDate: entry.timestamp,
  343. value: Double(entry.amount!),
  344. unit: .units,
  345. syncIdentifier: entry.id
  346. ))
  347. processQueue.async {
  348. tidepoolService.uploadDoseData(created: [], deleted: doseDataToDelete) { result in
  349. switch result {
  350. case let .failure(error):
  351. debug(.nightscout, "Error synchronizing Dose delete data: \(String(describing: error))")
  352. case .success:
  353. debug(.nightscout, "Success synchronizing Dose delete data:")
  354. }
  355. }
  356. }
  357. }
  358. func uploadGlucose(device: HKDevice?) async {
  359. // TODO: get correct glucose values
  360. let glucose: [BloodGlucose] = await glucoseStorage.getGlucoseNotYetUploadedToNightscout()
  361. guard !glucose.isEmpty, let tidepoolService = self.tidepoolService else { return }
  362. let glucoseWithoutCorrectID = glucose.filter { UUID(uuidString: $0._id ?? UUID().uuidString) != nil }
  363. let chunks = glucoseWithoutCorrectID.chunks(ofCount: tidepoolService.glucoseDataLimit ?? 100)
  364. processQueue.async {
  365. for chunk in chunks {
  366. // Link all glucose values with the current device
  367. let chunkStoreGlucose = chunk.map { $0.convertStoredGlucoseSample(device: device) }
  368. tidepoolService.uploadGlucoseData(chunkStoreGlucose) { result in
  369. switch result {
  370. case .success:
  371. debug(.nightscout, "Success synchronizing glucose data:")
  372. // After successful upload, update the isUploadedToTidepool flag in Core Data
  373. Task {
  374. await self.updateGlucoseAsUploaded(glucose)
  375. }
  376. case let .failure(error):
  377. debug(.nightscout, "Error synchronizing glucose data: \(String(describing: error))")
  378. }
  379. }
  380. }
  381. }
  382. }
  383. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  384. await backgroundContext.perform {
  385. let ids = glucose.map(\.id) as NSArray
  386. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  387. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  388. do {
  389. let results = try self.backgroundContext.fetch(fetchRequest)
  390. for result in results {
  391. result.isUploadedToHealth = true
  392. }
  393. guard self.backgroundContext.hasChanges else { return }
  394. try self.backgroundContext.save()
  395. } catch let error as NSError {
  396. debugPrint(
  397. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  398. )
  399. }
  400. }
  401. }
  402. /// force to uploads all data in Tidepool Service
  403. func forceTidepoolDataUpload(device: HKDevice?) {
  404. Task {
  405. await uploadInsulin()
  406. await uploadCarbs()
  407. await uploadGlucose(device: device)
  408. }
  409. }
  410. }
  411. extension BaseTidepoolManager: TempTargetsObserver {
  412. func tempTargetsDidUpdate(_: [TempTarget]) {}
  413. }
  414. extension BaseTidepoolManager: ServiceDelegate {
  415. var hostIdentifier: String {
  416. // TODO: shouldn't this rather be `org.nightscout.Trio` ?
  417. "com.loopkit.Loop" // To check
  418. }
  419. var hostVersion: String {
  420. var semanticVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
  421. while semanticVersion.split(separator: ".").count < 3 {
  422. semanticVersion += ".0"
  423. }
  424. semanticVersion += "+\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String)"
  425. return semanticVersion
  426. }
  427. func issueAlert(_: LoopKit.Alert) {}
  428. func retractAlert(identifier _: LoopKit.Alert.Identifier) {}
  429. func enactRemoteOverride(name _: String, durationTime _: TimeInterval?, remoteAddress _: String) async throws {}
  430. func cancelRemoteOverride() async throws {}
  431. func deliverRemoteCarbs(
  432. amountInGrams _: Double,
  433. absorptionTime _: TimeInterval?,
  434. foodType _: String?,
  435. startDate _: Date?
  436. ) async throws {}
  437. func deliverRemoteBolus(amountInUnits _: Double) async throws {}
  438. }
  439. extension BaseTidepoolManager: StatefulPluggableDelegate {
  440. func pluginDidUpdateState(_: LoopKit.StatefulPluggable) {}
  441. func pluginWantsDeletion(_: LoopKit.StatefulPluggable) {
  442. tidepoolService = nil
  443. }
  444. }
  445. // Service extension for rawValue
  446. extension Service {
  447. typealias RawValue = [String: Any]
  448. var rawValue: RawValue {
  449. [
  450. "serviceIdentifier": pluginIdentifier,
  451. "state": rawState
  452. ]
  453. }
  454. }