OpenAPS.swift 43 KB

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