OpenAPS.swift 13 KB

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