OpenAPS.swift 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. import Combine
  2. import CoreData
  3. import Foundation
  4. import JavaScriptCore
  5. final class OpenAPS {
  6. private let jsWorker = JavaScriptWorker()
  7. private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
  8. private let storage: FileStorage
  9. let context = CoreDataStack.shared.newTaskContext()
  10. let jsonConverter = JSONConverter()
  11. init(storage: FileStorage) {
  12. self.storage = storage
  13. }
  14. static let dateFormatter: ISO8601DateFormatter = {
  15. let formatter = ISO8601DateFormatter()
  16. formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  17. return formatter
  18. }()
  19. // Helper function to convert a Decimal? to NSDecimalNumber?
  20. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  21. guard let value = value else { return nil }
  22. return NSDecimalNumber(decimal: value)
  23. }
  24. // Use the helper function for cleaner code
  25. func processDetermination(_ determination: Determination) async {
  26. await context.perform {
  27. let newOrefDetermination = OrefDetermination(context: self.context)
  28. newOrefDetermination.id = UUID()
  29. newOrefDetermination.totalDailyDose = self.decimalToNSDecimalNumber(determination.tdd)
  30. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  31. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  32. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  33. newOrefDetermination.deliverAt = determination.deliverAt
  34. newOrefDetermination.insulinForManualBolus = self.decimalToNSDecimalNumber(determination.insulinForManualBolus)
  35. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  36. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  37. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  38. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  39. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  40. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  41. newOrefDetermination.reason = determination.reason
  42. newOrefDetermination.duration = self.decimalToNSDecimalNumber(determination.duration)
  43. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  44. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  45. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  46. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  47. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  48. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  49. newOrefDetermination.manualBolusErrorString = self.decimalToNSDecimalNumber(determination.manualBolusErrorString)
  50. newOrefDetermination.tempBasal = determination.insulin?.temp_basal.map { NSDecimalNumber(decimal: $0) }
  51. newOrefDetermination.scheduledBasal = determination.insulin?.scheduled_basal.map { NSDecimalNumber(decimal: $0) }
  52. newOrefDetermination.bolus = determination.insulin?.bolus.map { NSDecimalNumber(decimal: $0) }
  53. newOrefDetermination.smbToDeliver = determination.units.map { NSDecimalNumber(decimal: $0) }
  54. newOrefDetermination.carbsRequired = Int16(Int(determination.carbsReq ?? 0))
  55. newOrefDetermination.isUploadedToNS = false
  56. if let predictions = determination.predictions {
  57. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  58. .forEach { type, values in
  59. if let values = values {
  60. let forecast = Forecast(context: self.context)
  61. forecast.id = UUID()
  62. forecast.type = type
  63. forecast.date = Date()
  64. forecast.orefDetermination = newOrefDetermination
  65. for (index, value) in values.enumerated() {
  66. let forecastValue = ForecastValue(context: self.context)
  67. forecastValue.index = Int32(index)
  68. forecastValue.value = Int32(value)
  69. forecast.addToForecastValues(forecastValue)
  70. }
  71. newOrefDetermination.addToForecasts(forecast)
  72. }
  73. }
  74. }
  75. }
  76. // First save the current Determination to Core Data
  77. await attemptToSaveContext()
  78. // After that check for changes in iob and cob and if there are any post a custom Notification
  79. /// this is currently used to update Live Activity so that it stays up to date and not one loop cycle behind
  80. await checkForCobIobUpdate(determination)
  81. }
  82. func checkForCobIobUpdate(_ determination: Determination) async {
  83. let previousDeterminations = await CoreDataStack.shared.fetchEntitiesAsync(
  84. ofType: OrefDetermination.self,
  85. onContext: context,
  86. predicate: NSPredicate.predicateFor30MinAgoForDetermination,
  87. key: "deliverAt",
  88. ascending: false,
  89. fetchLimit: 2
  90. )
  91. // We need to get the second last Determination for this comparison because we have saved the current Determination already to Core Data
  92. if let previousDetermination = previousDeterminations.dropFirst().first {
  93. let iobChanged = previousDetermination.iob != decimalToNSDecimalNumber(determination.iob)
  94. let cobChanged = previousDetermination.cob != Int16(Int(determination.cob ?? 0))
  95. if iobChanged || cobChanged {
  96. Foundation.NotificationCenter.default.post(name: .didUpdateCobIob, object: nil)
  97. }
  98. }
  99. }
  100. func attemptToSaveContext() async {
  101. await context.perform {
  102. do {
  103. guard self.context.hasChanges else { return }
  104. try self.context.save()
  105. } catch {
  106. debugPrint("\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to save Determination to Core Data")
  107. }
  108. }
  109. }
  110. // fetch glucose to pass it to the meal function and to determine basal
  111. private func fetchAndProcessGlucose() async -> String {
  112. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  113. ofType: GlucoseStored.self,
  114. onContext: context,
  115. predicate: NSPredicate.predicateForOneDayAgoInMinutes,
  116. key: "date",
  117. ascending: false,
  118. fetchLimit: 72,
  119. batchSize: 24
  120. )
  121. return await context.perform {
  122. // convert to json
  123. return self.jsonConverter.convertToJSON(results)
  124. }
  125. }
  126. private func fetchAndProcessCarbs(additionalCarbs: Decimal? = nil) async -> String {
  127. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  128. ofType: CarbEntryStored.self,
  129. onContext: context,
  130. predicate: NSPredicate.predicateForOneDayAgo,
  131. key: "date",
  132. ascending: false
  133. )
  134. let json = await context.perform {
  135. var jsonArray = self.jsonConverter.convertToJSON(results)
  136. if let additionalCarbs = additionalCarbs {
  137. let additionalEntry = [
  138. "carbs": Double(additionalCarbs),
  139. "actualDate": ISO8601DateFormatter().string(from: Date()),
  140. "id": UUID().uuidString,
  141. "note": NSNull(),
  142. "protein": 0,
  143. "created_at": ISO8601DateFormatter().string(from: Date()),
  144. "isFPU": false,
  145. "fat": 0,
  146. "enteredBy": "Trio"
  147. ] as [String: Any]
  148. // Assuming jsonArray is a String, convert it to a list of dictionaries first
  149. if let jsonData = jsonArray.data(using: .utf8) {
  150. var jsonList = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [[String: Any]]
  151. jsonList?.append(additionalEntry)
  152. // Convert back to JSON string
  153. if let updatedJsonData = try? JSONSerialization
  154. .data(withJSONObject: jsonList ?? [], options: .prettyPrinted)
  155. {
  156. jsonArray = String(data: updatedJsonData, encoding: .utf8) ?? jsonArray
  157. }
  158. }
  159. }
  160. return jsonArray
  161. }
  162. return json
  163. }
  164. private func fetchPumpHistoryObjectIDs() async -> [NSManagedObjectID]? {
  165. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  166. ofType: PumpEventStored.self,
  167. onContext: context,
  168. predicate: NSPredicate.pumpHistoryLast1440Minutes,
  169. key: "timestamp",
  170. ascending: false,
  171. batchSize: 50
  172. )
  173. return await context.perform {
  174. return results.map(\.objectID)
  175. }
  176. }
  177. private func parsePumpHistory(_ pumpHistoryObjectIDs: [NSManagedObjectID], iob: Decimal? = nil) async -> String {
  178. // Return an empty JSON object if the list of object IDs is empty
  179. guard !pumpHistoryObjectIDs.isEmpty else { return "{}" }
  180. // Execute all operations on the background context
  181. return await context.perform {
  182. // Load and map pump events to DTOs
  183. var dtos = self.loadAndMapPumpEvents(pumpHistoryObjectIDs)
  184. // Optionally add the IOB as a DTO
  185. if let iob = iob {
  186. let iobDTO = self.createIOBDTO(iob: iob)
  187. dtos.insert(iobDTO, at: 0)
  188. }
  189. // Convert the DTOs to JSON
  190. return self.jsonConverter.convertToJSON(dtos)
  191. }
  192. }
  193. private func loadAndMapPumpEvents(_ pumpHistoryObjectIDs: [NSManagedObjectID]) -> [PumpEventDTO] {
  194. // Load the pump events from the object IDs
  195. let pumpHistory: [PumpEventStored] = pumpHistoryObjectIDs
  196. .compactMap { self.context.object(with: $0) as? PumpEventStored }
  197. // Create the DTOs
  198. let dtos: [PumpEventDTO] = pumpHistory.flatMap { event -> [PumpEventDTO] in
  199. var eventDTOs: [PumpEventDTO] = []
  200. if let bolusDTO = event.toBolusDTOEnum() {
  201. eventDTOs.append(bolusDTO)
  202. }
  203. if let tempBasalDTO = event.toTempBasalDTOEnum() {
  204. eventDTOs.append(tempBasalDTO)
  205. }
  206. if let tempBasalDurationDTO = event.toTempBasalDurationDTOEnum() {
  207. eventDTOs.append(tempBasalDurationDTO)
  208. }
  209. return eventDTOs
  210. }
  211. return dtos
  212. }
  213. private func createIOBDTO(iob: Decimal) -> PumpEventDTO {
  214. let oneSecondAgo = Calendar.current
  215. .date(
  216. byAdding: .second,
  217. value: -1,
  218. to: Date()
  219. )! // adding -1s to the current Date ensures that oref actually uses the mock entry to calculate iob and not guard it away
  220. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneSecondAgo)
  221. let bolusDTO = BolusDTO(
  222. id: UUID().uuidString,
  223. timestamp: dateFormatted,
  224. amount: Double(iob),
  225. isExternal: false,
  226. isSMB: true,
  227. duration: 0,
  228. _type: "Bolus"
  229. )
  230. return .bolus(bolusDTO)
  231. }
  232. func determineBasal(
  233. currentTemp: TempBasal,
  234. clock: Date = Date(),
  235. carbs: Decimal? = nil,
  236. iob: Decimal? = nil,
  237. simulation: Bool = false
  238. ) async throws -> Determination? {
  239. debug(.openAPS, "Start determineBasal")
  240. // temp_basal
  241. let tempBasal = currentTemp.rawJSON
  242. // Perform asynchronous calls in parallel
  243. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  244. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs ?? 0)
  245. async let glucose = fetchAndProcessGlucose()
  246. async let oref2 = oref2()
  247. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  248. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  249. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  250. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  251. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  252. // Await the results of asynchronous tasks
  253. let (
  254. pumpHistoryJSON,
  255. carbsAsJSON,
  256. glucoseAsJSON,
  257. oref2_variables,
  258. profile,
  259. basalProfile,
  260. autosens,
  261. reservoir,
  262. preferences
  263. ) = await (
  264. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  265. carbs,
  266. glucose,
  267. oref2,
  268. profileAsync,
  269. basalAsync,
  270. autosenseAsync,
  271. reservoirAsync,
  272. preferencesAsync
  273. )
  274. // Meal calculation
  275. let meal = try await self.meal(
  276. pumphistory: pumpHistoryJSON,
  277. profile: profile,
  278. basalProfile: basalProfile,
  279. clock: clock,
  280. carbs: carbsAsJSON,
  281. glucose: glucoseAsJSON
  282. )
  283. // IOB calculation
  284. let iob = try await self.iob(
  285. pumphistory: pumpHistoryJSON,
  286. profile: profile,
  287. clock: clock,
  288. autosens: autosens.isEmpty ? .null : autosens
  289. )
  290. // TODO: refactor this to core data
  291. if !simulation {
  292. storage.save(iob, as: Monitor.iob)
  293. }
  294. // Determine basal
  295. let orefDetermination = try await determineBasal(
  296. glucose: glucoseAsJSON,
  297. currentTemp: tempBasal,
  298. iob: iob,
  299. profile: profile,
  300. autosens: autosens.isEmpty ? .null : autosens,
  301. meal: meal,
  302. microBolusAllowed: true,
  303. reservoir: reservoir,
  304. pumpHistory: pumpHistoryJSON,
  305. preferences: preferences,
  306. basalProfile: basalProfile,
  307. oref2_variables: oref2_variables
  308. )
  309. debug(.openAPS, "Determinated: \(orefDetermination)")
  310. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  311. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  312. // AAPS does it the same way! we'll follow their example!
  313. determination.timestamp = deliverAt
  314. if !simulation {
  315. // save to core data asynchronously
  316. await processDetermination(determination)
  317. }
  318. return determination
  319. } else {
  320. return nil
  321. }
  322. }
  323. func oref2() async -> RawJSON {
  324. await context.perform {
  325. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  326. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  327. let wp = preferences?.weightPercentage ?? 1
  328. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  329. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  330. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  331. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  332. var uniqueEvents = [OrefDetermination]()
  333. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<OrefDetermination>
  334. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  335. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  336. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  337. requestTDD.sortDescriptors = [sortTDD]
  338. try? uniqueEvents = self.context.fetch(requestTDD)
  339. var sliderArray = [TempTargetsSlider]()
  340. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  341. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  342. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  343. // requestIsEnbled.fetchLimit = 1
  344. try? sliderArray = self.context.fetch(requestIsEnbled)
  345. /// Get the last active Override as only this information is apparently used in oref2
  346. var overrideArray = [OverrideStored]()
  347. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  348. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  349. requestOverrides.sortDescriptors = [sortOverride]
  350. requestOverrides.predicate = NSPredicate.lastActiveOverride
  351. requestOverrides.fetchLimit = 1
  352. try? overrideArray = self.context.fetch(requestOverrides)
  353. var tempTargetsArray = [TempTargets]()
  354. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  355. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  356. requestTempTargets.sortDescriptors = [sortTT]
  357. requestTempTargets.fetchLimit = 1
  358. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  359. let total = uniqueEvents.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  360. var indeces = uniqueEvents.count
  361. // Only fetch once. Use same (previous) fetch
  362. let twoHoursArray = uniqueEvents.filter({ ($0.timestamp ?? Date()) >= twoHoursAgo })
  363. var nrOfIndeces = twoHoursArray.count
  364. let totalAmount = twoHoursArray.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  365. var temptargetActive = tempTargetsArray.first?.active ?? false
  366. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  367. var useOverride = overrideArray.first?.enabled ?? false
  368. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  369. var unlimited = overrideArray.first?.indefinite ?? true
  370. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  371. let currentTDD = (uniqueEvents.last?.totalDailyDose ?? 0) as Decimal
  372. if indeces == 0 {
  373. indeces = 1
  374. }
  375. if nrOfIndeces == 0 {
  376. nrOfIndeces = 1
  377. }
  378. let average2hours = totalAmount / Decimal(nrOfIndeces)
  379. let average14 = total / Decimal(indeces)
  380. let weight = wp
  381. let weighted_average = weight * average2hours + (1 - weight) * average14
  382. var duration: Decimal = 0
  383. var newDuration: Decimal = 0
  384. var overrideTarget: Decimal = 0
  385. if useOverride {
  386. duration = (overrideArray.first?.duration ?? 0) as Decimal
  387. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  388. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  389. let addedMinutes = Int(duration)
  390. let date = overrideArray.first?.date ?? Date()
  391. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  392. !unlimited
  393. {
  394. useOverride = false
  395. let saveToCoreData = OverrideStored(context: self.context)
  396. saveToCoreData.enabled = false
  397. saveToCoreData.date = Date()
  398. saveToCoreData.duration = 0
  399. saveToCoreData.indefinite = false
  400. saveToCoreData.percentage = 100
  401. do {
  402. guard self.context.hasChanges else { return "{}" }
  403. try self.context.save()
  404. } catch {
  405. print(error.localizedDescription)
  406. }
  407. }
  408. }
  409. if !useOverride {
  410. unlimited = true
  411. overridePercentage = 100
  412. duration = 0
  413. overrideTarget = 0
  414. disableSMBs = false
  415. }
  416. if temptargetActive {
  417. var duration_ = 0
  418. var hbt = Double(hbt_)
  419. var dd = 0.0
  420. if temptargetActive {
  421. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  422. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  423. let startDate = tempTargetsArray.first?.startDate ?? Date()
  424. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  425. dd = durationPlusStart.timeIntervalSinceNow.minutes
  426. if dd > 0.1 {
  427. hbt_ = Decimal(hbt)
  428. temptargetActive = true
  429. } else {
  430. temptargetActive = false
  431. }
  432. }
  433. }
  434. if currentTDD > 0 {
  435. let averages = Oref2_variables(
  436. average_total_data: average14,
  437. weightedAverage: weighted_average,
  438. past2hoursAverage: average2hours,
  439. date: Date(),
  440. isEnabled: temptargetActive,
  441. presetActive: isPercentageEnabled,
  442. overridePercentage: overridePercentage,
  443. useOverride: useOverride,
  444. duration: duration,
  445. unlimited: unlimited,
  446. hbt: hbt_,
  447. overrideTarget: overrideTarget,
  448. smbIsOff: disableSMBs,
  449. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  450. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  451. isf: overrideArray.first?.isf ?? false,
  452. cr: overrideArray.first?.cr ?? false,
  453. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  454. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  455. )
  456. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  457. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  458. } else {
  459. let averages = Oref2_variables(
  460. average_total_data: 0,
  461. weightedAverage: 1,
  462. past2hoursAverage: 0,
  463. date: Date(),
  464. isEnabled: temptargetActive,
  465. presetActive: isPercentageEnabled,
  466. overridePercentage: overridePercentage,
  467. useOverride: useOverride,
  468. duration: duration,
  469. unlimited: unlimited,
  470. hbt: hbt_,
  471. overrideTarget: overrideTarget,
  472. smbIsOff: disableSMBs,
  473. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  474. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  475. isf: overrideArray.first?.isf ?? false,
  476. cr: overrideArray.first?.cr ?? false,
  477. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  478. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  479. )
  480. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  481. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  482. }
  483. }
  484. }
  485. func autosense() async throws -> Autosens? {
  486. debug(.openAPS, "Start autosens")
  487. // Perform asynchronous calls in parallel
  488. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  489. async let carbs = fetchAndProcessCarbs()
  490. async let glucose = fetchAndProcessGlucose()
  491. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  492. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  493. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  494. // Await the results of asynchronous tasks
  495. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  496. parsePumpHistory(await pumpHistoryObjectIDs),
  497. carbs,
  498. glucose,
  499. getProfile,
  500. getBasalProfile,
  501. getTempTargets
  502. )
  503. // Autosense
  504. let autosenseResult = try await autosense(
  505. glucose: glucoseAsJSON,
  506. pumpHistory: pumpHistoryJSON,
  507. basalprofile: basalProfile,
  508. profile: profile,
  509. carbs: carbsAsJSON,
  510. temptargets: tempTargets
  511. )
  512. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  513. if var autosens = Autosens(from: autosenseResult) {
  514. autosens.timestamp = Date()
  515. await storage.saveAsync(autosens, as: Settings.autosense)
  516. return autosens
  517. } else {
  518. return nil
  519. }
  520. }
  521. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  522. debug(.openAPS, "Start autotune")
  523. // Perform asynchronous calls in parallel
  524. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  525. async let carbs = fetchAndProcessCarbs()
  526. async let glucose = fetchAndProcessGlucose()
  527. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  528. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  529. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  530. // Await the results of asynchronous tasks
  531. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  532. parsePumpHistory(await pumpHistoryObjectIDs),
  533. carbs,
  534. glucose,
  535. getProfile,
  536. getPumpProfile,
  537. getPreviousAutotune
  538. )
  539. // Error need to be handled here because the function is not declared as throws
  540. do {
  541. // Autotune Prepare
  542. let autotunePreppedGlucose = try await autotunePrepare(
  543. pumphistory: pumpHistoryJSON,
  544. profile: profile,
  545. glucose: glucoseAsJSON,
  546. pumpprofile: pumpProfile,
  547. carbs: carbsAsJSON,
  548. categorizeUamAsBasal: categorizeUamAsBasal,
  549. tuneInsulinCurve: tuneInsulinCurve
  550. )
  551. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  552. // Autotune Run
  553. let autotuneResult = try await autotuneRun(
  554. autotunePreparedData: autotunePreppedGlucose,
  555. previousAutotuneResult: previousAutotune ?? profile,
  556. pumpProfile: pumpProfile
  557. )
  558. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  559. if let autotune = Autotune(from: autotuneResult) {
  560. storage.save(autotuneResult, as: Settings.autotune)
  561. return autotune
  562. } else {
  563. return nil
  564. }
  565. } catch {
  566. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  567. return nil
  568. }
  569. }
  570. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  571. debug(.openAPS, "Start makeProfiles")
  572. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  573. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  574. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  575. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  576. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  577. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  578. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  579. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  580. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  581. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  582. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  583. getPreferences,
  584. getPumpSettings,
  585. getBGTargets,
  586. getBasalProfile,
  587. getISF,
  588. getCR,
  589. getTempTargets,
  590. getModel,
  591. getAutotune,
  592. getFreeAPS
  593. )
  594. var adjustedPreferences = preferences
  595. if adjustedPreferences.isEmpty {
  596. adjustedPreferences = Preferences().rawJSON
  597. }
  598. do {
  599. // Pump Profile
  600. let pumpProfile = try await makeProfile(
  601. preferences: adjustedPreferences,
  602. pumpSettings: pumpSettings,
  603. bgTargets: bgTargets,
  604. basalProfile: basalProfile,
  605. isf: isf,
  606. carbRatio: cr,
  607. tempTargets: tempTargets,
  608. model: model,
  609. autotune: RawJSON.null,
  610. freeaps: freeaps
  611. )
  612. // Profile
  613. let profile = try await makeProfile(
  614. preferences: adjustedPreferences,
  615. pumpSettings: pumpSettings,
  616. bgTargets: bgTargets,
  617. basalProfile: basalProfile,
  618. isf: isf,
  619. carbRatio: cr,
  620. tempTargets: tempTargets,
  621. model: model,
  622. autotune: autotune.isEmpty ? .null : autotune,
  623. freeaps: freeaps
  624. )
  625. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  626. await storage.saveAsync(profile, as: Settings.profile)
  627. if let tunedProfile = Autotune(from: profile) {
  628. return tunedProfile
  629. } else {
  630. return nil
  631. }
  632. } catch {
  633. debug(
  634. .apsManager,
  635. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  636. )
  637. return nil
  638. }
  639. }
  640. // MARK: - Private
  641. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  642. await withCheckedContinuation { continuation in
  643. jsWorker.inCommonContext { worker in
  644. worker.evaluateBatch(scripts: [
  645. Script(name: Prepare.log),
  646. Script(name: Bundle.iob),
  647. Script(name: Prepare.iob)
  648. ])
  649. let result = worker.call(function: Function.generate, with: [
  650. pumphistory,
  651. profile,
  652. clock,
  653. autosens
  654. ])
  655. continuation.resume(returning: result)
  656. }
  657. }
  658. }
  659. private func meal(
  660. pumphistory: JSON,
  661. profile: JSON,
  662. basalProfile: JSON,
  663. clock: JSON,
  664. carbs: JSON,
  665. glucose: JSON
  666. ) async throws -> RawJSON {
  667. try await withCheckedThrowingContinuation { continuation in
  668. jsWorker.inCommonContext { worker in
  669. worker.evaluateBatch(scripts: [
  670. Script(name: Prepare.log),
  671. Script(name: Bundle.meal),
  672. Script(name: Prepare.meal)
  673. ])
  674. let result = worker.call(function: Function.generate, with: [
  675. pumphistory,
  676. profile,
  677. clock,
  678. glucose,
  679. basalProfile,
  680. carbs
  681. ])
  682. continuation.resume(returning: result)
  683. }
  684. }
  685. }
  686. private func autosense(
  687. glucose: JSON,
  688. pumpHistory: JSON,
  689. basalprofile: JSON,
  690. profile: JSON,
  691. carbs: JSON,
  692. temptargets: JSON
  693. ) async throws -> RawJSON {
  694. try await withCheckedThrowingContinuation { continuation in
  695. jsWorker.inCommonContext { worker in
  696. worker.evaluateBatch(scripts: [
  697. Script(name: Prepare.log),
  698. Script(name: Bundle.autosens),
  699. Script(name: Prepare.autosens)
  700. ])
  701. let result = worker.call(function: Function.generate, with: [
  702. glucose,
  703. pumpHistory,
  704. basalprofile,
  705. profile,
  706. carbs,
  707. temptargets
  708. ])
  709. continuation.resume(returning: result)
  710. }
  711. }
  712. }
  713. private func autotunePrepare(
  714. pumphistory: JSON,
  715. profile: JSON,
  716. glucose: JSON,
  717. pumpprofile: JSON,
  718. carbs: JSON,
  719. categorizeUamAsBasal: Bool,
  720. tuneInsulinCurve: Bool
  721. ) async throws -> RawJSON {
  722. try await withCheckedThrowingContinuation { continuation in
  723. jsWorker.inCommonContext { worker in
  724. worker.evaluateBatch(scripts: [
  725. Script(name: Prepare.log),
  726. Script(name: Bundle.autotunePrep),
  727. Script(name: Prepare.autotunePrep)
  728. ])
  729. let result = worker.call(function: Function.generate, with: [
  730. pumphistory,
  731. profile,
  732. glucose,
  733. pumpprofile,
  734. carbs,
  735. categorizeUamAsBasal,
  736. tuneInsulinCurve
  737. ])
  738. continuation.resume(returning: result)
  739. }
  740. }
  741. }
  742. private func autotuneRun(
  743. autotunePreparedData: JSON,
  744. previousAutotuneResult: JSON,
  745. pumpProfile: JSON
  746. ) async throws -> RawJSON {
  747. try await withCheckedThrowingContinuation { continuation in
  748. jsWorker.inCommonContext { worker in
  749. worker.evaluateBatch(scripts: [
  750. Script(name: Prepare.log),
  751. Script(name: Bundle.autotuneCore),
  752. Script(name: Prepare.autotuneCore)
  753. ])
  754. let result = worker.call(function: Function.generate, with: [
  755. autotunePreparedData,
  756. previousAutotuneResult,
  757. pumpProfile
  758. ])
  759. continuation.resume(returning: result)
  760. }
  761. }
  762. }
  763. private func determineBasal(
  764. glucose: JSON,
  765. currentTemp: JSON,
  766. iob: JSON,
  767. profile: JSON,
  768. autosens: JSON,
  769. meal: JSON,
  770. microBolusAllowed: Bool,
  771. reservoir: JSON,
  772. pumpHistory: JSON,
  773. preferences: JSON,
  774. basalProfile: JSON,
  775. oref2_variables: JSON
  776. ) async throws -> RawJSON {
  777. try await withCheckedThrowingContinuation { continuation in
  778. jsWorker.inCommonContext { worker in
  779. worker.evaluateBatch(scripts: [
  780. Script(name: Prepare.log),
  781. Script(name: Prepare.determineBasal),
  782. Script(name: Bundle.basalSetTemp),
  783. Script(name: Bundle.getLastGlucose),
  784. Script(name: Bundle.determineBasal)
  785. ])
  786. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  787. worker.evaluate(script: middleware)
  788. }
  789. let result = worker.call(function: Function.generate, with: [
  790. iob,
  791. currentTemp,
  792. glucose,
  793. profile,
  794. autosens,
  795. meal,
  796. microBolusAllowed,
  797. reservoir,
  798. Date(),
  799. pumpHistory,
  800. preferences,
  801. basalProfile,
  802. oref2_variables
  803. ])
  804. continuation.resume(returning: result)
  805. }
  806. }
  807. }
  808. private func exportDefaultPreferences() -> RawJSON {
  809. dispatchPrecondition(condition: .onQueue(processQueue))
  810. return jsWorker.inCommonContext { worker in
  811. worker.evaluateBatch(scripts: [
  812. Script(name: Prepare.log),
  813. Script(name: Bundle.profile),
  814. Script(name: Prepare.profile)
  815. ])
  816. return worker.call(function: Function.exportDefaults, with: [])
  817. }
  818. }
  819. private func makeProfile(
  820. preferences: JSON,
  821. pumpSettings: JSON,
  822. bgTargets: JSON,
  823. basalProfile: JSON,
  824. isf: JSON,
  825. carbRatio: JSON,
  826. tempTargets: JSON,
  827. model: JSON,
  828. autotune: JSON,
  829. freeaps: JSON
  830. ) async throws -> RawJSON {
  831. try await withCheckedThrowingContinuation { continuation in
  832. jsWorker.inCommonContext { worker in
  833. worker.evaluateBatch(scripts: [
  834. Script(name: Prepare.log),
  835. Script(name: Bundle.profile),
  836. Script(name: Prepare.profile)
  837. ])
  838. let result = worker.call(function: Function.generate, with: [
  839. pumpSettings,
  840. bgTargets,
  841. isf,
  842. basalProfile,
  843. preferences,
  844. carbRatio,
  845. tempTargets,
  846. model,
  847. autotune,
  848. freeaps
  849. ])
  850. continuation.resume(returning: result)
  851. }
  852. }
  853. }
  854. private func loadJSON(name: String) -> String {
  855. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  856. }
  857. private func loadFileFromStorage(name: String) -> RawJSON {
  858. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  859. }
  860. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  861. await withCheckedContinuation { continuation in
  862. DispatchQueue.global(qos: .userInitiated).async {
  863. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  864. continuation.resume(returning: result)
  865. }
  866. }
  867. }
  868. private func middlewareScript(name: String) -> Script? {
  869. if let body = storage.retrieveRaw(name) {
  870. return Script(name: "Middleware", body: body)
  871. }
  872. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  873. return Script(name: "Middleware", body: try! String(contentsOf: url))
  874. }
  875. return nil
  876. }
  877. static func defaults(for file: String) -> RawJSON {
  878. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  879. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  880. return ""
  881. }
  882. return (try? String(contentsOf: url)) ?? ""
  883. }
  884. func processAndSave(forecastData: [String: [Int]]) {
  885. let currentDate = Date()
  886. context.perform {
  887. for (type, values) in forecastData {
  888. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  889. }
  890. do {
  891. guard self.context.hasChanges else { return }
  892. try self.context.save()
  893. } catch {
  894. print(error.localizedDescription)
  895. }
  896. }
  897. }
  898. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  899. let forecast = Forecast(context: context)
  900. forecast.id = UUID()
  901. forecast.date = date
  902. forecast.type = type
  903. for (index, value) in values.enumerated() {
  904. let forecastValue = ForecastValue(context: context)
  905. forecastValue.value = Int32(value)
  906. forecastValue.index = Int32(index)
  907. forecastValue.forecast = forecast
  908. }
  909. }
  910. }