TidepoolManager.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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(withSyncId id: UUID, carbs: Decimal, at: Date, enteredBy: String)
  14. func uploadInsulin() async
  15. func deleteInsulin(withSyncId id: String, amount: Decimal, at: 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(withSyncId id: UUID, carbs: Decimal, at: Date, enteredBy: String) {
  142. guard let tidepoolService = self.tidepoolService else { return }
  143. processQueue.async {
  144. let syncCarb: [SyncCarbObject] = [SyncCarbObject(
  145. absorptionTime: nil,
  146. createdByCurrentApp: true,
  147. foodType: nil,
  148. grams: Double(carbs),
  149. startDate: at,
  150. uuid: id,
  151. provenanceIdentifier: enteredBy,
  152. syncIdentifier: id.uuidString,
  153. syncVersion: nil,
  154. userCreatedDate: nil,
  155. userUpdatedDate: nil,
  156. userDeletedDate: nil,
  157. operation: LoopKit.Operation.delete,
  158. addedDate: nil,
  159. supercededDate: nil
  160. )]
  161. tidepoolService.uploadCarbData(created: [], updated: [], deleted: syncCarb) { result in
  162. switch result {
  163. case let .failure(error):
  164. debug(.nightscout, "Error synchronizing carbs data: \(String(describing: error))")
  165. case .success:
  166. debug(.nightscout, "Success synchronizing carbs data.")
  167. }
  168. }
  169. }
  170. }
  171. func uploadInsulin() async {
  172. uploadDose(await pumpHistoryStorage.getPumpHistoryNotYetUploadedToTidepool())
  173. }
  174. func uploadDose(_ events: [PumpHistoryEvent]) {
  175. guard !events.isEmpty, let tidepoolService = self.tidepoolService else { return }
  176. let eventsBasal = events.filter { $0.type == .tempBasal || $0.type == .tempBasalDuration }
  177. .sorted { $0.timestamp < $1.timestamp }
  178. let doseDataBasal: [DoseEntry] = eventsBasal.reduce([]) { result, event in
  179. var result = result
  180. switch event.type {
  181. case .tempBasal:
  182. // update the previous tempBasal with endtime = starttime of the last event
  183. if let last: DoseEntry = result.popLast() {
  184. let value = max(
  185. 0,
  186. Double(event.timestamp.timeIntervalSince1970 - last.startDate.timeIntervalSince1970) / 3600
  187. ) *
  188. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  189. result.append(DoseEntry(
  190. type: .tempBasal,
  191. startDate: last.startDate,
  192. endDate: event.timestamp,
  193. value: value,
  194. unit: last.unit,
  195. deliveredUnits: value,
  196. syncIdentifier: last.syncIdentifier,
  197. insulinType: last.insulinType,
  198. automatic: last.automatic,
  199. manuallyEntered: last.manuallyEntered
  200. ))
  201. }
  202. result.append(DoseEntry(
  203. type: .tempBasal,
  204. startDate: event.timestamp,
  205. value: 0.0,
  206. unit: .units,
  207. syncIdentifier: event.id,
  208. scheduledBasalRate: HKQuantity(unit: .internationalUnitsPerHour, doubleValue: Double(event.amount!)),
  209. insulinType: nil,
  210. automatic: true,
  211. manuallyEntered: false,
  212. isMutable: true
  213. ))
  214. case .tempBasalDuration:
  215. if let last: DoseEntry = result.popLast(),
  216. last.type == .tempBasal,
  217. last.startDate == event.timestamp
  218. {
  219. let durationMin = event.durationMin ?? 0
  220. // result.append(last)
  221. let value = (Double(durationMin) / 60.0) *
  222. (last.scheduledBasalRate?.doubleValue(for: .internationalUnitsPerHour) ?? 0.0)
  223. result.append(DoseEntry(
  224. type: .tempBasal,
  225. startDate: last.startDate,
  226. endDate: Calendar.current.date(byAdding: .minute, value: durationMin, to: last.startDate) ?? last
  227. .startDate,
  228. value: value,
  229. unit: last.unit,
  230. deliveredUnits: value,
  231. syncIdentifier: last.syncIdentifier,
  232. scheduledBasalRate: last.scheduledBasalRate,
  233. insulinType: last.insulinType,
  234. automatic: last.automatic,
  235. manuallyEntered: last.manuallyEntered
  236. ))
  237. }
  238. default: break
  239. }
  240. return result
  241. }
  242. let boluses: [DoseEntry] = events.compactMap { event -> DoseEntry? in
  243. switch event.type {
  244. case .bolus:
  245. return DoseEntry(
  246. type: .bolus,
  247. startDate: event.timestamp,
  248. endDate: event.timestamp,
  249. value: Double(event.amount!),
  250. unit: .units,
  251. deliveredUnits: nil,
  252. syncIdentifier: event.id,
  253. scheduledBasalRate: nil,
  254. insulinType: nil,
  255. automatic: event.isSMB ?? true,
  256. manuallyEntered: event.isExternal ?? false
  257. )
  258. default: return nil
  259. }
  260. }
  261. let pumpEvents: [PersistedPumpEvent] = events.compactMap { event -> PersistedPumpEvent? in
  262. if let pumpEventType = event.type.mapEventTypeToPumpEventType() {
  263. let dose: DoseEntry? = switch pumpEventType {
  264. case .suspend:
  265. DoseEntry(suspendDate: event.timestamp, automatic: true)
  266. case .resume:
  267. DoseEntry(resumeDate: event.timestamp, automatic: true)
  268. default:
  269. nil
  270. }
  271. return PersistedPumpEvent(
  272. date: event.timestamp,
  273. persistedDate: event.timestamp,
  274. dose: dose,
  275. isUploaded: true,
  276. objectIDURL: URL(string: "x-coredata:///PumpEvent/\(event.id)")!,
  277. raw: event.id.data(using: .utf8),
  278. title: event.note,
  279. type: pumpEventType
  280. )
  281. } else {
  282. return nil
  283. }
  284. }
  285. processQueue.async {
  286. tidepoolService.uploadDoseData(created: doseDataBasal + boluses, deleted: []) { result in
  287. switch result {
  288. case let .failure(error):
  289. debug(.nightscout, "Error synchronizing Dose data: \(String(describing: error))")
  290. case .success:
  291. debug(.nightscout, "Success synchronizing Dose data")
  292. // After successful upload, update the isUploadedToTidepool flag in Core Data
  293. Task {
  294. let insulinEvents = events
  295. .filter {
  296. $0.type == .tempBasal || $0.type == .tempBasalDuration || $0.type == .bolus
  297. }
  298. await self.updateInsulinAsUploaded(insulinEvents)
  299. }
  300. }
  301. }
  302. tidepoolService.uploadPumpEventData(pumpEvents) { result in
  303. switch result {
  304. case let .failure(error):
  305. debug(.nightscout, "Error synchronizing Pump Event data: \(String(describing: error))")
  306. case .success:
  307. debug(.nightscout, "Success synchronizing Pump Event data")
  308. // After successful upload, update the isUploadedToTidepool flag in Core Data
  309. Task {
  310. let pumpEventType = events.map({ $0.type.mapEventTypeToPumpEventType()
  311. })
  312. let pumpEvents = events.filter { _ in pumpEventType.contains(pumpEventType) }
  313. await self.updateInsulinAsUploaded(pumpEvents)
  314. }
  315. }
  316. }
  317. }
  318. }
  319. private func updateInsulinAsUploaded(_ insulin: [PumpHistoryEvent]) async {
  320. await backgroundContext.perform {
  321. let ids = insulin.map(\.id) as NSArray
  322. let fetchRequest: NSFetchRequest<PumpEventStored> = PumpEventStored.fetchRequest()
  323. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  324. do {
  325. let results = try self.backgroundContext.fetch(fetchRequest)
  326. for result in results {
  327. result.isUploadedToHealth = true
  328. }
  329. guard self.backgroundContext.hasChanges else { return }
  330. try self.backgroundContext.save()
  331. } catch let error as NSError {
  332. debugPrint(
  333. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  334. )
  335. }
  336. }
  337. }
  338. func deleteInsulin(withSyncId id: String, amount: Decimal, at: Date) {
  339. guard let tidepoolService = self.tidepoolService else { return }
  340. // must be an array here, because `tidepoolService.uploadDoseData` expects a `deleted` array
  341. let doseDataToDelete: [DoseEntry] = [DoseEntry(
  342. type: .bolus,
  343. startDate: at,
  344. value: Double(amount),
  345. unit: .units,
  346. syncIdentifier: id
  347. )]
  348. processQueue.async {
  349. tidepoolService.uploadDoseData(created: [], deleted: doseDataToDelete) { result in
  350. switch result {
  351. case let .failure(error):
  352. debug(.nightscout, "Error synchronizing Dose delete data: \(String(describing: error))")
  353. case .success:
  354. debug(.nightscout, "Success synchronizing Dose delete data")
  355. }
  356. }
  357. }
  358. }
  359. func uploadGlucose(device: HKDevice?) async {
  360. // TODO: get correct glucose values
  361. let glucose: [BloodGlucose] = await glucoseStorage.getGlucoseNotYetUploadedToNightscout()
  362. guard !glucose.isEmpty, let tidepoolService = self.tidepoolService else { return }
  363. let glucoseWithoutCorrectID = glucose.filter { UUID(uuidString: $0._id ?? UUID().uuidString) != nil }
  364. let chunks = glucoseWithoutCorrectID.chunks(ofCount: tidepoolService.glucoseDataLimit ?? 100)
  365. processQueue.async {
  366. for chunk in chunks {
  367. // Link all glucose values with the current device
  368. let chunkStoreGlucose = chunk.map { $0.convertStoredGlucoseSample(device: device) }
  369. tidepoolService.uploadGlucoseData(chunkStoreGlucose) { result in
  370. switch result {
  371. case .success:
  372. debug(.nightscout, "Success synchronizing glucose data")
  373. // After successful upload, update the isUploadedToTidepool flag in Core Data
  374. Task {
  375. await self.updateGlucoseAsUploaded(glucose)
  376. }
  377. case let .failure(error):
  378. debug(.nightscout, "Error synchronizing glucose data: \(String(describing: error))")
  379. }
  380. }
  381. }
  382. }
  383. }
  384. private func updateGlucoseAsUploaded(_ glucose: [BloodGlucose]) async {
  385. await backgroundContext.perform {
  386. let ids = glucose.map(\.id) as NSArray
  387. let fetchRequest: NSFetchRequest<GlucoseStored> = GlucoseStored.fetchRequest()
  388. fetchRequest.predicate = NSPredicate(format: "id IN %@", ids)
  389. do {
  390. let results = try self.backgroundContext.fetch(fetchRequest)
  391. for result in results {
  392. result.isUploadedToHealth = true
  393. }
  394. guard self.backgroundContext.hasChanges else { return }
  395. try self.backgroundContext.save()
  396. } catch let error as NSError {
  397. debugPrint(
  398. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to update isUploadedToHealth: \(error.userInfo)"
  399. )
  400. }
  401. }
  402. }
  403. /// force to uploads all data in Tidepool Service
  404. func forceTidepoolDataUpload(device: HKDevice?) {
  405. Task {
  406. await uploadInsulin()
  407. await uploadCarbs()
  408. await uploadGlucose(device: device)
  409. }
  410. }
  411. }
  412. extension BaseTidepoolManager: TempTargetsObserver {
  413. func tempTargetsDidUpdate(_: [TempTarget]) {}
  414. }
  415. extension BaseTidepoolManager: ServiceDelegate {
  416. var hostIdentifier: String {
  417. // TODO: shouldn't this rather be `org.nightscout.Trio` ?
  418. "com.loopkit.Loop" // To check
  419. }
  420. var hostVersion: String {
  421. var semanticVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
  422. while semanticVersion.split(separator: ".").count < 3 {
  423. semanticVersion += ".0"
  424. }
  425. semanticVersion += "+\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String)"
  426. return semanticVersion
  427. }
  428. func issueAlert(_: LoopKit.Alert) {}
  429. func retractAlert(identifier _: LoopKit.Alert.Identifier) {}
  430. func enactRemoteOverride(name _: String, durationTime _: TimeInterval?, remoteAddress _: String) async throws {}
  431. func cancelRemoteOverride() async throws {}
  432. func deliverRemoteCarbs(
  433. amountInGrams _: Double,
  434. absorptionTime _: TimeInterval?,
  435. foodType _: String?,
  436. startDate _: Date?
  437. ) async throws {}
  438. func deliverRemoteBolus(amountInUnits _: Double) async throws {}
  439. }
  440. extension BaseTidepoolManager: StatefulPluggableDelegate {
  441. func pluginDidUpdateState(_: LoopKit.StatefulPluggable) {}
  442. func pluginWantsDeletion(_: LoopKit.StatefulPluggable) {
  443. tidepoolService = nil
  444. }
  445. }
  446. // Service extension for rawValue
  447. extension Service {
  448. typealias RawValue = [String: Any]
  449. var rawValue: RawValue {
  450. [
  451. "serviceIdentifier": pluginIdentifier,
  452. "state": rawState
  453. ]
  454. }
  455. }