OpenAPS.swift 13 KB

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