OpenAPS.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import Combine
  2. import Foundation
  3. import JavaScriptCore
  4. final class OpenAPS {
  5. private let jsWorker = JavaScriptWorker()
  6. private let processQueue = DispatchQueue(label: "OpenAPS.processQueue", qos: .utility)
  7. private let storage: FileStorage
  8. init(storage: FileStorage) {
  9. self.storage = storage
  10. }
  11. func determineBasal(currentTemp: TempBasal, clock: Date = Date()) -> Future<Suggestion?, Never> {
  12. Future { promise in
  13. self.processQueue.async {
  14. debug(.openAPS, "Start determineBasal")
  15. // clock
  16. self.storage.save(clock, as: Monitor.clock)
  17. // temp_basal
  18. let tempBasal = currentTemp.rawJSON
  19. self.storage.save(tempBasal, as: Monitor.tempBasal)
  20. // meal
  21. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  22. let carbs = self.loadFileFromStorage(name: Monitor.carbHistory)
  23. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  24. let profile = self.loadFileFromStorage(name: Settings.profile)
  25. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  26. let meal = self.meal(
  27. pumphistory: pumpHistory,
  28. profile: profile,
  29. basalProfile: basalProfile,
  30. clock: clock,
  31. carbs: carbs,
  32. glucose: glucose
  33. )
  34. self.storage.save(meal, as: Monitor.meal)
  35. // iob
  36. let autosens = self.loadFileFromStorage(name: Settings.autosense)
  37. let iob = self.iob(
  38. pumphistory: pumpHistory,
  39. profile: profile,
  40. clock: clock,
  41. autosens: autosens.isEmpty ? .null : autosens
  42. )
  43. self.storage.save(iob, as: Monitor.iob)
  44. // determine-basal
  45. let reservoir = self.loadFileFromStorage(name: Monitor.reservoir)
  46. let suggested = self.determineBasal(
  47. glucose: glucose,
  48. currentTemp: tempBasal,
  49. iob: iob,
  50. profile: profile,
  51. autosens: autosens.isEmpty ? .null : autosens,
  52. meal: meal,
  53. microBolusAllowed: true,
  54. reservoir: reservoir
  55. )
  56. debug(.openAPS, "SUGGESTED: \(suggested)")
  57. if var suggestion = Suggestion(from: suggested) {
  58. suggestion.timestamp = suggestion.deliverAt ?? clock
  59. self.storage.save(suggestion, as: Enact.suggested)
  60. promise(.success(suggestion))
  61. } else {
  62. promise(.success(nil))
  63. }
  64. }
  65. }
  66. }
  67. func autosense() -> Future<Autosens?, Never> {
  68. Future { promise in
  69. self.processQueue.async {
  70. debug(.openAPS, "Start autosens")
  71. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  72. let carbs = self.loadFileFromStorage(name: Monitor.carbHistory)
  73. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  74. let profile = self.loadFileFromStorage(name: Settings.profile)
  75. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  76. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  77. let autosensResult = self.autosense(
  78. glucose: glucose,
  79. pumpHistory: pumpHistory,
  80. basalprofile: basalProfile,
  81. profile: profile,
  82. carbs: carbs,
  83. temptargets: tempTargets
  84. )
  85. debug(.openAPS, "AUTOSENS: \(autosensResult)")
  86. if var autosens = Autosens(from: autosensResult) {
  87. autosens.timestamp = Date()
  88. self.storage.save(autosens, as: Settings.autosense)
  89. promise(.success(autosens))
  90. } else {
  91. promise(.success(nil))
  92. }
  93. }
  94. }
  95. }
  96. func autotune(categorizeUamAsBasal: Bool = false, tuneInsulinCurve: Bool = false) -> Future<Autotune?, Never> {
  97. Future { promise in
  98. self.processQueue.async {
  99. debug(.openAPS, "Start autotune")
  100. let pumpHistory = self.loadFileFromStorage(name: OpenAPS.Monitor.pumpHistory)
  101. let glucose = self.loadFileFromStorage(name: Monitor.glucose)
  102. let profile = self.loadFileFromStorage(name: Settings.profile)
  103. let autotunePreppedGlucose = self.autotunePrepare(
  104. pumphistory: pumpHistory,
  105. profile: profile,
  106. glucose: glucose,
  107. pumpprofile: profile,
  108. categorizeUamAsBasal: categorizeUamAsBasal,
  109. tuneInsulinCurve: tuneInsulinCurve
  110. )
  111. debug(.openAPS, "AUTOTUNE PREP: \(autotunePreppedGlucose)")
  112. let previousAutotune = self.storage.retrieve(Settings.autotune, as: RawJSON.self)
  113. let autotuneResult = self.autotuneRun(
  114. autotunePreparedData: autotunePreppedGlucose,
  115. previousAutotuneResult: previousAutotune ?? profile,
  116. pumpProfile: profile
  117. )
  118. debug(.openAPS, "AUTOTUNE RESULT: \(autotuneResult)")
  119. if let autotune = Autotune(from: autotuneResult) {
  120. self.storage.save(autotuneResult, as: Settings.autotune)
  121. promise(.success(autotune))
  122. } else {
  123. promise(.success(nil))
  124. }
  125. }
  126. }
  127. }
  128. func makeProfiles(useAutotune: Bool) -> Future<Autotune?, Never> {
  129. Future { promise in
  130. debug(.openAPS, "Start makeProfiles")
  131. self.processQueue.async {
  132. var preferences = self.loadFileFromStorage(name: Settings.preferences)
  133. if preferences.isEmpty {
  134. preferences = Preferences().rawJSON
  135. }
  136. let pumpSettings = self.loadFileFromStorage(name: Settings.settings)
  137. let bgTargets = self.loadFileFromStorage(name: Settings.bgTargets)
  138. let basalProfile = self.loadFileFromStorage(name: Settings.basalProfile)
  139. let isf = self.loadFileFromStorage(name: Settings.insulinSensitivities)
  140. let cr = self.loadFileFromStorage(name: Settings.carbRatios)
  141. let tempTargets = self.loadFileFromStorage(name: Settings.tempTargets)
  142. let model = self.loadFileFromStorage(name: Settings.model)
  143. let autotune = useAutotune ? self.loadFileFromStorage(name: Settings.autotune) : .empty
  144. let pumpProfile = self.makeProfile(
  145. preferences: preferences,
  146. pumpSettings: pumpSettings,
  147. bgTargets: bgTargets,
  148. basalProfile: basalProfile,
  149. isf: isf,
  150. carbRatio: cr,
  151. tempTargets: tempTargets,
  152. model: model,
  153. autotune: RawJSON.null
  154. )
  155. let profile = self.makeProfile(
  156. preferences: preferences,
  157. pumpSettings: pumpSettings,
  158. bgTargets: bgTargets,
  159. basalProfile: basalProfile,
  160. isf: isf,
  161. carbRatio: cr,
  162. tempTargets: tempTargets,
  163. model: model,
  164. autotune: autotune.isEmpty ? .null : autotune
  165. )
  166. self.storage.save(pumpProfile, as: Settings.pumpProfile)
  167. self.storage.save(profile, as: Settings.profile)
  168. if let tunedProfile = Autotune(from: profile) {
  169. promise(.success(tunedProfile))
  170. return
  171. }
  172. promise(.success(nil))
  173. }
  174. }
  175. }
  176. // MARK: - Private
  177. private func iob(pumphistory: JSON, profile: JSON, clock: JSON, autosens: JSON) -> RawJSON {
  178. dispatchPrecondition(condition: .onQueue(processQueue))
  179. return jsWorker.inCommonContext { worker in
  180. worker.evaluate(script: Script(name: Bundle.iob))
  181. worker.evaluate(script: Script(name: Prepare.iob))
  182. return worker.call(function: Function.generate, with: [
  183. pumphistory,
  184. profile,
  185. clock,
  186. autosens
  187. ])
  188. }
  189. }
  190. private func meal(pumphistory: JSON, profile: JSON, basalProfile: JSON, clock: JSON, carbs: JSON, glucose: JSON) -> RawJSON {
  191. dispatchPrecondition(condition: .onQueue(processQueue))
  192. return jsWorker.inCommonContext { worker in
  193. worker.evaluate(script: Script(name: Bundle.meal))
  194. worker.evaluate(script: Script(name: Prepare.meal))
  195. return worker.call(function: Function.generate, with: [
  196. pumphistory,
  197. profile,
  198. clock,
  199. glucose,
  200. basalProfile,
  201. carbs
  202. ])
  203. }
  204. }
  205. private func autotunePrepare(
  206. pumphistory: JSON,
  207. profile: JSON,
  208. glucose: JSON,
  209. pumpprofile: JSON,
  210. categorizeUamAsBasal: Bool,
  211. tuneInsulinCurve: Bool
  212. ) -> RawJSON {
  213. dispatchPrecondition(condition: .onQueue(processQueue))
  214. return jsWorker.inCommonContext { worker in
  215. worker.evaluate(script: Script(name: Bundle.autotunePrep))
  216. worker.evaluate(script: Script(name: Prepare.autotunePrep))
  217. return worker.call(function: Function.generate, with: [
  218. pumphistory,
  219. profile,
  220. glucose,
  221. pumpprofile,
  222. categorizeUamAsBasal,
  223. tuneInsulinCurve
  224. ])
  225. }
  226. }
  227. private func autotuneRun(
  228. autotunePreparedData: JSON,
  229. previousAutotuneResult: JSON,
  230. pumpProfile: JSON
  231. ) -> RawJSON {
  232. dispatchPrecondition(condition: .onQueue(processQueue))
  233. return jsWorker.inCommonContext { worker in
  234. worker.evaluate(script: Script(name: Bundle.autotuneCore))
  235. worker.evaluate(script: Script(name: Prepare.autotuneCore))
  236. return worker.call(function: Function.generate, with: [
  237. autotunePreparedData,
  238. previousAutotuneResult,
  239. pumpProfile
  240. ])
  241. }
  242. }
  243. private func determineBasal(
  244. glucose: JSON,
  245. currentTemp: JSON,
  246. iob: JSON,
  247. profile: JSON,
  248. autosens: JSON,
  249. meal: JSON,
  250. microBolusAllowed: Bool,
  251. reservoir: JSON
  252. ) -> RawJSON {
  253. dispatchPrecondition(condition: .onQueue(processQueue))
  254. return jsWorker.inCommonContext { worker in
  255. worker.evaluate(script: Script(name: Bundle.basalSetTemp))
  256. worker.evaluate(script: Script(name: Bundle.getLastGlucose))
  257. worker.evaluate(script: Script(name: Bundle.determineBasal))
  258. worker.evaluate(script: Script(name: Prepare.determineBasal))
  259. return worker.call(
  260. function: Function.generate,
  261. with: [
  262. iob,
  263. currentTemp,
  264. glucose,
  265. profile,
  266. autosens,
  267. meal,
  268. microBolusAllowed,
  269. reservoir
  270. ]
  271. )
  272. }
  273. }
  274. private func autosense(
  275. glucose: JSON,
  276. pumpHistory: JSON,
  277. basalprofile: JSON,
  278. profile: JSON,
  279. carbs: JSON,
  280. temptargets: JSON
  281. ) -> RawJSON {
  282. dispatchPrecondition(condition: .onQueue(processQueue))
  283. return jsWorker.inCommonContext { worker in
  284. worker.evaluate(script: Script(name: Bundle.autosens))
  285. worker.evaluate(script: Script(name: Prepare.autosens))
  286. return worker.call(
  287. function: Function.generate,
  288. with: [
  289. glucose,
  290. pumpHistory,
  291. basalprofile,
  292. profile,
  293. carbs,
  294. temptargets
  295. ]
  296. )
  297. }
  298. }
  299. private func exportDefaultPreferences() -> RawJSON {
  300. dispatchPrecondition(condition: .onQueue(processQueue))
  301. return jsWorker.inCommonContext { worker in
  302. worker.evaluate(script: Script(name: Bundle.profile))
  303. worker.evaluate(script: Script(name: Prepare.profile))
  304. return worker.call(function: Function.exportDefaults, with: [])
  305. }
  306. }
  307. private func makeProfile(
  308. preferences: JSON,
  309. pumpSettings: JSON,
  310. bgTargets: JSON,
  311. basalProfile: JSON,
  312. isf: JSON,
  313. carbRatio: JSON,
  314. tempTargets: JSON,
  315. model: JSON,
  316. autotune: JSON
  317. ) -> RawJSON {
  318. dispatchPrecondition(condition: .onQueue(processQueue))
  319. return jsWorker.inCommonContext { worker in
  320. worker.evaluate(script: Script(name: Bundle.profile))
  321. worker.evaluate(script: Script(name: Prepare.profile))
  322. return worker.call(
  323. function: Function.generate,
  324. with: [
  325. pumpSettings,
  326. bgTargets,
  327. isf,
  328. basalProfile,
  329. preferences,
  330. carbRatio,
  331. tempTargets,
  332. model,
  333. autotune
  334. ]
  335. )
  336. }
  337. }
  338. private func loadJSON(name: String) -> String {
  339. try! String(contentsOf: Foundation.Bundle.main.url(forResource: "json/\(name)", withExtension: "json")!)
  340. }
  341. private func loadFileFromStorage(name: String) -> RawJSON {
  342. storage.retrieveRaw(name) ?? OpenAPS.defaults(for: name)
  343. }
  344. static func defaults(for file: String) -> RawJSON {
  345. guard let url = Foundation.Bundle.main.url(forResource: "json/defaults/\(file)", withExtension: "") else {
  346. return ""
  347. }
  348. return (try? String(contentsOf: url)) ?? ""
  349. }
  350. }