OpenAPS.swift 13 KB

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