OpenAPS.swift 33 KB

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