OpenAPS.swift 50 KB

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