OpenAPS.swift 42 KB

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