OpenAPS.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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.backgroundContext
  10. init(storage: FileStorage) {
  11. self.storage = storage
  12. }
  13. // Helper function to convert a Decimal? to NSDecimalNumber?
  14. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  15. guard let value = value else { return nil }
  16. return NSDecimalNumber(decimal: value)
  17. }
  18. // Use the helper function for cleaner code
  19. func processDetermination(_ determination: Determination) {
  20. context.perform {
  21. let newOrefDetermination = OrefDetermination(context: self.context)
  22. newOrefDetermination.id = UUID()
  23. newOrefDetermination.totalDailyDose = self.decimalToNSDecimalNumber(determination.tdd)
  24. newOrefDetermination.insulinSensitivity = self.decimalToNSDecimalNumber(determination.isf)
  25. newOrefDetermination.currentTarget = self.decimalToNSDecimalNumber(determination.current_target)
  26. newOrefDetermination.eventualBG = determination.eventualBG.map(NSDecimalNumber.init)
  27. newOrefDetermination.deliverAt = determination.deliverAt
  28. newOrefDetermination.insulinForManualBolus = self.decimalToNSDecimalNumber(determination.insulinForManualBolus)
  29. newOrefDetermination.carbRatio = self.decimalToNSDecimalNumber(determination.carbRatio)
  30. newOrefDetermination.glucose = self.decimalToNSDecimalNumber(determination.bg)
  31. newOrefDetermination.reservoir = self.decimalToNSDecimalNumber(determination.reservoir)
  32. newOrefDetermination.insulinReq = self.decimalToNSDecimalNumber(determination.insulinReq)
  33. newOrefDetermination.temp = determination.temp?.rawValue ?? "absolute"
  34. newOrefDetermination.rate = self.decimalToNSDecimalNumber(determination.rate)
  35. newOrefDetermination.reason = determination.reason
  36. newOrefDetermination.duration = Int16(determination.duration ?? 0)
  37. newOrefDetermination.iob = self.decimalToNSDecimalNumber(determination.iob)
  38. newOrefDetermination.threshold = self.decimalToNSDecimalNumber(determination.threshold)
  39. newOrefDetermination.minDelta = self.decimalToNSDecimalNumber(determination.minDelta)
  40. newOrefDetermination.sensitivityRatio = self.decimalToNSDecimalNumber(determination.sensitivityRatio)
  41. newOrefDetermination.expectedDelta = self.decimalToNSDecimalNumber(determination.expectedDelta)
  42. newOrefDetermination.cob = Int16(Int(determination.cob ?? 0))
  43. newOrefDetermination.manualBolusErrorString = self.decimalToNSDecimalNumber(determination.manualBolusErrorString)
  44. newOrefDetermination.tempBasal = determination.insulin?.temp_basal.map { NSDecimalNumber(decimal: $0) }
  45. newOrefDetermination.scheduledBasal = determination.insulin?.scheduled_basal.map { NSDecimalNumber(decimal: $0) }
  46. newOrefDetermination.bolus = determination.insulin?.bolus.map { NSDecimalNumber(decimal: $0) }
  47. newOrefDetermination.smbToDeliver = determination.units.map { NSDecimalNumber(decimal: $0) }
  48. newOrefDetermination.carbsRequired = Int16(Int(determination.carbsReq ?? 0))
  49. if let predictions = determination.predictions {
  50. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  51. .forEach { type, values in
  52. if let values = values {
  53. let forecast = Forecast(context: self.context)
  54. forecast.id = UUID()
  55. forecast.type = type
  56. forecast.date = Date()
  57. forecast.orefDetermination = newOrefDetermination
  58. for (index, value) in values.enumerated() {
  59. let forecastValue = ForecastValue(context: self.context)
  60. forecastValue.index = Int32(index)
  61. forecastValue.value = Int32(value)
  62. forecast.addToForecastValues(forecastValue)
  63. }
  64. newOrefDetermination.addToForecasts(forecast)
  65. }
  66. }
  67. }
  68. self.attemptToSaveContext()
  69. }
  70. }
  71. func attemptToSaveContext() {
  72. if context.hasChanges {
  73. do {
  74. try context.save()
  75. debugPrint("OpenAPS: \(CoreDataStack.identifier) \(DebuggingIdentifiers.succeeded) saved determination")
  76. } catch {
  77. debugPrint(
  78. "OpenAPS: \(CoreDataStack.identifier) \(DebuggingIdentifiers.failed) error while saving determination: \(error.localizedDescription)"
  79. )
  80. }
  81. }
  82. }
  83. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) -> Future<Determination?, Never> {
  84. Future { promise in
  85. self.processQueue.async {
  86. debug(.openAPS, "Start determineBasal")
  87. // clock
  88. self.storage.save(clock, as: Monitor.clock)
  89. // temp_basal
  90. let tempBasal = currentTemp.rawJSON
  91. self.storage.save(tempBasal, as: Monitor.tempBasal)
  92. // meal
  93. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  94. let carbs = self.loadFileFromStorage(name: Monitor.carbHistory)
  95. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  96. let profile = self.loadFileFromStorage(name: Settings.profile)
  97. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  98. let meal = self.meal(
  99. pumphistory: pumpHistory,
  100. profile: profile,
  101. basalProfile: basalProfile,
  102. clock: clock,
  103. carbs: carbs,
  104. glucose: glucose
  105. )
  106. self.storage.save(meal, as: Monitor.meal)
  107. // iob
  108. let autosens = self.loadFileFromStorage(name: Settings.autosense)
  109. let iob = self.iob(
  110. pumphistory: pumpHistory,
  111. profile: profile,
  112. clock: clock,
  113. autosens: autosens.isEmpty ? .null : autosens
  114. )
  115. self.storage.save(iob, as: Monitor.iob)
  116. // determine-basal
  117. let reservoir = self.loadFileFromStorage(name: Monitor.reservoir)
  118. let preferences = self.loadFileFromStorage(name: Settings.preferences)
  119. // oref2
  120. let oref2_variables = self.oref2()
  121. let orefDetermination = self.determineBasal(
  122. glucose: glucose,
  123. currentTemp: tempBasal,
  124. iob: iob,
  125. profile: profile,
  126. autosens: autosens.isEmpty ? .null : autosens,
  127. meal: meal,
  128. microBolusAllowed: true,
  129. reservoir: reservoir,
  130. pumpHistory: pumpHistory,
  131. preferences: preferences,
  132. basalProfile: basalProfile,
  133. oref2_variables: oref2_variables
  134. )
  135. debug(.openAPS, "SUGGESTED: \(orefDetermination)")
  136. if var determination = Determination(from: orefDetermination) {
  137. determination.timestamp = determination.deliverAt ?? clock
  138. self.storage.save(determination, as: Enact.suggested)
  139. // save to core data asynchronously
  140. self.processDetermination(determination)
  141. if determination.tdd ?? 0 > 0 {
  142. self.context.perform {
  143. let saveToTDD = TDD(context: self.context)
  144. saveToTDD.timestamp = determination.timestamp ?? Date()
  145. saveToTDD.tdd = (determination.tdd ?? 0) as NSDecimalNumber?
  146. if self.context.hasChanges {
  147. try? self.context.save()
  148. }
  149. let saveTarget = Target(context: self.context)
  150. saveTarget.current = (determination.current_target ?? 100) as NSDecimalNumber?
  151. if self.context.hasChanges {
  152. try? self.context.save()
  153. }
  154. }
  155. }
  156. promise(.success(determination))
  157. } else {
  158. promise(.success(nil))
  159. }
  160. }
  161. }
  162. }
  163. func oref2() -> RawJSON {
  164. context.performAndWait {
  165. let preferences = storage.retrieve(OpenAPS.Settings.preferences, as: Preferences.self)
  166. var hbt_ = preferences?.halfBasalExerciseTarget ?? 160
  167. let wp = preferences?.weightPercentage ?? 1
  168. let smbMinutes = (preferences?.maxSMBBasalMinutes ?? 30) as NSDecimalNumber
  169. let uamMinutes = (preferences?.maxUAMSMBBasalMinutes ?? 30) as NSDecimalNumber
  170. let tenDaysAgo = Date().addingTimeInterval(-10.days.timeInterval)
  171. let twoHoursAgo = Date().addingTimeInterval(-2.hours.timeInterval)
  172. var uniqueEvents = [TDD]()
  173. let requestTDD = TDD.fetchRequest() as NSFetchRequest<TDD>
  174. requestTDD.predicate = NSPredicate(format: "timestamp > %@ AND tdd > 0", tenDaysAgo as NSDate)
  175. let sortTDD = NSSortDescriptor(key: "timestamp", ascending: true)
  176. requestTDD.sortDescriptors = [sortTDD]
  177. try? uniqueEvents = context.fetch(requestTDD)
  178. var sliderArray = [TempTargetsSlider]()
  179. let requestIsEnbled = TempTargetsSlider.fetchRequest() as NSFetchRequest<TempTargetsSlider>
  180. let sortIsEnabled = NSSortDescriptor(key: "date", ascending: false)
  181. requestIsEnbled.sortDescriptors = [sortIsEnabled]
  182. // requestIsEnbled.fetchLimit = 1
  183. try? sliderArray = context.fetch(requestIsEnbled)
  184. var overrideArray = [Override]()
  185. let requestOverrides = Override.fetchRequest() as NSFetchRequest<Override>
  186. let sortOverride = NSSortDescriptor(key: "date", ascending: false)
  187. requestOverrides.sortDescriptors = [sortOverride]
  188. // requestOverrides.fetchLimit = 1
  189. try? overrideArray = context.fetch(requestOverrides)
  190. var tempTargetsArray = [TempTargets]()
  191. let requestTempTargets = TempTargets.fetchRequest() as NSFetchRequest<TempTargets>
  192. let sortTT = NSSortDescriptor(key: "date", ascending: false)
  193. requestTempTargets.sortDescriptors = [sortTT]
  194. requestTempTargets.fetchLimit = 1
  195. try? tempTargetsArray = context.fetch(requestTempTargets)
  196. let total = uniqueEvents.compactMap({ each in each.tdd as? Decimal ?? 0 }).reduce(0, +)
  197. var indeces = uniqueEvents.count
  198. // Only fetch once. Use same (previous) fetch
  199. let twoHoursArray = uniqueEvents.filter({ ($0.timestamp ?? Date()) >= twoHoursAgo })
  200. var nrOfIndeces = twoHoursArray.count
  201. let totalAmount = twoHoursArray.compactMap({ each in each.tdd as? Decimal ?? 0 }).reduce(0, +)
  202. var temptargetActive = tempTargetsArray.first?.active ?? false
  203. let isPercentageEnabled = sliderArray.first?.enabled ?? false
  204. var useOverride = overrideArray.first?.enabled ?? false
  205. var overridePercentage = Decimal(overrideArray.first?.percentage ?? 100)
  206. var unlimited = overrideArray.first?.indefinite ?? true
  207. var disableSMBs = overrideArray.first?.smbIsOff ?? false
  208. let currentTDD = (uniqueEvents.last?.tdd ?? 0) as Decimal
  209. if indeces == 0 {
  210. indeces = 1
  211. }
  212. if nrOfIndeces == 0 {
  213. nrOfIndeces = 1
  214. }
  215. let average2hours = totalAmount / Decimal(nrOfIndeces)
  216. let average14 = total / Decimal(indeces)
  217. let weight = wp
  218. let weighted_average = weight * average2hours + (1 - weight) * average14
  219. var duration: Decimal = 0
  220. var newDuration: Decimal = 0
  221. var overrideTarget: Decimal = 0
  222. if useOverride {
  223. duration = (overrideArray.first?.duration ?? 0) as Decimal
  224. overrideTarget = (overrideArray.first?.target ?? 0) as Decimal
  225. let advancedSettings = overrideArray.first?.advancedSettings ?? false
  226. let addedMinutes = Int(duration)
  227. let date = overrideArray.first?.date ?? Date()
  228. if date.addingTimeInterval(addedMinutes.minutes.timeInterval) < Date(),
  229. !unlimited
  230. {
  231. useOverride = false
  232. let saveToCoreData = Override(context: self.context)
  233. saveToCoreData.enabled = false
  234. saveToCoreData.date = Date()
  235. saveToCoreData.duration = 0
  236. saveToCoreData.indefinite = false
  237. saveToCoreData.percentage = 100
  238. if self.context.hasChanges {
  239. try? self.context.save()
  240. }
  241. }
  242. }
  243. if !useOverride {
  244. unlimited = true
  245. overridePercentage = 100
  246. duration = 0
  247. overrideTarget = 0
  248. disableSMBs = false
  249. }
  250. if temptargetActive {
  251. var duration_ = 0
  252. var hbt = Double(hbt_)
  253. var dd = 0.0
  254. if temptargetActive {
  255. duration_ = Int(truncating: tempTargetsArray.first?.duration ?? 0)
  256. hbt = tempTargetsArray.first?.hbt ?? Double(hbt_)
  257. let startDate = tempTargetsArray.first?.startDate ?? Date()
  258. let durationPlusStart = startDate.addingTimeInterval(duration_.minutes.timeInterval)
  259. dd = durationPlusStart.timeIntervalSinceNow.minutes
  260. if dd > 0.1 {
  261. hbt_ = Decimal(hbt)
  262. temptargetActive = true
  263. } else {
  264. temptargetActive = false
  265. }
  266. }
  267. }
  268. if currentTDD > 0 {
  269. let averages = Oref2_variables(
  270. average_total_data: average14,
  271. weightedAverage: weighted_average,
  272. past2hoursAverage: average2hours,
  273. date: Date(),
  274. isEnabled: temptargetActive,
  275. presetActive: isPercentageEnabled,
  276. overridePercentage: overridePercentage,
  277. useOverride: useOverride,
  278. duration: duration,
  279. unlimited: unlimited,
  280. hbt: hbt_,
  281. overrideTarget: overrideTarget,
  282. smbIsOff: disableSMBs,
  283. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  284. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  285. isf: overrideArray.first?.isf ?? false,
  286. cr: overrideArray.first?.cr ?? false,
  287. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  288. start: (overrideArray.first?.start ?? 0) as Decimal,
  289. end: (overrideArray.first?.end ?? 0) as Decimal,
  290. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  291. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  292. )
  293. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  294. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  295. } else {
  296. let averages = Oref2_variables(
  297. average_total_data: 0,
  298. weightedAverage: 1,
  299. past2hoursAverage: 0,
  300. date: Date(),
  301. isEnabled: temptargetActive,
  302. presetActive: isPercentageEnabled,
  303. overridePercentage: overridePercentage,
  304. useOverride: useOverride,
  305. duration: duration,
  306. unlimited: unlimited,
  307. hbt: hbt_,
  308. overrideTarget: overrideTarget,
  309. smbIsOff: disableSMBs,
  310. advancedSettings: overrideArray.first?.advancedSettings ?? false,
  311. isfAndCr: overrideArray.first?.isfAndCr ?? false,
  312. isf: overrideArray.first?.isf ?? false,
  313. cr: overrideArray.first?.cr ?? false,
  314. smbIsAlwaysOff: overrideArray.first?.smbIsAlwaysOff ?? false,
  315. start: (overrideArray.first?.start ?? 0) as Decimal,
  316. end: (overrideArray.first?.end ?? 0) as Decimal,
  317. smbMinutes: (overrideArray.first?.smbMinutes ?? smbMinutes) as Decimal,
  318. uamMinutes: (overrideArray.first?.uamMinutes ?? uamMinutes) as Decimal
  319. )
  320. storage.save(averages, as: OpenAPS.Monitor.oref2_variables)
  321. return self.loadFileFromStorage(name: Monitor.oref2_variables)
  322. }
  323. }
  324. }
  325. func autosense() -> Future<Autosens?, Never> {
  326. Future { promise in
  327. self.processQueue.async {
  328. debug(.openAPS, "Start autosens")
  329. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  330. let carbs = self.loadFileFromStorage(name: Monitor.carbHistory)
  331. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  332. let profile = self.loadFileFromStorage(name: Settings.profile)
  333. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  334. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  335. let autosensResult = self.autosense(
  336. glucose: glucose,
  337. pumpHistory: pumpHistory,
  338. basalprofile: basalProfile,
  339. profile: profile,
  340. carbs: carbs,
  341. temptargets: tempTargets
  342. )
  343. debug(.openAPS, "AUTOSENS: \(autosensResult)")
  344. if var autosens = Autosens(from: autosensResult) {
  345. autosens.timestamp = Date()
  346. self.storage.save(autosens, as: Settings.autosense)
  347. promise(.success(autosens))
  348. } else {
  349. promise(.success(nil))
  350. }
  351. }
  352. }
  353. }
  354. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) -> Future<Autotune?, Never> {
  355. Future { promise in
  356. self.processQueue.async {
  357. debug(.openAPS, "Start autotune")
  358. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  359. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  360. let profile = self.loadFileFromStorage(name: Settings.profile)
  361. let pumpProfile = self.loadFileFromStorage(name: Settings.pumpProfile)
  362. let carbs = self.loadFileFromStorage(name: Monitor.carbHistory)
  363. let autotunePreppedGlucose = self.autotunePrepare(
  364. pumphistory: pumpHistory,
  365. profile: profile,
  366. glucose: glucose,
  367. pumpprofile: pumpProfile,
  368. carbs: carbs,
  369. categorizeUamAsBasal: categorizeUamAsBasal,
  370. tuneInsulinCurve: tuneInsulinCurve
  371. )
  372. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  373. let previousAutotune = self.storage.retrieve(Settings.autotune, as: RawJSON.self)
  374. let autotuneResult = self.autotuneRun(
  375. autotunePreparedData: autotunePreppedGlucose,
  376. previousAutotuneResult: previousAutotune ?? profile,
  377. pumpProfile: pumpProfile
  378. )
  379. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  380. if let autotune = Autotune(from: autotuneResult) {
  381. self.storage.save(autotuneResult, as: Settings.autotune)
  382. promise(.success(autotune))
  383. } else {
  384. promise(.success(nil))
  385. }
  386. }
  387. }
  388. }
  389. func makeProfiles(useAutotune: Bool) -> Future<Autotune?, Never> {
  390. Future { promise in
  391. debug(.openAPS, "Start makeProfiles")
  392. self.processQueue.async {
  393. var preferences = self.loadFileFromStorage(name: Settings.preferences)
  394. if preferences.isEmpty {
  395. preferences = Preferences().rawJSON
  396. }
  397. let pumpSettings = self.loadFileFromStorage(name: Settings.settings)
  398. let bgTargets = self.loadFileFromStorage(name: Settings.bgTargets)
  399. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  400. let isf = self.loadFileFromStorage(name: Settings.insulinSensitivities)
  401. let cr = self.loadFileFromStorage(name: Settings.carbRatios)
  402. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  403. let model = self.loadFileFromStorage(name: Settings.model)
  404. let autotune = useAutotune ? self.loadFileFromStorage(name: Settings.autotune) : .empty
  405. let freeaps = self.loadFileFromStorage(name: FreeAPS.settings)
  406. let pumpProfile = self.makeProfile(
  407. preferences: preferences,
  408. pumpSettings: pumpSettings,
  409. bgTargets: bgTargets,
  410. basalProfile: basalProfile,
  411. isf: isf,
  412. carbRatio: cr,
  413. tempTargets: tempTargets,
  414. model: model,
  415. autotune: RawJSON.null,
  416. freeaps: freeaps
  417. )
  418. let profile = self.makeProfile(
  419. preferences: preferences,
  420. pumpSettings: pumpSettings,
  421. bgTargets: bgTargets,
  422. basalProfile: basalProfile,
  423. isf: isf,
  424. carbRatio: cr,
  425. tempTargets: tempTargets,
  426. model: model,
  427. autotune: autotune.isEmpty ? .null : autotune,
  428. freeaps: freeaps
  429. )
  430. self.storage.save(pumpProfile, as: Settings.pumpProfile)
  431. self.storage.save(profile, as: Settings.profile)
  432. if let tunedProfile = Autotune(from: profile) {
  433. promise(.success(tunedProfile))
  434. return
  435. }
  436. promise(.success(nil))
  437. }
  438. }
  439. }
  440. // MARK: - Private
  441. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) -> RawJSON {
  442. dispatchPrecondition(condition: .onQueue(processQueue))
  443. return jsWorker.inCommonContext { worker in
  444. worker.evaluate(script: Script(name: Prepare.log))
  445. worker.evaluate(script: Script(name: Bundle.iob))
  446. worker.evaluate(script: Script(name: Prepare.iob))
  447. return worker.call(function: Function.generate, with: [
  448. pumphistory,
  449. profile,
  450. clock,
  451. autosens
  452. ])
  453. }
  454. }
  455. private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> RawJSON {
  456. dispatchPrecondition(condition: .onQueue(processQueue))
  457. return jsWorker.inCommonContext { worker in
  458. worker.evaluate(script: Script(name: Prepare.log))
  459. worker.evaluate(script: Script(name: Bundle.meal))
  460. worker.evaluate(script: Script(name: Prepare.meal))
  461. return worker.call(function: Function.generate, with: [
  462. pumphistory,
  463. profile,
  464. clock,
  465. glucose,
  466. basalProfile,
  467. carbs
  468. ])
  469. }
  470. }
  471. private func autotunePrepare(
  472. pumphistory: JSON,
  473. profile: JSON,
  474. glucose: JSON,
  475. pumpprofile: JSON,
  476. carbs: JSON,
  477. categorizeUamAsBasal: Bool,
  478. tuneInsulinCurve: Bool
  479. ) -> RawJSON {
  480. dispatchPrecondition(condition: .onQueue(processQueue))
  481. return jsWorker.inCommonContext { worker in
  482. worker.evaluate(script: Script(name: Prepare.log))
  483. worker.evaluate(script: Script(name: Bundle.autotunePrep))
  484. worker.evaluate(script: Script(name: Prepare.autotunePrep))
  485. return worker.call(function: Function.generate, with: [
  486. pumphistory,
  487. profile,
  488. glucose,
  489. pumpprofile,
  490. carbs,
  491. categorizeUamAsBasal,
  492. tuneInsulinCurve
  493. ])
  494. }
  495. }
  496. private func autotuneRun(
  497. autotunePreparedData: JSON,
  498. previousAutotuneResult: JSON,
  499. pumpProfile: JSON
  500. ) -> RawJSON {
  501. dispatchPrecondition(condition: .onQueue(processQueue))
  502. return jsWorker.inCommonContext { worker in
  503. worker.evaluate(script: Script(name: Prepare.log))
  504. worker.evaluate(script: Script(name: Bundle.autotuneCore))
  505. worker.evaluate(script: Script(name: Prepare.autotuneCore))
  506. return worker.call(function: Function.generate, with: [
  507. autotunePreparedData,
  508. previousAutotuneResult,
  509. pumpProfile
  510. ])
  511. }
  512. }
  513. private func determineBasal(
  514. glucose: JSON,
  515. currentTemp: JSON,
  516. iob: JSON,
  517. profile: JSON,
  518. autosens: JSON,
  519. meal: JSON,
  520. microBolusAllowed: Bool,
  521. reservoir: JSON,
  522. pumpHistory: JSON,
  523. preferences: JSON,
  524. basalProfile: JSON,
  525. oref2_variables: JSON
  526. ) -> RawJSON {
  527. dispatchPrecondition(condition: .onQueue(processQueue))
  528. return jsWorker.inCommonContext { worker in
  529. worker.evaluate(script: Script(name: Prepare.log))
  530. worker.evaluate(script: Script(name: Prepare.determineBasal))
  531. worker.evaluate(script: Script(name: Bundle.basalSetTemp))
  532. worker.evaluate(script: Script(name: Bundle.getLastGlucose))
  533. worker.evaluate(script: Script(name: Bundle.determineBasal))
  534. if let middleware = self.middlewareScript(name: OpenAPS.Middleware.determineBasal) {
  535. worker.evaluate(script: middleware)
  536. }
  537. return worker.call(
  538. function: Function.generate,
  539. with: [
  540. iob,
  541. currentTemp,
  542. glucose,
  543. profile,
  544. autosens,
  545. meal,
  546. microBolusAllowed,
  547. reservoir,
  548. Date(),
  549. pumpHistory,
  550. preferences,
  551. basalProfile,
  552. oref2_variables
  553. ]
  554. )
  555. }
  556. }
  557. private func autosense(
  558. glucose: JSON,
  559. pumpHistory: JSON,
  560. basalprofile: JSON,
  561. profile: JSON,
  562. carbs: JSON,
  563. temptargets: JSON
  564. ) -> RawJSON {
  565. dispatchPrecondition(condition: .onQueue(processQueue))
  566. return jsWorker.inCommonContext { worker in
  567. worker.evaluate(script: Script(name: Prepare.log))
  568. worker.evaluate(script: Script(name: Bundle.autosens))
  569. worker.evaluate(script: Script(name: Prepare.autosens))
  570. return worker.call(
  571. function: Function.generate,
  572. with: [
  573. glucose,
  574. pumpHistory,
  575. basalprofile,
  576. profile,
  577. carbs,
  578. temptargets
  579. ]
  580. )
  581. }
  582. }
  583. private func exportDefaultPreferences() -> RawJSON {
  584. dispatchPrecondition(condition: .onQueue(processQueue))
  585. return jsWorker.inCommonContext { worker in
  586. worker.evaluate(script: Script(name: Prepare.log))
  587. worker.evaluate(script: Script(name: Bundle.profile))
  588. worker.evaluate(script: Script(name: Prepare.profile))
  589. return worker.call(function: Function.exportDefaults, with: [])
  590. }
  591. }
  592. private func makeProfile(
  593. preferences: JSON,
  594. pumpSettings: JSON,
  595. bgTargets: JSON,
  596. basalProfile: JSON,
  597. isf: JSON,
  598. carbRatio: JSON,
  599. tempTargets: JSON,
  600. model: JSON,
  601. autotune: JSON,
  602. freeaps: JSON
  603. ) -> RawJSON {
  604. dispatchPrecondition(condition: .onQueue(processQueue))
  605. return jsWorker.inCommonContext { worker in
  606. worker.evaluate(script: Script(name: Prepare.log))
  607. worker.evaluate(script: Script(name: Bundle.profile))
  608. worker.evaluate(script: Script(name: Prepare.profile))
  609. return worker.call(
  610. function: Function.generate,
  611. with: [
  612. pumpSettings,
  613. bgTargets,
  614. isf,
  615. basalProfile,
  616. preferences,
  617. carbRatio,
  618. tempTargets,
  619. model,
  620. autotune,
  621. freeaps
  622. ]
  623. )
  624. }
  625. }
  626. private func loadJSON(name: String) -> String {
  627. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  628. }
  629. private func loadFileFromStorage(name: String) -> RawJSON {
  630. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  631. }
  632. private func middlewareScript(name: String) -> Script? {
  633. if let body = storage.retrieveRaw(name) {
  634. return Script(name: "Middleware", body: body)
  635. }
  636. if let url = Foundation.Bundle.main.url(forResource: "javascript/\(name)", withExtension: "") {
  637. return Script(name: "Middleware", body: try! String(contentsOf: url))
  638. }
  639. return nil
  640. }
  641. static func defaults(for file: String) -> RawJSON {
  642. let prefix = file.hasSuffix(".json") ? "json/defaults" : "javascript"
  643. guard let url = Foundation.Bundle.main.url(forResource: "\(prefix)/\(file)", withExtension: "") else {
  644. return ""
  645. }
  646. return (try? String(contentsOf: url)) ?? ""
  647. }
  648. func processAndSave(forecastData: [String: [Int]]) {
  649. let context = self.context
  650. let currentDate = Date()
  651. for (type, values) in forecastData {
  652. createForecast(type: type, values: values, date: currentDate, context: context)
  653. }
  654. }
  655. func createForecast(type: String, values: [Int], date: Date, context: NSManagedObjectContext) {
  656. let forecast = Forecast(context: context)
  657. forecast.id = UUID()
  658. forecast.date = date
  659. forecast.type = type
  660. for (index, value) in values.enumerated() {
  661. let forecastValue = ForecastValue(context: context)
  662. forecastValue.value = Int32(value)
  663. forecastValue.index = Int32(index)
  664. forecastValue.forecast = forecast
  665. }
  666. if self.context.hasChanges {
  667. do {
  668. try context.save()
  669. } catch {
  670. print("Failed to save forecast: \(error)")
  671. }
  672. }
  673. }
  674. }