OpenAPS.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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.predicateForSixHoursAgo,
  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. var 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 var 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.pumpHistoryLast24h,
  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 oneMinuteAgo = Calendar.current.date(byAdding: .minute, value: -1, to: Date())! // this ensures that oref actually uses the mock entry to calculate iob
  215. let dateFormatted = PumpEventStored.dateFormatter.string(from: oneMinuteAgo)
  216. let bolusDTO = BolusDTO(
  217. id: UUID().uuidString,
  218. timestamp: dateFormatted,
  219. amount: Double(iob),
  220. isExternal: false,
  221. isSMB: true,
  222. duration: 0,
  223. _type: "Bolus"
  224. )
  225. return .bolus(bolusDTO)
  226. }
  227. func simulateDetermineBasal(
  228. currentTemp: TempBasal,
  229. clock: Date = Date(),
  230. carbs: Decimal,
  231. iob: Decimal
  232. ) async throws -> Determination? {
  233. debug(.openAPS, "Start determineBasal")
  234. // clock
  235. let dateFormatted = OpenAPS.dateFormatter.string(from: clock)
  236. let dateFormattedAsString = "\"\(dateFormatted)\""
  237. // temp_basal
  238. let tempBasal = currentTemp.rawJSON
  239. // Perform asynchronous calls in parallel
  240. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  241. async let carbs = fetchAndProcessCarbs(additionalCarbs: carbs)
  242. async let glucose = fetchAndProcessGlucose()
  243. async let oref2 = oref2()
  244. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  245. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  246. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  247. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  248. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  249. // Await the results of asynchronous tasks
  250. let (
  251. pumpHistoryJSON,
  252. carbsAsJSON,
  253. glucoseAsJSON,
  254. oref2_variables,
  255. profile,
  256. basalProfile,
  257. autosens,
  258. reservoir,
  259. preferences
  260. ) = await (
  261. parsePumpHistory(await pumpHistoryObjectIDs, iob: iob),
  262. carbs,
  263. glucose,
  264. oref2,
  265. profileAsync,
  266. basalAsync,
  267. autosenseAsync,
  268. reservoirAsync,
  269. preferencesAsync
  270. )
  271. // print("carbs: \(carbsAsJSON)")
  272. // Meal
  273. let meal = try await self.meal(
  274. pumphistory: pumpHistoryJSON,
  275. profile: profile,
  276. basalProfile: basalProfile,
  277. clock: dateFormattedAsString,
  278. carbs: carbsAsJSON,
  279. glucose: glucoseAsJSON
  280. )
  281. // IOB
  282. let iob = try await self.iob(
  283. pumphistory: pumpHistoryJSON,
  284. profile: profile,
  285. clock: dateFormattedAsString,
  286. autosens: autosens.isEmpty ? .null : autosens
  287. )
  288. // print("pumphistory : \(pumpHistoryJSON)")
  289. print("iob: \(iob)")
  290. // print("profile: \(profile)")
  291. // Determine basal
  292. let orefDetermination = try await determineBasal(
  293. glucose: glucoseAsJSON,
  294. currentTemp: tempBasal,
  295. iob: iob,
  296. profile: profile,
  297. autosens: autosens.isEmpty ? .null : autosens,
  298. meal: meal,
  299. microBolusAllowed: true,
  300. reservoir: reservoir,
  301. pumpHistory: pumpHistoryJSON,
  302. preferences: preferences,
  303. basalProfile: basalProfile,
  304. oref2_variables: oref2_variables
  305. )
  306. // debug(.openAPS, "oref 2 scheiß: \(oref2_variables)")
  307. debug(.openAPS, "Determinated: \(orefDetermination)")
  308. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  309. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  310. // AAPS does it the same way! we'll follow their example!
  311. determination.timestamp = deliverAt
  312. return determination
  313. } else {
  314. return nil
  315. }
  316. }
  317. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) async throws -> Determination? {
  318. debug(.openAPS, "Start determineBasal")
  319. // clock
  320. let dateFormatted = OpenAPS.dateFormatter.string(from: clock)
  321. let dateFormattedAsString = "\"\(dateFormatted)\""
  322. // temp_basal
  323. let tempBasal = currentTemp.rawJSON
  324. // Perform asynchronous calls in parallel
  325. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  326. async let carbs = fetchAndProcessCarbs()
  327. async let glucose = fetchAndProcessGlucose()
  328. async let oref2 = oref2()
  329. async let profileAsync = loadFileFromStorageAsync(name: Settings.profile)
  330. async let basalAsync = loadFileFromStorageAsync(name: Settings.basalProfile)
  331. async let autosenseAsync = loadFileFromStorageAsync(name: Settings.autosense)
  332. async let reservoirAsync = loadFileFromStorageAsync(name: Monitor.reservoir)
  333. async let preferencesAsync = loadFileFromStorageAsync(name: Settings.preferences)
  334. // Await the results of asynchronous tasks
  335. let (
  336. pumpHistoryJSON,
  337. carbsAsJSON,
  338. glucoseAsJSON,
  339. oref2_variables,
  340. profile,
  341. basalProfile,
  342. autosens,
  343. reservoir,
  344. preferences
  345. ) = await (
  346. parsePumpHistory(await pumpHistoryObjectIDs),
  347. carbs,
  348. glucose,
  349. oref2,
  350. profileAsync,
  351. basalAsync,
  352. autosenseAsync,
  353. reservoirAsync,
  354. preferencesAsync
  355. )
  356. // TODO: - Save and fetch profile/basalProfile in/from UserDefaults!
  357. // Meal
  358. let meal = try await self.meal(
  359. pumphistory: pumpHistoryJSON,
  360. profile: profile,
  361. basalProfile: basalProfile,
  362. clock: dateFormattedAsString,
  363. carbs: carbsAsJSON,
  364. glucose: glucoseAsJSON
  365. )
  366. // IOB
  367. let iob = try await self.iob(
  368. pumphistory: pumpHistoryJSON,
  369. profile: profile,
  370. clock: dateFormattedAsString,
  371. autosens: autosens.isEmpty ? .null : autosens
  372. )
  373. // TODO: refactor this to core data
  374. storage.save(iob, as: Monitor.iob)
  375. // Determine basal
  376. let orefDetermination = try await determineBasal(
  377. glucose: glucoseAsJSON,
  378. currentTemp: tempBasal,
  379. iob: iob,
  380. profile: profile,
  381. autosens: autosens.isEmpty ? .null : autosens,
  382. meal: meal,
  383. microBolusAllowed: true,
  384. reservoir: reservoir,
  385. pumpHistory: pumpHistoryJSON,
  386. preferences: preferences,
  387. basalProfile: basalProfile,
  388. oref2_variables: oref2_variables
  389. )
  390. debug(.openAPS, "Determinated: \(orefDetermination)")
  391. if var determination = Determination(from: orefDetermination), let deliverAt = determination.deliverAt {
  392. // set both timestamp and deliverAt to the SAME date; this will be updated for timestamp once it is enacted
  393. // AAPS does it the same way! we'll follow their example!
  394. determination.timestamp = deliverAt
  395. // save to core data asynchronously
  396. await processDetermination(determination)
  397. return determination
  398. } else {
  399. return nil
  400. }
  401. }
  402. func oref2() async -> RawJSON {
  403. await context.perform {
  404. let preferences = self.storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  405. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  406. let wp = preferences?.weightPercentage ?? 1
  407. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  408. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  409. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  410. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  411. var uniqueEvents = [OrefDetermination]()
  412. let requestTDD = OrefDetermination.fetchRequest() as NSFetchRequest<OrefDetermination>
  413. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND totalDailyDose > 0", tenDaysAgo as NSDate)
  414. requestTDD.propertiesToFetch = ["timestamp", "totalDailyDose"]
  415. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  416. requestTDD.sortDescriptors = [sortTDD]
  417. try? uniqueEvents = self.context.fetch(requestTDD)
  418. var sliderArray = [TempTargetsSlider]()
  419. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  420. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  421. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  422. // requestIsEnbled.fetchLimit = 1
  423. try? sliderArray = self.context.fetch(requestIsEnbled)
  424. /// Get the last active Override as only this information is apparently used in oref2
  425. var overrideArray = [OverrideStored]()
  426. let requestOverrides = OverrideStored.fetchRequest() as NSFetchRequest<OverrideStored>
  427. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  428. requestOverrides.sortDescriptors = [sortOverride]
  429. requestOverrides.predicate = NSPredicate.lastActiveOverride
  430. requestOverrides.fetchLimit = 1
  431. try? overrideArray = self.context.fetch(requestOverrides)
  432. var tempTargetsArray = [TempTargets]()
  433. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  434. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  435. requestTempTargets.sortDescriptors = [sortTT]
  436. requestTempTargets.fetchLimit = 1
  437. try? tempTargetsArray = self.context.fetch(requestTempTargets)
  438. let total = uniqueEvents.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  439. var indeces = uniqueEvents.count
  440. // Only fetch once. Use same (previous) fetch
  441. let twoHoursArray = uniqueEvents.filter({ ($0.timestamp ?? Date()) >= twoHoursAgo })
  442. var nrOfIndeces = twoHoursArray.count
  443. let totalAmount = twoHoursArray.compactMap({ each in each.totalDailyDose as? Decimal ?? 0 }).reduce(0, +)
  444. var temptargetActive = tempTargetsArray.first?.active ?? false
  445. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  446. var useOverride = overrideArray.first?.enabled ?? false
  447. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  448. var unlimited = overrideArray.first?.indefinite ?? true
  449. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  450. let currentTDD = (uniqueEvents.last?.totalDailyDose ?? 0) as Decimal
  451. if indeces == 0 {
  452. indeces = 1
  453. }
  454. if nrOfIndeces == 0 {
  455. nrOfIndeces = 1
  456. }
  457. let average2hours = totalAmount / Decimal(nrOfIndeces)
  458. let average14 = total / Decimal(indeces)
  459. let weight = wp
  460. let weighted_average = weight * average2hours + (1 - weight) * average14
  461. var duration: Decimal = 0
  462. var newDuration: Decimal = 0
  463. var overrideTarget: Decimal = 0
  464. if useOverride {
  465. duration = (overrideArray.first?.duration ?? 0) as Decimal
  466. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  467. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  468. let addedMinutes = Int(duration)
  469. let date = overrideArray.first?.date ?? Date()
  470. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  471. !unlimited
  472. {
  473. useOverride = false
  474. let saveToCoreData = OverrideStored(context: self.context)
  475. saveToCoreData.enabled = false
  476. saveToCoreData.date = Date()
  477. saveToCoreData.duration = 0
  478. saveToCoreData.indefinite = false
  479. saveToCoreData.percentage = 100
  480. do {
  481. guard self.context.hasChanges else { return "{}" }
  482. try self.context.save()
  483. } catch {
  484. print(error.localizedDescription)
  485. }
  486. }
  487. }
  488. if !useOverride {
  489. unlimited = true
  490. overridePercentage = 100
  491. duration = 0
  492. overrideTarget = 0
  493. disableSMBs = false
  494. }
  495. if temptargetActive {
  496. var duration_ = 0
  497. var hbt = Double(hbt_)
  498. var dd = 0.0
  499. if temptargetActive {
  500. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  501. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  502. let startDate = tempTargetsArray.first?.startDate ?? Date()
  503. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  504. dd = durationPlusStart.timeIntervalSinceNow.minutes
  505. if dd > 0.1 {
  506. hbt_ = Decimal(hbt)
  507. temptargetActive = true
  508. } else {
  509. temptargetActive = false
  510. }
  511. }
  512. }
  513. if currentTDD > 0 {
  514. let averages = Oref2_variables(
  515. average_total_data: average14,
  516. weightedAverage: weighted_average,
  517. past2hoursAverage: average2hours,
  518. date: Date(),
  519. isEnabled: temptargetActive,
  520. presetActive: isPercentageEnabled,
  521. overridePercentage: overridePercentage,
  522. useOverride: useOverride,
  523. duration: duration,
  524. unlimited: unlimited,
  525. hbt: hbt_,
  526. overrideTarget: overrideTarget,
  527. smbIsOff: disableSMBs,
  528. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  529. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  530. isf: overrideArray.first?.isf ?? false,
  531. cr: overrideArray.first?.cr ?? false,
  532. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  533. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  534. )
  535. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  536. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  537. } else {
  538. let averages = Oref2_variables(
  539. average_total_data: 0,
  540. weightedAverage: 1,
  541. past2hoursAverage: 0,
  542. date: Date(),
  543. isEnabled: temptargetActive,
  544. presetActive: isPercentageEnabled,
  545. overridePercentage: overridePercentage,
  546. useOverride: useOverride,
  547. duration: duration,
  548. unlimited: unlimited,
  549. hbt: hbt_,
  550. overrideTarget: overrideTarget,
  551. smbIsOff: disableSMBs,
  552. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  553. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  554. isf: overrideArray.first?.isf ?? false,
  555. cr: overrideArray.first?.cr ?? false,
  556. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  557. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  558. )
  559. self.storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  560. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  561. }
  562. }
  563. }
  564. func autosense() async throws -> Autosens? {
  565. debug(.openAPS, "Start autosens")
  566. // Perform asynchronous calls in parallel
  567. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  568. async let carbs = fetchAndProcessCarbs()
  569. async let glucose = fetchAndProcessGlucose()
  570. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  571. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  572. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  573. // Await the results of asynchronous tasks
  574. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, basalProfile, tempTargets) = await (
  575. parsePumpHistory(await pumpHistoryObjectIDs),
  576. carbs,
  577. glucose,
  578. getProfile,
  579. getBasalProfile,
  580. getTempTargets
  581. )
  582. // Autosense
  583. let autosenseResult = try await autosense(
  584. glucose: glucoseAsJSON,
  585. pumpHistory: pumpHistoryJSON,
  586. basalprofile: basalProfile,
  587. profile: profile,
  588. carbs: carbsAsJSON,
  589. temptargets: tempTargets
  590. )
  591. debug(.openAPS, "AUTOSENS: \(autosenseResult)")
  592. if var autosens = Autosens(from: autosenseResult) {
  593. autosens.timestamp = Date()
  594. storage.save(autosens, as: Settings.autosense)
  595. return autosens
  596. } else {
  597. return nil
  598. }
  599. }
  600. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) async -> Autotune? {
  601. debug(.openAPS, "Start autotune")
  602. // Perform asynchronous calls in parallel
  603. async let pumpHistoryObjectIDs = fetchPumpHistoryObjectIDs() ?? []
  604. async let carbs = fetchAndProcessCarbs()
  605. async let glucose = fetchAndProcessGlucose()
  606. async let getProfile = loadFileFromStorageAsync(name: Settings.profile)
  607. async let getPumpProfile = loadFileFromStorageAsync(name: Settings.pumpProfile)
  608. async let getPreviousAutotune = storage.retrieveAsync(Settings.autotune, as: RawJSON.self)
  609. // Await the results of asynchronous tasks
  610. let (pumpHistoryJSON, carbsAsJSON, glucoseAsJSON, profile, pumpProfile, previousAutotune) = await (
  611. parsePumpHistory(await pumpHistoryObjectIDs),
  612. carbs,
  613. glucose,
  614. getProfile,
  615. getPumpProfile,
  616. getPreviousAutotune
  617. )
  618. // Error need to be handled here because the function is not declared as throws
  619. do {
  620. // Autotune Prepare
  621. let autotunePreppedGlucose = try await autotunePrepare(
  622. pumphistory: pumpHistoryJSON,
  623. profile: profile,
  624. glucose: glucoseAsJSON,
  625. pumpprofile: pumpProfile,
  626. carbs: carbsAsJSON,
  627. categorizeUamAsBasal: categorizeUamAsBasal,
  628. tuneInsulinCurve: tuneInsulinCurve
  629. )
  630. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  631. // Autotune Run
  632. let autotuneResult = try await autotuneRun(
  633. autotunePreparedData: autotunePreppedGlucose,
  634. previousAutotuneResult: previousAutotune ?? profile,
  635. pumpProfile: pumpProfile
  636. )
  637. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  638. if let autotune = Autotune(from: autotuneResult) {
  639. storage.save(autotuneResult, as: Settings.autotune)
  640. return autotune
  641. } else {
  642. return nil
  643. }
  644. } catch {
  645. debug(.openAPS, "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to prepare/run Autotune")
  646. return nil
  647. }
  648. }
  649. func makeProfiles(useAutotune _: Bool) async -> Autotune? {
  650. debug(.openAPS, "Start makeProfiles")
  651. async let getPreferences = loadFileFromStorageAsync(name: Settings.preferences)
  652. async let getPumpSettings = loadFileFromStorageAsync(name: Settings.settings)
  653. async let getBGTargets = loadFileFromStorageAsync(name: Settings.bgTargets)
  654. async let getBasalProfile = loadFileFromStorageAsync(name: Settings.basalProfile)
  655. async let getISF = loadFileFromStorageAsync(name: Settings.insulinSensitivities)
  656. async let getCR = loadFileFromStorageAsync(name: Settings.carbRatios)
  657. async let getTempTargets = loadFileFromStorageAsync(name: Settings.tempTargets)
  658. async let getModel = loadFileFromStorageAsync(name: Settings.model)
  659. async let getAutotune = loadFileFromStorageAsync(name: Settings.autotune)
  660. async let getFreeAPS = loadFileFromStorageAsync(name: FreeAPS.settings)
  661. let (preferences, pumpSettings, bgTargets, basalProfile, isf, cr, tempTargets, model, autotune, freeaps) = await (
  662. getPreferences,
  663. getPumpSettings,
  664. getBGTargets,
  665. getBasalProfile,
  666. getISF,
  667. getCR,
  668. getTempTargets,
  669. getModel,
  670. getAutotune,
  671. getFreeAPS
  672. )
  673. var adjustedPreferences = preferences
  674. if adjustedPreferences.isEmpty {
  675. adjustedPreferences = Preferences().rawJSON
  676. }
  677. do {
  678. // Pump Profile
  679. let pumpProfile = try await makeProfile(
  680. preferences: adjustedPreferences,
  681. pumpSettings: pumpSettings,
  682. bgTargets: bgTargets,
  683. basalProfile: basalProfile,
  684. isf: isf,
  685. carbRatio: cr,
  686. tempTargets: tempTargets,
  687. model: model,
  688. autotune: RawJSON.null,
  689. freeaps: freeaps
  690. )
  691. // Profile
  692. let profile = try await makeProfile(
  693. preferences: adjustedPreferences,
  694. pumpSettings: pumpSettings,
  695. bgTargets: bgTargets,
  696. basalProfile: basalProfile,
  697. isf: isf,
  698. carbRatio: cr,
  699. tempTargets: tempTargets,
  700. model: model,
  701. autotune: autotune.isEmpty ? .null : autotune,
  702. freeaps: freeaps
  703. )
  704. await storage.saveAsync(pumpProfile, as: Settings.pumpProfile)
  705. await storage.saveAsync(profile, as: Settings.profile)
  706. if let tunedProfile = Autotune(from: profile) {
  707. return tunedProfile
  708. } else {
  709. return nil
  710. }
  711. } catch {
  712. debug(
  713. .apsManager,
  714. "\(DebuggingIdentifiers.failed) \(#file) \(#function) Failed to execute makeProfiles() to return Autoune results"
  715. )
  716. return nil
  717. }
  718. }
  719. // MARK: - Private
  720. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) async throws -> RawJSON {
  721. await withCheckedContinuation { continuation in
  722. jsWorker.inCommonContext { worker in
  723. worker.evaluateBatch(scripts: [
  724. Script(name: Prepare.log),
  725. Script(name: Bundle.iob),
  726. Script(name: Prepare.iob)
  727. ])
  728. let result = worker.call(function: Function.generate, with: [
  729. pumphistory,
  730. profile,
  731. clock,
  732. autosens
  733. ])
  734. continuation.resume(returning: result)
  735. }
  736. }
  737. }
  738. private func meal(
  739. pumphistory: JSON,
  740. profile: JSON,
  741. basalProfile: JSON,
  742. clock: JSON,
  743. carbs: JSON,
  744. glucose: JSON
  745. ) async throws -> RawJSON {
  746. try await withCheckedThrowingContinuation { continuation in
  747. jsWorker.inCommonContext { worker in
  748. worker.evaluateBatch(scripts: [
  749. Script(name: Prepare.log),
  750. Script(name: Bundle.meal),
  751. Script(name: Prepare.meal)
  752. ])
  753. let result = worker.call(function: Function.generate, with: [
  754. pumphistory,
  755. profile,
  756. clock,
  757. glucose,
  758. basalProfile,
  759. carbs
  760. ])
  761. continuation.resume(returning: result)
  762. }
  763. }
  764. }
  765. private func autosense(
  766. glucose: JSON,
  767. pumpHistory: JSON,
  768. basalprofile: JSON,
  769. profile: JSON,
  770. carbs: JSON,
  771. temptargets: JSON
  772. ) async throws -> RawJSON {
  773. try await withCheckedThrowingContinuation { continuation in
  774. jsWorker.inCommonContext { worker in
  775. worker.evaluateBatch(scripts: [
  776. Script(name: Prepare.log),
  777. Script(name: Bundle.autosens),
  778. Script(name: Prepare.autosens)
  779. ])
  780. let result = worker.call(function: Function.generate, with: [
  781. glucose,
  782. pumpHistory,
  783. basalprofile,
  784. profile,
  785. carbs,
  786. temptargets
  787. ])
  788. continuation.resume(returning: result)
  789. }
  790. }
  791. }
  792. private func autotunePrepare(
  793. pumphistory: JSON,
  794. profile: JSON,
  795. glucose: JSON,
  796. pumpprofile: JSON,
  797. carbs: JSON,
  798. categorizeUamAsBasal: Bool,
  799. tuneInsulinCurve: Bool
  800. ) async throws -> RawJSON {
  801. try await withCheckedThrowingContinuation { continuation in
  802. jsWorker.inCommonContext { worker in
  803. worker.evaluateBatch(scripts: [
  804. Script(name: Prepare.log),
  805. Script(name: Bundle.autotunePrep),
  806. Script(name: Prepare.autotunePrep)
  807. ])
  808. let result = worker.call(function: Function.generate, with: [
  809. pumphistory,
  810. profile,
  811. glucose,
  812. pumpprofile,
  813. carbs,
  814. categorizeUamAsBasal,
  815. tuneInsulinCurve
  816. ])
  817. continuation.resume(returning: result)
  818. }
  819. }
  820. }
  821. private func autotuneRun(
  822. autotunePreparedData: JSON,
  823. previousAutotuneResult: JSON,
  824. pumpProfile: JSON
  825. ) async throws -> RawJSON {
  826. try await withCheckedThrowingContinuation { continuation in
  827. jsWorker.inCommonContext { worker in
  828. worker.evaluateBatch(scripts: [
  829. Script(name: Prepare.log),
  830. Script(name: Bundle.autotuneCore),
  831. Script(name: Prepare.autotuneCore)
  832. ])
  833. let result = worker.call(function: Function.generate, with: [
  834. autotunePreparedData,
  835. previousAutotuneResult,
  836. pumpProfile
  837. ])
  838. continuation.resume(returning: result)
  839. }
  840. }
  841. }
  842. private func determineBasal(
  843. glucose: JSON,
  844. currentTemp: JSON,
  845. iob: JSON,
  846. profile: JSON,
  847. autosens: JSON,
  848. meal: JSON,
  849. microBolusAllowed: Bool,
  850. reservoir: JSON,
  851. pumpHistory: JSON,
  852. preferences: JSON,
  853. basalProfile: JSON,
  854. oref2_variables: JSON
  855. ) async throws -> RawJSON {
  856. try await withCheckedThrowingContinuation { continuation in
  857. jsWorker.inCommonContext { worker in
  858. worker.evaluateBatch(scripts: [
  859. Script(name: Prepare.log),
  860. Script(name: Prepare.determineBasal),
  861. Script(name: Bundle.basalSetTemp),
  862. Script(name: Bundle.getLastGlucose),
  863. Script(name: Bundle.determineBasal)
  864. ])
  865. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  866. worker.evaluate(script: middleware)
  867. }
  868. let result = worker.call(function: Function.generate, with: [
  869. iob,
  870. currentTemp,
  871. glucose,
  872. profile,
  873. autosens,
  874. meal,
  875. microBolusAllowed,
  876. reservoir,
  877. Date(),
  878. pumpHistory,
  879. preferences,
  880. basalProfile,
  881. oref2_variables
  882. ])
  883. continuation.resume(returning: result)
  884. }
  885. }
  886. }
  887. private func exportDefaultPreferences() -> RawJSON {
  888. dispatchPrecondition(condition: .onQueue(processQueue))
  889. return jsWorker.inCommonContext { worker in
  890. worker.evaluateBatch(scripts: [
  891. Script(name: Prepare.log),
  892. Script(name: Bundle.profile),
  893. Script(name: Prepare.profile)
  894. ])
  895. return worker.call(function: Function.exportDefaults, with: [])
  896. }
  897. }
  898. private func makeProfile(
  899. preferences: JSON,
  900. pumpSettings: JSON,
  901. bgTargets: JSON,
  902. basalProfile: JSON,
  903. isf: JSON,
  904. carbRatio: JSON,
  905. tempTargets: JSON,
  906. model: JSON,
  907. autotune: JSON,
  908. freeaps: JSON
  909. ) async throws -> RawJSON {
  910. try await withCheckedThrowingContinuation { continuation in
  911. jsWorker.inCommonContext { worker in
  912. worker.evaluateBatch(scripts: [
  913. Script(name: Prepare.log),
  914. Script(name: Bundle.profile),
  915. Script(name: Prepare.profile)
  916. ])
  917. let result = worker.call(function: Function.generate, with: [
  918. pumpSettings,
  919. bgTargets,
  920. isf,
  921. basalProfile,
  922. preferences,
  923. carbRatio,
  924. tempTargets,
  925. model,
  926. autotune,
  927. freeaps
  928. ])
  929. continuation.resume(returning: result)
  930. }
  931. }
  932. }
  933. private func loadJSON(name: String) -> String {
  934. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  935. }
  936. private func loadFileFromStorage(name: String) -> RawJSON {
  937. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  938. }
  939. private func loadFileFromStorageAsync(name: String) async -> RawJSON {
  940. await withCheckedContinuation { continuation in
  941. DispatchQueue.global(qos: .userInitiated).async {
  942. let result = self.storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  943. continuation.resume(returning: result)
  944. }
  945. }
  946. }
  947. private func middlewareScript(name: String) -> Script? {
  948. if let body = storage.retrieveRaw(name) {
  949. return Script(name: "Middleware", body: body)
  950. }
  951. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  952. return Script(name: "Middleware", body: try! String(contentsOf: url))
  953. }
  954. return nil
  955. }
  956. static func defaults(for file: String) -> RawJSON {
  957. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  958. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  959. return ""
  960. }
  961. return (try? String(contentsOf: url)) ?? ""
  962. }
  963. func processAndSave(forecastData: [String: [Int]]) {
  964. let currentDate = Date()
  965. context.perform {
  966. for (type, values) in forecastData {
  967. self.createForecast(type: type, values: values, date: currentDate, context: self.context)
  968. }
  969. do {
  970. guard self.context.hasChanges else { return }
  971. try self.context.save()
  972. } catch {
  973. print(error.localizedDescription)
  974. }
  975. }
  976. }
  977. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  978. let forecast = Forecast(context: context)
  979. forecast.id = UUID()
  980. forecast.date = date
  981. forecast.type = type
  982. for (index, value) in values.enumerated() {
  983. let forecastValue = ForecastValue(context: context)
  984. forecastValue.value = Int32(value)
  985. forecastValue.index = Int32(index)
  986. forecastValue.forecast = forecast
  987. }
  988. }
  989. }