Merge branch 'dev' into bug798_meal_tbr

This commit is contained in:
Andy Rozman 2021-11-10 23:41:37 +00:00
commit 7c382f735b
583 changed files with 8112 additions and 4558 deletions

View file

@ -109,7 +109,7 @@ android {
defaultConfig { defaultConfig {
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.8.2.8-dev" version "2.8.2.10-dev"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'

View file

@ -113,7 +113,7 @@ class MainActivity : NoSplashAppCompatActivity() {
} }
// initialize screen wake lock // initialize screen wake lock
processPreferenceChange(EventPreferenceChange(resourceHelper.gs(R.string.key_keep_screen_on))) processPreferenceChange(EventPreferenceChange(rh.gs(R.string.key_keep_screen_on)))
binding.mainPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { binding.mainPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrollStateChanged(state: Int) {} override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
@ -124,7 +124,7 @@ class MainActivity : NoSplashAppCompatActivity() {
}) })
//Check here if loop plugin is disabled. Else check via constraints //Check here if loop plugin is disabled. Else check via constraints
if (!loopPlugin.isEnabled(PluginType.LOOP)) versionCheckerUtils.triggerCheckVersion() if (!loopPlugin.isEnabled()) versionCheckerUtils.triggerCheckVersion()
setUserStats() setUserStats()
setupViews() setupViews()
disposable += rxBus disposable += rxBus
@ -146,7 +146,7 @@ class MainActivity : NoSplashAppCompatActivity() {
} }
androidPermission.notifyForStoragePermission(this) androidPermission.notifyForStoragePermission(this)
androidPermission.notifyForBatteryOptimizationPermission(this) androidPermission.notifyForBatteryOptimizationPermission(this)
androidPermission.notifyForLocationPermissions(this) if (!config.NSCLIENT) androidPermission.notifyForLocationPermissions(this)
if (config.PUMPDRIVERS) { if (config.PUMPDRIVERS) {
androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin) androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin)
androidPermission.notifyForSystemWindowPermissions(this) androidPermission.notifyForSystemWindowPermissions(this)
@ -173,8 +173,8 @@ class MainActivity : NoSplashAppCompatActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
protectionCheck.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null, protectionCheck.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null,
UIRunnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed)) { finish() } }, UIRunnable { OKDialog.show(this, "", rh.gs(R.string.authorizationfailed)) { finish() } },
UIRunnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed)) { finish() } } UIRunnable { OKDialog.show(this, "", rh.gs(R.string.authorizationfailed)) { finish() } }
) )
} }
@ -184,8 +184,8 @@ class MainActivity : NoSplashAppCompatActivity() {
} }
private fun processPreferenceChange(ev: EventPreferenceChange) { private fun processPreferenceChange(ev: EventPreferenceChange) {
if (ev.isChanged(resourceHelper, R.string.key_keep_screen_on)) setWakeLock() if (ev.isChanged(rh, R.string.key_keep_screen_on)) setWakeLock()
if (ev.isChanged(resourceHelper, R.string.key_skin)) recreate() if (ev.isChanged(rh, R.string.key_skin)) recreate()
} }
private fun setupViews() { private fun setupViews() {
@ -259,7 +259,7 @@ class MainActivity : NoSplashAppCompatActivity() {
private fun setPluginPreferenceMenuName() { private fun setPluginPreferenceMenuName() {
if (binding.mainPager.currentItem >= 0) { if (binding.mainPager.currentItem >= 0) {
val plugin = (binding.mainPager.adapter as TabPageAdapter).getPluginAt(binding.mainPager.currentItem) val plugin = (binding.mainPager.adapter as TabPageAdapter).getPluginAt(binding.mainPager.currentItem)
this.menu?.findItem(R.id.nav_plugin_preferences)?.title = resourceHelper.gs(R.string.nav_preferences_plugin, plugin.name) this.menu?.findItem(R.id.nav_plugin_preferences)?.title = rh.gs(R.string.nav_preferences_plugin, plugin.name)
} }
} }
@ -309,18 +309,18 @@ class MainActivity : NoSplashAppCompatActivity() {
R.id.nav_about -> { R.id.nav_about -> {
var message = "Build: ${BuildConfig.BUILDVERSION}\n" var message = "Build: ${BuildConfig.BUILDVERSION}\n"
message += "Flavor: ${BuildConfig.FLAVOR}${BuildConfig.BUILD_TYPE}\n" message += "Flavor: ${BuildConfig.FLAVOR}${BuildConfig.BUILD_TYPE}\n"
message += "${resourceHelper.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.getVersion()}" message += "${rh.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.getVersion()}"
if (buildHelper.isEngineeringMode()) message += "\n${resourceHelper.gs(R.string.engineering_mode_enabled)}" if (buildHelper.isEngineeringMode()) message += "\n${rh.gs(R.string.engineering_mode_enabled)}"
if (!fabricPrivacy.fabricEnabled()) message += "\n${resourceHelper.gs(R.string.fabric_upload_disabled)}" if (!fabricPrivacy.fabricEnabled()) message += "\n${rh.gs(R.string.fabric_upload_disabled)}"
message += resourceHelper.gs(R.string.about_link_urls) message += rh.gs(R.string.about_link_urls)
val messageSpanned = SpannableString(message) val messageSpanned = SpannableString(message)
Linkify.addLinks(messageSpanned, Linkify.WEB_URLS) Linkify.addLinks(messageSpanned, Linkify.WEB_URLS)
AlertDialog.Builder(this) AlertDialog.Builder(this)
.setTitle(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION) .setTitle(rh.gs(R.string.app_name) + " " + BuildConfig.VERSION)
.setIcon(iconsProvider.getIcon()) .setIcon(iconsProvider.getIcon())
.setMessage(messageSpanned) .setMessage(messageSpanned)
.setPositiveButton(resourceHelper.gs(R.string.ok), null) .setPositiveButton(rh.gs(R.string.ok), null)
.setNeutralButton(resourceHelper.gs(R.string.cta_dont_kill_my_app_info)) { _, _ -> DokiActivity.start(context = this@MainActivity) } .setNeutralButton(rh.gs(R.string.cta_dont_kill_my_app_info)) { _, _ -> DokiActivity.start(context = this@MainActivity) }
.create().apply { .create().apply {
show() show()
findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance() findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance()

View file

@ -89,8 +89,8 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
setContentView(binding.root) setContentView(binding.root)
// We don't want to use injected singletons but own instance working on top of different data // We don't want to use injected singletons but own instance working on top of different data
iobCobCalculator = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) iobCobCalculator = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, rh, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository)
overviewData = OverviewData(injector, aapsLogger, resourceHelper, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, config, loopPlugin, nsDeviceStatus, repository, overviewMenus, iobCobCalculator, translator) overviewData = OverviewData(injector, aapsLogger, rh, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, config, loopPlugin, nsDeviceStatus, repository, overviewMenus, iobCobCalculator, translator)
binding.left.setOnClickListener { binding.left.setOnClickListener {
adjustTimeRange(overviewData.fromTime - T.hours(rangeToDisplay.toLong()).msecs()) adjustTimeRange(overviewData.fromTime - T.hours(rangeToDisplay.toLong()).msecs())
@ -158,7 +158,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80 axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80
binding.bgGraph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) binding.bgGraph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
binding.bgGraph.gridLabelRenderer?.reloadStyles() binding.bgGraph.gridLabelRenderer?.reloadStyles()
binding.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth binding.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth
@ -241,8 +241,8 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val graph = GraphView(this) val graph = GraphView(this)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) } graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rh.dpToPx(100)).also { it.setMargins(0, rh.dpToPx(15), 0, rh.dpToPx(10)) }
graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) graph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
@ -251,7 +251,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
relativeLayout.addView(graph) relativeLayout.addView(graph)
val label = TextView(this) val label = TextView(this)
val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) } val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) }
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
label.layoutParams = layoutParams label.layoutParams = layoutParams

View file

@ -62,7 +62,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
private var filter = "" private var filter = ""
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var pluginStore: PluginStore @Inject lateinit var pluginStore: PluginStore
@ -197,21 +197,21 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
rxBus.send(EventPreferenceChange(key)) rxBus.send(EventPreferenceChange(key))
if (key == resourceHelper.gs(R.string.key_language)) { if (key == rh.gs(R.string.key_language)) {
rxBus.send(EventRebuildTabs(true)) rxBus.send(EventRebuildTabs(true))
//recreate() does not update language so better close settings //recreate() does not update language so better close settings
activity?.finish() activity?.finish()
} }
if (key == resourceHelper.gs(R.string.key_short_tabtitles)) { if (key == rh.gs(R.string.key_short_tabtitles)) {
rxBus.send(EventRebuildTabs()) rxBus.send(EventRebuildTabs())
} }
if (key == resourceHelper.gs(R.string.key_units)) { if (key == rh.gs(R.string.key_units)) {
activity?.recreate() activity?.recreate()
return return
} }
if (key == resourceHelper.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) { if (key == rh.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) {
activity?.let { activity?.let {
show(it, resourceHelper.gs(R.string.configbuilder_sensitivity), resourceHelper.gs(R.string.sensitivity_warning)) show(it, rh.gs(R.string.configbuilder_sensitivity), rh.gs(R.string.sensitivity_warning))
} }
} }
checkForBiometricFallback(key) checkForBiometricFallback(key)
@ -228,15 +228,15 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
private fun checkForBiometricFallback(key: String) { private fun checkForBiometricFallback(key: String) {
// Biometric protection activated without set master password // Biometric protection activated without set master password
if ((resourceHelper.gs(R.string.key_settings_protection) == key || if ((rh.gs(R.string.key_settings_protection) == key ||
resourceHelper.gs(R.string.key_application_protection) == key || rh.gs(R.string.key_application_protection) == key ||
resourceHelper.gs(R.string.key_bolus_protection) == key) && rh.gs(R.string.key_bolus_protection) == key) &&
sp.getString(R.string.key_master_password, "") == "" && sp.getString(R.string.key_master_password, "") == "" &&
sp.getInt(key, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal sp.getInt(key, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal
) { ) {
activity?.let { activity?.let {
val title = resourceHelper.gs(R.string.unsecure_fallback_biometric) val title = rh.gs(R.string.unsecure_fallback_biometric)
val message = resourceHelper.gs(R.string.master_password_missing, resourceHelper.gs(R.string.configbuilder_general), resourceHelper.gs(R.string.protection)) val message = rh.gs(R.string.master_password_missing, rh.gs(R.string.configbuilder_general), rh.gs(R.string.protection))
show(it, title = title, message = message) show(it, title = title, message = message)
} }
} }
@ -245,10 +245,10 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
val isBiometricActivated = sp.getInt(R.string.key_settings_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal || val isBiometricActivated = sp.getInt(R.string.key_settings_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal ||
sp.getInt(R.string.key_application_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal || sp.getInt(R.string.key_application_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal ||
sp.getInt(R.string.key_bolus_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal sp.getInt(R.string.key_bolus_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal
if (resourceHelper.gs(R.string.key_master_password) == key && sp.getString(key, "") == "" && isBiometricActivated) { if (rh.gs(R.string.key_master_password) == key && sp.getString(key, "") == "" && isBiometricActivated) {
activity?.let { activity?.let {
val title = resourceHelper.gs(R.string.unsecure_fallback_biometric) val title = rh.gs(R.string.unsecure_fallback_biometric)
val message = resourceHelper.gs(R.string.unsecure_fallback_descriotion_biometric) val message = rh.gs(R.string.unsecure_fallback_descriotion_biometric)
show(it, title = title, message = message) show(it, title = title, message = message)
} }
} }
@ -278,11 +278,11 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
private fun adjustUnitDependentPrefs(pref: Preference) { // convert preferences values to current units private fun adjustUnitDependentPrefs(pref: Preference) { // convert preferences values to current units
val unitDependent = arrayOf( val unitDependent = arrayOf(
resourceHelper.gs(R.string.key_hypo_target), rh.gs(R.string.key_hypo_target),
resourceHelper.gs(R.string.key_activity_target), rh.gs(R.string.key_activity_target),
resourceHelper.gs(R.string.key_eatingsoon_target), rh.gs(R.string.key_eatingsoon_target),
resourceHelper.gs(R.string.key_high_mark), rh.gs(R.string.key_high_mark),
resourceHelper.gs(R.string.key_low_mark) rh.gs(R.string.key_low_mark)
) )
if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) { if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) {
val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text)) val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text))
@ -322,20 +322,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
pref.setSummary(pref.entry) pref.setSummary(pref.entry)
// Preferences // Preferences
// Preferences // Preferences
if (pref.getKey() == resourceHelper.gs(R.string.key_settings_protection)) { if (pref.getKey() == rh.gs(R.string.key_settings_protection)) {
val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_settings_password)) val pass: Preference? = findPreference(rh.gs(R.string.key_settings_password))
if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString()
} }
// Application // Application
// Application // Application
if (pref.getKey() == resourceHelper.gs(R.string.key_application_protection)) { if (pref.getKey() == rh.gs(R.string.key_application_protection)) {
val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_application_password)) val pass: Preference? = findPreference(rh.gs(R.string.key_application_password))
if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString()
} }
// Bolus // Bolus
// Bolus // Bolus
if (pref.getKey() == resourceHelper.gs(R.string.key_bolus_protection)) { if (pref.getKey() == rh.gs(R.string.key_bolus_protection)) {
val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_bolus_password)) val pass: Preference? = findPreference(rh.gs(R.string.key_bolus_password))
if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString()
} }
} }
@ -353,10 +353,10 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
} }
val hmacPasswords = arrayOf( val hmacPasswords = arrayOf(
resourceHelper.gs(R.string.key_bolus_password), rh.gs(R.string.key_bolus_password),
resourceHelper.gs(R.string.key_master_password), rh.gs(R.string.key_master_password),
resourceHelper.gs(R.string.key_application_password), rh.gs(R.string.key_application_password),
resourceHelper.gs(R.string.key_settings_password) rh.gs(R.string.key_settings_password)
) )
if (pref is Preference) { if (pref is Preference) {
@ -364,7 +364,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
if (sp.getString(pref.key, "").startsWith("hmac:")) { if (sp.getString(pref.key, "").startsWith("hmac:")) {
pref.summary = "******" pref.summary = "******"
} else { } else {
pref.summary = resourceHelper.gs(R.string.password_not_set) pref.summary = rh.gs(R.string.password_not_set)
} }
} }
} }
@ -393,26 +393,26 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
override fun onPreferenceTreeClick(preference: Preference?): Boolean { override fun onPreferenceTreeClick(preference: Preference?): Boolean {
context?.let { context -> context?.let { context ->
if (preference != null) { if (preference != null) {
if (preference.key == resourceHelper.gs(R.string.key_master_password)) { if (preference.key == rh.gs(R.string.key_master_password)) {
passwordCheck.queryPassword(context, R.string.current_master_password, R.string.key_master_password, { passwordCheck.queryPassword(context, R.string.current_master_password, R.string.key_master_password, {
passwordCheck.setPassword(context, R.string.master_password, R.string.key_master_password) passwordCheck.setPassword(context, R.string.master_password, R.string.key_master_password)
}) })
return true return true
} }
if (preference.key == resourceHelper.gs(R.string.key_settings_password)) { if (preference.key == rh.gs(R.string.key_settings_password)) {
passwordCheck.setPassword(context, R.string.settings_password, R.string.key_settings_password) passwordCheck.setPassword(context, R.string.settings_password, R.string.key_settings_password)
return true return true
} }
if (preference.key == resourceHelper.gs(R.string.key_bolus_password)) { if (preference.key == rh.gs(R.string.key_bolus_password)) {
passwordCheck.setPassword(context, R.string.bolus_password, R.string.key_bolus_password) passwordCheck.setPassword(context, R.string.bolus_password, R.string.key_bolus_password)
return true return true
} }
if (preference.key == resourceHelper.gs(R.string.key_application_password)) { if (preference.key == rh.gs(R.string.key_application_password)) {
passwordCheck.setPassword(context, R.string.application_password, R.string.key_application_password) passwordCheck.setPassword(context, R.string.application_password, R.string.key_application_password)
return true return true
} }
// NSClient copy settings // NSClient copy settings
if (preference.key == resourceHelper.gs(R.string.key_statuslights_copy_ns)) { if (preference.key == rh.gs(R.string.key_statuslights_copy_ns)) {
nsSettingStatus.copyStatusLightsNsSettings(context) nsSettingStatus.copyStatusLightsNsSettings(context)
return true return true
} }

View file

@ -31,7 +31,7 @@ class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompa
override fun afterTextChanged(s: Editable) {} override fun afterTextChanged(s: Editable) {}
}) })
title = resourceHelper.gs(R.string.nav_preferences) title = rh.gs(R.string.nav_preferences)
supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true)
myPreferenceFragment = MyPreferenceFragment() myPreferenceFragment = MyPreferenceFragment()

View file

@ -140,7 +140,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
val profile = if (typeSelected[tabSelected] == ProfileType.MOTOL_DEFAULT) defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) val profile = if (typeSelected[tabSelected] == ProfileType.MOTOL_DEFAULT) defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
else defaultProfileDPV.profile(age, tdd, pct / 100.0, profileFunction.getUnits()) else defaultProfileDPV.profile(age, tdd, pct / 100.0, profileFunction.getUnits())
profile?.let { profile?.let {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable { OKDialog.showConfirmation(this, rh.gs(R.string.careportal_profileswitch), rh.gs(R.string.copytolocalprofile), Runnable {
localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " + localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " +
dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) dateUtil.dateAndTimeAndSecondsString(dateUtil.now())
.replace(".", "/") .replace(".", "/")
@ -168,7 +168,11 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
binding.basalpctfromtdd.setParams(32.0, 32.0, 37.0, 1.0, DecimalFormat("0"), false, null) binding.basalpctfromtdd.setParams(32.0, 32.0, 37.0, 1.0, DecimalFormat("0"), false, null)
binding.tdds.text = tddCalculator.stats() binding.tdds.text = getString(R.string.tdd) + ": " + rh.gs(R.string.calculation_in_progress);
Thread {
val tdds = tddCalculator.stats()
runOnUiThread { binding.tdds.text = tdds }
}.start()
// Current profile // Current profile
binding.currentProfileText.text = profileFunction.getProfileName() binding.currentProfileText.text = profileFunction.getProfileName()
@ -242,8 +246,8 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
private fun getProfileName(age: Double, tdd: Double, weight: Double, basalSumPct: Double, tab: Int): String = private fun getProfileName(age: Double, tdd: Double, weight: Double, basalSumPct: Double, tab: Int): String =
when (typeSelected[tab]) { when (typeSelected[tab]) {
ProfileType.MOTOL_DEFAULT -> if (tdd > 0) resourceHelper.gs(R.string.formatwithtdd, age, tdd) else resourceHelper.gs(R.string.formatwithweight, age, weight) ProfileType.MOTOL_DEFAULT -> if (tdd > 0) rh.gs(R.string.formatwithtdd, age, tdd) else rh.gs(R.string.formatwithweight, age, weight)
ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt()) ProfileType.DPV_DEFAULT -> rh.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt())
ProfileType.CURRENT -> profileFunction.getProfileName() ProfileType.CURRENT -> profileFunction.getProfileName()
ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString() ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString()
ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].originalCustomizedName ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].originalCustomizedName
@ -263,16 +267,16 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
tabSelected = tab tabSelected = tab
typeSelected[tabSelected] = newContent typeSelected[tabSelected] = newContent
binding.profiletypeTitle.defaultHintTextColor = ColorStateList.valueOf(resourceHelper.gc(if (tab == 0) R.color.tabBgColorSelected else R.color.examinedProfile)) binding.profiletypeTitle.defaultHintTextColor = ColorStateList.valueOf(rh.gc(if (tab == 0) R.color.tabBgColorSelected else R.color.examinedProfile))
// show new content // show new content
binding.profiletype.setText( binding.profiletype.setText(
when (typeSelected[tabSelected]) { when (typeSelected[tabSelected]) {
ProfileType.MOTOL_DEFAULT -> resourceHelper.gs(R.string.motoldefaultprofile) ProfileType.MOTOL_DEFAULT -> rh.gs(R.string.motoldefaultprofile)
ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.dpvdefaultprofile) ProfileType.DPV_DEFAULT -> rh.gs(R.string.dpvdefaultprofile)
ProfileType.CURRENT -> resourceHelper.gs(R.string.currentprofile) ProfileType.CURRENT -> rh.gs(R.string.currentprofile)
ProfileType.AVAILABLE_PROFILE -> resourceHelper.gs(R.string.availableprofile) ProfileType.AVAILABLE_PROFILE -> rh.gs(R.string.availableprofile)
ProfileType.PROFILE_SWITCH -> resourceHelper.gs(R.string.careportal_profileswitch) ProfileType.PROFILE_SWITCH -> rh.gs(R.string.careportal_profileswitch)
}) })
binding.defaultProfile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility() binding.defaultProfile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility()
binding.currentProfile.visibility = (newContent == ProfileType.CURRENT).toVisibility() binding.currentProfile.visibility = (newContent == ProfileType.CURRENT).toVisibility()
@ -293,7 +297,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
} }
private fun setBackgroundColorOnSelected(tab: Int) { private fun setBackgroundColorOnSelected(tab: Int) {
binding.menu1.setBackgroundColor(resourceHelper.gc(if (tab == 1) R.color.defaultbackground else R.color.tempbasal)) binding.menu1.setBackgroundColor(rh.gc(if (tab == 1) R.color.defaultbackground else R.color.tempbasal))
binding.menu2.setBackgroundColor(resourceHelper.gc(if (tab == 0) R.color.defaultbackground else R.color.examinedProfile)) binding.menu2.setBackgroundColor(rh.gc(if (tab == 0) R.color.defaultbackground else R.color.examinedProfile))
} }
} }

View file

@ -9,6 +9,7 @@ import info.nightscout.androidaps.databinding.ActivityStatsBinding
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.utils.ActivityMonitor import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TddCalculator
import info.nightscout.androidaps.utils.stats.TirCalculator import info.nightscout.androidaps.utils.stats.TirCalculator
import javax.inject.Inject import javax.inject.Inject
@ -28,9 +29,9 @@ class StatsActivity : NoSplashAppCompatActivity() {
binding = ActivityStatsBinding.inflate(layoutInflater) binding = ActivityStatsBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
binding.tdds.text = getString(R.string.tdd) + ": " + getString(R.string.calculation_in_progress) binding.tdds.text = getString(R.string.tdd) + ": " + rh.gs(R.string.calculation_in_progress)
binding.tir.text = getString(R.string.tir) + ": " + getString(R.string.calculation_in_progress) binding.tir.text = getString(R.string.tir) + ": " + rh.gs(R.string.calculation_in_progress)
binding.activity.text = getString(R.string.activitymonitor) + ": " + getString(R.string.calculation_in_progress) binding.activity.text = rh.gs(R.string.activitymonitor) + ": " + rh.gs(R.string.calculation_in_progress)
Thread { Thread {
val tdds = tddCalculator.stats() val tdds = tddCalculator.stats()
@ -47,7 +48,7 @@ class StatsActivity : NoSplashAppCompatActivity() {
binding.ok.setOnClickListener { finish() } binding.ok.setOnClickListener { finish() }
binding.reset.setOnClickListener { binding.reset.setOnClickListener {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.doyouwantresetstats)) { OKDialog.showConfirmation(this, rh.gs(R.string.doyouwantresetstats)) {
uel.log(Action.STAT_RESET, Sources.Stats) uel.log(Action.STAT_RESET, Sources.Stats)
activityMonitor.reset() activityMonitor.reset()
recreate() recreate()

View file

@ -24,8 +24,8 @@ class TreatmentsActivity : NoSplashAppCompatActivity() {
binding = TreatmentsFragmentBinding.inflate(layoutInflater) binding = TreatmentsFragmentBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
binding.tempBasals.visibility = buildHelper.isEngineeringMode().toVisibility() //binding.tempBasals.visibility = buildHelper.isEngineeringMode().toVisibility()
binding.extendedBoluses.visibility = (buildHelper.isEngineeringMode() && !activePlugin.activePump.isFakingTempsByExtendedBoluses).toVisibility() //binding.extendedBoluses.visibility = (buildHelper.isEngineeringMode() && !activePlugin.activePump.isFakingTempsByExtendedBoluses).toVisibility()
binding.treatments.setOnClickListener { binding.treatments.setOnClickListener {
setFragment(TreatmentsBolusCarbsFragment()) setFragment(TreatmentsBolusCarbsFragment())
@ -67,14 +67,14 @@ class TreatmentsActivity : NoSplashAppCompatActivity() {
} }
private fun setBackgroundColorOnSelected(selected: View) { private fun setBackgroundColorOnSelected(selected: View) {
binding.treatments.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.treatments.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.extendedBoluses.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.extendedBoluses.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.tempBasals.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.tempBasals.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.tempTargets.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.tempTargets.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.profileSwitches.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.profileSwitches.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.careportal.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.careportal.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.userentry.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.userentry.setBackgroundColor(rh.gc(R.color.defaultbackground))
selected.setBackgroundColor(resourceHelper.gc(R.color.tabBgColorSelected)) selected.setBackgroundColor(rh.gc(R.color.tabBgColorSelected))
} }
} }

View file

@ -56,7 +56,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -93,7 +93,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { OKDialog.showConfirmation(activity, rh.gs(R.string.refresheventsfromnightscout) + "?") {
uel.log(Action.TREATMENTS_NS_REFRESH, Sources.Treatments) uel.log(Action.TREATMENTS_NS_REFRESH, Sources.Treatments)
disposable += disposable +=
Completable.fromAction { Completable.fromAction {
@ -116,7 +116,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
} }
binding.deleteFutureTreatments.setOnClickListener { binding.deleteFutureTreatments.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.deletefuturetreatments) + "?", Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.overview_treatment_label), rh.gs(R.string.deletefuturetreatments) + "?", Runnable {
uel.log(Action.DELETE_FUTURE_TREATMENTS, Sources.Treatments) uel.log(Action.DELETE_FUTURE_TREATMENTS, Sources.Treatments)
repository repository
.getBolusesDataFromTime(dateUtil.now(), false) .getBolusesDataFromTime(dateUtil.now(), false)
@ -278,28 +278,28 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
holder.binding.bolusLayout.visibility = (ml.bolus != null && (ml.bolus.isValid || binding.showInvalidated.isChecked)).toVisibility() holder.binding.bolusLayout.visibility = (ml.bolus != null && (ml.bolus.isValid || binding.showInvalidated.isChecked)).toVisibility()
ml.bolus?.let { bolus -> ml.bolus?.let { bolus ->
holder.binding.bolusDate.text = dateUtil.timeString(bolus.timestamp) holder.binding.bolusDate.text = dateUtil.timeString(bolus.timestamp)
holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, bolus.amount) holder.binding.insulin.text = rh.gs(R.string.formatinsulinunits, bolus.amount)
holder.binding.bolusNs.visibility = (bolus.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.bolusNs.visibility = (bolus.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.bolusPump.visibility = (bolus.interfaceIDs.pumpId != null).toVisibility() holder.binding.bolusPump.visibility = (bolus.interfaceIDs.pumpId != null).toVisibility()
holder.binding.bolusInvalid.visibility = bolus.isValid.not().toVisibility() holder.binding.bolusInvalid.visibility = bolus.isValid.not().toVisibility()
val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia) val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iobContrib) holder.binding.iob.text = rh.gs(R.string.formatinsulinunits, iob.iobContrib)
holder.binding.iobLabel.visibility = (iob.iobContrib != 0.0).toVisibility() holder.binding.iobLabel.visibility = (iob.iobContrib != 0.0).toVisibility()
holder.binding.iob.visibility = (iob.iobContrib != 0.0).toVisibility() holder.binding.iob.visibility = (iob.iobContrib != 0.0).toVisibility()
if (bolus.timestamp > dateUtil.now()) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor) if (bolus.timestamp > dateUtil.now()) holder.binding.date.setTextColor(rh.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor)
holder.binding.mealOrCorrection.text = holder.binding.mealOrCorrection.text =
when (ml.bolus.type) { when (ml.bolus.type) {
Bolus.Type.SMB -> "SMB" Bolus.Type.SMB -> "SMB"
Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus) Bolus.Type.NORMAL -> rh.gs(R.string.mealbolus)
Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime) Bolus.Type.PRIMING -> rh.gs(R.string.prime)
} }
} }
// Carbs // Carbs
holder.binding.carbsLayout.visibility = (ml.carbs != null && (ml.carbs.isValid || binding.showInvalidated.isChecked)).toVisibility() holder.binding.carbsLayout.visibility = (ml.carbs != null && (ml.carbs.isValid || binding.showInvalidated.isChecked)).toVisibility()
ml.carbs?.let { carbs -> ml.carbs?.let { carbs ->
holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp) holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp)
holder.binding.carbs.text = resourceHelper.gs(R.string.format_carbs, carbs.amount.toInt()) holder.binding.carbs.text = rh.gs(R.string.format_carbs, carbs.amount.toInt())
holder.binding.carbsDuration.text = if (carbs.duration > 0) resourceHelper.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) else "" holder.binding.carbsDuration.text = if (carbs.duration > 0) rh.gs(R.string.format_mins, T.msecs(carbs.duration).mins().toInt()) else ""
holder.binding.carbsNs.visibility = (carbs.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.carbsNs.visibility = (carbs.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility() holder.binding.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility()
holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility() holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility()
@ -334,10 +334,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
binding.bolusRemove.setOnClickListener { ml -> binding.bolusRemove.setOnClickListener { ml ->
val bolus = (ml.tag as MealLink?)?.bolus ?: return@setOnClickListener val bolus = (ml.tag as MealLink?)?.bolus ?: return@setOnClickListener
activity?.let { activity -> activity?.let { activity ->
val text = resourceHelper.gs(R.string.configbuilder_insulin) + ": " + val text = rh.gs(R.string.configbuilder_insulin) + ": " +
resourceHelper.gs(R.string.formatinsulinunits, bolus.amount) + "\n" + rh.gs(R.string.formatinsulinunits, bolus.amount) + "\n" +
resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(bolus.timestamp) rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(bolus.timestamp)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable {
uel.log( uel.log(
Action.BOLUS_REMOVED, Sources.Treatments, Action.BOLUS_REMOVED, Sources.Treatments,
ValueWithUnit.Timestamp(bolus.timestamp), ValueWithUnit.Timestamp(bolus.timestamp),
@ -356,10 +356,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
binding.carbsRemove.setOnClickListener { ml -> binding.carbsRemove.setOnClickListener { ml ->
val carb = (ml.tag as MealLink?)?.carbs ?: return@setOnClickListener val carb = (ml.tag as MealLink?)?.carbs ?: return@setOnClickListener
activity?.let { activity -> activity?.let { activity ->
val text = resourceHelper.gs(R.string.carbs) + ": " + val text = rh.gs(R.string.carbs) + ": " +
resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, carb.amount.toInt()) + "\n" + rh.gs(R.string.carbs) + ": " + rh.gs(R.string.format_carbs, carb.amount.toInt()) + "\n" +
resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(carb.timestamp) rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(carb.timestamp)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable {
uel.log( uel.log(
Action.CARBS_REMOVED, Sources.Treatments, Action.CARBS_REMOVED, Sources.Treatments,
ValueWithUnit.Timestamp(carb.timestamp), ValueWithUnit.Timestamp(carb.timestamp),

View file

@ -48,7 +48,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -76,7 +76,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal), rh.gs(R.string.refresheventsfromnightscout) + " ?", Runnable {
uel.log(Action.CAREPORTAL_NS_REFRESH, Sources.Treatments) uel.log(Action.CAREPORTAL_NS_REFRESH, Sources.Treatments)
disposable += Completable.fromAction { repository.deleteAllTherapyEventsEntries() } disposable += Completable.fromAction { repository.deleteAllTherapyEventsEntries() }
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
@ -90,9 +90,9 @@ class TreatmentsCareportalFragment : DaggerFragment() {
} }
binding.removeAndroidapsStartedEvents.setOnClickListener { binding.removeAndroidapsStartedEvents.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.careportal_removestartedevents), Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal), rh.gs(R.string.careportal_removestartedevents), Runnable {
uel.log(Action.RESTART_EVENTS_REMOVED, Sources.Treatments) uel.log(Action.RESTART_EVENTS_REMOVED, Sources.Treatments)
repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction(resourceHelper.gs(R.string.androidaps_start))) repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction(rh.gs(R.string.androidaps_start)))
.subscribe( .subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated therapy event $it") } }, { result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) } { aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) }
@ -164,7 +164,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility() holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(therapyEvent.timestamp) holder.binding.date.text = dateUtil.dateAndTimeString(therapyEvent.timestamp)
holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else dateUtil.niceTimeScalar(therapyEvent.duration, resourceHelper) holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else dateUtil.niceTimeScalar(therapyEvent.duration, rh)
holder.binding.note.text = therapyEvent.note holder.binding.note.text = therapyEvent.note
holder.binding.type.text = translator.translate(therapyEvent.type) holder.binding.type.text = translator.translate(therapyEvent.type)
holder.binding.remove.tag = therapyEvent holder.binding.remove.tag = therapyEvent
@ -182,11 +182,11 @@ class TreatmentsCareportalFragment : DaggerFragment() {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val therapyEvent = v.tag as TherapyEvent val therapyEvent = v.tag as TherapyEvent
activity?.let { activity -> activity?.let { activity ->
val text = resourceHelper.gs(R.string.eventtype) + ": " + translator.translate(therapyEvent.type) + "\n" + val text = rh.gs(R.string.eventtype) + ": " + translator.translate(therapyEvent.type) + "\n" +
resourceHelper.gs(R.string.notes_label) + ": " + (therapyEvent.note rh.gs(R.string.notes_label) + ": " + (therapyEvent.note
?: "") + "\n" + ?: "") + "\n" +
resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp) rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable {
uel.log(Action.CAREPORTAL_REMOVED, Sources.Treatments, therapyEvent.note , uel.log(Action.CAREPORTAL_REMOVED, Sources.Treatments, therapyEvent.note ,
ValueWithUnit.Timestamp(therapyEvent.timestamp), ValueWithUnit.Timestamp(therapyEvent.timestamp),
ValueWithUnit.TherapyEventType(therapyEvent.type)) ValueWithUnit.TherapyEventType(therapyEvent.type))

View file

@ -50,7 +50,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@ -128,18 +128,18 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
if (extendedBolus.isInProgress(dateUtil)) { if (extendedBolus.isInProgress(dateUtil)) {
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp)
holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive)) holder.binding.date.setTextColor(rh.gc(R.color.colorActive))
} else { } else {
holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) + " - " + dateUtil.timeString(extendedBolus.end) holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) + " - " + dateUtil.timeString(extendedBolus.end)
holder.binding.date.setTextColor(holder.binding.insulin.currentTextColor) holder.binding.date.setTextColor(holder.binding.insulin.currentTextColor)
} }
val profile = profileFunction.getProfile(extendedBolus.timestamp) ?: return val profile = profileFunction.getProfile(extendedBolus.timestamp) ?: return
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins()) holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins())
holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.amount) holder.binding.insulin.text = rh.gs(R.string.formatinsulinunits, extendedBolus.amount)
val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile, activePlugin.activeInsulin) val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile, activePlugin.activeInsulin)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iob) holder.binding.iob.text = rh.gs(R.string.formatinsulinunits, iob.iob)
holder.binding.ratio.text = resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate) holder.binding.ratio.text = rh.gs(R.string.pump_basebasalrate, extendedBolus.rate)
if (iob.iob != 0.0) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.insulin.currentTextColor) if (iob.iob != 0.0) holder.binding.iob.setTextColor(rh.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.insulin.currentTextColor)
holder.binding.remove.tag = extendedBolus holder.binding.remove.tag = extendedBolus
} }
@ -153,10 +153,10 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val extendedBolus = v.tag as ExtendedBolus val extendedBolus = v.tag as ExtendedBolus
context?.let { context -> context?.let { context ->
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(context, rh.gs(R.string.removerecord),
""" """
${resourceHelper.gs(R.string.extended_bolus)} ${rh.gs(R.string.extended_bolus)}
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.timestamp)} ${rh.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.timestamp)}
""".trimIndent(), { _: DialogInterface, _: Int -> """.trimIndent(), { _: DialogInterface, _: Int ->
uel.log(Action.EXTENDED_BOLUS_REMOVED, Sources.Treatments, uel.log(Action.EXTENDED_BOLUS_REMOVED, Sources.Treatments,
ValueWithUnit.Timestamp(extendedBolus.timestamp), ValueWithUnit.Timestamp(extendedBolus.timestamp),

View file

@ -52,7 +52,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@ -80,7 +80,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.refresheventsfromnightscout) + "?") { OKDialog.showConfirmation(activity, rh.gs(R.string.refresheventsfromnightscout) + "?") {
uel.log(Action.TREATMENTS_NS_REFRESH, Sources.Treatments) uel.log(Action.TREATMENTS_NS_REFRESH, Sources.Treatments)
disposable += disposable +=
Completable.fromAction { Completable.fromAction {
@ -179,9 +179,9 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
holder.binding.ph.visibility = (profileSwitch is ProfileSealed.EPS).toVisibility() holder.binding.ph.visibility = (profileSwitch is ProfileSealed.EPS).toVisibility()
holder.binding.ns.visibility = (profileSwitch.interfaceIDs_backing?.nightscoutId != null).toVisibility() holder.binding.ns.visibility = (profileSwitch.interfaceIDs_backing?.nightscoutId != null).toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(profileSwitch.timestamp) holder.binding.date.text = dateUtil.dateAndTimeString(profileSwitch.timestamp)
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(profileSwitch.duration ?: 0L).mins()) holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(profileSwitch.duration ?: 0L).mins())
holder.binding.name.text = if (profileSwitch is ProfileSealed.PS) profileSwitch.value.getCustomizedName() else if (profileSwitch is ProfileSealed.EPS) profileSwitch.value.originalCustomizedName else "" holder.binding.name.text = if (profileSwitch is ProfileSealed.PS) profileSwitch.value.getCustomizedName() else if (profileSwitch is ProfileSealed.EPS) profileSwitch.value.originalCustomizedName else ""
if (profileSwitch.isInProgress(dateUtil)) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive)) if (profileSwitch.isInProgress(dateUtil)) holder.binding.date.setTextColor(rh.gc(R.color.colorActive))
else holder.binding.date.setTextColor(holder.binding.duration.currentTextColor) else holder.binding.date.setTextColor(holder.binding.duration.currentTextColor)
holder.binding.remove.tag = profileSwitch holder.binding.remove.tag = profileSwitch
holder.binding.clone.tag = profileSwitch holder.binding.clone.tag = profileSwitch
@ -192,7 +192,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
holder.binding.remove.visibility = (profileSwitch is ProfileSealed.PS).toVisibility() holder.binding.remove.visibility = (profileSwitch is ProfileSealed.PS).toVisibility()
holder.binding.clone.visibility = (profileSwitch is ProfileSealed.PS).toVisibility() holder.binding.clone.visibility = (profileSwitch is ProfileSealed.PS).toVisibility()
holder.binding.spacer.visibility = (profileSwitch is ProfileSealed.PS).toVisibility() holder.binding.spacer.visibility = (profileSwitch is ProfileSealed.PS).toVisibility()
holder.binding.root.setBackgroundColor(resourceHelper.gc(if (profileSwitch is ProfileSealed.PS) R.color.defaultbackground else R.color.list_delimiter)) holder.binding.root.setBackgroundColor(rh.gc(if (profileSwitch is ProfileSealed.PS) R.color.defaultbackground else R.color.list_delimiter))
} }
override fun getItemCount(): Int { override fun getItemCount(): Int {
@ -207,9 +207,9 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
binding.remove.setOnClickListener { view -> binding.remove.setOnClickListener { view ->
val profileSwitch = view.tag as ProfileSealed.PS val profileSwitch = view.tag as ProfileSealed.PS
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord),
resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + rh.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName +
"\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { "\n" + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable {
uel.log(Action.PROFILE_SWITCH_REMOVED, Sources.Treatments, profileSwitch.profileName, uel.log(Action.PROFILE_SWITCH_REMOVED, Sources.Treatments, profileSwitch.profileName,
ValueWithUnit.Timestamp(profileSwitch.timestamp)) ValueWithUnit.Timestamp(profileSwitch.timestamp))
disposable += repository.runTransactionForResult(InvalidateProfileSwitchTransaction(profileSwitch.id)) disposable += repository.runTransactionForResult(InvalidateProfileSwitchTransaction(profileSwitch.id))
@ -224,7 +224,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
activity?.let { activity -> activity?.let { activity ->
val profileSwitch = (it.tag as ProfileSealed.PS).value val profileSwitch = (it.tag as ProfileSealed.PS).value
val profileSealed = it.tag as ProfileSealed val profileSealed = it.tag as ProfileSealed
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.getCustomizedName() + "\n" + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_profileswitch), rh.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.getCustomizedName() + "\n" + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable {
uel.log(Action.PROFILE_SWITCH_CLONED, Sources.Treatments, uel.log(Action.PROFILE_SWITCH_CLONED, Sources.Treatments,
profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"), profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"),
ValueWithUnit.Timestamp(profileSwitch.timestamp), ValueWithUnit.Timestamp(profileSwitch.timestamp),

View file

@ -56,7 +56,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -83,7 +83,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
context?.let { context -> context?.let { context ->
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", { OKDialog.showConfirmation(context, rh.gs(R.string.refresheventsfromnightscout) + " ?", {
uel.log(Action.TT_NS_REFRESH, Sources.Treatments) uel.log(Action.TT_NS_REFRESH, Sources.Treatments)
disposable += Completable.fromAction { repository.deleteAllTempTargetEntries() } disposable += Completable.fromAction { repository.deleteAllTempTargetEntries() }
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
@ -165,14 +165,14 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
holder.binding.invalid.visibility = tempTarget.isValid.not().toVisibility() holder.binding.invalid.visibility = tempTarget.isValid.not().toVisibility()
holder.binding.remove.visibility = tempTarget.isValid.toVisibility() holder.binding.remove.visibility = tempTarget.isValid.toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(tempTarget.timestamp) + " - " + dateUtil.timeString(tempTarget.end) holder.binding.date.text = dateUtil.dateAndTimeString(tempTarget.timestamp) + " - " + dateUtil.timeString(tempTarget.end)
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempTarget.duration).mins()) holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(tempTarget.duration).mins())
holder.binding.low.text = tempTarget.lowValueToUnitsToString(units) holder.binding.low.text = tempTarget.lowValueToUnitsToString(units)
holder.binding.high.text = tempTarget.highValueToUnitsToString(units) holder.binding.high.text = tempTarget.highValueToUnitsToString(units)
holder.binding.reason.text = translator.translate(tempTarget.reason) holder.binding.reason.text = translator.translate(tempTarget.reason)
holder.binding.date.setTextColor( holder.binding.date.setTextColor(
when { when {
tempTarget.id == currentlyActiveTarget?.id -> resourceHelper.gc(R.color.colorActive) tempTarget.id == currentlyActiveTarget?.id -> rh.gc(R.color.colorActive)
tempTarget.timestamp > dateUtil.now() -> resourceHelper.gc(R.color.colorScheduled) tempTarget.timestamp > dateUtil.now() -> rh.gc(R.color.colorScheduled)
else -> holder.binding.reasonColon.currentTextColor else -> holder.binding.reasonColon.currentTextColor
}) })
holder.binding.remove.tag = tempTarget holder.binding.remove.tag = tempTarget
@ -188,9 +188,9 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val tempTarget = v.tag as TemporaryTarget val tempTarget = v.tag as TemporaryTarget
context?.let { context -> context?.let { context ->
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(context, rh.gs(R.string.removerecord),
""" """
${resourceHelper.gs(R.string.careportal_temporarytarget)}: ${tempTarget.friendlyDescription(profileFunction.getUnits(), resourceHelper)} ${rh.gs(R.string.careportal_temporarytarget)}: ${tempTarget.friendlyDescription(profileFunction.getUnits(), rh)}
${dateUtil.dateAndTimeString(tempTarget.timestamp)} ${dateUtil.dateAndTimeString(tempTarget.timestamp)}
""".trimIndent(), """.trimIndent(),
{ _: DialogInterface?, _: Int -> { _: DialogInterface?, _: Int ->

View file

@ -55,7 +55,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@ -167,24 +167,24 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
holder.binding.ph.visibility = (tempBasal.interfaceIDs.pumpId != null).toVisibility() holder.binding.ph.visibility = (tempBasal.interfaceIDs.pumpId != null).toVisibility()
if (tempBasal.isInProgress) { if (tempBasal.isInProgress) {
holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.timestamp) holder.binding.date.text = dateUtil.dateAndTimeString(tempBasal.timestamp)
holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorActive)) holder.binding.date.setTextColor(rh.gc(R.color.colorActive))
} else { } else {
holder.binding.date.text = dateUtil.dateAndTimeRangeString(tempBasal.timestamp, tempBasal.end) holder.binding.date.text = dateUtil.dateAndTimeRangeString(tempBasal.timestamp, tempBasal.end)
holder.binding.date.setTextColor(holder.binding.duration.currentTextColor) holder.binding.date.setTextColor(holder.binding.duration.currentTextColor)
} }
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins()) holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins())
if (tempBasal.isAbsolute) holder.binding.rate.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.rate) if (tempBasal.isAbsolute) holder.binding.rate.text = rh.gs(R.string.pump_basebasalrate, tempBasal.rate)
else holder.binding.rate.text = resourceHelper.gs(R.string.format_percent, tempBasal.rate.toInt()) else holder.binding.rate.text = rh.gs(R.string.format_percent, tempBasal.rate.toInt())
val now = dateUtil.now() val now = dateUtil.now()
var iob = IobTotal(now) var iob = IobTotal(now)
val profile = profileFunction.getProfile(now) val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin) if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.basaliob) holder.binding.iob.text = rh.gs(R.string.formatinsulinunits, iob.basaliob)
holder.binding.extendedFlag.visibility = (tempBasal.type == TemporaryBasal.Type.FAKE_EXTENDED).toVisibility() holder.binding.extendedFlag.visibility = (tempBasal.type == TemporaryBasal.Type.FAKE_EXTENDED).toVisibility()
holder.binding.suspendFlag.visibility = (tempBasal.type == TemporaryBasal.Type.PUMP_SUSPEND).toVisibility() holder.binding.suspendFlag.visibility = (tempBasal.type == TemporaryBasal.Type.PUMP_SUSPEND).toVisibility()
holder.binding.emulatedSuspendFlag.visibility = (tempBasal.type == TemporaryBasal.Type.EMULATED_PUMP_SUSPEND).toVisibility() holder.binding.emulatedSuspendFlag.visibility = (tempBasal.type == TemporaryBasal.Type.EMULATED_PUMP_SUSPEND).toVisibility()
holder.binding.superBolusFlag.visibility = (tempBasal.type == TemporaryBasal.Type.SUPERBOLUS).toVisibility() holder.binding.superBolusFlag.visibility = (tempBasal.type == TemporaryBasal.Type.SUPERBOLUS).toVisibility()
if (abs(iob.basaliob) > 0.01) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.duration.currentTextColor) if (abs(iob.basaliob) > 0.01) holder.binding.iob.setTextColor(rh.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.duration.currentTextColor)
holder.binding.remove.tag = tempBasal holder.binding.remove.tag = tempBasal
} }
@ -206,10 +206,10 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
val profile = profileFunction.getProfile(dateUtil.now()) val profile = profileFunction.getProfile(dateUtil.now())
?: return@setOnClickListener ?: return@setOnClickListener
context?.let { context?.let {
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(it, rh.gs(R.string.removerecord),
""" """
${if (isFakeExtended) resourceHelper.gs(R.string.extended_bolus) else resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, dateUtil)} ${if (isFakeExtended) rh.gs(R.string.extended_bolus) else rh.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, dateUtil)}
${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)} ${rh.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)}
""".trimIndent(), """.trimIndent(),
{ _: DialogInterface?, _: Int -> { _: DialogInterface?, _: Int ->
if (isFakeExtended && extendedBolus != null) { if (isFakeExtended && extendedBolus != null) {

View file

@ -36,7 +36,7 @@ class TreatmentsUserEntryFragment : DaggerFragment() {
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@ -66,7 +66,7 @@ class TreatmentsUserEntryFragment : DaggerFragment() {
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.ueExportToXml.setOnClickListener { binding.ueExportToXml.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.ue_export_to_csv) + "?") { OKDialog.showConfirmation(activity, rh.gs(R.string.ue_export_to_csv) + "?") {
uel.log(Action.EXPORT_CSV, Sources.Treatments) uel.log(Action.EXPORT_CSV, Sources.Treatments)
importExportPrefs.exportUserEntriesCsv(activity) importExportPrefs.exportUserEntriesCsv(activity)
} }

View file

@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.data.DeviceStatusData
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.PumpSyncImplementation import info.nightscout.androidaps.plugins.pump.PumpSyncImplementation
import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.CommandQueueImplementation
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HardLimits
@ -74,13 +74,13 @@ open class AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideProfileFunction( fun provideProfileFunction(
aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, resourceHelper: aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, rh:
ResourceHelper, activePlugin: ResourceHelper, activePlugin:
ActivePlugin, repository: AppRepository, dateUtil: DateUtil, config: Config, hardLimits: HardLimits, ActivePlugin, repository: AppRepository, dateUtil: DateUtil, config: Config, hardLimits: HardLimits,
aapsSchedulers: AapsSchedulers, fabricPrivacy: FabricPrivacy, deviceStatusData: DeviceStatusData aapsSchedulers: AapsSchedulers, fabricPrivacy: FabricPrivacy, deviceStatusData: DeviceStatusData
): ProfileFunction = ): ProfileFunction =
ProfileFunctionImplementation( ProfileFunctionImplementation(
aapsLogger, sp, rxBus, resourceHelper, activePlugin, repository, dateUtil, aapsLogger, sp, rxBus, rh, activePlugin, repository, dateUtil,
config, hardLimits, aapsSchedulers, fabricPrivacy, deviceStatusData config, hardLimits, aapsSchedulers, fabricPrivacy, deviceStatusData
) )
@ -89,8 +89,8 @@ open class AppModule {
@Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePlugin @Binds fun bindActivePlugin(pluginStore: PluginStore): ActivePlugin
@Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider @Binds fun bindCommandQueue(commandQueue: CommandQueueImplementation): CommandQueue
@Binds fun bindConfigInterface(config: ConfigImpl): Config @Binds fun bindConfigInterface(config: ConfigImpl): Config
@Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder @Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder

View file

@ -2,14 +2,14 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.CommandQueueImplementation
import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.*
@Module @Module
@Suppress("unused") @Suppress("unused")
abstract class CommandQueueModule { abstract class CommandQueueModule {
@ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueueImplementation
@ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus
@ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus
@ContributesAndroidInjector abstract fun commandCancelTempBasalInjector(): CommandCancelTempBasal @ContributesAndroidInjector abstract fun commandCancelTempBasalInjector(): CommandCancelTempBasal

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.constraints.bgQualityCheck.BgQualityCheckPlugin
import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
@ -294,6 +295,12 @@ abstract class PluginsModule {
@IntKey(380) @IntKey(380)
abstract fun bindDstHelperPlugin(plugin: DstHelperPlugin): PluginBase abstract fun bindDstHelperPlugin(plugin: DstHelperPlugin): PluginBase
@Binds
@AllConfigs
@IntoMap
@IntKey(381)
abstract fun bindBgQualityCheckPlugin(plugin: BgQualityCheckPlugin): PluginBase
@Binds @Binds
@AllConfigs @AllConfigs
@IntoMap @IntoMap

View file

@ -27,7 +27,7 @@ import javax.inject.Inject
class CalibrationDialog : DialogFragmentWithDate() { class CalibrationDialog : DialogFragmentWithDate() {
@Inject lateinit var injector: HasAndroidInjector @Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var xdripCalibrations: XdripCalibrations @Inject lateinit var xdripCalibrations: XdripCalibrations
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -63,7 +63,7 @@ class CalibrationDialog : DialogFragmentWithDate() {
else else
binding.bg.setParams(savedInstanceState?.getDouble("bg") binding.bg.setParams(savedInstanceState?.getDouble("bg")
?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok) ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok)
binding.units.text = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) binding.units.text = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
} }
override fun onDestroyView() { override fun onDestroyView() {
@ -74,20 +74,20 @@ class CalibrationDialog : DialogFragmentWithDate() {
override fun submit(): Boolean { override fun submit(): Boolean {
if (_binding == null) return false if (_binding == null) return false
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val unitLabel = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
val actions: LinkedList<String?> = LinkedList() val actions: LinkedList<String?> = LinkedList()
val bg = binding.bg.value ?: return false val bg = binding.bg.value ?: return false
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel) actions.add(rh.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel)
if (bg > 0) { if (bg > 0) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
uel.log(Action.CALIBRATION, Sources.CalibrationDialog, ValueWithUnit.fromGlucoseUnit(bg, units.asText)) uel.log(Action.CALIBRATION, Sources.CalibrationDialog, ValueWithUnit.fromGlucoseUnit(bg, units.asText))
xdripCalibrations.sendIntent(bg) xdripCalibrations.sendIntent(bg)
}) })
} }
} else } else
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.overview_calibration), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.overview_calibration), rh.gs(R.string.no_action_selected))
} }
return true return true
} }

View file

@ -11,7 +11,6 @@ import com.google.common.base.Joiner
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Action
@ -20,16 +19,12 @@ import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction
import info.nightscout.androidaps.databinding.DialogCarbsBinding import info.nightscout.androidaps.databinding.DialogCarbsBinding
import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.extensions.formatColor
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -44,7 +39,7 @@ import kotlin.math.max
class CarbsDialog : DialogFragmentWithDate() { class CarbsDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@ -79,15 +74,15 @@ class CarbsDialog : DialogFragmentWithDate() {
val time = binding.time.value.toInt() val time = binding.time.value.toInt()
if (time > 12 * 60 || time < -12 * 60) { if (time > 12 * 60 || time < -12 * 60) {
binding.time.value = 0.0 binding.time.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.constraintapllied))
} }
if (binding.duration.value > 10) { if (binding.duration.value > 10) {
binding.duration.value = 0.0 binding.duration.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.constraintapllied))
} }
if (binding.carbs.value.toInt() > maxCarbs) { if (binding.carbs.value.toInt() > maxCarbs) {
binding.carbs.value = 0.0 binding.carbs.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.carbsconstraintapplied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.carbsconstraintapplied))
} }
} }
@ -104,8 +99,10 @@ class CarbsDialog : DialogFragmentWithDate() {
savedInstanceState.putDouble("carbs", binding.carbs.value) savedInstanceState.putDouble("carbs", binding.carbs.value)
} }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(
savedInstanceState: Bundle?): View { inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
onCreateViewGeneral() onCreateViewGeneral()
_binding = DialogCarbsBinding.inflate(inflater, container, false) _binding = DialogCarbsBinding.inflate(inflater, container, false)
return binding.root return binding.root
@ -120,33 +117,45 @@ class CarbsDialog : DialogFragmentWithDate() {
} }
} }
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
binding.time.setParams(savedInstanceState?.getDouble("time") binding.time.setParams(
?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) savedInstanceState?.getDouble("time")
?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher
)
binding.duration.setParams(savedInstanceState?.getDouble("duration") binding.duration.setParams(
?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) savedInstanceState?.getDouble("duration")
?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher
)
binding.carbs.setParams(savedInstanceState?.getDouble("carbs") binding.carbs.setParams(
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) savedInstanceState?.getDouble("carbs")
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher
)
binding.plus1.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)) binding.plus1.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
binding.plus1.setOnClickListener { binding.plus1.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value binding.carbs.value = max(
+ sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)) 0.0, binding.carbs.value
+ sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)
)
validateInputs() validateInputs()
} }
binding.plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) binding.plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
binding.plus2.setOnClickListener { binding.plus2.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value binding.carbs.value = max(
+ sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) 0.0, binding.carbs.value
+ sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)
)
validateInputs() validateInputs()
} }
binding.plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) binding.plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
binding.plus3.setOnClickListener { binding.plus3.setOnClickListener {
binding.carbs.value = max(0.0, binding.carbs.value binding.carbs.value = max(
+ sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) 0.0, binding.carbs.value
+ sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)
)
validateInputs() validateInputs()
} }
@ -190,101 +199,128 @@ class CarbsDialog : DialogFragmentWithDate() {
val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() val hypoTTDuration = defaultValueHelper.determineHypoTTDuration()
val hypoTT = defaultValueHelper.determineHypoTT() val hypoTT = defaultValueHelper.determineHypoTT()
val actions: LinkedList<String?> = LinkedList() val actions: LinkedList<String?> = LinkedList()
val unitLabel = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
val useAlarm = binding.alarmCheckBox.isChecked val useAlarm = binding.alarmCheckBox.isChecked
val remindBolus = binding.bolusReminderCheckBox.isChecked val remindBolus = binding.bolusReminderCheckBox.isChecked
val activitySelected = binding.activityTt.isChecked val activitySelected = binding.activityTt.isChecked
if (activitySelected) if (activitySelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(
rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(
rh,
R.color.tempTargetConfirmation
)
)
val eatingSoonSelected = binding.eatingSoonTt.isChecked val eatingSoonSelected = binding.eatingSoonTt.isChecked
if (eatingSoonSelected) if (eatingSoonSelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(
rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs(
R.string.format_mins,
eatingSoonTTDuration
) + ")").formatColor(rh, R.color.tempTargetConfirmation)
)
val hypoSelected = binding.hypoTt.isChecked val hypoSelected = binding.hypoTt.isChecked
if (hypoSelected) if (hypoSelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(
rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(
rh,
R.color.tempTargetConfirmation
)
)
val timeOffset = binding.time.value.toInt() val timeOffset = binding.time.value.toInt()
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
val time = eventTime + timeOffset * 1000 * 60 val time = eventTime + timeOffset * 1000 * 60
if (timeOffset != 0) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
if (useAlarm && carbs > 0 && timeOffset > 0) if (useAlarm && carbs > 0 && timeOffset > 0)
actions.add(resourceHelper.gs(R.string.alarminxmin, timeOffset).formatColor(resourceHelper, R.color.info)) actions.add(rh.gs(R.string.alarminxmin, timeOffset).formatColor(rh, R.color.info))
val duration = binding.duration.value.toInt() val duration = binding.duration.value.toInt()
if (duration > 0) if (duration > 0)
actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) actions.add(rh.gs(R.string.duration) + ": " + duration + rh.gs(R.string.shorthour))
if (carbsAfterConstraints > 0) { if (carbsAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.carbs) + ": " + "<font color='" + resourceHelper.gc(R.color.carbs) + "'>" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>") actions.add(rh.gs(R.string.carbs) + ": " + "<font color='" + rh.gc(R.color.carbs) + "'>" + rh.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>")
if (carbsAfterConstraints != carbs) if (carbsAfterConstraints != carbs)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.carbsconstraintapplied) + "</font>") actions.add("<font color='" + rh.gc(R.color.warning) + "'>" + rh.gs(R.string.carbsconstraintapplied) + "</font>")
} }
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
when { when {
activitySelected -> { activitySelected -> {
uel.log(Action.TT, Sources.CarbDialog, uel.log(
Action.TT, Sources.CarbDialog,
ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY), ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY),
ValueWithUnit.fromGlucoseUnit(activityTT, units.asText), ValueWithUnit.fromGlucoseUnit(activityTT, units.asText),
ValueWithUnit.Minute(activityTTDuration)) ValueWithUnit.Minute(activityTTDuration)
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( )
timestamp = System.currentTimeMillis(), disposable += repository.runTransactionForResult(
duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()), InsertAndCancelCurrentTemporaryTargetTransaction(
reason = TemporaryTarget.Reason.ACTIVITY, timestamp = System.currentTimeMillis(),
lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()), duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()),
highTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()) reason = TemporaryTarget.Reason.ACTIVITY,
)).subscribe({ result -> lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()),
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } highTarget = Profile.toMgdl(activityTT, profileFunction.getUnits())
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } )
}, { ).subscribe({ result ->
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
}) result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
} }
eatingSoonSelected -> { eatingSoonSelected -> {
uel.log(Action.TT, Sources.CarbDialog, uel.log(
Action.TT, Sources.CarbDialog,
ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON), ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON),
ValueWithUnit.fromGlucoseUnit(eatingSoonTT, units.asText), ValueWithUnit.fromGlucoseUnit(eatingSoonTT, units.asText),
ValueWithUnit.Minute(eatingSoonTTDuration)) ValueWithUnit.Minute(eatingSoonTTDuration)
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( )
timestamp = System.currentTimeMillis(), disposable += repository.runTransactionForResult(
duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), InsertAndCancelCurrentTemporaryTargetTransaction(
reason = TemporaryTarget.Reason.EATING_SOON, timestamp = System.currentTimeMillis(),
lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()),
highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()) reason = TemporaryTarget.Reason.EATING_SOON,
)).subscribe({ result -> lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()),
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } )
}, { ).subscribe({ result ->
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
}) result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
} }
hypoSelected -> { hypoSelected -> {
uel.log(Action.TT, Sources.CarbDialog, uel.log(
Action.TT, Sources.CarbDialog,
ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA), ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA),
ValueWithUnit.fromGlucoseUnit(hypoTT, units.asText), ValueWithUnit.fromGlucoseUnit(hypoTT, units.asText),
ValueWithUnit.Minute(hypoTTDuration)) ValueWithUnit.Minute(hypoTTDuration)
disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( )
timestamp = System.currentTimeMillis(), disposable += repository.runTransactionForResult(
duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()), InsertAndCancelCurrentTemporaryTargetTransaction(
reason = TemporaryTarget.Reason.HYPOGLYCEMIA, timestamp = System.currentTimeMillis(),
lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()), duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()),
highTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()) reason = TemporaryTarget.Reason.HYPOGLYCEMIA,
)).subscribe({ result -> lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()),
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } highTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits())
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } )
}, { ).subscribe({ result ->
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
}) result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
} }
} }
if (carbsAfterConstraints > 0) { if (carbsAfterConstraints > 0) {
@ -296,17 +332,17 @@ class CarbsDialog : DialogFragmentWithDate() {
detailedBolusInfo.carbsDuration = T.hours(duration.toLong()).msecs() detailedBolusInfo.carbsDuration = T.hours(duration.toLong()).msecs()
detailedBolusInfo.carbsTimestamp = time detailedBolusInfo.carbsTimestamp = time
uel.log(if (duration == 0) Action.CARBS else Action.EXTENDED_CARBS, Sources.CarbDialog, uel.log(if (duration == 0) Action.CARBS else Action.EXTENDED_CARBS, Sources.CarbDialog,
notes, notes,
ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged },
ValueWithUnit.Gram(carbsAfterConstraints), ValueWithUnit.Gram(carbsAfterConstraints),
ValueWithUnit.Minute(timeOffset).takeIf { timeOffset != 0 }, ValueWithUnit.Minute(timeOffset).takeIf { timeOffset != 0 },
ValueWithUnit.Hour(duration).takeIf { duration != 0 }) ValueWithUnit.Hour(duration).takeIf { duration != 0 })
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
carbTimer.removeEatReminder() carbTimer.removeEatReminder()
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus) } else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus)
bolusTimer.scheduleBolusReminder() bolusTimer.scheduleBolusReminder()
} }
}) })
@ -318,7 +354,7 @@ class CarbsDialog : DialogFragmentWithDate() {
} }
} else } else
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.carbs), rh.gs(R.string.no_action_selected))
} }
return true return true
} }

View file

@ -41,7 +41,7 @@ class CareDialog : DialogFragmentWithDate() {
@Inject lateinit var injector: HasAndroidInjector @Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -111,7 +111,7 @@ class CareDialog : DialogFragmentWithDate() {
EventType.QUESTION -> R.drawable.ic_cp_question EventType.QUESTION -> R.drawable.ic_cp_question
EventType.ANNOUNCEMENT -> R.drawable.ic_cp_announcement EventType.ANNOUNCEMENT -> R.drawable.ic_cp_announcement
}) })
binding.title.text = resourceHelper.gs(when (options) { binding.title.text = rh.gs(when (options) {
EventType.BGCHECK -> R.string.careportal_bgcheck EventType.BGCHECK -> R.string.careportal_bgcheck
EventType.SENSOR_INSERT -> R.string.careportal_cgmsensorinsert EventType.SENSOR_INSERT -> R.string.careportal_cgmsensorinsert
EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange
@ -153,11 +153,11 @@ class CareDialog : DialogFragmentWithDate() {
} }
if (profileFunction.getUnits() == GlucoseUnit.MMOL) { if (profileFunction.getUnits() == GlucoseUnit.MMOL) {
binding.bgunits.text = resourceHelper.gs(R.string.mmol) binding.bgunits.text = rh.gs(R.string.mmol)
binding.bg.setParams(savedInstanceState?.getDouble("bg") binding.bg.setParams(savedInstanceState?.getDouble("bg")
?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, binding.okcancel.ok, bgTextWatcher) ?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, binding.okcancel.ok, bgTextWatcher)
} else { } else {
binding.bgunits.text = resourceHelper.gs(R.string.mgdl) binding.bgunits.text = rh.gs(R.string.mgdl)
binding.bg.setParams(savedInstanceState?.getDouble("bg") binding.bg.setParams(savedInstanceState?.getDouble("bg")
?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, bgTextWatcher) ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, bgTextWatcher)
} }
@ -200,25 +200,25 @@ class CareDialog : DialogFragmentWithDate() {
binding.sensor.isChecked -> TherapyEvent.MeterType.SENSOR binding.sensor.isChecked -> TherapyEvent.MeterType.SENSOR
else -> TherapyEvent.MeterType.MANUAL else -> TherapyEvent.MeterType.MANUAL
} }
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + translator.translate(meterType)) actions.add(rh.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + translator.translate(meterType))
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, binding.bg.value) + " " + resourceHelper.gs(unitResId)) actions.add(rh.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, binding.bg.value) + " " + rh.gs(unitResId))
therapyEvent.glucoseType = meterType therapyEvent.glucoseType = meterType
therapyEvent.glucose = binding.bg.value therapyEvent.glucose = binding.bg.value
valuesWithUnit.add(ValueWithUnit.fromGlucoseUnit(binding.bg.value.toDouble(), profileFunction.getUnits().asText)) valuesWithUnit.add(ValueWithUnit.fromGlucoseUnit(binding.bg.value.toDouble(), profileFunction.getUnits().asText))
valuesWithUnit.add(ValueWithUnit.TherapyEventMeterType(meterType)) valuesWithUnit.add(ValueWithUnit.TherapyEventMeterType(meterType))
} }
if (options == EventType.NOTE || options == EventType.EXERCISE) { if (options == EventType.NOTE || options == EventType.EXERCISE) {
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_duration_label) + ": " + resourceHelper.gs(R.string.format_mins, binding.duration.value.toInt())) actions.add(rh.gs(R.string.careportal_newnstreatment_duration_label) + ": " + rh.gs(R.string.format_mins, binding.duration.value.toInt()))
therapyEvent.duration = T.mins(binding.duration.value.toLong()).msecs() therapyEvent.duration = T.mins(binding.duration.value.toLong()).msecs()
valuesWithUnit.add(ValueWithUnit.Minute(binding.duration.value.toInt()).takeIf { !binding.duration.value.equals(0.0) } ) valuesWithUnit.add(ValueWithUnit.Minute(binding.duration.value.toInt()).takeIf { !binding.duration.value.equals(0.0) } )
} }
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) { if (notes.isNotEmpty()) {
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
therapyEvent.note = notes therapyEvent.note = notes
} }
if (eventTimeChanged) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) if (eventTimeChanged) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
therapyEvent.enteredBy = enteredBy therapyEvent.enteredBy = enteredBy
@ -233,7 +233,7 @@ class CareDialog : DialogFragmentWithDate() {
} }
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(event), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent)) disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent))
.subscribe( .subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } }, { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } },

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.DialogExtendedbolusBinding import info.nightscout.androidaps.databinding.DialogExtendedbolusBinding
import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
@ -31,9 +31,9 @@ import kotlin.math.abs
class ExtendedBolusDialog : DialogFragmentWithDate() { class ExtendedBolusDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -83,20 +83,20 @@ class ExtendedBolusDialog : DialogFragmentWithDate() {
val durationInMinutes = binding.duration.value.toInt() val durationInMinutes = binding.duration.value.toInt()
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value()
actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint)) actions.add(rh.gs(R.string.formatinsulinunits, insulinAfterConstraint))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes))
if (abs(insulinAfterConstraint - insulin) > 0.01) if (abs(insulinAfterConstraint - insulin) > 0.01)
actions.add(resourceHelper.gs(R.string.constraintapllied).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.constraintapllied).formatColor(rh, R.color.warning))
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
uel.log(Action.EXTENDED_BOLUS, Sources.ExtendedBolusDialog, uel.log(Action.EXTENDED_BOLUS, Sources.ExtendedBolusDialog,
ValueWithUnit.Insulin(insulinAfterConstraint), ValueWithUnit.Insulin(insulinAfterConstraint),
ValueWithUnit.Minute(durationInMinutes)) ValueWithUnit.Minute(durationInMinutes))
commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} }
} }
}) })

View file

@ -17,7 +17,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.databinding.DialogFillBinding import info.nightscout.androidaps.databinding.DialogFillBinding
import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
@ -38,9 +38,9 @@ import kotlin.math.abs
class FillDialog : DialogFragmentWithDate() { class FillDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -111,29 +111,29 @@ class FillDialog : DialogFragmentWithDate() {
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.fillwarning)) actions.add(rh.gs(R.string.fillwarning))
actions.add("") actions.add("")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, resourceHelper).formatColor(resourceHelper, R.color.colorInsulinButton)) actions.add(rh.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(rh, R.color.colorInsulinButton))
if (abs(insulinAfterConstraints - insulin) > 0.01) if (abs(insulinAfterConstraints - insulin) > 0.01)
actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(rh, R.color.warning))
} }
val siteChange = binding.fillCatheterChange.isChecked val siteChange = binding.fillCatheterChange.isChecked
if (siteChange) if (siteChange)
actions.add(resourceHelper.gs(R.string.record_pump_site_change).formatColor(resourceHelper, R.color.actionsConfirm)) actions.add(rh.gs(R.string.record_pump_site_change).formatColor(rh, R.color.actionsConfirm))
val insulinChange = binding.fillCartridgeChange.isChecked val insulinChange = binding.fillCartridgeChange.isChecked
if (insulinChange) if (insulinChange)
actions.add(resourceHelper.gs(R.string.record_insulin_cartridge_change).formatColor(resourceHelper, R.color.actionsConfirm)) actions.add(rh.gs(R.string.record_insulin_cartridge_change).formatColor(rh, R.color.actionsConfirm))
val notes: String = binding.notesLayout.notes.text.toString() val notes: String = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
if (insulinAfterConstraints > 0 || binding.fillCatheterChange.isChecked || binding.fillCartridgeChange.isChecked) { if (insulinAfterConstraints > 0 || binding.fillCatheterChange.isChecked || binding.fillCartridgeChange.isChecked) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
uel.log(Action.PRIME_BOLUS, Sources.FillDialog, uel.log(Action.PRIME_BOLUS, Sources.FillDialog,
notes, notes,
@ -175,7 +175,7 @@ class FillDialog : DialogFragmentWithDate() {
} }
} else { } else {
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.primefill), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.primefill), rh.gs(R.string.no_action_selected))
} }
} }
dismiss() dismiss()
@ -191,7 +191,7 @@ class FillDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} }
} }
}) })

View file

@ -41,10 +41,10 @@ import kotlin.math.max
class InsulinDialog : DialogFragmentWithDate() { class InsulinDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -80,11 +80,11 @@ class InsulinDialog : DialogFragmentWithDate() {
val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
if (abs(binding.time.value.toInt()) > 12 * 60) { if (abs(binding.time.value.toInt()) > 12 * 60) {
binding.time.value = 0.0 binding.time.value = 0.0
ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.constraintapllied)) ToastUtils.showToastInUiThread(context, rh.gs(R.string.constraintapllied))
} }
if (binding.amount.value > maxInsulin) { if (binding.amount.value > maxInsulin) {
binding.amount.value = 0.0 binding.amount.value = 0.0
ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.bolusconstraintapplied)) ToastUtils.showToastInUiThread(context, rh.gs(R.string.bolusconstraintapplied))
} }
} }
@ -115,22 +115,22 @@ class InsulinDialog : DialogFragmentWithDate() {
binding.amount.setParams(savedInstanceState?.getDouble("amount") binding.amount.setParams(savedInstanceState?.getDouble("amount")
?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher) ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher)
binding.plus05.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString(activePlugin.activePump) binding.plus05.text = sp.getDouble(rh.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT).toSignedString(activePlugin.activePump)
binding.plus05.setOnClickListener { binding.plus05.setOnClickListener {
binding.amount.value = max(0.0, binding.amount.value binding.amount.value = max(0.0, binding.amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) + sp.getDouble(rh.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
validateInputs() validateInputs()
} }
binding.plus10.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString(activePlugin.activePump) binding.plus10.text = sp.getDouble(rh.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT).toSignedString(activePlugin.activePump)
binding.plus10.setOnClickListener { binding.plus10.setOnClickListener {
binding.amount.value = max(0.0, binding.amount.value binding.amount.value = max(0.0, binding.amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) + sp.getDouble(rh.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
validateInputs() validateInputs()
} }
binding.plus20.text = sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString(activePlugin.activePump) binding.plus20.text = sp.getDouble(rh.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT).toSignedString(activePlugin.activePump)
binding.plus20.setOnClickListener { binding.plus20.setOnClickListener {
binding.amount.value = max(0.0, binding.amount.value binding.amount.value = max(0.0, binding.amount.value
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) + sp.getDouble(rh.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
validateInputs() validateInputs()
} }
@ -153,34 +153,34 @@ class InsulinDialog : DialogFragmentWithDate() {
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
val actions: LinkedList<String?> = LinkedList() val actions: LinkedList<String?> = LinkedList()
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val unitLabel = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
val recordOnlyChecked = binding.recordOnly.isChecked val recordOnlyChecked = binding.recordOnly.isChecked
val eatingSoonChecked = binding.startEatingSoonTt.isChecked val eatingSoonChecked = binding.startEatingSoonTt.isChecked
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, resourceHelper).formatColor(resourceHelper, R.color.bolus)) actions.add(rh.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(rh, R.color.bolus))
if (recordOnlyChecked) if (recordOnlyChecked)
actions.add(resourceHelper.gs(R.string.bolusrecordedonly).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.bolusrecordedonly).formatColor(rh, R.color.warning))
if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints))
actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(rh, R.color.warning))
} }
val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration() val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration()
val eatingSoonTT = defaultValueHelper.determineEatingSoonTT() val eatingSoonTT = defaultValueHelper.determineEatingSoonTT()
if (eatingSoonChecked) if (eatingSoonChecked)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(rh, R.color.tempTargetConfirmation))
val timeOffset = binding.time.value.toInt() val timeOffset = binding.time.value.toInt()
val time = dateUtil.now() + T.mins(timeOffset.toLong()).msecs() val time = dateUtil.now() + T.mins(timeOffset.toLong()).msecs()
if (timeOffset != 0) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
if (insulinAfterConstraints > 0 || eatingSoonChecked) { if (insulinAfterConstraints > 0 || eatingSoonChecked) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
if (eatingSoonChecked) { if (eatingSoonChecked) {
uel.log(Action.TT, Sources.InsulinDialog, uel.log(Action.TT, Sources.InsulinDialog,
notes, notes,
@ -209,8 +209,8 @@ class InsulinDialog : DialogFragmentWithDate() {
detailedBolusInfo.timestamp = time detailedBolusInfo.timestamp = time
if (recordOnlyChecked) { if (recordOnlyChecked) {
uel.log(Action.BOLUS, Sources.InsulinDialog, uel.log(Action.BOLUS, Sources.InsulinDialog,
resourceHelper.gs(R.string.record) + if (notes.isNotEmpty()) ": " + notes else "", rh.gs(R.string.record) + if (notes.isNotEmpty()) ": " + notes else "",
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.record)), ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.record)),
ValueWithUnit.Insulin(insulinAfterConstraints), ValueWithUnit.Insulin(insulinAfterConstraints),
ValueWithUnit.Minute(timeOffset).takeIf { timeOffset!= 0 }) ValueWithUnit.Minute(timeOffset).takeIf { timeOffset!= 0 })
disposable += repository.runTransactionForResult(detailedBolusInfo.insertBolusTransaction()) disposable += repository.runTransactionForResult(detailedBolusInfo.insertBolusTransaction())
@ -227,7 +227,7 @@ class InsulinDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} else { } else {
bolusTimer.removeBolusReminder() bolusTimer.removeBolusReminder()
} }
@ -239,7 +239,7 @@ class InsulinDialog : DialogFragmentWithDate() {
} }
} else } else
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.bolus), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.bolus), rh.gs(R.string.no_action_selected))
} }
return true return true
} }

View file

@ -51,12 +51,12 @@ class LoopDialog : DaggerDialogFragment() {
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var configBuilder: ConfigBuilder @Inject lateinit var configBuilder: ConfigBuilder
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -185,12 +185,12 @@ class LoopDialog : DaggerDialogFragment() {
binding.overviewLoop.visibility = View.GONE binding.overviewLoop.visibility = View.GONE
binding.overviewSuspend.visibility = View.GONE binding.overviewSuspend.visibility = View.GONE
binding.overviewPump.visibility = View.VISIBLE binding.overviewPump.visibility = View.VISIBLE
binding.overviewPumpHeader.text = resourceHelper.gs(R.string.reconnect) binding.overviewPumpHeader.text = rh.gs(R.string.reconnect)
binding.overviewDisconnectButtons.visibility = View.VISIBLE binding.overviewDisconnectButtons.visibility = View.VISIBLE
binding.overviewReconnect.visibility = View.VISIBLE binding.overviewReconnect.visibility = View.VISIBLE
} }
!loopPlugin.isEnabled(PluginType.LOOP) -> { !loopPlugin.isEnabled() -> {
binding.overviewLoop.visibility = View.VISIBLE binding.overviewLoop.visibility = View.VISIBLE
binding.overviewEnable.visibility = View.VISIBLE binding.overviewEnable.visibility = View.VISIBLE
binding.overviewDisable.visibility = View.GONE binding.overviewDisable.visibility = View.GONE
@ -202,7 +202,7 @@ class LoopDialog : DaggerDialogFragment() {
loopPlugin.isSuspended -> { loopPlugin.isSuspended -> {
binding.overviewLoop.visibility = View.GONE binding.overviewLoop.visibility = View.GONE
binding.overviewSuspend.visibility = View.VISIBLE binding.overviewSuspend.visibility = View.VISIBLE
binding.overviewSuspendHeader.text = resourceHelper.gs(R.string.resumeloop) binding.overviewSuspendHeader.text = rh.gs(R.string.resumeloop)
binding.overviewSuspendButtons.visibility = View.VISIBLE binding.overviewSuspendButtons.visibility = View.VISIBLE
binding.overviewResume.visibility = View.VISIBLE binding.overviewResume.visibility = View.VISIBLE
binding.overviewPump.visibility = View.GONE binding.overviewPump.visibility = View.GONE
@ -238,12 +238,12 @@ class LoopDialog : DaggerDialogFragment() {
} }
} }
binding.overviewSuspend.visibility = View.VISIBLE binding.overviewSuspend.visibility = View.VISIBLE
binding.overviewSuspendHeader.text = resourceHelper.gs(R.string.suspendloop) binding.overviewSuspendHeader.text = rh.gs(R.string.suspendloop)
binding.overviewSuspendButtons.visibility = View.VISIBLE binding.overviewSuspendButtons.visibility = View.VISIBLE
binding.overviewResume.visibility = View.GONE binding.overviewResume.visibility = View.GONE
binding.overviewPump.visibility = View.VISIBLE binding.overviewPump.visibility = View.VISIBLE
binding.overviewPumpHeader.text = resourceHelper.gs(R.string.disconnectpump) binding.overviewPumpHeader.text = rh.gs(R.string.disconnectpump)
binding.overviewDisconnectButtons.visibility = View.VISIBLE binding.overviewDisconnectButtons.visibility = View.VISIBLE
binding.overviewReconnect.visibility = View.GONE binding.overviewReconnect.visibility = View.GONE
@ -254,25 +254,25 @@ class LoopDialog : DaggerDialogFragment() {
private fun onClickOkCancelEnabled(v: View): Boolean { private fun onClickOkCancelEnabled(v: View): Boolean {
var description = "" var description = ""
when (v.id) { when (v.id) {
R.id.overview_closeloop -> description = resourceHelper.gs(R.string.closedloop) R.id.overview_closeloop -> description = rh.gs(R.string.closedloop)
R.id.overview_lgsloop -> description = resourceHelper.gs(R.string.lowglucosesuspend) R.id.overview_lgsloop -> description = rh.gs(R.string.lowglucosesuspend)
R.id.overview_openloop -> description = resourceHelper.gs(R.string.openloop) R.id.overview_openloop -> description = rh.gs(R.string.openloop)
R.id.overview_disable -> description = resourceHelper.gs(R.string.disableloop) R.id.overview_disable -> description = rh.gs(R.string.disableloop)
R.id.overview_enable -> description = resourceHelper.gs(R.string.enableloop) R.id.overview_enable -> description = rh.gs(R.string.enableloop)
R.id.overview_resume -> description = resourceHelper.gs(R.string.resume) R.id.overview_resume -> description = rh.gs(R.string.resume)
R.id.overview_reconnect -> description = resourceHelper.gs(R.string.reconnect) R.id.overview_reconnect -> description = rh.gs(R.string.reconnect)
R.id.overview_suspend_1h -> description = resourceHelper.gs(R.string.suspendloopfor1h) R.id.overview_suspend_1h -> description = rh.gs(R.string.suspendloopfor1h)
R.id.overview_suspend_2h -> description = resourceHelper.gs(R.string.suspendloopfor2h) R.id.overview_suspend_2h -> description = rh.gs(R.string.suspendloopfor2h)
R.id.overview_suspend_3h -> description = resourceHelper.gs(R.string.suspendloopfor3h) R.id.overview_suspend_3h -> description = rh.gs(R.string.suspendloopfor3h)
R.id.overview_suspend_10h -> description = resourceHelper.gs(R.string.suspendloopfor10h) R.id.overview_suspend_10h -> description = rh.gs(R.string.suspendloopfor10h)
R.id.overview_disconnect_15m -> description = resourceHelper.gs(R.string.disconnectpumpfor15m) R.id.overview_disconnect_15m -> description = rh.gs(R.string.disconnectpumpfor15m)
R.id.overview_disconnect_30m -> description = resourceHelper.gs(R.string.disconnectpumpfor30m) R.id.overview_disconnect_30m -> description = rh.gs(R.string.disconnectpumpfor30m)
R.id.overview_disconnect_1h -> description = resourceHelper.gs(R.string.disconnectpumpfor1h) R.id.overview_disconnect_1h -> description = rh.gs(R.string.disconnectpumpfor1h)
R.id.overview_disconnect_2h -> description = resourceHelper.gs(R.string.disconnectpumpfor2h) R.id.overview_disconnect_2h -> description = rh.gs(R.string.disconnectpumpfor2h)
R.id.overview_disconnect_3h -> description = resourceHelper.gs(R.string.disconnectpumpfor3h) R.id.overview_disconnect_3h -> description = rh.gs(R.string.disconnectpumpfor3h)
} }
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.confirm), description, Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.confirm), description, Runnable {
onClick(v) onClick(v)
}) })
} }
@ -284,21 +284,21 @@ class LoopDialog : DaggerDialogFragment() {
R.id.overview_closeloop -> { R.id.overview_closeloop -> {
uel.log(Action.CLOSED_LOOP_MODE, Sources.LoopDialog) uel.log(Action.CLOSED_LOOP_MODE, Sources.LoopDialog)
sp.putString(R.string.key_aps_mode, "closed") sp.putString(R.string.key_aps_mode, "closed")
rxBus.send(EventPreferenceChange(resourceHelper.gs(R.string.closedloop))) rxBus.send(EventPreferenceChange(rh.gs(R.string.closedloop)))
return true return true
} }
R.id.overview_lgsloop -> { R.id.overview_lgsloop -> {
uel.log(Action.LGS_LOOP_MODE, Sources.LoopDialog) uel.log(Action.LGS_LOOP_MODE, Sources.LoopDialog)
sp.putString(R.string.key_aps_mode, "lgs") sp.putString(R.string.key_aps_mode, "lgs")
rxBus.send(EventPreferenceChange(resourceHelper.gs(R.string.lowglucosesuspend))) rxBus.send(EventPreferenceChange(rh.gs(R.string.lowglucosesuspend)))
return true return true
} }
R.id.overview_openloop -> { R.id.overview_openloop -> {
uel.log(Action.OPEN_LOOP_MODE, Sources.LoopDialog) uel.log(Action.OPEN_LOOP_MODE, Sources.LoopDialog)
sp.putString(R.string.key_aps_mode, "open") sp.putString(R.string.key_aps_mode, "open")
rxBus.send(EventPreferenceChange(resourceHelper.gs(R.string.lowglucosesuspend))) rxBus.send(EventPreferenceChange(rh.gs(R.string.lowglucosesuspend)))
return true return true
} }
@ -311,7 +311,7 @@ class LoopDialog : DaggerDialogFragment() {
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.tempbasaldeliveryerror)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.tempbasaldeliveryerror))
} }
} }
}) })
@ -352,7 +352,7 @@ class LoopDialog : DaggerDialogFragment() {
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
}) })

View file

@ -38,10 +38,11 @@ import java.text.DecimalFormat
import java.util.* import java.util.*
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import kotlin.collections.ArrayList
class ProfileSwitchDialog : DialogFragmentWithDate() { class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -113,7 +114,17 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
context?.let { context -> context?.let { context ->
val profileStore = activePlugin.activeProfileSource.profile val profileStore = activePlugin.activeProfileSource.profile
?: return ?: return
val profileList = profileStore.getProfileList() val profileListToCheck = profileStore.getProfileList()
val profileList = ArrayList<CharSequence>()
for (profileName in profileListToCheck) {
val profileToCheck = activePlugin.activeProfileSource.profile?.getSpecificProfile(profileName.toString())
if (profileToCheck != null && ProfileSealed.Pure(profileToCheck).isValid("ProfileSwitch", activePlugin.activePump, config, rh, rxBus, hardLimits, false).isValid)
profileList.add(profileName)
}
if (profileList.isEmpty()) {
dismiss()
return
}
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
binding.profile.adapter = adapter binding.profile.adapter = adapter
// set selected to actual profile // set selected to actual profile
@ -123,19 +134,17 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
for (p in profileList.indices) for (p in profileList.indices)
if (profileList[p] == profileFunction.getOriginalProfileName()) if (profileList[p] == profileFunction.getOriginalProfileName())
binding.profile.setSelection(p) binding.profile.setSelection(p)
} ?: return }
profileFunction.getProfile()?.let { profile -> profileFunction.getProfile()?.let { profile ->
if (profile is ProfileSealed.EPS) if (profile is ProfileSealed.EPS)
if (profile.value.originalPercentage != 100 || profile.value.originalTimeshift != 0L) { if (profile.value.originalPercentage != 100 || profile.value.originalTimeshift != 0L) {
binding.reuselayout.visibility = View.VISIBLE binding.reuselayout.visibility = View.VISIBLE
binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, profile.value.originalPercentage, T.msecs(profile.value.originalTimeshift).hours().toInt()) binding.reusebutton.text = rh.gs(R.string.reuse_profile_pct_hours, profile.value.originalPercentage, T.msecs(profile.value.originalTimeshift).hours().toInt())
binding.reusebutton.setOnClickListener { binding.reusebutton.setOnClickListener {
binding.percentage.value = profile.value.originalPercentage.toDouble() binding.percentage.value = profile.value.originalPercentage.toDouble()
binding.timeshift.value = profile.value.originalTimeshift.toDouble() binding.timeshift.value = profile.value.originalTimeshift.toDouble()
} }
} else {
binding.reuselayout.visibility = View.GONE
} }
} }
binding.ttLayout.visibility = View.GONE binding.ttLayout.visibility = View.GONE
@ -155,75 +164,77 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
val duration = binding.duration.value?.toInt() ?: return false val duration = binding.duration.value?.toInt() ?: return false
if (duration > 0L) if (duration > 0L)
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, duration))
val profileName = binding.profile.selectedItem.toString() val profileName = binding.profile.selectedItem.toString()
actions.add(resourceHelper.gs(R.string.profile) + ": " + profileName) actions.add(rh.gs(R.string.profile) + ": " + profileName)
val percent = binding.percentage.value.toInt() val percent = binding.percentage.value.toInt()
if (percent != 100) if (percent != 100)
actions.add(resourceHelper.gs(R.string.percent) + ": " + percent + "%") actions.add(rh.gs(R.string.percent) + ": " + percent + "%")
val timeShift = binding.timeshift.value.toInt() val timeShift = binding.timeshift.value.toInt()
if (timeShift != 0) if (timeShift != 0)
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + resourceHelper.gs(R.string.format_hours, timeShift.toDouble())) actions.add(rh.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + rh.gs(R.string.format_hours, timeShift.toDouble()))
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
val isTT = binding.duration.value > 0 && binding.percentage.value < 100 && binding.tt.isChecked val isTT = binding.duration.value > 0 && binding.percentage.value < 100 && binding.tt.isChecked
val target = defaultValueHelper.determineActivityTT() val target = defaultValueHelper.determineActivityTT()
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
if (isTT) if (isTT)
actions.add(resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + resourceHelper.gs(R.string.activity)) actions.add(rh.gs(R.string.careportal_temporarytarget) + ": " + rh.gs(R.string.activity))
activity?.let { activity -> activity?.let { activity ->
val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) ?: return@let
val validity = ProfileSealed.PS(ps).isValid(resourceHelper.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) val validity = ProfileSealed.PS(ps).isValid(rh.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, rh, rxBus, hardLimits, false)
if (validity.isValid) if (validity.isValid)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
profileFunction.createProfileSwitch( if (profileFunction.createProfileSwitch(
profileStore, profileStore,
profileName = profileName, profileName = profileName,
durationInMinutes = duration, durationInMinutes = duration,
percentage = percent, percentage = percent,
timeShiftInHours = timeShift, timeShiftInHours = timeShift,
timestamp = eventTime timestamp = eventTime
)
uel.log(Action.PROFILE_SWITCH,
Sources.ProfileSwitchDialog,
notes,
ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged },
ValueWithUnit.SimpleString(profileName),
ValueWithUnit.Percent(percent),
ValueWithUnit.Hour(timeShift).takeIf { timeShift != 0 },
ValueWithUnit.Minute(duration).takeIf { duration != 0 })
if (percent == 90 && duration == 10) sp.putBoolean(R.string.key_objectiveuseprofileswitch, true)
if (isTT) {
disposable += repository.runTransactionForResult(
InsertAndCancelCurrentTemporaryTargetTransaction(
timestamp = eventTime,
duration = TimeUnit.MINUTES.toMillis(duration.toLong()),
reason = TemporaryTarget.Reason.ACTIVITY,
lowTarget = Profile.toMgdl(target, profileFunction.getUnits()),
highTarget = Profile.toMgdl(target, profileFunction.getUnits())
)
).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
uel.log(
Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(
TemporaryTarget.Reason.ACTIVITY
), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)
) )
) {
uel.log(Action.PROFILE_SWITCH,
Sources.ProfileSwitchDialog,
notes,
ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged },
ValueWithUnit.SimpleString(profileName),
ValueWithUnit.Percent(percent),
ValueWithUnit.Hour(timeShift).takeIf { timeShift != 0 },
ValueWithUnit.Minute(duration).takeIf { duration != 0 })
if (percent == 90 && duration == 10) sp.putBoolean(R.string.key_objectiveuseprofileswitch, true)
if (isTT) {
disposable += repository.runTransactionForResult(
InsertAndCancelCurrentTemporaryTargetTransaction(
timestamp = eventTime,
duration = TimeUnit.MINUTES.toMillis(duration.toLong()),
reason = TemporaryTarget.Reason.ACTIVITY,
lowTarget = Profile.toMgdl(target, profileFunction.getUnits()),
highTarget = Profile.toMgdl(target, profileFunction.getUnits())
)
).subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
uel.log(
Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(
TemporaryTarget.Reason.ACTIVITY
), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)
)
}
} }
}) })
else { else {
OKDialog.show( OKDialog.show(
activity, activity,
resourceHelper.gs(R.string.careportal_profileswitch), rh.gs(R.string.careportal_profileswitch),
HtmlHelper.fromHtml(Joiner.on("<br/>").join(validity.reasons)) HtmlHelper.fromHtml(Joiner.on("<br/>").join(validity.reasons))
) )
return false return false

View file

@ -29,10 +29,10 @@ import kotlin.math.abs
class TempBasalDialog : DialogFragmentWithDate() { class TempBasalDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -103,23 +103,23 @@ class TempBasalDialog : DialogFragmentWithDate() {
if (isPercentPump) { if (isPercentPump) {
val basalPercentInput = SafeParse.stringToInt(binding.basalpercentinput.text) val basalPercentInput = SafeParse.stringToInt(binding.basalpercentinput.text)
percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value()
actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": $percent%") actions.add(rh.gs(R.string.tempbasal_label) + ": $percent%")
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes))
if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) if (percent != basalPercentInput) actions.add(rh.gs(R.string.constraintapllied))
} else { } else {
val basalAbsoluteInput = SafeParse.stringToDouble(binding.basalabsoluteinput.text) val basalAbsoluteInput = SafeParse.stringToDouble(binding.basalabsoluteinput.text)
absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value()
actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) actions.add(rh.gs(R.string.tempbasal_label) + ": " + rh.gs(R.string.pump_basebasalrate, absolute))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes))
if (abs(absolute - basalAbsoluteInput) > 0.01) if (abs(absolute - basalAbsoluteInput) > 0.01)
actions.add(resourceHelper.gs(R.string.constraintapllied).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.constraintapllied).formatColor(rh, R.color.warning))
} }
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
val callback: Callback = object : Callback() { val callback: Callback = object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
} }

View file

@ -38,7 +38,7 @@ import javax.inject.Inject
class TempTargetDialog : DialogFragmentWithDate() { class TempTargetDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -85,7 +85,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, binding.okcancel.ok) Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, binding.okcancel.ok)
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
binding.units.text = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) binding.units.text = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
// temp target // temp target
context?.let { context -> context?.let { context ->
@ -95,10 +95,10 @@ class TempTargetDialog : DialogFragmentWithDate() {
binding.targetCancel.visibility = View.GONE binding.targetCancel.visibility = View.GONE
reasonList = Lists.newArrayList( reasonList = Lists.newArrayList(
resourceHelper.gs(R.string.manual), rh.gs(R.string.manual),
resourceHelper.gs(R.string.eatingsoon), rh.gs(R.string.eatingsoon),
resourceHelper.gs(R.string.activity), rh.gs(R.string.activity),
resourceHelper.gs(R.string.hypo) rh.gs(R.string.hypo)
) )
val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList)
binding.reason.adapter = adapterReason binding.reason.adapter = adapterReason
@ -133,19 +133,19 @@ class TempTargetDialog : DialogFragmentWithDate() {
R.id.eating_soon -> { R.id.eating_soon -> {
binding.temptarget.value = defaultValueHelper.determineEatingSoonTT() binding.temptarget.value = defaultValueHelper.determineEatingSoonTT()
binding.duration.value = defaultValueHelper.determineEatingSoonTTDuration().toDouble() binding.duration.value = defaultValueHelper.determineEatingSoonTTDuration().toDouble()
binding.reason.setSelection(reasonList.indexOf(resourceHelper.gs(R.string.eatingsoon))) binding.reason.setSelection(reasonList.indexOf(rh.gs(R.string.eatingsoon)))
} }
R.id.activity -> { R.id.activity -> {
binding.temptarget.value = defaultValueHelper.determineActivityTT() binding.temptarget.value = defaultValueHelper.determineActivityTT()
binding.duration.value = defaultValueHelper.determineActivityTTDuration().toDouble() binding.duration.value = defaultValueHelper.determineActivityTTDuration().toDouble()
binding.reason.setSelection(reasonList.indexOf(resourceHelper.gs(R.string.activity))) binding.reason.setSelection(reasonList.indexOf(rh.gs(R.string.activity)))
} }
R.id.hypo -> { R.id.hypo -> {
binding.temptarget.value = defaultValueHelper.determineHypoTT() binding.temptarget.value = defaultValueHelper.determineHypoTT()
binding.duration.value = defaultValueHelper.determineHypoTTDuration().toDouble() binding.duration.value = defaultValueHelper.determineHypoTTDuration().toDouble()
binding.reason.setSelection(reasonList.indexOf(resourceHelper.gs(R.string.hypo))) binding.reason.setSelection(reasonList.indexOf(rh.gs(R.string.hypo)))
} }
R.id.cancel -> { R.id.cancel -> {
@ -168,25 +168,25 @@ class TempTargetDialog : DialogFragmentWithDate() {
val target = binding.temptarget.value val target = binding.temptarget.value
val duration = binding.duration.value.toInt() val duration = binding.duration.value.toInt()
if (target != 0.0 && duration != 0) { if (target != 0.0 && duration != 0) {
actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) actions.add(rh.gs(R.string.reason) + ": " + reason)
actions.add(resourceHelper.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) actions.add(rh.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + rh.gs(unitResId))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, duration))
} else { } else {
actions.add(resourceHelper.gs(R.string.stoptemptarget)) actions.add(rh.gs(R.string.stoptemptarget))
reason = resourceHelper.gs(R.string.stoptemptarget) reason = rh.gs(R.string.stoptemptarget)
} }
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
when(reason) { when(reason) {
resourceHelper.gs(R.string.eatingsoon) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)) rh.gs(R.string.eatingsoon) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
resourceHelper.gs(R.string.activity) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)) rh.gs(R.string.activity) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
resourceHelper.gs(R.string.hypo) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)) rh.gs(R.string.hypo) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
resourceHelper.gs(R.string.manual) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.CUSTOM), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration)) rh.gs(R.string.manual) -> uel.log(Action.TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.CUSTOM), ValueWithUnit.fromGlucoseUnit(target, units.asText), ValueWithUnit.Minute(duration))
resourceHelper.gs(R.string.stoptemptarget) -> uel.log(Action.CANCEL_TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }) rh.gs(R.string.stoptemptarget) -> uel.log(Action.CANCEL_TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged })
} }
if (target == 0.0 || duration == 0) { if (target == 0.0 || duration == 0) {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(eventTime)) disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(eventTime))
@ -200,9 +200,9 @@ class TempTargetDialog : DialogFragmentWithDate() {
timestamp = eventTime, timestamp = eventTime,
duration = TimeUnit.MINUTES.toMillis(duration.toLong()), duration = TimeUnit.MINUTES.toMillis(duration.toLong()),
reason = when (reason) { reason = when (reason) {
resourceHelper.gs(R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON rh.gs(R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON
resourceHelper.gs(R.string.activity) -> TemporaryTarget.Reason.ACTIVITY rh.gs(R.string.activity) -> TemporaryTarget.Reason.ACTIVITY
resourceHelper.gs(R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA rh.gs(R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA
else -> TemporaryTarget.Reason.CUSTOM else -> TemporaryTarget.Reason.CUSTOM
}, },
lowTarget = Profile.toMgdl(target, profileFunction.getUnits()), lowTarget = Profile.toMgdl(target, profileFunction.getUnits()),

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.DialogTreatmentBinding import info.nightscout.androidaps.databinding.DialogTreatmentBinding
import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
@ -41,9 +41,9 @@ import kotlin.math.abs
class TreatmentDialog : DialogFragmentWithDate() { class TreatmentDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -64,11 +64,11 @@ class TreatmentDialog : DialogFragmentWithDate() {
val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
if (SafeParse.stringToInt(binding.carbs.text) > maxCarbs) { if (SafeParse.stringToInt(binding.carbs.text) > maxCarbs) {
binding.carbs.value = 0.0 binding.carbs.value = 0.0
ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.carbsconstraintapplied)) ToastUtils.showToastInUiThread(context, rh.gs(R.string.carbsconstraintapplied))
} }
if (SafeParse.stringToDouble(binding.insulin.text) > maxInsulin) { if (SafeParse.stringToDouble(binding.insulin.text) > maxInsulin) {
binding.insulin.value = 0.0 binding.insulin.value = 0.0
ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.bolusconstraintapplied)) ToastUtils.showToastInUiThread(context, rh.gs(R.string.bolusconstraintapplied))
} }
} }
@ -123,20 +123,20 @@ class TreatmentDialog : DialogFragmentWithDate() {
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
if (insulinAfterConstraints > 0) { if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, resourceHelper).formatColor(resourceHelper, R.color.bolus)) actions.add(rh.gs(R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(rh, R.color.bolus))
if (recordOnlyChecked) if (recordOnlyChecked)
actions.add(resourceHelper.gs(R.string.bolusrecordedonly).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.bolusrecordedonly).formatColor(rh, R.color.warning))
if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints))
actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.bolusconstraintappliedwarn, insulin, insulinAfterConstraints).formatColor(rh, R.color.warning))
} }
if (carbsAfterConstraints > 0) { if (carbsAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints).formatColor(resourceHelper, R.color.carbs)) actions.add(rh.gs(R.string.carbs) + ": " + rh.gs(R.string.format_carbs, carbsAfterConstraints).formatColor(rh, R.color.carbs))
if (carbsAfterConstraints != carbs) if (carbsAfterConstraints != carbs)
actions.add(resourceHelper.gs(R.string.carbsconstraintapplied).formatColor(resourceHelper, R.color.warning)) actions.add(rh.gs(R.string.carbsconstraintapplied).formatColor(rh, R.color.warning))
} }
if (insulinAfterConstraints > 0 || carbsAfterConstraints > 0) { if (insulinAfterConstraints > 0 || carbsAfterConstraints > 0) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
val action = when { val action = when {
insulinAfterConstraints.equals(0.0) -> Action.CARBS insulinAfterConstraints.equals(0.0) -> Action.CARBS
carbsAfterConstraints.equals(0) -> Action.BOLUS carbsAfterConstraints.equals(0) -> Action.BOLUS
@ -149,9 +149,9 @@ class TreatmentDialog : DialogFragmentWithDate() {
detailedBolusInfo.carbs = carbsAfterConstraints.toDouble() detailedBolusInfo.carbs = carbsAfterConstraints.toDouble()
detailedBolusInfo.context = context detailedBolusInfo.context = context
if (recordOnlyChecked) { if (recordOnlyChecked) {
uel.log(action, Sources.TreatmentDialog, if (insulinAfterConstraints != 0.0) resourceHelper.gs(R.string.record) else "", uel.log(action, Sources.TreatmentDialog, if (insulinAfterConstraints != 0.0) rh.gs(R.string.record) else "",
ValueWithUnit.Timestamp(detailedBolusInfo.timestamp).takeIf { eventTimeChanged }, ValueWithUnit.Timestamp(detailedBolusInfo.timestamp).takeIf { eventTimeChanged },
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.record)).takeIf { insulinAfterConstraints != 0.0 }, ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.record)).takeIf { insulinAfterConstraints != 0.0 },
ValueWithUnit.Insulin(insulinAfterConstraints).takeIf { insulinAfterConstraints != 0.0 }, ValueWithUnit.Insulin(insulinAfterConstraints).takeIf { insulinAfterConstraints != 0.0 },
ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbsAfterConstraints != 0 }) ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbsAfterConstraints != 0 })
if (detailedBolusInfo.insulin > 0) if (detailedBolusInfo.insulin > 0)
@ -174,7 +174,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -186,7 +186,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
} }
} else } else
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.overview_treatment_label), rh.gs(R.string.no_action_selected))
} }
return true return true
} }

View file

@ -55,7 +55,7 @@ class WizardDialog : DaggerDialogFragment() {
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var iobCobCalculator: IobCobCalculator
@ -140,7 +140,7 @@ class WizardDialog : DaggerDialogFragment() {
?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, binding.ok, timeTextWatcher) ?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, binding.ok, timeTextWatcher)
initDialog() initDialog()
binding.percentUsed.text = resourceHelper.gs(R.string.format_percent, sp.getInt(R.string.key_boluswizard_percentage, 100)) binding.percentUsed.text = rh.gs(R.string.format_percent, sp.getInt(R.string.key_boluswizard_percentage, 100))
// ok button // ok button
binding.ok.setOnClickListener { binding.ok.setOnClickListener {
if (okClicked) { if (okClicked) {
@ -171,7 +171,7 @@ class WizardDialog : DaggerDialogFragment() {
binding.calculationcheckbox.isChecked = showCalc binding.calculationcheckbox.isChecked = showCalc
binding.calculationcheckbox.setOnCheckedChangeListener { _, isChecked -> binding.calculationcheckbox.setOnCheckedChangeListener { _, isChecked ->
run { run {
sp.putBoolean(resourceHelper.gs(R.string.key_wizard_calculation_visible), isChecked) sp.putBoolean(rh.gs(R.string.key_wizard_calculation_visible), isChecked)
binding.delimiter.visibility = isChecked.toVisibility() binding.delimiter.visibility = isChecked.toVisibility()
binding.resulttable.visibility = isChecked.toVisibility() binding.resulttable.visibility = isChecked.toVisibility()
} }
@ -179,7 +179,7 @@ class WizardDialog : DaggerDialogFragment() {
// profile spinner // profile spinner
binding.profile.onItemSelectedListener = object : OnItemSelectedListener { binding.profile.onItemSelectedListener = object : OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) { override fun onNothingSelected(parent: AdapterView<*>?) {
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.noprofileselected)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.noprofileset))
binding.ok.visibility = View.GONE binding.ok.visibility = View.GONE
} }
@ -244,13 +244,13 @@ class WizardDialog : DaggerDialogFragment() {
val profileStore = activePlugin.activeProfileSource.profile val profileStore = activePlugin.activeProfileSource.profile
if (profile == null || profileStore == null) { if (profile == null || profileStore == null) {
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.noprofile)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.noprofile))
dismiss() dismiss()
return return
} }
val profileList: ArrayList<CharSequence> = profileStore.getProfileList() val profileList: ArrayList<CharSequence> = profileStore.getProfileList()
profileList.add(0, resourceHelper.gs(R.string.active)) profileList.add(0, rh.gs(R.string.active))
context?.let { context -> context?.let { context ->
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
binding.profile.adapter = adapter binding.profile.adapter = adapter
@ -271,8 +271,8 @@ class WizardDialog : DaggerDialogFragment() {
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob) binding.bolusiobinsulin.text = rh.gs(R.string.formatinsulinunits, -bolusIob.iob)
binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -basalIob.basaliob) binding.basaliobinsulin.text = rh.gs(R.string.formatinsulinunits, -basalIob.basaliob)
calculateInsulin() calculateInsulin()
@ -285,7 +285,7 @@ class WizardDialog : DaggerDialogFragment() {
return // not initialized yet return // not initialized yet
var profileName = binding.profile.selectedItem.toString() var profileName = binding.profile.selectedItem.toString()
val specificProfile: Profile? val specificProfile: Profile?
if (profileName == resourceHelper.gs(R.string.active)) { if (profileName == rh.gs(R.string.active)) {
specificProfile = profileFunction.getProfile() specificProfile = profileFunction.getProfile()
profileName = profileFunction.getProfileName() profileName = profileFunction.getProfileName()
} else } else
@ -300,7 +300,7 @@ class WizardDialog : DaggerDialogFragment() {
val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
if (abs(carbs - carbsAfterConstraint) > 0.01) { if (abs(carbs - carbsAfterConstraint) > 0.01) {
binding.carbsInput.value = 0.0 binding.carbsInput.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.carbsconstraintapplied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.carbsconstraintapplied))
return return
} }
@ -330,20 +330,20 @@ class WizardDialog : DaggerDialogFragment() {
binding.notes.text.toString(), carbTime) binding.notes.text.toString(), carbTime)
wizard?.let { wizard -> wizard?.let { wizard ->
binding.bg.text = String.format(resourceHelper.gs(R.string.format_bg_isf), valueToUnitsToString(Profile.toMgdl(bg, profileFunction.getUnits()), profileFunction.getUnits().asText), wizard.sens) binding.bg.text = String.format(rh.gs(R.string.format_bg_isf), valueToUnitsToString(Profile.toMgdl(bg, profileFunction.getUnits()), profileFunction.getUnits().asText), wizard.sens)
binding.bginsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBG) binding.bginsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromBG)
binding.carbs.text = String.format(resourceHelper.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) binding.carbs.text = String.format(rh.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic)
binding.carbsinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromCarbs) binding.carbsinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromCarbs)
binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBolusIOB) binding.bolusiobinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromBolusIOB)
binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBasalIOB) binding.basaliobinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromBasalIOB)
binding.correctioninsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromCorrection) binding.correctioninsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromCorrection)
// Superbolus // Superbolus
binding.sb.text = if (binding.sbcheckbox.isChecked) resourceHelper.gs(R.string.twohours) else "" binding.sb.text = if (binding.sbcheckbox.isChecked) rh.gs(R.string.twohours) else ""
binding.sbinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromSuperBolus) binding.sbinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromSuperBolus)
// Trend // Trend
if (binding.bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) { if (binding.bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) {
@ -353,24 +353,24 @@ class WizardDialog : DaggerDialogFragment() {
} else { } else {
binding.bgtrend.text = "" binding.bgtrend.text = ""
} }
binding.bgtrendinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromTrend) binding.bgtrendinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromTrend)
// COB // COB
if (binding.cobcheckbox.isChecked) { if (binding.cobcheckbox.isChecked) {
binding.cob.text = String.format(resourceHelper.gs(R.string.format_cob_ic), cob, wizard.ic) binding.cob.text = String.format(rh.gs(R.string.format_cob_ic), cob, wizard.ic)
binding.cobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromCOB) binding.cobinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromCOB)
} else { } else {
binding.cob.text = "" binding.cob.text = ""
binding.cobinsulin.text = "" binding.cobinsulin.text = ""
} }
if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) { if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) {
val insulinText = if (wizard.calculatedTotalInsulin > 0.0) resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" val insulinText = if (wizard.calculatedTotalInsulin > 0.0) rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else ""
val carbsText = if (carbsAfterConstraint > 0.0) resourceHelper.gs(R.string.format_carbs, carbsAfterConstraint) else "" val carbsText = if (carbsAfterConstraint > 0.0) rh.gs(R.string.format_carbs, carbsAfterConstraint) else ""
binding.total.text = resourceHelper.gs(R.string.result_insulin_carbs, insulinText, carbsText) binding.total.text = rh.gs(R.string.result_insulin_carbs, insulinText, carbsText)
binding.ok.visibility = View.VISIBLE binding.ok.visibility = View.VISIBLE
} else { } else {
binding.total.text = resourceHelper.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt()) binding.total.text = rh.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt())
binding.ok.visibility = View.INVISIBLE binding.ok.visibility = View.INVISIBLE
} }
} }

View file

@ -19,7 +19,7 @@ import javax.inject.Inject
class WizardInfoDialog : DaggerDialogFragment() { class WizardInfoDialog : DaggerDialogFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
private lateinit var data: BolusCalculatorResult private lateinit var data: BolusCalculatorResult
@ -51,40 +51,40 @@ class WizardInfoDialog : DaggerDialogFragment() {
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val bgString = Profile.toUnitsString(data.glucoseValue, data.glucoseValue * Constants.MGDL_TO_MMOLL, units) val bgString = Profile.toUnitsString(data.glucoseValue, data.glucoseValue * Constants.MGDL_TO_MMOLL, units)
// BG // BG
binding.bg.text = resourceHelper.gs(R.string.format_bg_isf, bgString, data.isf) binding.bg.text = rh.gs(R.string.format_bg_isf, bgString, data.isf)
binding.bginsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.glucoseInsulin) binding.bginsulin.text = rh.gs(R.string.formatinsulinunits, data.glucoseInsulin)
binding.bgcheckbox.isChecked = data.wasGlucoseUsed binding.bgcheckbox.isChecked = data.wasGlucoseUsed
binding.ttcheckbox.isChecked = data.wasTempTargetUsed binding.ttcheckbox.isChecked = data.wasTempTargetUsed
// Trend // Trend
binding.bgtrend.text = DecimalFormatter.to1Decimal(data.glucoseTrend) binding.bgtrend.text = DecimalFormatter.to1Decimal(data.glucoseTrend)
binding.bgtrendinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.trendInsulin) binding.bgtrendinsulin.text = rh.gs(R.string.formatinsulinunits, data.trendInsulin)
binding.bgtrendcheckbox.isChecked = data.wasTrendUsed binding.bgtrendcheckbox.isChecked = data.wasTrendUsed
// COB // COB
binding.cob.text = resourceHelper.gs(R.string.format_cob_ic, data.cob, data.ic) binding.cob.text = rh.gs(R.string.format_cob_ic, data.cob, data.ic)
binding.cobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.cobInsulin) binding.cobinsulin.text = rh.gs(R.string.formatinsulinunits, data.cobInsulin)
binding.cobcheckbox.isChecked = data.wasCOBUsed binding.cobcheckbox.isChecked = data.wasCOBUsed
// Bolus IOB // Bolus IOB
binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.bolusIOB) binding.bolusiobinsulin.text = rh.gs(R.string.formatinsulinunits, data.bolusIOB)
binding.bolusiobcheckbox.isChecked = data.wasBolusIOBUsed binding.bolusiobcheckbox.isChecked = data.wasBolusIOBUsed
// Basal IOB // Basal IOB
binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.basalIOB) binding.basaliobinsulin.text = rh.gs(R.string.formatinsulinunits, data.basalIOB)
binding.basaliobcheckbox.isChecked = data.wasBasalIOBUsed binding.basaliobcheckbox.isChecked = data.wasBasalIOBUsed
// Superbolus // Superbolus
binding.sbinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.superbolusInsulin) binding.sbinsulin.text = rh.gs(R.string.formatinsulinunits, data.superbolusInsulin)
binding.sbcheckbox.isChecked = data.wasSuperbolusUsed binding.sbcheckbox.isChecked = data.wasSuperbolusUsed
// Carbs // Carbs
binding.carbs.text = resourceHelper.gs(R.string.format_carbs_ic, data.carbs, data.ic) binding.carbs.text = rh.gs(R.string.format_carbs_ic, data.carbs, data.ic)
binding.carbsinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.carbsInsulin) binding.carbsinsulin.text = rh.gs(R.string.formatinsulinunits, data.carbsInsulin)
// Correction // Correction
binding.correctioninsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.otherCorrection) binding.correctioninsulin.text = rh.gs(R.string.formatinsulinunits, data.otherCorrection)
// Profile // Profile
binding.profile.text = data.profileName binding.profile.text = data.profileName
// Notes // Notes
binding.notes.text = data.note binding.notes.text = data.note
// Percentage // Percentage
binding.percentUsed.text = resourceHelper.gs(R.string.format_percent, data.percentageCorrection) binding.percentUsed.text = rh.gs(R.string.format_percent, data.percentageCorrection)
// Total // Total
binding.totalinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.totalInsulin) binding.totalinsulin.text = rh.gs(R.string.formatinsulinunits, data.totalInsulin)
} }
override fun onStart() { override fun onStart() {

View file

@ -28,7 +28,7 @@ class LoopFragment : DaggerFragment() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -51,7 +51,7 @@ class LoopFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.run.setOnClickListener { binding.run.setOnClickListener {
binding.lastrun.text = resourceHelper.gs(R.string.executing) binding.lastrun.text = rh.gs(R.string.executing)
Thread { loopPlugin.invoke("Loop button", true) }.start() Thread { loopPlugin.invoke("Loop button", true) }.start()
} }
} }

View file

@ -75,10 +75,10 @@ class LoopPlugin @Inject constructor(
private val sp: SP, private val sp: SP,
config: Config, config: Config,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val commandQueue: CommandQueueProvider, private val commandQueue: CommandQueue,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val virtualPumpPlugin: VirtualPumpPlugin, private val virtualPumpPlugin: VirtualPumpPlugin,
private val iobCobCalculator: IobCobCalculator, private val iobCobCalculator: IobCobCalculator,
@ -97,7 +97,7 @@ class LoopPlugin @Inject constructor(
.preferencesId(R.xml.pref_loop) .preferencesId(R.xml.pref_loop)
.enableByDefault(config.APS) .enableByDefault(config.APS)
.description(R.string.description_loop), .description(R.string.description_loop),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Loop { ), Loop {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -230,7 +230,7 @@ class LoopPlugin @Inject constructor(
val loopEnabled = constraintChecker.isLoopInvocationAllowed() val loopEnabled = constraintChecker.isLoopInvocationAllowed()
if (!loopEnabled.value()) { if (!loopEnabled.value()) {
val message = """ val message = """
${resourceHelper.gs(R.string.loopdisabled)} ${rh.gs(R.string.loopdisabled)}
${loopEnabled.getReasons(aapsLogger)} ${loopEnabled.getReasons(aapsLogger)}
""".trimIndent() """.trimIndent()
aapsLogger.debug(LTag.APS, message) aapsLogger.debug(LTag.APS, message)
@ -242,28 +242,28 @@ class LoopPlugin @Inject constructor(
if (!isEnabled(PluginType.LOOP)) return if (!isEnabled(PluginType.LOOP)) return
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
if (profile == null || !profileFunction.isProfileValid("Loop")) { if (profile == null || !profileFunction.isProfileValid("Loop")) {
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset))
rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.noprofileselected))) rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.noprofileset)))
return return
} }
// Check if pump info is loaded // Check if pump info is loaded
if (pump.baseBasalRate < 0.01) return if (pump.baseBasalRate < 0.01) return
val usedAPS = activePlugin.activeAPS val usedAPS = activePlugin.activeAPS
if ((usedAPS as PluginBase).isEnabled(PluginType.APS)) { if ((usedAPS as PluginBase).isEnabled()) {
usedAPS.invoke(initiator, tempBasalFallback) usedAPS.invoke(initiator, tempBasalFallback)
apsResult = usedAPS.lastAPSResult apsResult = usedAPS.lastAPSResult
} }
// Check if we have any result // Check if we have any result
if (apsResult == null) { if (apsResult == null) {
rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.noapsselected))) rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.noapsselected)))
return return
} else rxBus.send(EventLoopInvoked()) } else rxBus.send(EventLoopInvoked())
if (!isEmptyQueue()) { if (!isEmptyQueue()) {
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.pumpbusy)) aapsLogger.debug(LTag.APS, rh.gs(R.string.pumpbusy))
rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpbusy))) rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.pumpbusy)))
return return
} }
@ -307,13 +307,13 @@ class LoopPlugin @Inject constructor(
} }
if (isSuspended) { if (isSuspended) {
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)) aapsLogger.debug(LTag.APS, rh.gs(R.string.loopsuspended))
rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.loopsuspended))) rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.loopsuspended)))
return return
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.pumpsuspended)) aapsLogger.debug(LTag.APS, rh.gs(R.string.pumpsuspended))
rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpsuspended))) rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.pumpsuspended)))
return return
} }
val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() val closedLoopEnabled = constraintChecker.isClosedLoopAllowed()
@ -332,18 +332,18 @@ class LoopPlugin @Inject constructor(
val intentAction5m = Intent(context, CarbSuggestionReceiver::class.java) val intentAction5m = Intent(context, CarbSuggestionReceiver::class.java)
intentAction5m.putExtra("ignoreDuration", 5) intentAction5m.putExtra("ignoreDuration", 5)
val pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val actionIgnore5m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore5m, "Ignore 5m"), pendingIntent5m) val actionIgnore5m = NotificationCompat.Action(R.drawable.ic_notif_aaps, rh.gs(R.string.ignore5m, "Ignore 5m"), pendingIntent5m)
val intentAction15m = Intent(context, CarbSuggestionReceiver::class.java) val intentAction15m = Intent(context, CarbSuggestionReceiver::class.java)
intentAction15m.putExtra("ignoreDuration", 15) intentAction15m.putExtra("ignoreDuration", 15)
val pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val actionIgnore15m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore15m, "Ignore 15m"), pendingIntent15m) val actionIgnore15m = NotificationCompat.Action(R.drawable.ic_notif_aaps, rh.gs(R.string.ignore15m, "Ignore 15m"), pendingIntent15m)
val intentAction30m = Intent(context, CarbSuggestionReceiver::class.java) val intentAction30m = Intent(context, CarbSuggestionReceiver::class.java)
intentAction30m.putExtra("ignoreDuration", 30) intentAction30m.putExtra("ignoreDuration", 30)
val pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
val actionIgnore30m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore30m, "Ignore 30m"), pendingIntent30m) val actionIgnore30m = NotificationCompat.Action(R.drawable.ic_notif_aaps, rh.gs(R.string.ignore30m, "Ignore 30m"), pendingIntent30m)
val builder = NotificationCompat.Builder(context, CHANNEL_ID) val builder = NotificationCompat.Builder(context, CHANNEL_ID)
builder.setSmallIcon(R.drawable.notif_icon) builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(resourceHelper.gs(R.string.carbssuggestion)) .setContentTitle(rh.gs(R.string.carbssuggestion))
.setContentText(resultAfterConstraints.carbsRequiredText) .setContentText(resultAfterConstraints.carbsRequiredText)
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.IMPORTANCE_HIGH) .setPriority(Notification.IMPORTANCE_HIGH)
@ -357,9 +357,9 @@ class LoopPlugin @Inject constructor(
// mId allows you to update the notification later on. // mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build()) mNotificationManager.notify(Constants.notificationID, builder.build())
uel.log(Action.CAREPORTAL, Sources.Loop, resourceHelper.gs(R.string.carbsreq, resultAfterConstraints.carbsReq, resultAfterConstraints.carbsReqWithin), uel.log(Action.CAREPORTAL, Sources.Loop, rh.gs(R.string.carbsreq, resultAfterConstraints.carbsReq, resultAfterConstraints.carbsReqWithin),
ValueWithUnit.Gram(resultAfterConstraints.carbsReq), ValueWithUnit.Gram(resultAfterConstraints.carbsReq),
ValueWithUnit.Minute(resultAfterConstraints.carbsReqWithin)) ValueWithUnit.Minute(resultAfterConstraints.carbsReqWithin))
rxBus.send(EventNewOpenLoopNotification()) rxBus.send(EventNewOpenLoopNotification())
//only send to wear if Native notifications are turned off //only send to wear if Native notifications are turned off
@ -422,7 +422,7 @@ class LoopPlugin @Inject constructor(
if (resultAfterConstraints.isChangeRequested && allowNotification) { if (resultAfterConstraints.isChangeRequested && allowNotification) {
val builder = NotificationCompat.Builder(context, CHANNEL_ID) val builder = NotificationCompat.Builder(context, CHANNEL_ID)
builder.setSmallIcon(R.drawable.notif_icon) builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion)) .setContentTitle(rh.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString()) .setContentText(resultAfterConstraints.toString())
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.IMPORTANCE_HIGH) .setPriority(Notification.IMPORTANCE_HIGH)
@ -516,12 +516,12 @@ class LoopPlugin @Inject constructor(
} }
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (!pump.isInitialized()) { if (!pump.isInitialized()) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpNotInitialized)) aapsLogger.debug(LTag.APS, "applyAPSRequest: " + rh.gs(R.string.pumpNotInitialized))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run() callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
return return
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: " + resourceHelper.gs(R.string.pumpsuspended)) aapsLogger.debug(LTag.APS, "applyAPSRequest: " + rh.gs(R.string.pumpsuspended))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run() callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
return return
} }
@ -591,12 +591,12 @@ class LoopPlugin @Inject constructor(
return return
} }
if (!pump.isInitialized()) { if (!pump.isInitialized()) {
aapsLogger.debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpNotInitialized)) aapsLogger.debug(LTag.APS, "applySMBRequest: " + rh.gs(R.string.pumpNotInitialized))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run() callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
return return
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
aapsLogger.debug(LTag.APS, "applySMBRequest: " + resourceHelper.gs(R.string.pumpsuspended)) aapsLogger.debug(LTag.APS, "applySMBRequest: " + rh.gs(R.string.pumpsuspended))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run() callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
return return
} }
@ -616,7 +616,7 @@ class LoopPlugin @Inject constructor(
} }
private fun allowPercentage(): Boolean { private fun allowPercentage(): Boolean {
return virtualPumpPlugin.isEnabled(PluginType.PUMP) return virtualPumpPlugin.isEnabled()
} }
override fun goToZeroTemp(durationInMinutes: Int, profile: Profile, reason: OfflineEvent.Reason) { override fun goToZeroTemp(durationInMinutes: Int, profile: Profile, reason: OfflineEvent.Reason) {
@ -632,7 +632,7 @@ class LoopPlugin @Inject constructor(
commandQueue.tempBasalAbsolute(0.0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() { commandQueue.tempBasalAbsolute(0.0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -640,7 +640,7 @@ class LoopPlugin @Inject constructor(
commandQueue.tempBasalPercent(0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() { commandQueue.tempBasalPercent(0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -649,7 +649,7 @@ class LoopPlugin @Inject constructor(
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -667,7 +667,7 @@ class LoopPlugin @Inject constructor(
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
}) })

View file

@ -31,7 +31,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -101,7 +101,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterAMAJS.currentTempParam) binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
try { try {
val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam) val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0))) binding.iobdata.text = TextUtils.concat(rh.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e) aapsLogger.error(LTag.APS, "Unhandled exception", e)
@Suppress("SetTextI18n") @Suppress("SetTextI18n")

View file

@ -35,7 +35,7 @@ class OpenAPSAMAPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -54,7 +54,7 @@ class OpenAPSAMAPlugin @Inject constructor(
.shortName(R.string.oaps_shortname) .shortName(R.string.oaps_shortname)
.preferencesId(R.xml.pref_openapsama) .preferencesId(R.xml.pref_openapsama)
.description(R.string.description_ama), .description(R.string.description_ama),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), APS { ), APS {
// last values // last values
@ -86,18 +86,18 @@ class OpenAPSAMAPlugin @Inject constructor(
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (profile == null) { if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset))
return return
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return return
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return return
} }
val inputConstraints = Constraint(0.0) // fake. only for collecting all results val inputConstraints = Constraint(0.0) // fake. only for collecting all results
@ -114,9 +114,9 @@ class OpenAPSAMAPlugin @Inject constructor(
val maxIob = constraintChecker.getMaxIOBAllowed().also { maxIOBAllowedConstraint -> val maxIob = constraintChecker.getMaxIOBAllowed().also { maxIOBAllowedConstraint ->
inputConstraints.copyReasons(maxIOBAllowedConstraint) inputConstraints.copyReasons(maxIOBAllowedConstraint)
}.value() }.value()
var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MIN_BG[1].toDouble()) var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1])
var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MAX_BG[1].toDouble()) var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1])
var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble()) var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1])
var isTempTarget = false var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
@ -134,7 +134,7 @@ class OpenAPSAMAPlugin @Inject constructor(
if (constraintChecker.isAutosensModeEnabled().value()) { if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) { if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return return
} }
lastAutosensResult = autosensData.autosensResult lastAutosensResult = autosensData.autosensResult

View file

@ -36,7 +36,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin

View file

@ -32,7 +32,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@ -101,7 +101,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterSMBJS.currentTempParam) binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
try { try {
val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam) val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam)
binding.iobdata.text = TextUtils.concat(resourceHelper.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0))) binding.iobdata.text = TextUtils.concat(rh.gs(R.string.array_of_elements, iobArray.length()) + "\n", jsonFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e) aapsLogger.error(LTag.APS, "Unhandled exception", e)
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")

View file

@ -35,7 +35,7 @@ class OpenAPSSMBPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -55,7 +55,7 @@ class OpenAPSSMBPlugin @Inject constructor(
.preferencesId(R.xml.pref_openapssmb) .preferencesId(R.xml.pref_openapssmb)
.description(R.string.description_smb) .description(R.string.description_smb)
.setDefault(), .setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), APS, Constraints { ), APS, Constraints {
// last values // last values
@ -81,9 +81,9 @@ class OpenAPSSMBPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) super.preprocessPreferences(preferenceFragment)
val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false) val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false)
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled
} }
override fun invoke(initiator: String, tempBasalFallback: Boolean) { override fun invoke(initiator: String, tempBasalFallback: Boolean) {
@ -93,18 +93,18 @@ class OpenAPSSMBPlugin @Inject constructor(
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (profile == null) { if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset))
return return
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return return
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return return
} }
@ -119,9 +119,9 @@ class OpenAPSSMBPlugin @Inject constructor(
inputConstraints.copyReasons(maxIOBAllowedConstraint) inputConstraints.copyReasons(maxIOBAllowedConstraint)
}.value() }.value()
var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MIN_BG[1].toDouble()) var minBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetLowMgdl(), 0.1), R.string.profile_low_target, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1])
var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MAX_BG[1].toDouble()) var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.getTargetHighMgdl(), 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1])
var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble()) var targetBg = hardLimits.verifyHardLimits(profile.getTargetMgdl(), R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1])
var isTempTarget = false var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
@ -139,7 +139,7 @@ class OpenAPSSMBPlugin @Inject constructor(
if (constraintChecker.isAutosensModeEnabled().value()) { if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) { if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return return
} }
lastAutosensResult = autosensData.autosensResult lastAutosensResult = autosensData.autosensResult

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.configBuilder package info.nightscout.androidaps.plugins.configBuilder
import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
@ -32,13 +33,14 @@ class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var ctx: Context
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList<PluginViewHolder>() private val pluginViewHolders = ArrayList<PluginViewHolder>()
@ -125,8 +127,8 @@ class ConfigBuilderFragment : DaggerFragment() {
if (plugins.isEmpty()) return if (plugins.isEmpty()) return
@Suppress("InflateParams") @Suppress("InflateParams")
val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout
(parent.findViewById<View>(R.id.category_title) as TextView).text = resourceHelper.gs(title) (parent.findViewById<View>(R.id.category_title) as TextView).text = rh.gs(title)
(parent.findViewById<View>(R.id.category_description) as TextView).text = resourceHelper.gs(description) (parent.findViewById<View>(R.id.category_description) as TextView).text = rh.gs(description)
val pluginContainer = parent.findViewById<LinearLayout>(R.id.category_plugins) val pluginContainer = parent.findViewById<LinearLayout>(R.id.category_plugins)
for (plugin in plugins) { for (plugin in plugins) {
val pluginViewHolder = PluginViewHolder(this, pluginType, plugin) val pluginViewHolder = PluginViewHolder(this, pluginType, plugin)
@ -170,7 +172,7 @@ class ConfigBuilderFragment : DaggerFragment() {
pluginPreferences.setOnClickListener { pluginPreferences.setOnClickListener {
fragment.activity?.let { activity -> fragment.activity?.let { activity ->
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, {
val i = Intent(fragment.context, PreferencesActivity::class.java) val i = Intent(ctx, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId) i.putExtra("id", plugin.preferencesId)
fragment.startActivity(i) fragment.startActivity(i)
}, null) }, null)

View file

@ -26,7 +26,7 @@ import javax.inject.Singleton
class ConfigBuilderPlugin @Inject constructor( class ConfigBuilderPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -42,7 +42,7 @@ class ConfigBuilderPlugin @Inject constructor(
.pluginName(R.string.configbuilder) .pluginName(R.string.configbuilder)
.shortName(R.string.configbuilder_shortname) .shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder), .description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), ConfigBuilder { ), ConfigBuilder {
override fun initialize() { override fun initialize() {
@ -134,7 +134,7 @@ class ConfigBuilderPlugin @Inject constructor(
// Ask when switching to physical pump plugin // Ask when switching to physical pump plugin
fun switchAllowed(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) { fun switchAllowed(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != resourceHelper.gs(R.string.virtualpump)) if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != rh.gs(R.string.virtualpump))
confirmPumpPluginActivation(changedPlugin, newState, activity, type) confirmPumpPluginActivation(changedPlugin, newState, activity, type)
else if (changedPlugin.getType() == PluginType.PUMP) { else if (changedPlugin.getType() == PluginType.PUMP) {
performPluginSwitch(changedPlugin, newState, type) performPluginSwitch(changedPlugin, newState, type)
@ -148,12 +148,12 @@ class ConfigBuilderPlugin @Inject constructor(
performPluginSwitch(changedPlugin, newState, type) performPluginSwitch(changedPlugin, newState, type)
pumpSync.connectNewPump() pumpSync.connectNewPump()
} else { } else {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.allow_hardware_pump_text), { OKDialog.showConfirmation(activity, rh.gs(R.string.allow_hardware_pump_text), {
performPluginSwitch(changedPlugin, newState, type) performPluginSwitch(changedPlugin, newState, type)
pumpSync.connectNewPump() pumpSync.connectNewPump()
sp.putBoolean("allow_hardware_pump", true) sp.putBoolean("allow_hardware_pump", true)
uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName)))
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!") aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!")
}, { }, {
rxBus.send(EventConfigBuilderUpdateGui()) rxBus.send(EventConfigBuilderUpdateGui())
@ -164,12 +164,12 @@ class ConfigBuilderPlugin @Inject constructor(
override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) { override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
if(enabled && !changedPlugin.isEnabled()) { if(enabled && !changedPlugin.isEnabled()) {
uel.log(Action.PLUGIN_ENABLED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), uel.log(Action.PLUGIN_ENABLED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName)))
} }
else if(!enabled) { else if(!enabled) {
uel.log(Action.PLUGIN_DISABLED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), uel.log(Action.PLUGIN_DISABLED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName)))
} }
changedPlugin.setPluginEnabled(type, enabled) changedPlugin.setPluginEnabled(type, enabled)
changedPlugin.setFragmentVisible(type, enabled) changedPlugin.setFragmentVisible(type, enabled)

View file

@ -33,7 +33,7 @@ class ProfileFunctionImplementation @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val repository: AppRepository, private val repository: AppRepository,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -78,13 +78,13 @@ class ProfileFunctionImplementation @Inject constructor(
getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true) getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true)
fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String { fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String {
var profileName = resourceHelper.gs(R.string.noprofileselected) var profileName = rh.gs(R.string.noprofileset)
val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet() val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet()
if (profileSwitch is ValueWrapper.Existing) { if (profileSwitch is ValueWrapper.Existing) {
profileName = if (customized) profileSwitch.value.originalCustomizedName else profileSwitch.value.originalProfileName profileName = if (customized) profileSwitch.value.originalCustomizedName else profileSwitch.value.originalProfileName
if (showRemainingTime && profileSwitch.value.originalDuration != 0L) { if (showRemainingTime && profileSwitch.value.originalDuration != 0L) {
profileName += dateUtil.untilString(profileSwitch.value.originalEnd, resourceHelper) profileName += dateUtil.untilString(profileSwitch.value.originalEnd, rh)
} }
} }
return profileName return profileName
@ -141,9 +141,8 @@ class ProfileFunctionImplementation @Inject constructor(
if (sp.getString(R.string.key_units, Constants.MGDL) == Constants.MGDL) GlucoseUnit.MGDL if (sp.getString(R.string.key_units, Constants.MGDL) == Constants.MGDL) GlucoseUnit.MGDL
else GlucoseUnit.MMOL else GlucoseUnit.MMOL
override fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch { override fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch? {
val pureProfile = profileStore.getSpecificProfile(profileName) val pureProfile = profileStore.getSpecificProfile(profileName) ?: return null
?: throw InvalidParameterSpecException(profileName)
return ProfileSwitch( return ProfileSwitch(
timestamp = timestamp, timestamp = timestamp,
basalBlocks = pureProfile.basalBlocks, basalBlocks = pureProfile.basalBlocks,
@ -161,8 +160,8 @@ class ProfileFunctionImplementation @Inject constructor(
) )
} }
override fun createProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long) { override fun createProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): Boolean {
val ps = buildProfileSwitch(profileStore, profileName, durationInMinutes, percentage, timeShiftInHours, timestamp) val ps = buildProfileSwitch(profileStore, profileName, durationInMinutes, percentage, timeShiftInHours, timestamp) ?: return false
disposable += repository.runTransactionForResult(InsertOrUpdateProfileSwitch(ps)) disposable += repository.runTransactionForResult(InsertOrUpdateProfileSwitch(ps))
.subscribe({ result -> .subscribe({ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted ProfileSwitch $it") } result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted ProfileSwitch $it") }
@ -170,17 +169,18 @@ class ProfileFunctionImplementation @Inject constructor(
}, { }, {
aapsLogger.error(LTag.DATABASE, "Error while saving ProfileSwitch", it) aapsLogger.error(LTag.DATABASE, "Error while saving ProfileSwitch", it)
}) })
return true
} }
override fun createProfileSwitch(durationInMinutes: Int, percentage: Int, timeShiftInHours: Int): Boolean { override fun createProfileSwitch(durationInMinutes: Int, percentage: Int, timeShiftInHours: Int): Boolean {
val profile = repository.getPermanentProfileSwitch(dateUtil.now()) ?: return false val profile = repository.getPermanentProfileSwitch(dateUtil.now()) ?: return false
val profileStore = activePlugin.activeProfileSource.profile ?: return false val profileStore = activePlugin.activeProfileSource.profile ?: return false
val ps = buildProfileSwitch(profileStore, profile.profileName, durationInMinutes, percentage, 0, dateUtil.now()) val ps = buildProfileSwitch(profileStore, profile.profileName, durationInMinutes, percentage, 0, dateUtil.now()) ?: return false
val validity = ProfileSealed.PS(ps).isValid( val validity = ProfileSealed.PS(ps).isValid(
resourceHelper.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch), rh.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch),
activePlugin.activePump, activePlugin.activePump,
config, config,
resourceHelper, rh,
rxBus, rxBus,
hardLimits, hardLimits,
false false

View file

@ -0,0 +1,102 @@
package info.nightscout.androidaps.plugins.constraints.bgQualityCheck
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventBucketedDataCreated
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.abs
@Singleton
class BgQualityCheckPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
rh: ResourceHelper,
private val rxBus: RxBus,
private val iobCobCalculator: IobCobCalculator,
private val aapsSchedulers: AapsSchedulers,
private val fabricPrivacy: FabricPrivacy
) : PluginBase(
PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.neverVisible(true)
.alwaysEnabled(true)
.showInList(false)
.pluginName(R.string.dst_plugin_name),
aapsLogger, rh, injector
), Constraints {
private var disposable: CompositeDisposable = CompositeDisposable()
enum class State {
UNKNOWN,
FIVE_MIN_DATA,
RECALCULATED,
DOUBLED
}
override fun onStart() {
super.onStart()
disposable += rxBus
.toObservable(EventBucketedDataCreated::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ processBgData() }, fabricPrivacy::logException)
}
override fun onStop() {
super.onStop()
disposable.clear()
}
var state: State = State.UNKNOWN
var message: String = ""
// Return false if BG values are doubled
@Suppress("ReplaceGetOrSet")
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (state == State.DOUBLED)
value.set(aapsLogger, false, "Doubled values in BGSource", this)
return value
}
fun processBgData() {
val readings = iobCobCalculator.ads.getBgReadingsDataTableCopy()
for (i in readings.indices)
if (i < readings.size - 2)
if (abs(readings[i].timestamp - readings[i + 1].timestamp) <= T.secs(20).msecs()) {
state = State.DOUBLED
aapsLogger.debug(LTag.CORE, "BG similar. Turning on red state.\n${readings[i]}\n${readings[i+1]}")
message = rh.gs(R.string.bg_too_close, readings[i].toString(), readings[i+1].toString())
return
}
if (iobCobCalculator.ads.lastUsed5minCalculation == true) {
state = State.FIVE_MIN_DATA
message = "Data is clean"
} else if (iobCobCalculator.ads.lastUsed5minCalculation == false) {
state = State.RECALCULATED
message = rh.gs(R.string.recalculated_data_used)
} else {
state = State.UNKNOWN
message = ""
}
}
fun icon(): Int =
when (state) {
State.UNKNOWN -> 0
State.FIVE_MIN_DATA -> 0
State.RECALCULATED -> R.drawable.ic_baseline_warning_24_yellow
State.DOUBLED -> R.drawable.ic_baseline_warning_24_red
}
}

View file

@ -21,18 +21,18 @@ import javax.inject.Singleton
class DstHelperPlugin @Inject constructor( class DstHelperPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private var rxBus: RxBus, private val rxBus: RxBus,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private var sp: SP, private val sp: SP,
private var activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private var loopPlugin: LoopPlugin private val loopPlugin: LoopPlugin
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
.neverVisible(true) .neverVisible(true)
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.dst_plugin_name), .pluginName(R.string.dst_plugin_name),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
companion object { companion object {
@ -41,6 +41,7 @@ class DstHelperPlugin @Inject constructor(
} }
//Return false if time to DST change happened in the last 3 hours. //Return false if time to DST change happened in the last 3 hours.
@Suppress("ReplaceGetOrSet")
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (pump.canHandleDST()) { if (pump.canHandleDST()) {
@ -51,10 +52,10 @@ class DstHelperPlugin @Inject constructor(
if (willBeDST(cal)) { if (willBeDST(cal)) {
val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L) val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val notification = NotificationWithAction(injector, Notification.DST_IN_24H, resourceHelper.gs(R.string.dst_in_24h_warning), Notification.LOW) val notification = NotificationWithAction(injector, Notification.DST_IN_24H, rh.gs(R.string.dst_in_24h_warning), Notification.LOW)
notification.action(R.string.snooze, Runnable { notification.action(R.string.snooze) {
sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs()) sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs())
}) }
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
} }
@ -66,10 +67,10 @@ class DstHelperPlugin @Inject constructor(
if (!loopPlugin.isSuspended) { if (!loopPlugin.isSuspended) {
val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L) val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, resourceHelper.gs(R.string.dst_loop_disabled_warning), Notification.LOW) val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, rh.gs(R.string.dst_loop_disabled_warning), Notification.LOW)
notification.action(R.string.snooze, Runnable { notification.action(R.string.snooze) {
sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs()) sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs())
}) }
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
} else { } else {

View file

@ -50,7 +50,7 @@ class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var objectivesPlugin: ObjectivesPlugin
@Inject lateinit var receiverStatusStore: ReceiverStatusStore @Inject lateinit var receiverStatusStore: ReceiverStatusStore
@ -155,15 +155,15 @@ class ObjectivesFragment : DaggerFragment() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) { override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val objective = objectivesPlugin.objectives[position] val objective = objectivesPlugin.objectives[position]
holder.binding.title.text = resourceHelper.gs(R.string.nth_objective, position + 1) holder.binding.title.text = rh.gs(R.string.nth_objective, position + 1)
if (objective.objective != 0) { if (objective.objective != 0) {
holder.binding.objective.visibility = View.VISIBLE holder.binding.objective.visibility = View.VISIBLE
holder.binding.objective.text = resourceHelper.gs(objective.objective) holder.binding.objective.text = rh.gs(objective.objective)
} else } else
holder.binding.objective.visibility = View.GONE holder.binding.objective.visibility = View.GONE
if (objective.gate != 0) { if (objective.gate != 0) {
holder.binding.gate.visibility = View.VISIBLE holder.binding.gate.visibility = View.VISIBLE
holder.binding.gate.text = resourceHelper.gs(objective.gate) holder.binding.gate.text = rh.gs(objective.gate)
} else } else
holder.binding.gate.visibility = View.GONE holder.binding.gate.visibility = View.GONE
if (!objective.isStarted) { if (!objective.isStarted) {
@ -199,7 +199,7 @@ class ObjectivesFragment : DaggerFragment() {
if (task.shouldBeIgnored()) continue if (task.shouldBeIgnored()) continue
// name // name
val name = TextView(holder.binding.progress.context) val name = TextView(holder.binding.progress.context)
name.text = "${resourceHelper.gs(task.task)}:" name.text = "${rh.gs(task.task)}:"
name.setTextColor(-0x1) name.setTextColor(-0x1)
holder.binding.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) holder.binding.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
// hint // hint
@ -232,7 +232,7 @@ class ObjectivesFragment : DaggerFragment() {
holder.binding.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) holder.binding.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2)
} }
} }
holder.binding.accomplished.text = resourceHelper.gs(R.string.accomplished, dateUtil.dateAndTimeString(objective.accomplishedOn)) holder.binding.accomplished.text = rh.gs(R.string.accomplished, dateUtil.dateAndTimeString(objective.accomplishedOn))
holder.binding.accomplished.setTextColor(-0x3e3e3f) holder.binding.accomplished.setTextColor(-0x3e3e3f)
holder.binding.verify.setOnClickListener { holder.binding.verify.setOnClickListener {
receiverStatusStore.updateNetworkStatus() receiverStatusStore.updateNetworkStatus()
@ -246,27 +246,27 @@ class ObjectivesFragment : DaggerFragment() {
// move out of UI thread // move out of UI thread
Thread { Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(rh.gs(R.string.timedetection), 0))
sntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)
if (!networkConnected) { if (!networkConnected) {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99))
} else if (success) { } else if (success) {
if (objective.isCompleted(time)) { if (objective.isCompleted(time)) {
objective.accomplishedOn = time objective.accomplishedOn = time
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.success), 100)) rxBus.send(EventNtpStatus(rh.gs(R.string.success), 100))
SystemClock.sleep(1000) SystemClock.sleep(1000)
rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false)) rxBus.send(EventSWUpdate(false))
SystemClock.sleep(100) SystemClock.sleep(100)
scrollToCurrentObjective() scrollToCurrentObjective()
} else { } else {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.requirementnotmet), 99)) rxBus.send(EventNtpStatus(rh.gs(R.string.requirementnotmet), 99))
} }
} else { } else {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99))
} }
} }
}, receiverStatusStore.isConnected) }, receiverStatusStore.isConnected)
@ -285,23 +285,23 @@ class ObjectivesFragment : DaggerFragment() {
// move out of UI thread // move out of UI thread
Thread { Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(rh.gs(R.string.timedetection), 0))
sntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)
if (!networkConnected) { if (!networkConnected) {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99))
} else if (success) { } else if (success) {
objective.startedOn = time objective.startedOn = time
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.success), 100)) rxBus.send(EventNtpStatus(rh.gs(R.string.success), 100))
SystemClock.sleep(1000) SystemClock.sleep(1000)
rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false)) rxBus.send(EventSWUpdate(false))
SystemClock.sleep(100) SystemClock.sleep(100)
scrollToCurrentObjective() scrollToCurrentObjective()
} else { } else {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99))
} }
} }
}, receiverStatusStore.isConnected) }, receiverStatusStore.isConnected)
@ -309,7 +309,7 @@ class ObjectivesFragment : DaggerFragment() {
} }
holder.binding.unstart.setOnClickListener { holder.binding.unstart.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.doyouwantresetstart), Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.objectives), rh.gs(R.string.doyouwantresetstart), Runnable {
uel.log(Action.OBJECTIVE_UNSTARTED, Sources.Objectives, uel.log(Action.OBJECTIVE_UNSTARTED, Sources.Objectives,
ValueWithUnit.SimpleInt(position + 1)) ValueWithUnit.SimpleInt(position + 1))
objective.startedOn = 0 objective.startedOn = 0
@ -329,7 +329,7 @@ class ObjectivesFragment : DaggerFragment() {
// generate random request code if none exists // generate random request code if none exists
val request = sp.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt())) val request = sp.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt()))
sp.putString(R.string.key_objectives_request_code, request) sp.putString(R.string.key_objectives_request_code, request)
holder.binding.requestcode.text = resourceHelper.gs(R.string.requestcode, request) holder.binding.requestcode.text = rh.gs(R.string.requestcode, request)
holder.binding.requestcode.visibility = View.VISIBLE holder.binding.requestcode.visibility = View.VISIBLE
holder.binding.enterbutton.visibility = View.VISIBLE holder.binding.enterbutton.visibility = View.VISIBLE
holder.binding.input.visibility = View.VISIBLE holder.binding.input.visibility = View.VISIBLE

View file

@ -24,7 +24,7 @@ import javax.inject.Singleton
class ObjectivesPlugin @Inject constructor( class ObjectivesPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val sp: SP, private val sp: SP,
config: Config, config: Config,
@ -39,7 +39,7 @@ class ObjectivesPlugin @Inject constructor(
.pluginName(R.string.objectives) .pluginName(R.string.objectives)
.shortName(R.string.objectives_shortname) .shortName(R.string.objectives_shortname)
.description(R.string.description_objectives), .description(R.string.description_objectives),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
var objectives: MutableList<Objective> = ArrayList() var objectives: MutableList<Objective> = ArrayList()
@ -119,10 +119,10 @@ class ObjectivesPlugin @Inject constructor(
sp.putLong("Objectives_" + "auto" + "_started", dateUtil.now()) sp.putLong("Objectives_" + "auto" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "auto" + "_accomplished", dateUtil.now()) sp.putLong("Objectives_" + "auto" + "_accomplished", dateUtil.now())
setupObjectives() setupObjectives()
OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeaccepted)) OKDialog.show(activity, rh.gs(R.string.objectives), rh.gs(R.string.codeaccepted))
uel.log(Action.OBJECTIVES_SKIPPED, Sources.Objectives) uel.log(Action.OBJECTIVES_SKIPPED, Sources.Objectives)
} else { } else {
OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeinvalid)) OKDialog.show(activity, rh.gs(R.string.objectives), rh.gs(R.string.codeinvalid))
} }
} }
@ -139,43 +139,43 @@ class ObjectivesPlugin @Inject constructor(
*/ */
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[FIRST_OBJECTIVE].isStarted) if (!objectives[FIRST_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this)
return value return value
} }
override fun isLgsAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isLgsAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[MAXBASAL_OBJECTIVE].isStarted) if (!objectives[MAXBASAL_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, MAXBASAL_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, MAXBASAL_OBJECTIVE + 1), this)
return value return value
} }
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted) if (!objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return value return value
} }
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AUTOSENS_OBJECTIVE].isStarted) if (!objectives[AUTOSENS_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this)
return value return value
} }
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[SMB_OBJECTIVE].isStarted) if (!objectives[SMB_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this)
return value return value
} }
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> { override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
if (objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted && !objectives[MAXIOB_ZERO_CL_OBJECTIVE].isAccomplished) if (objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted && !objectives[MAXIOB_ZERO_CL_OBJECTIVE].isAccomplished)
maxIob.set(aapsLogger, 0.0, resourceHelper.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) maxIob.set(aapsLogger, 0.0, rh.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return maxIob return maxIob
} }
override fun isAutomationEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isAutomationEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AUTO_OBJECTIVE].isStarted) if (!objectives[AUTO_OBJECTIVE].isStarted)
value.set(aapsLogger, false, resourceHelper.gs(R.string.objectivenotstarted, AUTO_OBJECTIVE + 1), this) value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, AUTO_OBJECTIVE + 1), this)
return value return value
} }
} }

View file

@ -21,7 +21,7 @@ import javax.inject.Inject
class ObjectivesExamDialog : DaggerDialogFragment() { class ObjectivesExamDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
companion object { companion object {
@ -96,7 +96,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() {
context?.let { binding.examHints.addView(h.generate(it)) } context?.let { binding.examHints.addView(h.generate(it)) }
} }
// Disabled to // Disabled to
binding.examDisabledto.text = resourceHelper.gs(R.string.answerdisabledto, dateUtil.timeString(task.disabledTo)) binding.examDisabledto.text = rh.gs(R.string.answerdisabledto, dateUtil.timeString(task.disabledTo))
binding.examDisabledto.visibility = if (task.isEnabledAnswer()) View.GONE else View.VISIBLE binding.examDisabledto.visibility = if (task.isEnabledAnswer()) View.GONE else View.VISIBLE
// Buttons // Buttons
binding.examVerify.isEnabled = !task.answered && task.isEnabledAnswer() binding.examVerify.isEnabled = !task.answered && task.isEnabledAnswer()

View file

@ -20,7 +20,7 @@ import kotlin.math.floor
abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRes objective: Int, @StringRes gate: Int) { abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRes objective: Int, @StringRes gate: Int) {
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
private val spName: String private val spName: String
@ -89,7 +89,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
open fun isCompleted(trueTime: Long): Boolean = isCompleted() open fun isCompleted(trueTime: Long): Boolean = isCompleted()
open val progress: String open val progress: String
get() = resourceHelper.gs(if (isCompleted()) R.string.completed_well_done else R.string.not_completed_yet) get() = rh.gs(if (isCompleted()) R.string.completed_well_done else R.string.not_completed_yet)
fun hint(hint: Hint): Task { fun hint(hint: Hint): Task {
hints.add(hint) hints.add(hint)
@ -117,9 +117,9 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
val hours = floor(duration.toDouble() / T.hours(1).msecs()).toInt() val hours = floor(duration.toDouble() / T.hours(1).msecs()).toInt()
val minutes = floor(duration.toDouble() / T.mins(1).msecs()).toInt() val minutes = floor(duration.toDouble() / T.mins(1).msecs()).toInt()
return when { return when {
days > 0 -> resourceHelper.gq(R.plurals.days, days, days) days > 0 -> rh.gq(R.plurals.days, days, days)
hours > 0 -> resourceHelper.gq(R.plurals.hours, hours, hours) hours > 0 -> rh.gq(R.plurals.hours, hours, hours)
else -> resourceHelper.gq(R.plurals.minutes, minutes, minutes) else -> rh.gq(R.plurals.minutes, minutes, minutes)
} }
} }
} }

View file

@ -39,7 +39,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R
} }
override fun shouldBeIgnored(): Boolean { override fun shouldBeIgnored(): Boolean {
return !virtualPumpPlugin.isEnabled(PluginType.PUMP) return !virtualPumpPlugin.isEnabled()
} }
}) })
tasks.add(object : Task(this, R.string.objectives_pumpstatusavailableinns) { tasks.add(object : Task(this, R.string.objectives_pumpstatusavailableinns) {
@ -54,13 +54,13 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R
}) })
tasks.add(object : Task(this, R.string.loopenabled) { tasks.add(object : Task(this, R.string.loopenabled) {
override fun isCompleted(): Boolean { override fun isCompleted(): Boolean {
return loopPlugin.isEnabled(PluginType.LOOP) return loopPlugin.isEnabled()
} }
}) })
tasks.add(object : Task(this, R.string.apsselected) { tasks.add(object : Task(this, R.string.apsselected) {
override fun isCompleted(): Boolean { override fun isCompleted(): Boolean {
val usedAPS = activePlugin.activeAPS val usedAPS = activePlugin.activeAPS
return (usedAPS as PluginBase).isEnabled(PluginType.APS) return (usedAPS as PluginBase).isEnabled()
} }
}) })
tasks.add(object : Task(this, R.string.activate_profile) { tasks.add(object : Task(this, R.string.activate_profile) {

View file

@ -33,7 +33,7 @@ class Objective1 @Inject constructor(injector: HasAndroidInjector) : Objective(i
}.hint(Hint(R.string.usetemptarget_hint))) }.hint(Hint(R.string.usetemptarget_hint)))
tasks.add(object : Task(this, R.string.objectives_useactions) { tasks.add(object : Task(this, R.string.objectives_useactions) {
override fun isCompleted(): Boolean { override fun isCompleted(): Boolean {
return sp.getBoolean(R.string.key_objectiveuseactions, false) && actionsPlugin.isEnabled(PluginType.GENERAL) && actionsPlugin.isFragmentVisible() return sp.getBoolean(R.string.key_objectiveuseactions, false) && actionsPlugin.isEnabled() && actionsPlugin.isFragmentVisible()
} }
}.hint(Hint(R.string.useaction_hint))) }.hint(Hint(R.string.useaction_hint)))
tasks.add(object : Task(this, R.string.objectives_useloop) { tasks.add(object : Task(this, R.string.objectives_useloop) {

View file

@ -22,7 +22,7 @@ class Objective3 @Inject constructor(injector: HasAndroidInjector) : Objective(i
} }
override val progress: String override val progress: String
get() = if (sp.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED) resourceHelper.gs(R.string.completed_well_done) else sp.getInt(R.string.key_ObjectivesmanualEnacts, 0).toString() + " / " + MANUAL_ENACTS_NEEDED get() = if (sp.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED) rh.gs(R.string.completed_well_done) else sp.getInt(R.string.key_ObjectivesmanualEnacts, 0).toString() + " / " + MANUAL_ENACTS_NEEDED
}) })
} }

View file

@ -18,7 +18,7 @@ import javax.inject.Singleton
class PhoneCheckerPlugin @Inject constructor( class PhoneCheckerPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val context: Context private val context: Context
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
@ -26,7 +26,7 @@ class PhoneCheckerPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.phonechecker), .pluginName(R.string.phonechecker),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
var phoneRooted: Boolean = false var phoneRooted: Boolean = false

View file

@ -30,7 +30,7 @@ import kotlin.math.floor
class SafetyPlugin @Inject constructor( class SafetyPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
@ -50,86 +50,86 @@ class SafetyPlugin @Inject constructor(
.showInList(false) .showInList(false)
.pluginName(R.string.safety) .pluginName(R.string.safety)
.preferencesId(R.xml.pref_safety), .preferencesId(R.xml.pref_safety),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints, Safety { ), Constraints, Safety {
/** /**
* Constraints interface * Constraints interface
*/ */
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!activePlugin.activePump.pumpDescription.isTempBasalCapable) value[aapsLogger, false, resourceHelper.gs(R.string.pumpisnottempbasalcapable)] = this if (!activePlugin.activePump.pumpDescription.isTempBasalCapable) value[aapsLogger, false, rh.gs(R.string.pumpisnottempbasalcapable)] = this
return value return value
} }
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val mode = sp.getString(R.string.key_aps_mode, "open") val mode = sp.getString(R.string.key_aps_mode, "open")
if (mode == "open") value[aapsLogger, false, resourceHelper.gs(R.string.closedmodedisabledinpreferences)] = this if (mode == "open") value[aapsLogger, false, rh.gs(R.string.closedmodedisabledinpreferences)] = this
if (!buildHelper.isEngineeringModeOrRelease()) { if (!buildHelper.isEngineeringModeOrRelease()) {
if (value.value()) { if (value.value()) {
val n = Notification(Notification.TOAST_ALARM, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL) val n = Notification(Notification.TOAST_ALARM, rh.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL)
rxBus.send(EventNewNotification(n)) rxBus.send(EventNewNotification(n))
} }
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this value[aapsLogger, false, rh.gs(R.string.closed_loop_disabled_on_dev_branch)] = this
} }
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) {
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_with_eb)] = this value[aapsLogger, false, rh.gs(R.string.closed_loop_disabled_with_eb)] = this
} }
return value return value
} }
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false) val enabled = sp.getBoolean(R.string.key_openapsama_useautosens, false)
if (!enabled) value[aapsLogger, false, resourceHelper.gs(R.string.autosensdisabledinpreferences)] = this if (!enabled) value[aapsLogger, false, rh.gs(R.string.autosensdisabledinpreferences)] = this
return value return value
} }
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val enabled = sp.getBoolean(R.string.key_use_smb, false) val enabled = sp.getBoolean(R.string.key_use_smb, false)
if (!enabled) value[aapsLogger, false, resourceHelper.gs(R.string.smbdisabledinpreferences)] = this if (!enabled) value[aapsLogger, false, rh.gs(R.string.smbdisabledinpreferences)] = this
val closedLoop = constraintChecker.isClosedLoopAllowed() val closedLoop = constraintChecker.isClosedLoopAllowed()
if (!closedLoop.value()) value[aapsLogger, false, resourceHelper.gs(R.string.smbnotallowedinopenloopmode)] = this if (!closedLoop.value()) value[aapsLogger, false, rh.gs(R.string.smbnotallowedinopenloopmode)] = this
return value return value
} }
override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isUAMEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val enabled = sp.getBoolean(R.string.key_use_uam, false) val enabled = sp.getBoolean(R.string.key_use_uam, false)
if (!enabled) value[aapsLogger, false, resourceHelper.gs(R.string.uamdisabledinpreferences)] = this if (!enabled) value[aapsLogger, false, rh.gs(R.string.uamdisabledinpreferences)] = this
val oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY) val oref1Enabled = sensitivityOref1Plugin.isEnabled()
if (!oref1Enabled) value[aapsLogger, false, resourceHelper.gs(R.string.uamdisabledoref1notselected)] = this if (!oref1Enabled) value[aapsLogger, false, rh.gs(R.string.uamdisabledoref1notselected)] = this
return value return value
} }
override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> { override fun isAdvancedFilteringEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
val bgSource = activePlugin.activeBgSource val bgSource = activePlugin.activeBgSource
if (!bgSource.advancedFilteringSupported()) value[aapsLogger, false, resourceHelper.gs(R.string.smbalwaysdisabled)] = this if (!bgSource.advancedFilteringSupported()) value[aapsLogger, false, rh.gs(R.string.smbalwaysdisabled)] = this
return value return value
} }
override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> { override fun applyBasalConstraints(absoluteRate: Constraint<Double>, profile: Profile): Constraint<Double> {
absoluteRate.setIfGreater(aapsLogger, 0.0, String.format(resourceHelper.gs(R.string.limitingbasalratio), 0.0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) absoluteRate.setIfGreater(aapsLogger, 0.0, String.format(rh.gs(R.string.limitingbasalratio), 0.0, rh.gs(R.string.itmustbepositivevalue)), this)
if (config.APS) { if (config.APS) {
var maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1.0) var maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1.0)
if (maxBasal < profile.getMaxDailyBasal()) { if (maxBasal < profile.getMaxDailyBasal()) {
maxBasal = profile.getMaxDailyBasal() maxBasal = profile.getMaxDailyBasal()
absoluteRate.addReason(resourceHelper.gs(R.string.increasingmaxbasal), this) absoluteRate.addReason(rh.gs(R.string.increasingmaxbasal), this)
} }
absoluteRate.setIfSmaller(aapsLogger, maxBasal, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxBasal, resourceHelper.gs(R.string.maxvalueinpreferences)), this) absoluteRate.setIfSmaller(aapsLogger, maxBasal, String.format(rh.gs(R.string.limitingbasalratio), maxBasal, rh.gs(R.string.maxvalueinpreferences)), this)
// Check percentRate but absolute rate too, because we know real current basal in pump // Check percentRate but absolute rate too, because we know real current basal in pump
val maxBasalMultiplier = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0) val maxBasalMultiplier = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)
val maxFromBasalMultiplier = floor(maxBasalMultiplier * profile.getBasal() * 100) / 100 val maxFromBasalMultiplier = floor(maxBasalMultiplier * profile.getBasal() * 100) / 100
absoluteRate.setIfSmaller(aapsLogger, maxFromBasalMultiplier, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromBasalMultiplier, resourceHelper.gs(R.string.maxbasalmultiplier)), this) absoluteRate.setIfSmaller(aapsLogger, maxFromBasalMultiplier, String.format(rh.gs(R.string.limitingbasalratio), maxFromBasalMultiplier, rh.gs(R.string.maxbasalmultiplier)), this)
val maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0) val maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0)
val maxFromDaily = floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100 val maxFromDaily = floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100
absoluteRate.setIfSmaller(aapsLogger, maxFromDaily, String.format(resourceHelper.gs(R.string.limitingbasalratio), maxFromDaily, resourceHelper.gs(R.string.maxdailybasalmultiplier)), this) absoluteRate.setIfSmaller(aapsLogger, maxFromDaily, String.format(rh.gs(R.string.limitingbasalratio), maxFromDaily, rh.gs(R.string.maxdailybasalmultiplier)), this)
} }
absoluteRate.setIfSmaller(aapsLogger, hardLimits.maxBasal(), String.format(resourceHelper.gs(R.string.limitingbasalratio), hardLimits.maxBasal(), resourceHelper.gs(R.string.hardlimit)), this) absoluteRate.setIfSmaller(aapsLogger, hardLimits.maxBasal(), String.format(rh.gs(R.string.limitingbasalratio), hardLimits.maxBasal(), rh.gs(R.string.hardlimit)), this)
val pump = activePlugin.activePump val pump = activePlugin.activePump
// check for pump max // check for pump max
if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0
absoluteRate.setIfSmaller(aapsLogger, pumpLimit, String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this) absoluteRate.setIfSmaller(aapsLogger, pumpLimit, String.format(rh.gs(R.string.limitingbasalratio), pumpLimit, rh.gs(R.string.pumplimit)), this)
} }
// do rounding // do rounding
@ -149,62 +149,62 @@ class SafetyPlugin @Inject constructor(
val pump = activePlugin.activePump val pump = activePlugin.activePump
var percentRateAfterConst = java.lang.Double.valueOf(absoluteConstraint.value() / currentBasal * 100).toInt() var percentRateAfterConst = java.lang.Double.valueOf(absoluteConstraint.value() / currentBasal * 100).toInt()
percentRateAfterConst = if (percentRateAfterConst < 100) Round.ceilTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() else Round.floorTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() percentRateAfterConst = if (percentRateAfterConst < 100) Round.ceilTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() else Round.floorTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt()
percentRate[aapsLogger, percentRateAfterConst, String.format(resourceHelper.gs(R.string.limitingpercentrate), percentRateAfterConst, resourceHelper.gs(R.string.pumplimit))] = this percentRate[aapsLogger, percentRateAfterConst, String.format(rh.gs(R.string.limitingpercentrate), percentRateAfterConst, rh.gs(R.string.pumplimit))] = this
if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) { if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) {
val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0
percentRate.setIfSmaller(aapsLogger, pumpLimit.toInt(), String.format(resourceHelper.gs(R.string.limitingbasalratio), pumpLimit, resourceHelper.gs(R.string.pumplimit)), this) percentRate.setIfSmaller(aapsLogger, pumpLimit.toInt(), String.format(rh.gs(R.string.limitingbasalratio), pumpLimit, rh.gs(R.string.pumplimit)), this)
} }
return percentRate return percentRate
} }
override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> { override fun applyBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
insulin.setIfGreater(aapsLogger, 0.0, String.format(resourceHelper.gs(R.string.limitingbolus), 0.0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) insulin.setIfGreater(aapsLogger, 0.0, String.format(rh.gs(R.string.limitingbolus), 0.0, rh.gs(R.string.itmustbepositivevalue)), this)
val maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0) val maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)
insulin.setIfSmaller(aapsLogger, maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this) insulin.setIfSmaller(aapsLogger, maxBolus, String.format(rh.gs(R.string.limitingbolus), maxBolus, rh.gs(R.string.maxvalueinpreferences)), this)
insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingbolus), hardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this) insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), String.format(rh.gs(R.string.limitingbolus), hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this)
val pump = activePlugin.activePump val pump = activePlugin.activePump
val rounded = pump.pumpDescription.pumpType.determineCorrectBolusSize(insulin.value()) val rounded = pump.pumpDescription.pumpType.determineCorrectBolusSize(insulin.value())
insulin.setIfDifferent(aapsLogger, rounded, resourceHelper.gs(R.string.pumplimit), this) insulin.setIfDifferent(aapsLogger, rounded, rh.gs(R.string.pumplimit), this)
return insulin return insulin
} }
override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> { override fun applyExtendedBolusConstraints(insulin: Constraint<Double>): Constraint<Double> {
insulin.setIfGreater(aapsLogger, 0.0, String.format(resourceHelper.gs(R.string.limitingextendedbolus), 0.0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) insulin.setIfGreater(aapsLogger, 0.0, String.format(rh.gs(R.string.limitingextendedbolus), 0.0, rh.gs(R.string.itmustbepositivevalue)), this)
val maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0) val maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)
insulin.setIfSmaller(aapsLogger, maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.gs(R.string.maxvalueinpreferences)), this) insulin.setIfSmaller(aapsLogger, maxBolus, String.format(rh.gs(R.string.limitingextendedbolus), maxBolus, rh.gs(R.string.maxvalueinpreferences)), this)
insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), String.format(resourceHelper.gs(R.string.limitingextendedbolus), hardLimits.maxBolus(), resourceHelper.gs(R.string.hardlimit)), this) insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), String.format(rh.gs(R.string.limitingextendedbolus), hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this)
val pump = activePlugin.activePump val pump = activePlugin.activePump
val rounded = pump.pumpDescription.pumpType.determineCorrectExtendedBolusSize(insulin.value()) val rounded = pump.pumpDescription.pumpType.determineCorrectExtendedBolusSize(insulin.value())
insulin.setIfDifferent(aapsLogger, rounded, resourceHelper.gs(R.string.pumplimit), this) insulin.setIfDifferent(aapsLogger, rounded, rh.gs(R.string.pumplimit), this)
return insulin return insulin
} }
override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> { override fun applyCarbsConstraints(carbs: Constraint<Int>): Constraint<Int> {
carbs.setIfGreater(aapsLogger, 0, String.format(resourceHelper.gs(R.string.limitingcarbs), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) carbs.setIfGreater(aapsLogger, 0, String.format(rh.gs(R.string.limitingcarbs), 0, rh.gs(R.string.itmustbepositivevalue)), this)
val maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48) val maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48)
carbs.setIfSmaller(aapsLogger, maxCarbs, String.format(resourceHelper.gs(R.string.limitingcarbs), maxCarbs, resourceHelper.gs(R.string.maxvalueinpreferences)), this) carbs.setIfSmaller(aapsLogger, maxCarbs, String.format(rh.gs(R.string.limitingcarbs), maxCarbs, rh.gs(R.string.maxvalueinpreferences)), this)
return carbs return carbs
} }
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> { override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
val apsMode = sp.getString(R.string.key_aps_mode, "open") val apsMode = sp.getString(R.string.key_aps_mode, "open")
val maxIobPref: Double = if (openAPSSMBPlugin.isEnabled()) sp.getDouble(R.string.key_openapssmb_max_iob, 3.0) else sp.getDouble(R.string.key_openapsma_max_iob, 1.5) val maxIobPref: Double = if (openAPSSMBPlugin.isEnabled()) sp.getDouble(R.string.key_openapssmb_max_iob, 3.0) else sp.getDouble(R.string.key_openapsma_max_iob, 1.5)
maxIob.setIfSmaller(aapsLogger, maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.gs(R.string.maxvalueinpreferences)), this) maxIob.setIfSmaller(aapsLogger, maxIobPref, String.format(rh.gs(R.string.limitingiob), maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this)
if (openAPSAMAPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobAMA(), String.format(resourceHelper.gs(R.string.limitingiob), hardLimits.maxIobAMA(), resourceHelper.gs(R.string.hardlimit)), this) if (openAPSAMAPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobAMA(), String.format(rh.gs(R.string.limitingiob), hardLimits.maxIobAMA(), rh.gs(R.string.hardlimit)), this)
if (openAPSSMBPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), hardLimits.maxIobSMB(), resourceHelper.gs(R.string.hardlimit)), this) if (openAPSSMBPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), String.format(rh.gs(R.string.limitingiob), hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this)
if (apsMode == "lgs") maxIob.setIfSmaller(aapsLogger, HardLimits.MAX_IOB_LGS, String.format(resourceHelper.gs(R.string.limitingiob), HardLimits.MAX_IOB_LGS, resourceHelper.gs(R.string.lowglucosesuspend)), this) if (apsMode == "lgs") maxIob.setIfSmaller(aapsLogger, HardLimits.MAX_IOB_LGS, String.format(rh.gs(R.string.limitingiob), HardLimits.MAX_IOB_LGS, rh.gs(R.string.lowglucosesuspend)), this)
return maxIob return maxIob
} }
override fun configuration(): JSONObject = override fun configuration(): JSONObject =
JSONObject() JSONObject()
.putString(R.string.key_age, sp, resourceHelper) .putString(R.string.key_age, sp, rh)
.putDouble(R.string.key_treatmentssafety_maxbolus, sp, resourceHelper) .putDouble(R.string.key_treatmentssafety_maxbolus, sp, rh)
.putInt(R.string.key_treatmentssafety_maxcarbs, sp, resourceHelper) .putInt(R.string.key_treatmentssafety_maxcarbs, sp, rh)
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
configuration.storeString(R.string.key_age, sp, resourceHelper) configuration.storeString(R.string.key_age, sp, rh)
configuration.storeDouble(R.string.key_treatmentssafety_maxbolus, sp, resourceHelper) configuration.storeDouble(R.string.key_treatmentssafety_maxbolus, sp, rh)
configuration.storeInt(R.string.key_treatmentssafety_maxcarbs, sp, resourceHelper) configuration.storeInt(R.string.key_treatmentssafety_maxcarbs, sp, rh)
} }
} }

View file

@ -35,7 +35,7 @@ import javax.inject.Singleton
class SignatureVerifierPlugin @Inject constructor( class SignatureVerifierPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val context: Context private val context: Context
@ -45,7 +45,7 @@ class SignatureVerifierPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.signature_verifier), .pluginName(R.string.signature_verifier),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
private val REVOKED_CERTS_URL = "https://raw.githubusercontent.com/nightscout/AndroidAPS/master/app/src/main/assets/revoked_certs.txt" private val REVOKED_CERTS_URL = "https://raw.githubusercontent.com/nightscout/AndroidAPS/master/app/src/main/assets/revoked_certs.txt"
@ -88,7 +88,7 @@ class SignatureVerifierPlugin @Inject constructor(
} }
private fun showNotification() { private fun showNotification() {
val notification = Notification(Notification.INVALID_VERSION, resourceHelper.gs(R.string.running_invalid_version), Notification.URGENT) val notification = Notification(Notification.INVALID_VERSION, rh.gs(R.string.running_invalid_version), Notification.URGENT)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }

View file

@ -26,7 +26,7 @@ import javax.inject.Singleton
class StorageConstraintPlugin @Inject constructor( class StorageConstraintPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val rxBus: RxBus private val rxBus: RxBus
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
@ -34,15 +34,15 @@ class StorageConstraintPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.storage), .pluginName(R.string.storage),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> { override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
val diskFree = availableInternalMemorySize() val diskFree = availableInternalMemorySize()
aapsLogger.debug(LTag.CONSTRAINTS, "Internal storage free (Mb):$diskFree") aapsLogger.debug(LTag.CONSTRAINTS, "Internal storage free (Mb):$diskFree")
if (diskFree < Constants.MINIMUM_FREE_SPACE) { if (diskFree < Constants.MINIMUM_FREE_SPACE) {
value[aapsLogger, false, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this value[aapsLogger, false, rh.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this
val notification = Notification(Notification.DISK_FULL, resourceHelper.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL) val notification = Notification(Notification.DISK_FULL, rh.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} else { } else {
rxBus.send(EventDismissNotification(Notification.DISK_FULL)) rxBus.send(EventDismissNotification(Notification.DISK_FULL))

View file

@ -21,7 +21,7 @@ import kotlin.math.roundToInt
class VersionCheckerPlugin @Inject constructor( class VersionCheckerPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
private val sp: SP, private val sp: SP,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val versionCheckerUtils: VersionCheckerUtils, private val versionCheckerUtils: VersionCheckerUtils,
val rxBus: RxBus, val rxBus: RxBus,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
@ -34,7 +34,7 @@ class VersionCheckerPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.versionChecker), .pluginName(R.string.versionChecker),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) {
@ -59,10 +59,10 @@ class VersionCheckerPlugin @Inject constructor(
checkWarning() checkWarning()
versionCheckerUtils.triggerCheckVersion() versionCheckerUtils.triggerCheckVersion()
if (isOldVersion(gracePeriod.veryOld.daysToMillis())) if (isOldVersion(gracePeriod.veryOld.daysToMillis()))
value[aapsLogger, false, resourceHelper.gs(R.string.very_old_version)] = this value[aapsLogger, false, rh.gs(R.string.very_old_version)] = this
val endDate = sp.getLong(resourceHelper.gs(info.nightscout.androidaps.core.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) val endDate = sp.getLong(rh.gs(info.nightscout.androidaps.core.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0)
if (endDate != 0L && dateUtil.now() > endDate) if (endDate != 0L && dateUtil.now() > endDate)
value[aapsLogger, false, resourceHelper.gs(R.string.application_expired)] = this value[aapsLogger, false, rh.gs(R.string.application_expired)] = this
return value return value
} }
@ -80,7 +80,7 @@ class VersionCheckerPlugin @Inject constructor(
sp.putLong(R.string.key_last_versionchecker_plugin_warning, now) sp.putLong(R.string.key_last_versionchecker_plugin_warning, now)
//notify //notify
val message = resourceHelper.gs( val message = rh.gs(
R.string.new_version_warning, R.string.new_version_warning,
((now - sp.getLong(R.string.key_last_time_this_version_detected, now)) / 1L.daysToMillis().toDouble()).roundToInt(), ((now - sp.getLong(R.string.key_last_time_this_version_detected, now)) / 1L.daysToMillis().toDouble()).roundToInt(),
gracePeriod.old, gracePeriod.old,
@ -90,13 +90,13 @@ class VersionCheckerPlugin @Inject constructor(
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
val endDate = sp.getLong(resourceHelper.gs(info.nightscout.androidaps.core.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) val endDate = sp.getLong(rh.gs(info.nightscout.androidaps.core.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0)
if (endDate != 0L && dateUtil.now() > endDate && shouldWarnAgain(now)) { if (endDate != 0L && dateUtil.now() > endDate && shouldWarnAgain(now)) {
// store last notification time // store last notification time
sp.putLong(R.string.key_last_versionchecker_plugin_warning, now) sp.putLong(R.string.key_last_versionchecker_plugin_warning, now)
//notify //notify
val notification = Notification(Notification.VERSION_EXPIRE, resourceHelper.gs(R.string.application_expired), Notification.URGENT) val notification = Notification(Notification.VERSION_EXPIRE, rh.gs(R.string.application_expired), Notification.URGENT)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
} }
@ -106,7 +106,7 @@ class VersionCheckerPlugin @Inject constructor(
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> = override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> =
if (isOldVersion(gracePeriod.old.daysToMillis())) if (isOldVersion(gracePeriod.old.daysToMillis()))
maxIob.set(aapsLogger, 0.0, resourceHelper.gs(R.string.old_version), this) maxIob.set(aapsLogger, 0.0, rh.gs(R.string.old_version), this)
else else
maxIob maxIob

View file

@ -31,7 +31,7 @@ import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.activities.HistoryBrowseActivity import info.nightscout.androidaps.activities.HistoryBrowseActivity
import info.nightscout.androidaps.diaconn.DiaconnG8Plugin import info.nightscout.androidaps.diaconn.DiaconnG8Plugin
import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
@ -67,12 +67,12 @@ class ActionsFragment : DaggerFragment() {
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var statusLightHandler: StatusLightHandler
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueue
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var skinProvider: SkinProvider @Inject lateinit var skinProvider: SkinProvider
@ -164,7 +164,7 @@ class ActionsFragment : DaggerFragment() {
extendedBolus?.setOnClickListener { extendedBolus?.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), resourceHelper.gs(R.string.ebstopsloop), OKDialog.showConfirmation(activity, rh.gs(R.string.extended_bolus), rh.gs(R.string.ebstopsloop),
Runnable { Runnable {
ExtendedBolusDialog().show(childFragmentManager, "Actions") ExtendedBolusDialog().show(childFragmentManager, "Actions")
}, null) }, null)
@ -177,7 +177,7 @@ class ActionsFragment : DaggerFragment() {
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -192,7 +192,7 @@ class ActionsFragment : DaggerFragment() {
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
} }
} }
}) })
@ -274,7 +274,7 @@ class ActionsFragment : DaggerFragment() {
pump.isInitialized() && pump.isInitialized() &&
!pump.isSuspended()).toVisibility() !pump.isSuspended()).toVisibility()
if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses) { if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses || config.NSCLIENT) {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE
} else { } else {
@ -283,14 +283,14 @@ class ActionsFragment : DaggerFragment() {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.VISIBLE extendedBolusCancel?.visibility = View.VISIBLE
@Suppress("SetTextI18n") @Suppress("SetTextI18n")
extendedBolusCancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil) extendedBolusCancel?.text = rh.gs(R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil)
} else { } else {
extendedBolus?.visibility = View.VISIBLE extendedBolus?.visibility = View.VISIBLE
extendedBolusCancel?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE
} }
} }
if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) { if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized() || pump.isSuspended() || config.NSCLIENT) {
setTempBasal?.visibility = View.GONE setTempBasal?.visibility = View.GONE
cancelTempBasal?.visibility = View.GONE cancelTempBasal?.visibility = View.GONE
} else { } else {
@ -299,7 +299,7 @@ class ActionsFragment : DaggerFragment() {
setTempBasal?.visibility = View.GONE setTempBasal?.visibility = View.GONE
cancelTempBasal?.visibility = View.VISIBLE cancelTempBasal?.visibility = View.VISIBLE
@Suppress("SetTextI18n") @Suppress("SetTextI18n")
cancelTempBasal?.text = resourceHelper.gs(R.string.cancel) + " " + activeTemp.toStringShort() cancelTempBasal?.text = rh.gs(R.string.cancel) + " " + activeTemp.toStringShort()
} else { } else {
setTempBasal?.visibility = View.VISIBLE setTempBasal?.visibility = View.VISIBLE
cancelTempBasal?.visibility = View.GONE cancelTempBasal?.visibility = View.GONE
@ -318,7 +318,7 @@ class ActionsFragment : DaggerFragment() {
if (!config.NSCLIENT) { if (!config.NSCLIENT) {
statusLightHandler.updateStatusLights(cannulaAge, insulinAge, reservoirLevel, sensorAge, sensorLevel, pbAge, batteryLevel) statusLightHandler.updateStatusLights(cannulaAge, insulinAge, reservoirLevel, sensorAge, sensorLevel, pbAge, batteryLevel)
sensorLevelLabel?.text = if (activeBgSource.sensorBatteryLevel == -1) "" else resourceHelper.gs(R.string.careportal_level_label) sensorLevelLabel?.text = if (activeBgSource.sensorBatteryLevel == -1) "" else rh.gs(R.string.careportal_level_label)
} else { } else {
statusLightHandler.updateStatusLights(cannulaAge, insulinAge, null, sensorAge, null, pbAge, null) statusLightHandler.updateStatusLights(cannulaAge, insulinAge, null, sensorAge, null, pbAge, null)
sensorLevelLabel?.text = "" sensorLevelLabel?.text = ""
@ -339,7 +339,7 @@ class ActionsFragment : DaggerFragment() {
if (!customAction.isEnabled) continue if (!customAction.isEnabled) continue
val btn = SingleClickButton(currentContext, null, android.R.attr.buttonStyle) val btn = SingleClickButton(currentContext, null, android.R.attr.buttonStyle)
btn.text = resourceHelper.gs(customAction.name) btn.text = rh.gs(customAction.name)
val layoutParams = LinearLayout.LayoutParams( val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f) LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f)
@ -357,7 +357,7 @@ class ActionsFragment : DaggerFragment() {
buttonsLayout?.addView(btn) buttonsLayout?.addView(btn)
this.pumpCustomActions[resourceHelper.gs(customAction.name)] = customAction this.pumpCustomActions[rh.gs(customAction.name)] = customAction
this.pumpCustomButtons.add(btn) this.pumpCustomButtons.add(btn)
} }
} }

View file

@ -15,7 +15,7 @@ import javax.inject.Singleton
class ActionsPlugin @Inject constructor( class ActionsPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
config: Config config: Config
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
@ -26,5 +26,5 @@ class ActionsPlugin @Inject constructor(
.pluginName(R.string.actions) .pluginName(R.string.actions)
.shortName(R.string.actions_shortname) .shortName(R.string.actions_shortname)
.description(R.string.description_actions), .description(R.string.description_actions),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) )

View file

@ -34,7 +34,7 @@ import javax.inject.Singleton
class DataBroadcastPlugin @Inject constructor( class DataBroadcastPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val context: Context, private val context: Context,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -57,7 +57,7 @@ class DataBroadcastPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.neverVisible(true) .neverVisible(true)
.showInList(false), .showInList(false),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()

View file

@ -47,7 +47,7 @@ class FoodFragment : DaggerFragment() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@ -75,9 +75,9 @@ class FoodFragment : DaggerFragment() {
binding.refreshFromNightscout.setOnClickListener { binding.refreshFromNightscout.setOnClickListener {
context?.let { context -> context?.let { context ->
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", { OKDialog.showConfirmation(context, rh.gs(R.string.refresheventsfromnightscout) + " ?", {
uel.log(Action.FOOD, Sources.Food, resourceHelper.gs(R.string.refresheventsfromnightscout), uel.log(Action.FOOD, Sources.Food, rh.gs(R.string.refresheventsfromnightscout),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.refresheventsfromnightscout))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.refresheventsfromnightscout)))
disposable += Completable.fromAction { repository.deleteAllFoods() } disposable += Completable.fromAction { repository.deleteAllFoods() }
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
@ -172,7 +172,7 @@ class FoodFragment : DaggerFragment() {
} }
// make it unique // make it unique
val categories = ArrayList(catSet) val categories = ArrayList(catSet)
categories.add(0, resourceHelper.gs(R.string.none)) categories.add(0, rh.gs(R.string.none))
context?.let { context -> context?.let { context ->
val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories)
binding.category.adapter = adapterCategories binding.category.adapter = adapterCategories
@ -182,7 +182,7 @@ class FoodFragment : DaggerFragment() {
private fun fillSubcategories() { private fun fillSubcategories() {
val categoryFilter = binding.category.selectedItem.toString() val categoryFilter = binding.category.selectedItem.toString()
val subCatSet: MutableSet<CharSequence> = HashSet() val subCatSet: MutableSet<CharSequence> = HashSet()
if (categoryFilter != resourceHelper.gs(R.string.none)) { if (categoryFilter != rh.gs(R.string.none)) {
for (f in unfiltered) { for (f in unfiltered) {
if (f.category != null && f.category == categoryFilter) { if (f.category != null && f.category == categoryFilter) {
val subCategory = f.subCategory val subCategory = f.subCategory
@ -192,7 +192,7 @@ class FoodFragment : DaggerFragment() {
} }
// make it unique // make it unique
val subcategories = ArrayList(subCatSet) val subcategories = ArrayList(subCatSet)
subcategories.add(0, resourceHelper.gs(R.string.none)) subcategories.add(0, rh.gs(R.string.none))
context?.let { context -> context?.let { context ->
val adapterSubcategories = ArrayAdapter(context, R.layout.spinner_centered, subcategories) val adapterSubcategories = ArrayAdapter(context, R.layout.spinner_centered, subcategories)
binding.subcategory.adapter = adapterSubcategories binding.subcategory.adapter = adapterSubcategories
@ -202,14 +202,14 @@ class FoodFragment : DaggerFragment() {
private fun filterData() { private fun filterData() {
val textFilter = binding.filter.text.toString() val textFilter = binding.filter.text.toString()
val categoryFilter = binding.category.selectedItem?.toString() val categoryFilter = binding.category.selectedItem?.toString()
?: resourceHelper.gs(R.string.none) ?: rh.gs(R.string.none)
val subcategoryFilter = binding.subcategory.selectedItem?.toString() val subcategoryFilter = binding.subcategory.selectedItem?.toString()
?: resourceHelper.gs(R.string.none) ?: rh.gs(R.string.none)
val newFiltered = ArrayList<Food>() val newFiltered = ArrayList<Food>()
for (f in unfiltered) { for (f in unfiltered) {
if (f.category == null || f.subCategory == null) continue if (f.category == null || f.subCategory == null) continue
if (subcategoryFilter != resourceHelper.gs(R.string.none) && f.subCategory != subcategoryFilter) continue if (subcategoryFilter != rh.gs(R.string.none) && f.subCategory != subcategoryFilter) continue
if (categoryFilter != resourceHelper.gs(R.string.none) && f.category != categoryFilter) continue if (categoryFilter != rh.gs(R.string.none) && f.category != categoryFilter) continue
if (textFilter != "" && !f.name.lowercase(Locale.getDefault()).contains(textFilter.lowercase(Locale.getDefault()))) continue if (textFilter != "" && !f.name.lowercase(Locale.getDefault()).contains(textFilter.lowercase(Locale.getDefault()))) continue
newFiltered.add(f) newFiltered.add(f)
} }
@ -232,12 +232,12 @@ class FoodFragment : DaggerFragment() {
holder.binding.nsSign.visibility = (food.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.nsSign.visibility = (food.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.name.text = food.name holder.binding.name.text = food.name
holder.binding.portion.text = food.portion.toString() + food.unit holder.binding.portion.text = food.portion.toString() + food.unit
holder.binding.carbs.text = food.carbs.toString() + resourceHelper.gs(R.string.shortgramm) holder.binding.carbs.text = food.carbs.toString() + rh.gs(R.string.shortgramm)
holder.binding.fat.text = resourceHelper.gs(R.string.shortfat) + ": " + food.fat + resourceHelper.gs(R.string.shortgramm) holder.binding.fat.text = rh.gs(R.string.shortfat) + ": " + food.fat + rh.gs(R.string.shortgramm)
holder.binding.fat.visibility = food.fat.isNotZero().toVisibility() holder.binding.fat.visibility = food.fat.isNotZero().toVisibility()
holder.binding.protein.text = resourceHelper.gs(R.string.shortprotein) + ": " + food.protein + resourceHelper.gs(R.string.shortgramm) holder.binding.protein.text = rh.gs(R.string.shortprotein) + ": " + food.protein + rh.gs(R.string.shortgramm)
holder.binding.protein.visibility = food.protein.isNotZero().toVisibility() holder.binding.protein.visibility = food.protein.isNotZero().toVisibility()
holder.binding.energy.text = resourceHelper.gs(R.string.shortenergy) + ": " + food.energy + resourceHelper.gs(R.string.shortkilojoul) holder.binding.energy.text = rh.gs(R.string.shortenergy) + ": " + food.energy + rh.gs(R.string.shortkilojoul)
holder.binding.energy.visibility = food.energy.isNotZero().toVisibility() holder.binding.energy.visibility = food.energy.isNotZero().toVisibility()
holder.binding.remove.tag = food holder.binding.remove.tag = food
} }
@ -252,7 +252,7 @@ class FoodFragment : DaggerFragment() {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val food = v.tag as Food val food = v.tag as Food
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord) + "\n" + food.name, { OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord) + "\n" + food.name, {
uel.log(Action.FOOD_REMOVED, Sources.Food, food.name) uel.log(Action.FOOD_REMOVED, Sources.Food, food.name)
disposable += repository.runTransactionForResult(InvalidateFoodTransaction(food.id)) disposable += repository.runTransactionForResult(InvalidateFoodTransaction(food.id))
.subscribe( .subscribe(

View file

@ -27,7 +27,7 @@ import javax.inject.Singleton
class FoodPlugin @Inject constructor( class FoodPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper rh: ResourceHelper
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(FoodFragment::class.java.name) .fragmentClass(FoodFragment::class.java.name)
@ -35,7 +35,7 @@ class FoodPlugin @Inject constructor(
.pluginName(R.string.food) .pluginName(R.string.food)
.shortName(R.string.food_short) .shortName(R.string.food_short)
.description(R.string.description_food), .description(R.string.description_food),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
// cannot be inner class because of needed injection // cannot be inner class because of needed injection

View file

@ -58,7 +58,7 @@ import kotlin.system.exitProcess
@Singleton @Singleton
class ImportExportPrefsImpl @Inject constructor( class ImportExportPrefsImpl @Inject constructor(
private var log: AAPSLogger, private var log: AAPSLogger,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val buildHelper: BuildHelper, private val buildHelper: BuildHelper,
private val rxBus: RxBus, private val rxBus: RxBus,
@ -121,7 +121,7 @@ class ImportExportPrefsImpl @Inject constructor(
// name provided (hopefully) by user // name provided (hopefully) by user
val patientName = sp.getString(R.string.key_patient_name, "") val patientName = sp.getString(R.string.key_patient_name, "")
val defaultPatientName = resourceHelper.gs(R.string.patient_name_default) val defaultPatientName = rh.gs(R.string.patient_name_default)
// name we detect from OS // name we detect from OS
val systemName = n1 ?: n2 ?: n3 ?: n4 ?: n5 ?: n6 ?: defaultPatientName val systemName = n1 ?: n2 ?: n3 ?: n4 ?: n5 ?: n6 ?: defaultPatientName
@ -132,7 +132,7 @@ class ImportExportPrefsImpl @Inject constructor(
passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { password -> passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { password ->
then(password) then(password)
}, { }, {
ToastUtils.warnToast(activity, resourceHelper.gs(canceledMsg)) ToastUtils.warnToast(activity, rh.gs(canceledMsg))
}) })
} }
@ -142,7 +142,7 @@ class ImportExportPrefsImpl @Inject constructor(
passwordCheck.queryAnyPassword(activity, passwordName, R.string.key_master_password, passwordExplanation, passwordWarning, { password -> passwordCheck.queryAnyPassword(activity, passwordName, R.string.key_master_password, passwordExplanation, passwordWarning, { password ->
then(password) then(password)
}, { }, {
ToastUtils.warnToast(activity, resourceHelper.gs(canceledMsg)) ToastUtils.warnToast(activity, rh.gs(canceledMsg))
}) })
} }
@ -154,8 +154,8 @@ class ImportExportPrefsImpl @Inject constructor(
private fun assureMasterPasswordSet(activity: FragmentActivity, @StringRes wrongPwdTitle: Int): Boolean { private fun assureMasterPasswordSet(activity: FragmentActivity, @StringRes wrongPwdTitle: Int): Boolean {
if (!sp.contains(R.string.key_master_password) || (sp.getString(R.string.key_master_password, "") == "")) { if (!sp.contains(R.string.key_master_password) || (sp.getString(R.string.key_master_password, "") == "")) {
WarningDialog.showWarning(activity, WarningDialog.showWarning(activity,
resourceHelper.gs(wrongPwdTitle), rh.gs(wrongPwdTitle),
resourceHelper.gs(R.string.master_password_missing, resourceHelper.gs(R.string.configbuilder_general), resourceHelper.gs(R.string.protection)), rh.gs(R.string.master_password_missing, rh.gs(R.string.configbuilder_general), rh.gs(R.string.protection)),
R.string.nav_preferences, { R.string.nav_preferences, {
val intent = Intent(activity, PreferencesActivity::class.java).apply { val intent = Intent(activity, PreferencesActivity::class.java).apply {
putExtra("id", R.xml.pref_general) putExtra("id", R.xml.pref_general)
@ -170,18 +170,18 @@ class ImportExportPrefsImpl @Inject constructor(
private fun askToConfirmExport(activity: FragmentActivity, fileToExport: File, then: ((password: String) -> Unit)) { private fun askToConfirmExport(activity: FragmentActivity, fileToExport: File, then: ((password: String) -> Unit)) {
if (!assureMasterPasswordSet(activity, R.string.nav_export)) return if (!assureMasterPasswordSet(activity, R.string.nav_export)) return
TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_export), TwoMessagesAlertDialog.showAlert(activity, rh.gs(R.string.nav_export),
resourceHelper.gs(R.string.export_to) + " " + fileToExport.name + " ?", rh.gs(R.string.export_to) + " " + fileToExport.name + " ?",
resourceHelper.gs(R.string.password_preferences_encrypt_prompt), { rh.gs(R.string.password_preferences_encrypt_prompt), {
askForMasterPassIfNeeded(activity, R.string.preferences_export_canceled, then) askForMasterPassIfNeeded(activity, R.string.preferences_export_canceled, then)
}, null, R.drawable.ic_header_export) }, null, R.drawable.ic_header_export)
} }
private fun askToConfirmImport(activity: FragmentActivity, fileToImport: PrefsFile, then: ((password: String) -> Unit)) { private fun askToConfirmImport(activity: FragmentActivity, fileToImport: PrefsFile, then: ((password: String) -> Unit)) {
if (!assureMasterPasswordSet(activity, R.string.nav_import)) return if (!assureMasterPasswordSet(activity, R.string.nav_import)) return
TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_import), TwoMessagesAlertDialog.showAlert(activity, rh.gs(R.string.nav_import),
resourceHelper.gs(R.string.import_from) + " " + fileToImport.name + " ?", rh.gs(R.string.import_from) + " " + fileToImport.name + " ?",
resourceHelper.gs(R.string.password_preferences_decrypt_prompt), { rh.gs(R.string.password_preferences_decrypt_prompt), {
askForMasterPass(activity, R.string.preferences_import_canceled, then) askForMasterPass(activity, R.string.preferences_import_canceled, then)
}, null, R.drawable.ic_header_import) }, null, R.drawable.ic_header_import)
} }
@ -224,22 +224,22 @@ class ImportExportPrefsImpl @Inject constructor(
encryptedPrefsFormat.savePreferences(newFile, prefs, password) encryptedPrefsFormat.savePreferences(newFile, prefs, password)
ToastUtils.okToast(activity, resourceHelper.gs(R.string.exported)) ToastUtils.okToast(activity, rh.gs(R.string.exported))
} catch (e: FileNotFoundException) { } catch (e: FileNotFoundException) {
ToastUtils.errorToast(activity, resourceHelper.gs(R.string.filenotfound) + " " + newFile) ToastUtils.errorToast(activity, rh.gs(R.string.filenotfound) + " " + newFile)
log.error(LTag.CORE, "Unhandled exception", e) log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: IOException) { } catch (e: IOException) {
ToastUtils.errorToast(activity, e.message) ToastUtils.errorToast(activity, e.message)
log.error(LTag.CORE, "Unhandled exception", e) log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: PrefFileNotFoundError) { } catch (e: PrefFileNotFoundError) {
ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) ToastUtils.Long.errorToast(activity, rh.gs(R.string.preferences_export_canceled)
+ "\n\n" + resourceHelper.gs(R.string.filenotfound) + "\n\n" + rh.gs(R.string.filenotfound)
+ ": " + e.message + ": " + e.message
+ "\n\n" + resourceHelper.gs(R.string.needstoragepermission)) + "\n\n" + rh.gs(R.string.needstoragepermission))
log.error(LTag.CORE, "File system exception", e) log.error(LTag.CORE, "File system exception", e)
} catch (e: PrefIOError) { } catch (e: PrefIOError) {
ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) ToastUtils.Long.errorToast(activity, rh.gs(R.string.preferences_export_canceled)
+ "\n\n" + resourceHelper.gs(R.string.needstoragepermission) + "\n\n" + rh.gs(R.string.needstoragepermission)
+ ": " + e.message) + ": " + e.message)
log.error(LTag.CORE, "File system exception", e) log.error(LTag.CORE, "File system exception", e)
} }
@ -260,7 +260,7 @@ class ImportExportPrefsImpl @Inject constructor(
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
// this exception happens on some early implementations of ActivityResult contracts // this exception happens on some early implementations of ActivityResult contracts
// when registered and called for the second time // when registered and called for the second time
ToastUtils.errorToast(activity, resourceHelper.gs(R.string.goto_main_try_again)) ToastUtils.errorToast(activity, rh.gs(R.string.goto_main_try_again))
log.error(LTag.CORE, "Internal android framework exception", e) log.error(LTag.CORE, "Internal android framework exception", e)
} }
} }
@ -298,14 +298,14 @@ class ImportExportPrefsImpl @Inject constructor(
restartAppAfterImport(activity) restartAppAfterImport(activity)
} else { } else {
// for impossible imports it should not be called // for impossible imports it should not be called
ToastUtils.errorToast(activity, resourceHelper.gs(R.string.preferences_import_impossible)) ToastUtils.errorToast(activity, rh.gs(R.string.preferences_import_impossible))
} }
}) })
} }
} catch (e: PrefFileNotFoundError) { } catch (e: PrefFileNotFoundError) {
ToastUtils.errorToast(activity, resourceHelper.gs(R.string.filenotfound) + " " + importFile) ToastUtils.errorToast(activity, rh.gs(R.string.filenotfound) + " " + importFile)
log.error(LTag.CORE, "Unhandled exception", e) log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: PrefIOError) { } catch (e: PrefIOError) {
log.error(LTag.CORE, "Unhandled exception", e) log.error(LTag.CORE, "Unhandled exception", e)
@ -326,7 +326,7 @@ class ImportExportPrefsImpl @Inject constructor(
private fun restartAppAfterImport(context: Context) { private fun restartAppAfterImport(context: Context) {
sp.putBoolean(R.string.key_setupwizard_processed, true) sp.putBoolean(R.string.key_setupwizard_processed, true)
OKDialog.show(context, resourceHelper.gs(R.string.setting_imported), resourceHelper.gs(R.string.restartingapp)) { OKDialog.show(context, rh.gs(R.string.setting_imported), rh.gs(R.string.restartingapp)) {
uel.log(Action.IMPORT_SETTINGS, Sources.Maintenance) uel.log(Action.IMPORT_SETTINGS, Sources.Maintenance)
log.debug(LTag.CORE, "Exiting") log.debug(LTag.CORE, "Exiting")
rxBus.send(EventAppExit()) rxBus.send(EventAppExit())
@ -354,7 +354,7 @@ class ImportExportPrefsImpl @Inject constructor(
@Inject lateinit var injector: HasAndroidInjector @Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var prefFileList: PrefFileListProvider @Inject lateinit var prefFileList: PrefFileListProvider
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var userEntryPresentationHelper: UserEntryPresentationHelper @Inject lateinit var userEntryPresentationHelper: UserEntryPresentationHelper
@ -371,9 +371,9 @@ class ImportExportPrefsImpl @Inject constructor(
var ret = Result.success() var ret = Result.success()
try { try {
saveCsv(newFile, entries) saveCsv(newFile, entries)
ToastUtils.okToast(context, resourceHelper.gs(R.string.ue_exported)) ToastUtils.okToast(context, rh.gs(R.string.ue_exported))
} catch (e: FileNotFoundException) { } catch (e: FileNotFoundException) {
ToastUtils.errorToast(context, resourceHelper.gs(R.string.filenotfound) + " " + newFile) ToastUtils.errorToast(context, rh.gs(R.string.filenotfound) + " " + newFile)
aapsLogger.error(LTag.CORE, "Unhandled exception", e) aapsLogger.error(LTag.CORE, "Unhandled exception", e)
ret = Result.failure(workDataOf("Error" to "Error FileNotFoundException")) ret = Result.failure(workDataOf("Error" to "Error FileNotFoundException"))
} catch (e: IOException) { } catch (e: IOException) {

View file

@ -12,7 +12,8 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding import info.nightscout.androidaps.databinding.MaintenanceFragmentBinding
import info.nightscout.androidaps.events.EventNewBG import info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.insight.database.InsightDatabase
import info.nightscout.androidaps.interfaces.DataSyncSelector import info.nightscout.androidaps.interfaces.DataSyncSelector
import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.ImportExportPrefs
@ -23,7 +24,8 @@ import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity
import info.nightscout.androidaps.plugins.general.overview.OverviewData import info.nightscout.androidaps.plugins.general.overview.OverviewData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase
import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryDatabase
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
@ -37,12 +39,15 @@ class MaintenanceFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var maintenancePlugin: MaintenancePlugin
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var importExportPrefs: ImportExportPrefs @Inject lateinit var importExportPrefs: ImportExportPrefs
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase
@Inject lateinit var insightDatabase: InsightDatabase @Inject lateinit var insightDatabase: InsightDatabase
@Inject lateinit var diaconnDatabase: DiaconnHistoryDatabase
@Inject lateinit var erosDatabase: ErosHistoryDatabase
@Inject lateinit var dashDatabase: DashHistoryDatabase
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var dataSyncSelector: DataSyncSelector
@Inject lateinit var pumpSync: PumpSync @Inject lateinit var pumpSync: PumpSync
@ -73,12 +78,15 @@ class MaintenanceFragment : DaggerFragment() {
} }
binding.navResetdb.setOnClickListener { binding.navResetdb.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.maintenance), resourceHelper.gs(R.string.reset_db_confirm), Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.maintenance), rh.gs(R.string.reset_db_confirm), Runnable {
compositeDisposable.add( compositeDisposable.add(
fromAction { fromAction {
repository.clearDatabases() repository.clearDatabases()
danaHistoryDatabase.clearAllTables() danaHistoryDatabase.clearAllTables()
insightDatabase.clearAllTables() insightDatabase.clearAllTables()
diaconnDatabase.clearAllTables()
erosDatabase.clearAllTables()
dashDatabase.clearAllTables()
dataSyncSelector.resetToNextFullSync() dataSyncSelector.resetToNextFullSync()
pumpSync.connectNewPump() pumpSync.connectNewPump()
overviewData.reset() overviewData.reset()
@ -86,12 +94,10 @@ class MaintenanceFragment : DaggerFragment() {
iobCobCalculator.clearCache() iobCobCalculator.clearCache()
} }
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)
.subscribeBy( .subscribeBy(
onError = { aapsLogger.error("Error clearing databases", it) }, onError = { aapsLogger.error("Error clearing databases", it) },
onComplete = { onComplete = {
rxBus.send(EventNewBG(null)) rxBus.send(EventPreferenceChange(rh, R.string.key_units))
rxBus.send(EventNewHistoryData(0, true))
} }
) )
) )
@ -116,7 +122,7 @@ class MaintenanceFragment : DaggerFragment() {
binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) } binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) }
binding.exportCsv.setOnClickListener { binding.exportCsv.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.ue_export_to_csv) + "?") { OKDialog.showConfirmation(activity, rh.gs(R.string.ue_export_to_csv) + "?") {
uel.log(Action.EXPORT_CSV, Sources.Maintenance) uel.log(Action.EXPORT_CSV, Sources.Maintenance)
importExportPrefs.exportUserEntriesCsv(activity) importExportPrefs.exportUserEntriesCsv(activity)
} }

View file

@ -27,7 +27,7 @@ import javax.inject.Singleton
class MaintenancePlugin @Inject constructor( class MaintenancePlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
private val context: Context, private val context: Context,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val nsSettingsStatus: NSSettingsStatus, private val nsSettingsStatus: NSSettingsStatus,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
@ -46,7 +46,7 @@ class MaintenancePlugin @Inject constructor(
.shortName(R.string.maintenance_shortname) .shortName(R.string.maintenance_shortname)
.preferencesId(R.xml.pref_maintenance) .preferencesId(R.xml.pref_maintenance)
.description(R.string.description_maintenance), .description(R.string.description_maintenance),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
fun sendLogs() { fun sendLogs() {
@ -169,13 +169,13 @@ class MaintenancePlugin @Inject constructor(
builder.append("If you want to provide logs for event older than a few hours," + System.lineSeparator()) builder.append("If you want to provide logs for event older than a few hours," + System.lineSeparator())
builder.append("you have to do it manually)" + System.lineSeparator()) builder.append("you have to do it manually)" + System.lineSeparator())
builder.append("-------------------------------------------------------" + System.lineSeparator()) builder.append("-------------------------------------------------------" + System.lineSeparator())
builder.append(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator()) builder.append(rh.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator())
if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator()) if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator())
builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator()) builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator())
builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator())
builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator()) builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator())
builder.append(resourceHelper.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator()) builder.append(rh.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator())
if (buildHelper.isEngineeringMode()) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled)) if (buildHelper.isEngineeringMode()) builder.append(rh.gs(R.string.engineering_mode_enabled))
return sendMail(attachmentUri, recipient, subject, builder.toString()) return sendMail(attachmentUri, recipient, subject, builder.toString())
} }

View file

@ -621,7 +621,6 @@ class DataSyncSelectorImplementation @Inject constructor(
//private var lastTbrId = -1L //private var lastTbrId = -1L
//private var lastTbrTime = -1L //private var lastTbrTime = -1L
override fun processChangedTemporaryBasalsCompat(): Boolean { override fun processChangedTemporaryBasalsCompat(): Boolean {
val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false)
val lastDbIdWrapped = appRepository.getLastTemporaryBasalIdWrapped().blockingGet() val lastDbIdWrapped = appRepository.getLastTemporaryBasalIdWrapped().blockingGet()
val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L
var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0) var startId = sp.getLong(R.string.key_ns_temporary_basal_last_synced_id, 0)
@ -658,7 +657,7 @@ class DataSyncSelectorImplementation @Inject constructor(
tb.first.interfaceIDs.nightscoutId == null -> tb.first.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd( nsClientPlugin.nsClientService?.dbAdd(
"treatments", "treatments",
tb.first.toJson(true, profile, dateUtil, useAbsolute), tb.first.toJson(true, profile, dateUtil),
DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id),
"$startId/$lastDbId" "$startId/$lastDbId"
) )
@ -667,7 +666,7 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbUpdate( nsClientPlugin.nsClientService?.dbUpdate(
"treatments", "treatments",
tb.first.interfaceIDs.nightscoutId, tb.first.interfaceIDs.nightscoutId,
tb.first.toJson(false, profile, dateUtil, useAbsolute), tb.first.toJson(false, profile, dateUtil),
DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id),
"$startId/$lastDbId" "$startId/$lastDbId"
) )
@ -700,7 +699,6 @@ class DataSyncSelectorImplementation @Inject constructor(
//private var lastEbId = -1L //private var lastEbId = -1L
//private var lastEbTime = -1L //private var lastEbTime = -1L
override fun processChangedExtendedBolusesCompat(): Boolean { override fun processChangedExtendedBolusesCompat(): Boolean {
val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false)
val lastDbIdWrapped = appRepository.getLastExtendedBolusIdWrapped().blockingGet() val lastDbIdWrapped = appRepository.getLastExtendedBolusIdWrapped().blockingGet()
val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L val lastDbId = if (lastDbIdWrapped is ValueWrapper.Existing) lastDbIdWrapped.value else 0L
var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0) var startId = sp.getLong(R.string.key_ns_extended_bolus_last_synced_id, 0)
@ -737,7 +735,7 @@ class DataSyncSelectorImplementation @Inject constructor(
eb.first.interfaceIDs.nightscoutId == null -> eb.first.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd( nsClientPlugin.nsClientService?.dbAdd(
"treatments", "treatments",
eb.first.toJson(true, profile, dateUtil, useAbsolute), eb.first.toJson(true, profile, dateUtil),
DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id),
"$startId/$lastDbId" "$startId/$lastDbId"
) )
@ -746,7 +744,7 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbUpdate( nsClientPlugin.nsClientService?.dbUpdate(
"treatments", "treatments",
eb.first.interfaceIDs.nightscoutId, eb.first.interfaceIDs.nightscoutId,
eb.first.toJson(false, profile, dateUtil, useAbsolute), eb.first.toJson(false, profile, dateUtil),
DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id),
"$startId/$lastDbId" "$startId/$lastDbId"
) )

View file

@ -1,10 +1,12 @@
package info.nightscout.androidaps.plugins.general.nsclient package info.nightscout.androidaps.plugins.general.nsclient
import android.content.Context import android.content.Context
import android.os.SystemClock
import androidx.work.Worker import androidx.work.Worker
import androidx.work.WorkerParameters import androidx.work.WorkerParameters
import androidx.work.workDataOf import androidx.work.workDataOf
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.DeviceStatus import info.nightscout.androidaps.database.entities.DeviceStatus
import info.nightscout.androidaps.database.transactions.* import info.nightscout.androidaps.database.transactions.*
@ -17,6 +19,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
class NSClientAddAckWorker( class NSClientAddAckWorker(
@ -30,6 +33,7 @@ class NSClientAddAckWorker(
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var dataSyncSelector: DataSyncSelector
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var sp: SP
override fun doWork(): Result { override fun doWork(): Result {
var ret = Result.success() var ret = Result.success()
@ -37,6 +41,8 @@ class NSClientAddAckWorker(
val ack = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as NSAddAck? val ack = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as NSAddAck?
?: return Result.failure(workDataOf("Error" to "missing input data")) ?: return Result.failure(workDataOf("Error" to "missing input data"))
if (sp.getBoolean(R.string.key_ns_sync_slow, false)) SystemClock.sleep(1000)
when (ack.originalObject) { when (ack.originalObject) {
is PairTemporaryTarget -> { is PairTemporaryTarget -> {
val pair = ack.originalObject val pair = ack.originalObject

View file

@ -28,7 +28,7 @@ class NSClientFragment : DaggerFragment() {
@Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@ -70,8 +70,8 @@ class NSClientFragment : DaggerFragment() {
binding.deliverNow.paintFlags = binding.deliverNow.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.deliverNow.paintFlags = binding.deliverNow.paintFlags or Paint.UNDERLINE_TEXT_FLAG
binding.fullSync.setOnClickListener { binding.fullSync.setOnClickListener {
context?.let { context -> context?.let { context ->
OKDialog.showConfirmation(context, resourceHelper.gs(R.string.nsclientinternal), OKDialog.showConfirmation(context, rh.gs(R.string.nsclientinternal),
resourceHelper.gs(R.string.full_sync_comment), Runnable { rh.gs(R.string.full_sync_comment), Runnable {
dataSyncSelector.resetToNextFullSync() dataSyncSelector.resetToNextFullSync()
}) })
} }

View file

@ -49,7 +49,7 @@ class NSClientPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val rxBus: RxBus, private val rxBus: RxBus,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val context: Context, private val context: Context,
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
private val sp: SP, private val sp: SP,
@ -64,7 +64,7 @@ class NSClientPlugin @Inject constructor(
.shortName(R.string.nsclientinternal_shortname) .shortName(R.string.nsclientinternal_shortname)
.preferencesId(R.xml.pref_nsclientinternal) .preferencesId(R.xml.pref_nsclientinternal)
.description(R.string.description_ns_client), .description(R.string.description_ns_client),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -100,7 +100,7 @@ class NSClientPlugin @Inject constructor(
.toObservable(EventNSClientStatus::class.java) .toObservable(EventNSClientStatus::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventNSClientStatus -> .subscribe({ event: EventNSClientStatus ->
status = event.getStatus(resourceHelper) status = event.getStatus(rh)
rxBus.send(EventNSClientUpdateGUI()) rxBus.send(EventNSClientUpdateGUI())
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
) )
@ -148,17 +148,17 @@ class NSClientPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) super.preprocessPreferences(preferenceFragment)
if (config.NSCLIENT) { if (config.NSCLIENT) {
preferenceFragment.findPreference<PreferenceScreen>(resourceHelper.gs(R.string.ns_sync_options))?.isVisible = false preferenceFragment.findPreference<PreferenceScreen>(rh.gs(R.string.ns_sync_options))?.isVisible = false
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_create_announcements_from_errors))?.isVisible = false preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_create_announcements_from_errors))?.isVisible = false
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_create_announcements_from_carbs_req))?.isVisible = false preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_create_announcements_from_carbs_req))?.isVisible = false
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_sync_use_absolute))?.isVisible = false // preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_sync_use_absolute))?.isVisible = false
} else { } else {
// APS or pumpControl mode // APS or pumpControl mode
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_receive_profile_switch))?.isVisible = buildHelper.isEngineeringMode() preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_profile_switch))?.isVisible = buildHelper.isEngineeringMode()
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_receive_insulin))?.isVisible = buildHelper.isEngineeringMode() preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_insulin))?.isVisible = buildHelper.isEngineeringMode()
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_receive_carbs))?.isVisible = buildHelper.isEngineeringMode() preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_carbs))?.isVisible = buildHelper.isEngineeringMode()
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_ns_receive_temp_target))?.isVisible = buildHelper.isEngineeringMode() preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_ns_receive_temp_target))?.isVisible = buildHelper.isEngineeringMode()
} }
} }
@ -217,7 +217,7 @@ class NSClientPlugin @Inject constructor(
fun pause(newState: Boolean) { fun pause(newState: Boolean) {
sp.putBoolean(R.string.key_nsclientinternal_paused, newState) sp.putBoolean(R.string.key_nsclientinternal_paused, newState)
paused = newState paused = newState
rxBus.send(EventPreferenceChange(resourceHelper, R.string.key_nsclientinternal_paused)) rxBus.send(EventPreferenceChange(rh, R.string.key_nsclientinternal_paused))
} }
fun url(): String = nsClientService?.nsURL ?: "" fun url(): String = nsClientService?.nsURL ?: ""
@ -225,7 +225,7 @@ class NSClientPlugin @Inject constructor(
fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) { fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) {
if (!isEnabled(PluginType.GENERAL)) return if (!isEnabled(PluginType.GENERAL)) return
if (!sp.getBoolean(R.string.key_ns_upload, false)) { if (!sp.getBoolean(R.string.key_ns_upload, true)) {
aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped") aapsLogger.debug(LTag.NSCLIENT, "Upload disabled. Message dropped")
return return
} }

View file

@ -14,7 +14,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class NsClientReceiverDelegate @Inject constructor( class NsClientReceiverDelegate @Inject constructor(
private val rxBus: RxBus, private val rxBus: RxBus,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val receiverStatusStore: ReceiverStatusStore private val receiverStatusStore: ReceiverStatusStore
) { ) {
@ -28,12 +28,12 @@ class NsClientReceiverDelegate @Inject constructor(
} }
fun onStatusEvent(ev: EventPreferenceChange) { fun onStatusEvent(ev: EventPreferenceChange) {
if (ev.isChanged(resourceHelper, R.string.key_ns_wifionly) || if (ev.isChanged(rh, R.string.key_ns_wifionly) ||
ev.isChanged(resourceHelper, R.string.key_ns_wifi_ssids) || ev.isChanged(rh, R.string.key_ns_wifi_ssids) ||
ev.isChanged(resourceHelper, R.string.key_ns_allowroaming)) { ev.isChanged(rh, R.string.key_ns_allowroaming)) {
receiverStatusStore.updateNetworkStatus() receiverStatusStore.updateNetworkStatus()
onStatusEvent(receiverStatusStore.lastNetworkEvent) onStatusEvent(receiverStatusStore.lastNetworkEvent)
} else if (ev.isChanged(resourceHelper, R.string.key_ns_chargingonly)) { } else if (ev.isChanged(rh, R.string.key_ns_chargingonly)) {
receiverStatusStore.broadcastChargingState() receiverStatusStore.broadcastChargingState()
} }
} }
@ -58,7 +58,7 @@ class NsClientReceiverDelegate @Inject constructor(
val newAllowedState = allowedChargingState && allowedNetworkState val newAllowedState = allowedChargingState && allowedNetworkState
if (newAllowedState != allowed) { if (newAllowedState != allowed) {
allowed = newAllowedState allowed = newAllowedState
rxBus.send(EventPreferenceChange(resourceHelper.gs(R.string.key_nsclientinternal_paused))) rxBus.send(EventPreferenceChange(rh.gs(R.string.key_nsclientinternal_paused)))
} }
} }

View file

@ -1,28 +0,0 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONObject;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.plugins.bus.RxBus;
import io.socket.client.Ack;
public class NSAuthAck extends Event implements Ack {
private final RxBus rxBus;
public boolean read = false;
public boolean write = false;
public boolean write_treatment = false;
public NSAuthAck(RxBus rxBus) {
this.rxBus = rxBus;
}
public void call(Object... args) {
JSONObject response = (JSONObject) args[0];
read = response.optBoolean("read");
write = response.optBoolean("write");
write_treatment = response.optBoolean("write_treatment");
rxBus.send(this);
}
}

View file

@ -0,0 +1,20 @@
package info.nightscout.androidaps.plugins.general.nsclient.acks
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.plugins.bus.RxBus
import io.socket.client.Ack
import org.json.JSONObject
class NSAuthAck(private val rxBus: RxBus) : Event(), Ack {
var read = false
var write = false
var writeTreatment = false
override fun call(vararg args: Any) {
val response = args[0] as JSONObject
read = response.optBoolean("read")
write = response.optBoolean("write")
writeTreatment = response.optBoolean("write_treatment")
rxBus.send(this)
}
}

View file

@ -18,7 +18,6 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -77,7 +76,7 @@ import javax.inject.Singleton
class NSDeviceStatus @Inject constructor( class NSDeviceStatus @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val nsSettingsStatus: NSSettingsStatus, private val nsSettingsStatus: NSSettingsStatus,
private val config: Config, private val config: Config,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -158,8 +157,8 @@ class NSDeviceStatus @Inject constructor(
//String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"}; //String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"};
val string = StringBuilder() val string = StringBuilder()
.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") .append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
.append(resourceHelper.gs(R.string.pump)) .append(rh.gs(R.string.pump))
.append(": </span>") .append(": </span>")
// test warning level // test warning level
@ -179,7 +178,7 @@ class NSDeviceStatus @Inject constructor(
if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ") if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ")
if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ") if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ")
if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ") if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ")
if (fields.contains("clock")) string.append(dateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ") if (fields.contains("clock")) string.append(dateUtil.minAgo(rh, pumpData.clock)).append(" ")
if (fields.contains("status")) string.append(pumpData.status).append(" ") if (fields.contains("status")) string.append(pumpData.status).append(" ")
if (fields.contains("device")) string.append(device).append(" ") if (fields.contains("device")) string.append(device).append(" ")
string.append("</span>") // color string.append("</span>") // color
@ -195,7 +194,7 @@ class NSDeviceStatus @Inject constructor(
if (clock == 0L || deviceStatusData.pumpData != null && clock < deviceStatusData.pumpData!!.clock) return if (clock == 0L || deviceStatusData.pumpData != null && clock < deviceStatusData.pumpData!!.clock) return
// create new status and process data // create new status and process data
var deviceStatusPumpData = DeviceStatusData.PumpData() val deviceStatusPumpData = DeviceStatusData.PumpData()
deviceStatusPumpData.clock = clock deviceStatusPumpData.clock = clock
if (pump.has("status") && pump.getJSONObject("status").has("status")) deviceStatusPumpData.status = pump.getJSONObject("status").getString("status") if (pump.has("status") && pump.getJSONObject("status").has("status")) deviceStatusPumpData.status = pump.getJSONObject("status").getString("status")
if (pump.has("reservoir")) deviceStatusPumpData.reservoir = pump.getDouble("reservoir") if (pump.has("reservoir")) deviceStatusPumpData.reservoir = pump.getDouble("reservoir")
@ -249,8 +248,8 @@ class NSDeviceStatus @Inject constructor(
val openApsStatus: Spanned val openApsStatus: Spanned
get() { get() {
val string = StringBuilder() val string = StringBuilder()
.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") .append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
.append(resourceHelper.gs(R.string.openaps_short)) .append(rh.gs(R.string.openaps_short))
.append(": </span>") .append(": </span>")
// test warning level // test warning level
@ -260,7 +259,7 @@ class NSDeviceStatus @Inject constructor(
else -> Levels.INFO else -> Levels.INFO
} }
string.append("<span style=\"color:${level.toColor()}\">") string.append("<span style=\"color:${level.toColor()}\">")
if (deviceStatusData.openAPSData.clockSuggested != 0L) string.append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockSuggested)).append(" ") if (deviceStatusData.openAPSData.clockSuggested != 0L) string.append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockSuggested)).append(" ")
string.append("</span>") // color string.append("</span>") // color
return fromHtml(string.toString()) return fromHtml(string.toString())
} }
@ -269,8 +268,8 @@ class NSDeviceStatus @Inject constructor(
get() { get() {
val string = StringBuilder() val string = StringBuilder()
try { try {
if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockEnacted)).append("</b> ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("<br>") if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("<b>").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockEnacted)).append("</b> ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("<br>")
if (deviceStatusData.openAPSData.suggested != null) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockSuggested)).append("</b> ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("<br>") if (deviceStatusData.openAPSData.suggested != null) string.append("<b>").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockSuggested)).append("</b> ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("<br>")
return fromHtml(string.toString()) return fromHtml(string.toString())
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
@ -322,8 +321,8 @@ class NSDeviceStatus @Inject constructor(
val uploaderStatusSpanned: Spanned val uploaderStatusSpanned: Spanned
get() { get() {
val string = StringBuilder() val string = StringBuilder()
string.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") string.append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
string.append(resourceHelper.gs(R.string.uploader_short)) string.append(rh.gs(R.string.uploader_short))
string.append(": </span>") string.append(": </span>")
val iterator: Iterator<*> = deviceStatusData.uploaderMap.entries.iterator() val iterator: Iterator<*> = deviceStatusData.uploaderMap.entries.iterator()
var minBattery = 100 var minBattery = 100

View file

@ -118,7 +118,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class NSSettingsStatus @Inject constructor( class NSSettingsStatus @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val rxBus: RxBus, private val rxBus: RxBus,
private val defaultValueHelper: DefaultValueHelper, private val defaultValueHelper: DefaultValueHelper,
private val sp: SP, private val sp: SP,
@ -150,7 +150,7 @@ class NSSettingsStatus @Inject constructor(
data = status data = status
aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: ${getVersion()}") aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: ${getVersion()}")
if (getVersionNum() < config.SUPPORTEDNSVERSION) { if (getVersionNum() < config.SUPPORTEDNSVERSION) {
val notification = Notification(Notification.OLD_NS, resourceHelper.gs(R.string.unsupportednsversion), Notification.NORMAL) val notification = Notification(Notification.OLD_NS, rh.gs(R.string.unsupportednsversion), Notification.NORMAL)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} else { } else {
rxBus.send(EventDismissNotification(Notification.OLD_NS)) rxBus.send(EventDismissNotification(Notification.OLD_NS))
@ -252,7 +252,7 @@ class NSSettingsStatus @Inject constructor(
uel.log(Action.NS_SETTINGS_COPIED, UserEntry.Sources.NSClient) uel.log(Action.NS_SETTINGS_COPIED, UserEntry.Sources.NSClient)
} }
if (context != null) OKDialog.showConfirmation(context, resourceHelper.gs(R.string.statuslights), resourceHelper.gs(R.string.copyexistingvalues), action) if (context != null) OKDialog.showConfirmation(context, rh.gs(R.string.statuslights), rh.gs(R.string.copyexistingvalues), action)
else action.run() else action.run()
} }
} }

View file

@ -4,5 +4,5 @@ import info.nightscout.androidaps.events.EventStatus
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
class EventNSClientStatus(var text: String) : EventStatus() { class EventNSClientStatus(var text: String) : EventStatus() {
override fun getStatus(resourceHelper: ResourceHelper): String = text override fun getStatus(rh: ResourceHelper): String = text
} }

View file

@ -70,7 +70,7 @@ class NSClientService : DaggerService() {
@Inject lateinit var nsSettingsStatus: NSSettingsStatus @Inject lateinit var nsSettingsStatus: NSSettingsStatus
@Inject lateinit var nsDeviceStatus: NSDeviceStatus @Inject lateinit var nsDeviceStatus: NSDeviceStatus
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin
@ -119,7 +119,7 @@ class NSClientService : DaggerService() {
.toObservable(EventConfigBuilderChange::class.java) .toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
if (nsEnabled != nsClientPlugin.isEnabled(PluginType.GENERAL)) { if (nsEnabled != nsClientPlugin.isEnabled()) {
latestDateInReceivedData = 0 latestDateInReceivedData = 0
destroy() destroy()
initialize() initialize()
@ -130,9 +130,9 @@ class NSClientService : DaggerService() {
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange -> .subscribe({ event: EventPreferenceChange ->
if (event.isChanged(resourceHelper, R.string.key_nsclientinternal_url) || if (event.isChanged(rh, R.string.key_nsclientinternal_url) ||
event.isChanged(resourceHelper, R.string.key_nsclientinternal_api_secret) || event.isChanged(rh, R.string.key_nsclientinternal_api_secret) ||
event.isChanged(resourceHelper, R.string.key_nsclientinternal_paused)) { event.isChanged(rh, R.string.key_nsclientinternal_paused)) {
latestDateInReceivedData = 0 latestDateInReceivedData = 0
destroy() destroy()
initialize() initialize()
@ -199,20 +199,20 @@ class NSClientService : DaggerService() {
var connectionStatus = "Authenticated (" var connectionStatus = "Authenticated ("
if (ack.read) connectionStatus += "R" if (ack.read) connectionStatus += "R"
if (ack.write) connectionStatus += "W" if (ack.write) connectionStatus += "W"
if (ack.write_treatment) connectionStatus += "T" if (ack.writeTreatment) connectionStatus += "T"
connectionStatus += ')' connectionStatus += ')'
isConnected = true isConnected = true
hasWriteAuth = ack.write && ack.write_treatment hasWriteAuth = ack.write && ack.writeTreatment
rxBus.send(EventNSClientStatus(connectionStatus)) rxBus.send(EventNSClientStatus(connectionStatus))
rxBus.send(EventNSClientNewLog("AUTH", connectionStatus)) rxBus.send(EventNSClientNewLog("AUTH", connectionStatus))
if (!ack.write) { if (!ack.write) {
rxBus.send(EventNSClientNewLog("ERROR", "Write permission not granted ")) rxBus.send(EventNSClientNewLog("ERROR", "Write permission not granted "))
} }
if (!ack.write_treatment) { if (!ack.writeTreatment) {
rxBus.send(EventNSClientNewLog("ERROR", "Write treatment permission not granted ")) rxBus.send(EventNSClientNewLog("ERROR", "Write treatment permission not granted "))
} }
if (!hasWriteAuth) { if (!hasWriteAuth) {
val noWritePerm = Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, resourceHelper.gs(R.string.nowritepermission), Notification.URGENT) val noWritePerm = Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, rh.gs(R.string.nowritepermission), Notification.URGENT)
rxBus.send(EventNewNotification(noWritePerm)) rxBus.send(EventNewNotification(noWritePerm))
} else { } else {
rxBus.send(EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)) rxBus.send(EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION))
@ -304,7 +304,7 @@ class NSClientService : DaggerService() {
} }
rxBus.send(EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " minutes: " + reconnections.size + "/" + WATCHDOG_MAX_CONNECTIONS)) rxBus.send(EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " minutes: " + reconnections.size + "/" + WATCHDOG_MAX_CONNECTIONS))
if (reconnections.size >= WATCHDOG_MAX_CONNECTIONS) { if (reconnections.size >= WATCHDOG_MAX_CONNECTIONS) {
val n = Notification(Notification.NS_MALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT) val n = Notification(Notification.NS_MALFUNCTION, rh.gs(R.string.nsmalfunction), Notification.URGENT)
rxBus.send(EventNewNotification(n)) rxBus.send(EventNewNotification(n))
rxBus.send(EventNSClientNewLog("WATCHDOG", "pausing for $WATCHDOG_RECONNECT_IN minutes")) rxBus.send(EventNSClientNewLog("WATCHDOG", "pausing for $WATCHDOG_RECONNECT_IN minutes"))
nsClientPlugin.pause(true) nsClientPlugin.pause(true)
@ -356,7 +356,7 @@ class NSClientService : DaggerService() {
} }
fun readPreferences() { fun readPreferences() {
nsEnabled = nsClientPlugin.isEnabled(PluginType.GENERAL) nsEnabled = nsClientPlugin.isEnabled()
nsURL = sp.getString(R.string.key_nsclientinternal_url, "") nsURL = sp.getString(R.string.key_nsclientinternal_url, "")
nsAPISecret = sp.getString(R.string.key_nsclientinternal_api_secret, "") nsAPISecret = sp.getString(R.string.key_nsclientinternal_api_secret, "")
nsDevice = sp.getString("careportal_enteredby", "") nsDevice = sp.getString("careportal_enteredby", "")

View file

@ -38,7 +38,7 @@ import kotlin.math.min
class OverviewData @Inject constructor( class OverviewData @Inject constructor(
private val injector: HasAndroidInjector, private val injector: HasAndroidInjector,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val sp: SP, private val sp: SP,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -53,20 +53,6 @@ class OverviewData @Inject constructor(
private val translator: Translator private val translator: Translator
) { ) {
enum class Property {
TIME,
CALC_PROGRESS,
PROFILE,
TEMPORARY_BASAL,
EXTENDED_BOLUS,
TEMPORARY_TARGET,
BG,
IOB_COB,
SENSITIVITY,
GRAPH,
PUMPSTATUS
}
var rangeToDisplay = 6 // for graph var rangeToDisplay = 6 // for graph
var toTime: Long = 0 var toTime: Long = 0
var fromTime: Long = 0 var fromTime: Long = 0
@ -76,8 +62,6 @@ class OverviewData @Inject constructor(
pumpStatus = "" pumpStatus = ""
calcProgress = "" calcProgress = ""
lastBg = null lastBg = null
temporaryBasal = null
extendedBolus = null
bolusIob = null bolusIob = null
basalIob = null basalIob = null
cobInfo = null cobInfo = null
@ -145,11 +129,11 @@ class OverviewData @Inject constructor(
val lastBgColor: Int val lastBgColor: Int
get() = lastBg?.let { lastBg -> get() = lastBg?.let { lastBg ->
when { when {
lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> resourceHelper.gc(R.color.low) lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> rh.gc(R.color.low)
lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> resourceHelper.gc(R.color.high) lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> rh.gc(R.color.high)
else -> resourceHelper.gc(R.color.inrange) else -> rh.gc(R.color.inrange)
} }
} ?: resourceHelper.gc(R.color.inrange) } ?: rh.gc(R.color.inrange)
val isActualBg: Boolean val isActualBg: Boolean
get() = get() =
@ -161,29 +145,28 @@ class OverviewData @Inject constructor(
* TEMPORARY BASAL * TEMPORARY BASAL
*/ */
var temporaryBasal: TemporaryBasal? = null
val temporaryBasalText: String val temporaryBasalText: String
get() = get() =
profileFunction.getProfile()?.let { profile -> profileFunction.getProfile()?.let { profile ->
var temporaryBasal = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())
if (temporaryBasal?.isInProgress == false) temporaryBasal = null if (temporaryBasal?.isInProgress == false) temporaryBasal = null
temporaryBasal?.let { "T:" + it.toStringShort() } temporaryBasal?.let { "T:" + it.toStringShort() }
?: resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()) ?: rh.gs(R.string.pump_basebasalrate, profile.getBasal())
} ?: resourceHelper.gs(R.string.notavailable) } ?: rh.gs(R.string.notavailable)
val temporaryBasalDialogText: String val temporaryBasalDialogText: String
get() = profileFunction.getProfile()?.let { profile -> get() = profileFunction.getProfile()?.let { profile ->
temporaryBasal?.let { temporaryBasal -> iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { temporaryBasal ->
"${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal())}" + "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}" +
"\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil) "\n" + rh.gs(R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil)
} }
?: "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal())}" ?: "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}"
} ?: resourceHelper.gs(R.string.notavailable) } ?: rh.gs(R.string.notavailable)
val temporaryBasalIcon: Int val temporaryBasalIcon: Int
get() = get() =
profileFunction.getProfile()?.let { profile -> profileFunction.getProfile()?.let { profile ->
temporaryBasal?.let { temporaryBasal -> iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { temporaryBasal ->
val percentRate = temporaryBasal.convertedToPercent(dateUtil.now(), profile) val percentRate = temporaryBasal.convertedToPercent(dateUtil.now(), profile)
when { when {
percentRate > 100 -> R.drawable.ic_cp_basal_tbr_high percentRate > 100 -> R.drawable.ic_cp_basal_tbr_high
@ -194,27 +177,23 @@ class OverviewData @Inject constructor(
} ?: R.drawable.ic_cp_basal_no_tbr } ?: R.drawable.ic_cp_basal_no_tbr
val temporaryBasalColor: Int val temporaryBasalColor: Int
get() = temporaryBasal?.let { resourceHelper.gc(R.color.basal) } get() = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { rh.gc(R.color.basal) }
?: resourceHelper.gc(R.color.defaulttextcolor) ?: rh.gc(R.color.defaulttextcolor)
/* /*
* EXTENDED BOLUS * EXTENDED BOLUS
*/ */
var extendedBolus: ExtendedBolus? = null
val extendedBolusText: String val extendedBolusText: String
get() = get() =
extendedBolus?.let { extendedBolus -> iobCobCalculator.getExtendedBolus(dateUtil.now())?.let { extendedBolus ->
if (!extendedBolus.isInProgress(dateUtil)) { if (!extendedBolus.isInProgress(dateUtil)) ""
this@OverviewData.extendedBolus = null else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) rh.gs(R.string.pump_basebasalrate, extendedBolus.rate)
""
} else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate)
else "" else ""
} ?: "" } ?: ""
val extendedBolusDialogText: String val extendedBolusDialogText: String
get() = extendedBolus?.toStringFull(dateUtil) ?: "" get() = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) ?: ""
/* /*
* IOB, COB * IOB, COB
@ -229,19 +208,19 @@ class OverviewData @Inject constructor(
get() = get() =
bolusIob?.let { bolusIob -> bolusIob?.let { bolusIob ->
basalIob?.let { basalIob -> basalIob?.let { basalIob ->
resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
val iobDialogText: String val iobDialogText: String
get() = get() =
bolusIob?.let { bolusIob -> bolusIob?.let { bolusIob ->
basalIob?.let { basalIob -> basalIob?.let { basalIob ->
resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" + rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" +
resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" + rh.gs(R.string.bolus) + ": " + rh.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" +
resourceHelper.gs(R.string.basal) + ": " + resourceHelper.gs(R.string.formatinsulinunits, basalIob.basaliob) rh.gs(R.string.basal) + ": " + rh.gs(R.string.formatinsulinunits, basalIob.basaliob)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
/* /*
* TEMP TARGET * TEMP TARGET
@ -324,8 +303,9 @@ class OverviewData @Inject constructor(
for (bg in bgReadingsArray) { for (bg in bgReadingsArray) {
if (bg.timestamp < fromTime || bg.timestamp > toTime) continue if (bg.timestamp < fromTime || bg.timestamp > toTime) continue
if (bg.value > maxBgValue) maxBgValue = bg.value if (bg.value > maxBgValue) maxBgValue = bg.value
bgListArray.add(GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) bgListArray.add(GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh))
} }
bgListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) }
bgReadingGraphSeries = PointsWithLabelGraphSeries(Array(bgListArray.size) { i -> bgListArray[i] }) bgReadingGraphSeries = PointsWithLabelGraphSeries(Array(bgListArray.size) { i -> bgListArray[i] })
maxBgValue = Profile.fromMgdlToUnits(maxBgValue, profileFunction.getUnits()) maxBgValue = Profile.fromMgdlToUnits(maxBgValue, profileFunction.getUnits())
if (defaultValueHelper.determineHighLine() > maxBgValue) maxBgValue = defaultValueHelper.determineHighLine() if (defaultValueHelper.determineHighLine() > maxBgValue) maxBgValue = defaultValueHelper.determineHighLine()
@ -364,7 +344,7 @@ class OverviewData @Inject constructor(
val bgListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val bgListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val predictions: MutableList<GlucoseValueDataPoint>? = apsResult?.predictions val predictions: MutableList<GlucoseValueDataPoint>? = apsResult?.predictions
?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper) } ?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh) }
?.toMutableList() ?.toMutableList()
if (predictions != null) { if (predictions != null) {
predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) } predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) }
@ -386,8 +366,9 @@ class OverviewData @Inject constructor(
val bucketedListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val bucketedListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
for (inMemoryGlucoseValue in bucketedData) { for (inMemoryGlucoseValue in bucketedData) {
if (inMemoryGlucoseValue.timestamp < fromTime || inMemoryGlucoseValue.timestamp > toTime) continue if (inMemoryGlucoseValue.timestamp < fromTime || inMemoryGlucoseValue.timestamp > toTime) continue
bucketedListArray.add(InMemoryGlucoseValueDataPoint(inMemoryGlucoseValue, profileFunction, resourceHelper)) bucketedListArray.add(InMemoryGlucoseValueDataPoint(inMemoryGlucoseValue, profileFunction, rh))
} }
bucketedListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) }
bucketedGraphSeries = PointsWithLabelGraphSeries(Array(bucketedListArray.size) { i -> bucketedListArray[i] }) bucketedGraphSeries = PointsWithLabelGraphSeries(Array(bucketedListArray.size) { i -> bucketedListArray[i] })
// profiler.log(LTag.UI, "prepareBucketedData() $from", start) // profiler.log(LTag.UI, "prepareBucketedData() $from", start)
} }
@ -464,27 +445,27 @@ class OverviewData @Inject constructor(
// create series // create series
baseBasalGraphSeries = LineGraphSeries(Array(baseBasalArray.size) { i -> baseBasalArray[i] }).also { baseBasalGraphSeries = LineGraphSeries(Array(baseBasalArray.size) { i -> baseBasalArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = resourceHelper.gc(R.color.basebasal) it.backgroundColor = rh.gc(R.color.basebasal)
it.thickness = 0 it.thickness = 0
} }
tempBasalGraphSeries = LineGraphSeries(Array(tempBasalArray.size) { i -> tempBasalArray[i] }).also { tempBasalGraphSeries = LineGraphSeries(Array(tempBasalArray.size) { i -> tempBasalArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = resourceHelper.gc(R.color.tempbasal) it.backgroundColor = rh.gc(R.color.tempbasal)
it.thickness = 0 it.thickness = 0
} }
basalLineGraphSeries = LineGraphSeries(Array(basalLineArray.size) { i -> basalLineArray[i] }).also { basalLineGraphSeries = LineGraphSeries(Array(basalLineArray.size) { i -> basalLineArray[i] }).also {
it.setCustomPaint(Paint().also { paint -> it.setCustomPaint(Paint().also { paint ->
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = resourceHelper.getDisplayMetrics().scaledDensity * 2 paint.strokeWidth = rh.getDisplayMetrics().scaledDensity * 2
paint.pathEffect = DashPathEffect(floatArrayOf(2f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(2f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.basal) paint.color = rh.gc(R.color.basal)
}) })
} }
absoluteBasalGraphSeries = LineGraphSeries(Array(absoluteBasalLineArray.size) { i -> absoluteBasalLineArray[i] }).also { absoluteBasalGraphSeries = LineGraphSeries(Array(absoluteBasalLineArray.size) { i -> absoluteBasalLineArray[i] }).also {
it.setCustomPaint(Paint().also { absolutePaint -> it.setCustomPaint(Paint().also { absolutePaint ->
absolutePaint.style = Paint.Style.STROKE absolutePaint.style = Paint.Style.STROKE
absolutePaint.strokeWidth = resourceHelper.getDisplayMetrics().scaledDensity * 2 absolutePaint.strokeWidth = rh.getDisplayMetrics().scaledDensity * 2
absolutePaint.color = resourceHelper.gc(R.color.basal) absolutePaint.color = rh.gc(R.color.basal)
}) })
} }
// profiler.log(LTag.UI, "prepareBasalData() $from", start) // profiler.log(LTag.UI, "prepareBasalData() $from", start)
@ -520,7 +501,7 @@ class OverviewData @Inject constructor(
// create series // create series
temporaryTargetSeries = LineGraphSeries(Array(targetsSeriesArray.size) { i -> targetsSeriesArray[i] }).also { temporaryTargetSeries = LineGraphSeries(Array(targetsSeriesArray.size) { i -> targetsSeriesArray[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.tempTargetBackground) it.color = rh.gc(R.color.tempTargetBackground)
it.thickness = 2 it.thickness = 2
} }
// profiler.log(LTag.UI, "prepareTemporaryTargetData() $from", start) // profiler.log(LTag.UI, "prepareTemporaryTargetData() $from", start)
@ -533,14 +514,14 @@ class OverviewData @Inject constructor(
maxTreatmentsValue = 0.0 maxTreatmentsValue = 0.0
val filteredTreatments: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val filteredTreatments: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
repository.getBolusesDataFromTimeToTime(fromTime, endTime, true).blockingGet() repository.getBolusesDataFromTimeToTime(fromTime, endTime, true).blockingGet()
.map { BolusDataPoint(it, resourceHelper, activePlugin, defaultValueHelper) } .map { BolusDataPoint(it, rh, activePlugin, defaultValueHelper) }
.filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB } .filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB }
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())
filteredTreatments.add(it) filteredTreatments.add(it)
} }
repository.getCarbsDataFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet() repository.getCarbsDataFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet()
.map { CarbsDataPoint(it, resourceHelper) } .map { CarbsDataPoint(it, rh) }
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())
filteredTreatments.add(it) filteredTreatments.add(it)
@ -553,7 +534,14 @@ class OverviewData @Inject constructor(
// OfflineEvent // OfflineEvent
repository.getOfflineEventDataFromTimeToTime(fromTime, endTime, true).blockingGet() repository.getOfflineEventDataFromTimeToTime(fromTime, endTime, true).blockingGet()
.map { TherapyEventDataPoint(TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL), resourceHelper, profileFunction, translator) } .map {
TherapyEventDataPoint(
TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL),
rh,
profileFunction,
translator
)
}
.forEach(filteredTreatments::add) .forEach(filteredTreatments::add)
// Extended bolus // Extended bolus
@ -569,7 +557,7 @@ class OverviewData @Inject constructor(
// Careportal // Careportal
repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet()
.map { TherapyEventDataPoint(it, resourceHelper, profileFunction, translator) } .map { TherapyEventDataPoint(it, rh, profileFunction, translator) }
.filterTimeframe(fromTime, endTime) .filterTimeframe(fromTime, endTime)
.forEach { .forEach {
if (it.y == 0.0) it.y = getNearestBg(it.x.toLong()) if (it.y == 0.0) it.y = getNearestBg(it.x.toLong())
@ -680,15 +668,15 @@ class OverviewData @Inject constructor(
// DEVIATIONS // DEVIATIONS
if (autosensData != null) { if (autosensData != null) {
var color = resourceHelper.gc(R.color.deviationblack) // "=" var color = rh.gc(R.color.deviationblack) // "="
if (autosensData.type == "" || autosensData.type == "non-meal") { if (autosensData.type == "" || autosensData.type == "non-meal") {
if (autosensData.pastSensitivity == "C") color = resourceHelper.gc(R.color.deviationgrey) if (autosensData.pastSensitivity == "C") color = rh.gc(R.color.deviationgrey)
if (autosensData.pastSensitivity == "+") color = resourceHelper.gc(R.color.deviationgreen) if (autosensData.pastSensitivity == "+") color = rh.gc(R.color.deviationgreen)
if (autosensData.pastSensitivity == "-") color = resourceHelper.gc(R.color.deviationred) if (autosensData.pastSensitivity == "-") color = rh.gc(R.color.deviationred)
} else if (autosensData.type == "uam") { } else if (autosensData.type == "uam") {
color = resourceHelper.gc(R.color.uam) color = rh.gc(R.color.uam)
} else if (autosensData.type == "csf") { } else if (autosensData.type == "csf") {
color = resourceHelper.gc(R.color.deviationgrey) color = rh.gc(R.color.deviationgrey)
} }
devArray.add(OverviewPlugin.DeviationDataPoint(time.toDouble(), autosensData.deviation, color, devScale)) devArray.add(OverviewPlugin.DeviationDataPoint(time.toDouble(), autosensData.deviation, color, devScale))
maxDevValueFound = maxOf(maxDevValueFound, abs(autosensData.deviation), abs(bgi)) maxDevValueFound = maxOf(maxDevValueFound, abs(autosensData.deviation), abs(bgi))
@ -714,14 +702,14 @@ class OverviewData @Inject constructor(
// IOB // IOB
iobSeries = FixedLineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also { iobSeries = FixedLineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50%
it.color = resourceHelper.gc(R.color.iob) it.color = rh.gc(R.color.iob)
it.thickness = 3 it.thickness = 3
} }
absIobSeries = FixedLineGraphSeries(Array(absIobArray.size) { i -> absIobArray[i] }).also { absIobSeries = FixedLineGraphSeries(Array(absIobArray.size) { i -> absIobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50%
it.color = resourceHelper.gc(R.color.iob) it.color = rh.gc(R.color.iob)
it.thickness = 3 it.thickness = 3
} }
@ -732,14 +720,14 @@ class OverviewData @Inject constructor(
val iobPrediction: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val iobPrediction: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
for (i in iobPredictionArray) { for (i in iobPredictionArray) {
iobPrediction.add(i.setColor(resourceHelper.gc(R.color.iobPredAS))) iobPrediction.add(i.setColor(rh.gc(R.color.iobPredAS)))
maxIobValueFound = max(maxIobValueFound, abs(i.iob)) maxIobValueFound = max(maxIobValueFound, abs(i.iob))
} }
iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] }) iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] })
val iobPrediction2: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val iobPrediction2: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
for (i in iobPredictionArray2) { for (i in iobPredictionArray2) {
iobPrediction2.add(i.setColor(resourceHelper.gc(R.color.iobPred))) iobPrediction2.add(i.setColor(rh.gc(R.color.iobPred)))
maxIobValueFound = max(maxIobValueFound, abs(i.iob)) maxIobValueFound = max(maxIobValueFound, abs(i.iob))
} }
iobPredictions2Series = PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] }) iobPredictions2Series = PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] })
@ -753,8 +741,8 @@ class OverviewData @Inject constructor(
// COB // COB
cobSeries = FixedLineGraphSeries(Array(cobArray.size) { i -> cobArray[i] }).also { cobSeries = FixedLineGraphSeries(Array(cobArray.size) { i -> cobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.cob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.cob) //50%
it.color = resourceHelper.gc(R.color.cob) it.color = rh.gc(R.color.cob)
it.thickness = 3 it.thickness = 3
} }
cobMinFailOverSeries = PointsWithLabelGraphSeries(Array(minFailOverActiveList.size) { i -> minFailOverActiveList[i] }) cobMinFailOverSeries = PointsWithLabelGraphSeries(Array(minFailOverActiveList.size) { i -> minFailOverActiveList[i] })
@ -762,7 +750,7 @@ class OverviewData @Inject constructor(
// ACTIVITY // ACTIVITY
activitySeries = FixedLineGraphSeries(Array(actArrayHist.size) { i -> actArrayHist[i] }).also { activitySeries = FixedLineGraphSeries(Array(actArrayHist.size) { i -> actArrayHist[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.activity) it.color = rh.gc(R.color.activity)
it.thickness = 3 it.thickness = 3
} }
activityPredictionSeries = FixedLineGraphSeries(Array(actArrayPrediction.size) { i -> actArrayPrediction[i] }).also { activityPredictionSeries = FixedLineGraphSeries(Array(actArrayPrediction.size) { i -> actArrayPrediction[i] }).also {
@ -770,14 +758,14 @@ class OverviewData @Inject constructor(
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = 3f paint.strokeWidth = 3f
paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.activity) paint.color = rh.gc(R.color.activity)
}) })
} }
// BGI // BGI
minusBgiSeries = FixedLineGraphSeries(Array(bgiArrayHist.size) { i -> bgiArrayHist[i] }).also { minusBgiSeries = FixedLineGraphSeries(Array(bgiArrayHist.size) { i -> bgiArrayHist[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.bgi) it.color = rh.gc(R.color.bgi)
it.thickness = 3 it.thickness = 3
} }
minusBgiHistSeries = FixedLineGraphSeries(Array(bgiArrayPrediction.size) { i -> bgiArrayPrediction[i] }).also { minusBgiHistSeries = FixedLineGraphSeries(Array(bgiArrayPrediction.size) { i -> bgiArrayPrediction[i] }).also {
@ -785,7 +773,7 @@ class OverviewData @Inject constructor(
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = 3f paint.strokeWidth = 3f
paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.bgi) paint.color = rh.gc(R.color.bgi)
}) })
} }
@ -796,17 +784,17 @@ class OverviewData @Inject constructor(
// RATIO // RATIO
ratioSeries = LineGraphSeries(Array(ratioArray.size) { i -> ratioArray[i] }).also { ratioSeries = LineGraphSeries(Array(ratioArray.size) { i -> ratioArray[i] }).also {
it.color = resourceHelper.gc(R.color.ratio) it.color = rh.gc(R.color.ratio)
it.thickness = 3 it.thickness = 3
} }
// DEV SLOPE // DEV SLOPE
dsMaxSeries = LineGraphSeries(Array(dsMaxArray.size) { i -> dsMaxArray[i] }).also { dsMaxSeries = LineGraphSeries(Array(dsMaxArray.size) { i -> dsMaxArray[i] }).also {
it.color = resourceHelper.gc(R.color.devslopepos) it.color = rh.gc(R.color.devslopepos)
it.thickness = 3 it.thickness = 3
} }
dsMinSeries = LineGraphSeries(Array(dsMinArray.size) { i -> dsMinArray[i] }).also { dsMinSeries = LineGraphSeries(Array(dsMinArray.size) { i -> dsMinArray[i] }).also {
it.color = resourceHelper.gc(R.color.devslopeneg) it.color = rh.gc(R.color.devslopeneg)
it.thickness = 3 it.thickness = 3
} }

View file

@ -45,15 +45,17 @@ import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.constraints.bgQualityCheck.BgQualityCheckPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus
import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity
import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverview import info.nightscout.androidaps.plugins.general.overview.events.*
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction
@ -61,7 +63,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.source.DexcomPlugin import info.nightscout.androidaps.plugins.source.DexcomPlugin
import info.nightscout.androidaps.plugins.source.XdripPlugin import info.nightscout.androidaps.plugins.source.XdripPlugin
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.skins.SkinProvider
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.DefaultValueHelper
@ -93,7 +94,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@ -122,6 +123,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
@Inject lateinit var overviewData: OverviewData @Inject lateinit var overviewData: OverviewData
@Inject lateinit var overviewPlugin: OverviewPlugin @Inject lateinit var overviewPlugin: OverviewPlugin
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var bgQualityCheckPlugin: BgQualityCheckPlugin
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -165,16 +167,16 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
smallHeight = screenHeight <= Constants.SMALL_HEIGHT smallHeight = screenHeight <= Constants.SMALL_HEIGHT
val landscape = screenHeight < screenWidth val landscape = screenHeight < screenWidth
skinProvider.activeSkin().preProcessLandscapeOverviewLayout(dm, view, landscape, resourceHelper.gb(R.bool.isTablet), smallHeight) skinProvider.activeSkin().preProcessLandscapeOverviewLayout(dm, view, landscape, rh.gb(R.bool.isTablet), smallHeight)
binding.nsclientLayout.visibility = config.NSCLIENT.toVisibility() binding.nsclientLayout.visibility = config.NSCLIENT.toVisibility()
binding.notifications.setHasFixedSize(false) binding.notifications.setHasFixedSize(false)
binding.notifications.layoutManager = LinearLayoutManager(view.context) binding.notifications.layoutManager = LinearLayoutManager(view.context)
axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80 axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80
binding.graphsLayout.bgGraph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) binding.graphsLayout.bgGraph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
binding.graphsLayout.bgGraph.gridLabelRenderer?.reloadStyles() binding.graphsLayout.bgGraph.gridLabelRenderer?.reloadStyles()
binding.graphsLayout.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth binding.graphsLayout.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth
binding.graphsLayout.bgGraph.layoutParams?.height = resourceHelper.dpToPx(skinProvider.activeSkin().mainGraphHeight) binding.graphsLayout.bgGraph.layoutParams?.height = rh.dpToPx(skinProvider.activeSkin().mainGraphHeight)
carbAnimation = binding.infoLayout.carbsIcon.background as AnimationDrawable? carbAnimation = binding.infoLayout.carbsIcon.background as AnimationDrawable?
carbAnimation?.setEnterFadeDuration(1200) carbAnimation?.setEnterFadeDuration(1200)
@ -188,8 +190,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
overviewData.initRange() overviewData.initRange()
overviewData.prepareBucketedData("EventBucketedDataCreated") overviewData.prepareBucketedData("EventBucketedDataCreated")
overviewData.prepareBgData("EventBucketedDataCreated") overviewData.prepareBgData("EventBucketedDataCreated")
updateGUI("rangeChange", OverviewData.Property.GRAPH) updateGraph("rangeChange")
rxBus.send(EventPreferenceChange(resourceHelper, R.string.key_rangetodisplay)) rxBus.send(EventPreferenceChange(rh, R.string.key_rangetodisplay))
sp.putBoolean(R.string.key_objectiveusescale, true) sp.putBoolean(R.string.key_objectiveusescale, true)
false false
} }
@ -225,41 +227,93 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
disposable += activePlugin.activeOverview.overviewBus disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverview::class.java) .toObservable(EventUpdateOverviewTime::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe({ updateGUI(it.from, it.what) }, fabricPrivacy::logException) .subscribe({ updateTime(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
disposable.add(rxBus .toObservable(EventUpdateOverviewCalcProgress::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateCalcProgress(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewProfile::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateProfile(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewTemporaryBasal::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateTemporaryBasal(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewExtendedBolus::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateExtendedBolus(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewTemporaryTarget::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateTemporaryTarget(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewBg::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateBg(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewIobCob::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateIobCob(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewSensitivity::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateSensitivity(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewGraph::class.java)
.debounce(1L, TimeUnit.SECONDS)
.observeOn(aapsSchedulers.main)
.subscribe({ updateGraph(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewPumpStatus::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updatePumpStatus(it.from) }, fabricPrivacy::logException)
disposable += activePlugin.activeOverview.overviewBus
.toObservable(EventUpdateOverviewNotification::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateNotification(it.from) }, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventRefreshOverview::class.java) .toObservable(EventRefreshOverview::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
if (it.now) overviewPlugin.refreshLoop(it.from) if (it.now) overviewPlugin.refreshLoop(it.from)
else scheduleUpdateGUI(it.from) else scheduleUpdateGUI(it.from)
}, fabricPrivacy::logException)) }, fabricPrivacy::logException)
disposable.add(rxBus disposable += rxBus
.toObservable(EventAcceptOpenLoopChange::class.java) .toObservable(EventAcceptOpenLoopChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }, fabricPrivacy::logException)) .subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }, fabricPrivacy::logException)
disposable.add(rxBus disposable += rxBus
.toObservable(EventInitializationChanged::class.java) .toObservable(EventInitializationChanged::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe({ updateGUI("EventInitializationChanged", OverviewData.Property.TIME) }, fabricPrivacy::logException)) .subscribe({ updateTime("EventInitializationChanged") }, fabricPrivacy::logException)
disposable.add(rxBus disposable += rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ scheduleUpdateGUI("EventPreferenceChange") }, fabricPrivacy::logException)) .subscribe({ scheduleUpdateGUI("EventPreferenceChange") }, fabricPrivacy::logException)
disposable.add(rxBus disposable += rxBus
.toObservable(EventNewOpenLoopNotification::class.java) .toObservable(EventNewOpenLoopNotification::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }, fabricPrivacy::logException)) .subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventPumpStatusChanged::class.java) .toObservable(EventPumpStatusChanged::class.java)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.delay (30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .delay(30, TimeUnit.MILLISECONDS, aapsSchedulers.main)
.subscribe({ .subscribe({
overviewData.pumpStatus = it.getStatus(resourceHelper) overviewData.pumpStatus = it.getStatus(rh)
updateGUI("EventPumpStatusChanged", OverviewData.Property.PUMPSTATUS) updatePumpStatus("EventPumpStatusChanged")
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
refreshLoop = Runnable { refreshLoop = Runnable {
overviewPlugin.refreshLoop("refreshLoop") overviewPlugin.refreshLoop("refreshLoop")
@ -267,7 +321,17 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
handler.postDelayed(refreshLoop, 60 * 1000L) handler.postDelayed(refreshLoop, 60 * 1000L)
for (p in OverviewData.Property.values()) updateGUI("onResume", p) updateTime("onResume")
updateCalcProgress("onResume")
updateProfile("onResume")
updateTemporaryBasal("onResume")
updateExtendedBolus("onResume")
updateTemporaryTarget("onResume")
updateBg("onResume")
updateIobCob("onResume")
updateSensitivity("onResume")
updateGraph("onResume")
updatePumpStatus("onResume")
} }
@Synchronized @Synchronized
@ -282,12 +346,27 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (childFragmentManager.isStateSaved) return if (childFragmentManager.isStateSaved) return
activity?.let { activity -> activity?.let { activity ->
when (v.id) { when (v.id) {
R.id.treatment_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) TreatmentDialog().show(childFragmentManager, "Overview") }) R.id.treatment_button -> protectionCheck.queryProtection(
R.id.wizard_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) WizardDialog().show(childFragmentManager, "Overview") }) activity,
R.id.insulin_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) InsulinDialog().show(childFragmentManager, "Overview") }) ProtectionCheck.Protection.BOLUS,
UIRunnable { if (isAdded) TreatmentDialog().show(childFragmentManager, "Overview") })
R.id.wizard_button -> protectionCheck.queryProtection(
activity,
ProtectionCheck.Protection.BOLUS,
UIRunnable { if (isAdded) WizardDialog().show(childFragmentManager, "Overview") })
R.id.insulin_button -> protectionCheck.queryProtection(
activity,
ProtectionCheck.Protection.BOLUS,
UIRunnable { if (isAdded) InsulinDialog().show(childFragmentManager, "Overview") })
R.id.quick_wizard_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) onClickQuickWizard() }) R.id.quick_wizard_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) onClickQuickWizard() })
R.id.carbs_button -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) CarbsDialog().show(childFragmentManager, "Overview") }) R.id.carbs_button -> protectionCheck.queryProtection(
R.id.temp_target -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { if (isAdded) TempTargetDialog().show(childFragmentManager, "Overview") }) activity,
ProtectionCheck.Protection.BOLUS,
UIRunnable { if (isAdded) CarbsDialog().show(childFragmentManager, "Overview") })
R.id.temp_target -> protectionCheck.queryProtection(
activity,
ProtectionCheck.Protection.BOLUS,
UIRunnable { if (isAdded) TempTargetDialog().show(childFragmentManager, "Overview") })
R.id.active_profile -> { R.id.active_profile -> {
ProfileViewerDialog().also { pvd -> ProfileViewerDialog().also { pvd ->
@ -299,47 +378,47 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
R.id.cgm_button -> { R.id.cgm_button -> {
if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) if (xdripPlugin.isEnabled())
openCgmApp("com.eveningoutpost.dexdrip") openCgmApp("com.eveningoutpost.dexdrip")
else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { else if (dexcomPlugin.isEnabled()) {
dexcomMediator.findDexcomPackageName()?.let { dexcomMediator.findDexcomPackageName()?.let {
openCgmApp(it) openCgmApp(it)
} }
?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed))
} }
} }
R.id.calibration_button -> { R.id.calibration_button -> {
if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) { if (xdripPlugin.isEnabled()) {
CalibrationDialog().show(childFragmentManager, "CalibrationDialog") CalibrationDialog().show(childFragmentManager, "CalibrationDialog")
} else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { } else if (dexcomPlugin.isEnabled()) {
try { try {
dexcomMediator.findDexcomPackageName()?.let { dexcomMediator.findDexcomPackageName()?.let {
startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it)) startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it))
} }
?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed))
} catch (e: ActivityNotFoundException) { } catch (e: ActivityNotFoundException) {
ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.g5appnotdetected)) ToastUtils.showToastInUiThread(activity, rh.gs(R.string.g5appnotdetected))
} }
} }
} }
R.id.accept_temp_button -> { R.id.accept_temp_button -> {
profileFunction.getProfile() ?: return profileFunction.getProfile() ?: return
if (loopPlugin.isEnabled(PluginType.LOOP)) { if (loopPlugin.isEnabled()) {
handler.post { handler.post {
val lastRun = loopPlugin.lastRun val lastRun = loopPlugin.lastRun
loopPlugin.invoke("Accept temp button", false) loopPlugin.invoke("Accept temp button", false)
if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) {
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned() OKDialog.showConfirmation(activity, rh.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned()
?: "".toSpanned(), { ?: "".toSpanned(), {
uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview)
binding.buttonsLayout.acceptTempButton.visibility = View.GONE binding.buttonsLayout.acceptTempButton.visibility = View.GONE
(context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID)
rxBus.send(EventWearInitiateAction("cancelChangeRequest")) rxBus.send(EventWearInitiateAction("cancelChangeRequest"))
Thread { loopPlugin.acceptChangeRequest() }.run() Thread { loopPlugin.acceptChangeRequest() }.run()
}) })
}) })
} }
} }
@ -366,7 +445,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
intent.addCategory(Intent.CATEGORY_LAUNCHER) intent.addCategory(Intent.CATEGORY_LAUNCHER)
it.startActivity(intent) it.startActivity(intent)
} catch (e: ActivityNotFoundException) { } catch (e: ActivityNotFoundException) {
OKDialog.show(it, "", resourceHelper.gs(R.string.error_starting_cgm)) OKDialog.show(it, "", rh.gs(R.string.error_starting_cgm))
} }
} }
} }
@ -389,7 +468,12 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
R.id.temp_target -> v.performClick() R.id.temp_target -> v.performClick()
R.id.active_profile -> activity?.let { activity -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { ProfileSwitchDialog().show(childFragmentManager, "ProfileSwitchDialog") }) } R.id.active_profile -> activity?.let { activity ->
protectionCheck.queryProtection(
activity,
ProtectionCheck.Protection.BOLUS,
UIRunnable { ProfileSwitchDialog().show(childFragmentManager, "ProfileSwitchDialog") })
}
} }
return false return false
@ -408,7 +492,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value()
activity?.let { activity?.let {
if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) { if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) {
OKDialog.show(it, resourceHelper.gs(R.string.treatmentdeliveryerror), resourceHelper.gs(R.string.constraints_violation) + "\n" + resourceHelper.gs(R.string.changeyourinput)) OKDialog.show(it, rh.gs(R.string.treatmentdeliveryerror), rh.gs(R.string.constraints_violation) + "\n" + rh.gs(R.string.changeyourinput))
return return
} }
wizard.confirmAndExecute(it) wizard.confirmAndExecute(it)
@ -430,8 +514,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended()) { if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended()) {
binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE
val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false) val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false)
binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + resourceHelper.gs(R.string.format_carbs, quickWizardEntry.carbs()) + binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + rh.gs(R.string.format_carbs, quickWizardEntry.carbs()) +
" " + resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) " " + rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin)
if (wizard.calculatedTotalInsulin <= 0) binding.buttonsLayout.quickWizardButton.visibility = View.GONE if (wizard.calculatedTotalInsulin <= 0) binding.buttonsLayout.quickWizardButton.visibility = View.GONE
} else binding.buttonsLayout.quickWizardButton.visibility = View.GONE } else binding.buttonsLayout.quickWizardButton.visibility = View.GONE
@ -444,22 +528,26 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
(lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result (lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result
lastRun.constraintsProcessed?.isChangeRequested == true // change is requested lastRun.constraintsProcessed?.isChangeRequested == true // change is requested
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && loopPlugin.isEnabled(PluginType.LOOP)) { if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && loopPlugin.isEnabled()) {
binding.buttonsLayout.acceptTempButton.visibility = View.VISIBLE binding.buttonsLayout.acceptTempButton.visibility = View.VISIBLE
binding.buttonsLayout.acceptTempButton.text = "${resourceHelper.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}" binding.buttonsLayout.acceptTempButton.text = "${rh.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}"
} else { } else {
binding.buttonsLayout.acceptTempButton.visibility = View.GONE binding.buttonsLayout.acceptTempButton.visibility = View.GONE
} }
// **** Various treatment buttons **** // **** Various treatment buttons ****
binding.buttonsLayout.carbsButton.visibility = ((!activePlugin.activePump.pumpDescription.storesCarbInfo || pump.isInitialized() && !pump.isSuspended()) && profile != null && sp.getBoolean(R.string.key_show_carbs_button, true)).toVisibility() binding.buttonsLayout.carbsButton.visibility =
((!activePlugin.activePump.pumpDescription.storesCarbInfo || pump.isInitialized() && !pump.isSuspended()) && profile != null && sp.getBoolean(
R.string.key_show_carbs_button,
true
)).toVisibility()
binding.buttonsLayout.treatmentButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_treatment_button, false)).toVisibility() binding.buttonsLayout.treatmentButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_treatment_button, false)).toVisibility()
binding.buttonsLayout.wizardButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_wizard_button, true)).toVisibility() binding.buttonsLayout.wizardButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_wizard_button, true)).toVisibility()
binding.buttonsLayout.insulinButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_insulin_button, true)).toVisibility() binding.buttonsLayout.insulinButton.visibility = (pump.isInitialized() && !pump.isSuspended() && profile != null && sp.getBoolean(R.string.key_show_insulin_button, true)).toVisibility()
// **** Calibration & CGM buttons **** // **** Calibration & CGM buttons ****
val xDripIsBgSource = xdripPlugin.isEnabled(PluginType.BGSOURCE) val xDripIsBgSource = xdripPlugin.isEnabled()
val dexcomIsSource = dexcomPlugin.isEnabled(PluginType.BGSOURCE) val dexcomIsSource = dexcomPlugin.isEnabled()
binding.buttonsLayout.calibrationButton.visibility = ((xDripIsBgSource || dexcomIsSource) && actualBG != null && sp.getBoolean(R.string.key_show_calibration_button, true)).toVisibility() binding.buttonsLayout.calibrationButton.visibility = ((xDripIsBgSource || dexcomIsSource) && actualBG != null && sp.getBoolean(R.string.key_show_calibration_button, true)).toVisibility()
binding.buttonsLayout.cgmButton.visibility = (sp.getBoolean(R.string.key_show_cgm_button, false) && (xDripIsBgSource || dexcomIsSource)).toVisibility() binding.buttonsLayout.cgmButton.visibility = (sp.getBoolean(R.string.key_show_cgm_button, false) && (xDripIsBgSource || dexcomIsSource)).toVisibility()
@ -470,18 +558,18 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (event.isEnabled && event.trigger.shouldRun()) if (event.isEnabled && event.trigger.shouldRun())
context?.let { context -> context?.let { context ->
SingleClickButton(context).also { SingleClickButton(context).also {
it.setTextColor(resourceHelper.gc(R.color.colorTreatmentButton)) it.setTextColor(rh.gc(R.color.colorTreatmentButton))
it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f) it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
it.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f).also { l -> it.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f).also { l ->
l.setMargins(0, 0, resourceHelper.dpToPx(-4), 0) l.setMargins(0, 0, rh.dpToPx(-4), 0)
} }
it.setCompoundDrawablesWithIntrinsicBounds(null, resourceHelper.gd(R.drawable.ic_danar_useropt), null, null) it.setCompoundDrawablesWithIntrinsicBounds(null, rh.gd(R.drawable.ic_danar_useropt), null, null)
it.text = event.title it.text = event.title
it.setOnClickListener { it.setOnClickListener {
OKDialog.showConfirmation( OKDialog.showConfirmation(
context, context,
resourceHelper.gs(R.string.run_question, event.title), rh.gs(R.string.run_question, event.title),
{ handler.post { automationPlugin.processEvent(event, true) } } { handler.post { automationPlugin.processEvent(event, true) } }
) )
} }
@ -502,30 +590,32 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
when { when {
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isDisconnected -> { loopPlugin.isDisconnected -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isEnabled() && loopPlugin.isSuspended -> { loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
pump.isSuspended() -> { pump.isSuspended() -> {
binding.infoLayout.apsMode.setImageResource(if (pump.model() == PumpType.OMNIPOD_EROS || pump.model() == PumpType.OMNIPOD_DASH) { binding.infoLayout.apsMode.setImageResource(
// For Omnipod, indicate the pump as disconnected when it's suspended. if (pump.model() == PumpType.OMNIPOD_EROS || pump.model() == PumpType.OMNIPOD_DASH) {
// The only way to 'reconnect' it, is through the Omnipod tab // For Omnipod, indicate the pump as disconnected when it's suspended.
R.drawable.ic_loop_disconnected // The only way to 'reconnect' it, is through the Omnipod tab
} else { R.drawable.ic_loop_disconnected
R.drawable.ic_loop_paused } else {
}) R.drawable.ic_loop_paused
}
)
binding.infoLayout.apsModeText.visibility = View.GONE binding.infoLayout.apsModeText.visibility = View.GONE
} }
@ -558,15 +648,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
// pump status from ns // pump status from ns
binding.pump.text = nsDeviceStatus.pumpStatus binding.pump.text = nsDeviceStatus.pumpStatus
binding.pump.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.pump), nsDeviceStatus.extendedPumpStatus) } } binding.pump.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.pump), nsDeviceStatus.extendedPumpStatus) } }
// OpenAPS status from ns // OpenAPS status from ns
binding.openaps.text = nsDeviceStatus.openApsStatus binding.openaps.text = nsDeviceStatus.openApsStatus
binding.openaps.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.openaps), nsDeviceStatus.extendedOpenApsStatus) } } binding.openaps.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.openaps), nsDeviceStatus.extendedOpenApsStatus) } }
// Uploader status from ns // Uploader status from ns
binding.uploader.text = nsDeviceStatus.uploaderStatusSpanned binding.uploader.text = nsDeviceStatus.uploaderStatusSpanned
binding.uploader.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } } binding.uploader.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } }
} }
private fun prepareGraphsIfNeeded(numOfGraphs: Int) { private fun prepareGraphsIfNeeded(numOfGraphs: Int) {
@ -581,8 +671,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val graph = GraphView(context) val graph = GraphView(context)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(skinProvider.activeSkin().secondaryGraphHeight)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) } graph.layoutParams =
graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rh.dpToPx(skinProvider.activeSkin().secondaryGraphHeight)).also { it.setMargins(0, rh.dpToPx(15), 0, rh.dpToPx(10)) }
graph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
@ -591,7 +682,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
relativeLayout.addView(graph) relativeLayout.addView(graph)
val label = TextView(context) val label = TextView(context)
val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) } val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) }
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
label.layoutParams = layoutParams label.layoutParams = layoutParams
@ -619,257 +710,283 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
task?.let { handler.postDelayed(it, 500) } task?.let { handler.postDelayed(it, 500) }
} }
@Suppress("UNUSED_PARAMETER")
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
fun updateGUI(from: String, what: OverviewData.Property) { @Suppress("UNUSED_PARAMETER")
// if (what != OverviewData.Property.CALC_PROGRESS) fun updateBg(from: String) {
// aapsLogger.debug(LTag.UI, "UpdateGui $from $what")
if (profileFunction.getProfile() == null) {
binding.activeProfile.setText(R.string.noprofileset)
binding.activeProfile.setBackgroundColor(resourceHelper.gc(R.color.errorAlertBackground))
return
}
binding.notifications.let { notificationStore.updateNotifications(it) }
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
binding.infoLayout.bg.text = overviewData.lastBg?.valueToUnitsString(units)
?: rh.gs(R.string.notavailable)
binding.infoLayout.bg.setTextColor(overviewData.lastBgColor)
binding.infoLayout.arrow.setImageResource(trendCalculator.getTrendArrow(overviewData.lastBg).directionToIcon())
binding.infoLayout.arrow.setColorFilter(overviewData.lastBgColor)
val glucoseStatus = glucoseStatusProvider.glucoseStatusData
if (glucoseStatus != null) {
binding.infoLayout.deltaLarge.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)
binding.infoLayout.deltaLarge.setTextColor(overviewData.lastBgColor)
binding.infoLayout.delta.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)
binding.infoLayout.avgDelta.text = Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units)
binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units)
} else {
binding.infoLayout.deltaLarge.text = ""
binding.infoLayout.delta.text = "Δ " + rh.gs(R.string.notavailable)
binding.infoLayout.avgDelta.text = ""
binding.infoLayout.longAvgDelta.text = ""
}
// strike through if BG is old
binding.infoLayout.bg.paintFlags =
if (!overviewData.isActualBg) binding.infoLayout.bg.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
else binding.infoLayout.bg.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
binding.infoLayout.timeAgo.text = dateUtil.minAgo(rh, overviewData.lastBg?.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(overviewData.lastBg?.timestamp) + ")"
val qualityIcon = bgQualityCheckPlugin.icon()
if (qualityIcon != 0) {
binding.infoLayout.bgQuality.visibility = View.VISIBLE
binding.infoLayout.bgQuality.setImageResource(qualityIcon)
binding.infoLayout.bgQuality.setOnClickListener {
context?.let { context -> OKDialog.show(context, rh.gs(R.string.data_status), bgQualityCheckPlugin.message) }
}
} else {
binding.infoLayout.bgQuality.visibility = View.GONE
}
}
@Suppress("UNUSED_PARAMETER")
fun updateProfile(from: String) {
val profileBackgroundColor =
profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
rh.gc(R.color.ribbonWarning)
else rh.gc(R.color.ribbonDefault)
} else if (it is ProfileSealed.PS) {
rh.gc(R.color.ribbonDefault)
} else {
rh.gc(R.color.ribbonDefault)
}
} ?: rh.gc(R.color.ribbonCritical)
val profileTextColor =
profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
rh.gc(R.color.ribbonTextWarning)
else rh.gc(R.color.ribbonTextDefault)
} else if (it is ProfileSealed.PS) {
rh.gc(R.color.ribbonTextDefault)
} else {
rh.gc(R.color.ribbonTextDefault)
}
} ?: rh.gc(R.color.ribbonTextDefault)
binding.activeProfile.text = profileFunction.getProfileNameWithRemainingTime()
binding.activeProfile.setBackgroundColor(profileBackgroundColor)
binding.activeProfile.setTextColor(profileTextColor)
}
@Suppress("UNUSED_PARAMETER")
fun updateTemporaryBasal(from: String) {
binding.infoLayout.baseBasal.text = overviewData.temporaryBasalText
binding.infoLayout.baseBasal.setTextColor(overviewData.temporaryBasalColor)
binding.infoLayout.baseBasalIcon.setImageResource(overviewData.temporaryBasalIcon)
binding.infoLayout.basalLayout.setOnClickListener {
activity?.let { OKDialog.show(it, rh.gs(R.string.basal), overviewData.temporaryBasalDialogText) }
}
}
@Suppress("UNUSED_PARAMETER")
fun updateExtendedBolus(from: String) {
val pump = activePlugin.activePump val pump = activePlugin.activePump
when (what) { binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText
OverviewData.Property.BG -> { binding.infoLayout.extendedLayout.setOnClickListener {
binding.infoLayout.bg.text = overviewData.lastBg?.valueToUnitsString(units) activity?.let { OKDialog.show(it, rh.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) }
?: resourceHelper.gs(R.string.notavailable) }
binding.infoLayout.bg.setTextColor(overviewData.lastBgColor) binding.infoLayout.extendedLayout.visibility = (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null && !pump.isFakingTempsByExtendedBoluses).toVisibility()
binding.infoLayout.arrow.setImageResource(trendCalculator.getTrendArrow(overviewData.lastBg).directionToIcon()) }
binding.infoLayout.arrow.setColorFilter(overviewData.lastBgColor)
val glucoseStatus = glucoseStatusProvider.glucoseStatusData @Suppress("UNUSED_PARAMETER")
if (glucoseStatus != null) { fun updateTime(from: String) {
binding.infoLayout.deltaLarge.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) binding.infoLayout.time.text = dateUtil.timeString(dateUtil.now())
binding.infoLayout.deltaLarge.setTextColor(overviewData.lastBgColor) // Status lights
binding.infoLayout.delta.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) binding.statusLightsLayout.statusLights.visibility = (sp.getBoolean(R.string.key_show_statuslights, true) || config.NSCLIENT).toVisibility()
binding.infoLayout.avgDelta.text = Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units) statusLightHandler.updateStatusLights(
binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units) binding.statusLightsLayout.cannulaAge,
binding.statusLightsLayout.insulinAge,
binding.statusLightsLayout.reservoirLevel,
binding.statusLightsLayout.sensorAge,
null,
binding.statusLightsLayout.pbAge,
binding.statusLightsLayout.batteryLevel
)
processButtonsVisibility()
processAps()
}
@Suppress("UNUSED_PARAMETER")
fun updateIobCob(from: String) {
binding.infoLayout.iob.text = overviewData.iobText
binding.infoLayout.iobLayout.setOnClickListener {
activity?.let { OKDialog.show(it, rh.gs(R.string.iob), overviewData.iobDialogText) }
}
// cob
var cobText = overviewData.cobInfo?.displayText(rh, dateUtil, buildHelper.isEngineeringMode()) ?: rh.gs(R.string.value_unavailable_short)
val constraintsProcessed = loopPlugin.lastRun?.constraintsProcessed
val lastRun = loopPlugin.lastRun
if (config.APS && constraintsProcessed != null && lastRun != null) {
if (constraintsProcessed.carbsReq > 0) {
//only display carbsreq when carbs have not been entered recently
if (overviewData.lastCarbsTime < lastRun.lastAPSRun) {
cobText += " | " + constraintsProcessed.carbsReq + " " + rh.gs(R.string.required)
}
if (carbAnimation?.isRunning == false)
carbAnimation?.start()
} else {
carbAnimation?.stop()
carbAnimation?.selectDrawable(0)
}
}
binding.infoLayout.cob.text = cobText
}
@SuppressLint("SetTextI18n")
@Suppress("UNUSED_PARAMETER")
fun updateTemporaryTarget(from: String) {
val units = profileFunction.getUnits()
if (overviewData.temporaryTarget?.isInProgress(dateUtil) == false) overviewData.temporaryTarget = null
val tempTarget = overviewData.temporaryTarget
if (tempTarget != null) {
binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(rh.gc(R.color.ribbonWarning))
binding.tempTarget.text = Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh)
} else {
// If the target is not the same as set in the profile then oref has overridden it
profileFunction.getProfile()?.let { profile ->
val targetUsed = loopPlugin.lastRun?.constraintsProcessed?.targetBG ?: 0.0
if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) {
aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed")
binding.tempTarget.text = Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units)
binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(rh.gc(R.color.tempTargetBackground))
} else { } else {
binding.infoLayout.deltaLarge.text = "" binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextDefault))
binding.infoLayout.delta.text = "Δ " + resourceHelper.gs(R.string.notavailable) binding.tempTarget.setBackgroundColor(rh.gc(R.color.ribbonDefault))
binding.infoLayout.avgDelta.text = "" binding.tempTarget.text = Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)
binding.infoLayout.longAvgDelta.text = ""
} }
// strike through if BG is old
binding.infoLayout.bg.paintFlags =
if (!overviewData.isActualBg) binding.infoLayout.bg.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
else binding.infoLayout.bg.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
binding.infoLayout.timeAgo.text = dateUtil.minAgo(resourceHelper, overviewData.lastBg?.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(overviewData.lastBg?.timestamp) + ")"
}
OverviewData.Property.PROFILE -> {
val profileBackgroundColor =
profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
resourceHelper.gc(R.color.ribbonWarning)
else resourceHelper.gc(R.color.ribbonDefault)
} else if (it is ProfileSealed.PS) {
resourceHelper.gc(R.color.ribbonDefault)
} else {
resourceHelper.gc(R.color.ribbonDefault)
}
} ?: resourceHelper.gc(R.color.ribbonCritical)
val profileTextColor =
profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
resourceHelper.gc(R.color.ribbonTextWarning)
else resourceHelper.gc(R.color.ribbonTextDefault)
}else if (it is ProfileSealed.PS) {
resourceHelper.gc(R.color.ribbonTextDefault)
} else {
resourceHelper.gc(R.color.ribbonTextDefault)
}
} ?: resourceHelper.gc(R.color.ribbonTextDefault)
binding.activeProfile.text = profileFunction.getProfileNameWithRemainingTime()
binding.activeProfile.setBackgroundColor(profileBackgroundColor)
binding.activeProfile.setTextColor(profileTextColor)
}
OverviewData.Property.TEMPORARY_BASAL -> {
binding.infoLayout.baseBasal.text = overviewData.temporaryBasalText
binding.infoLayout.baseBasal.setTextColor(overviewData.temporaryBasalColor)
binding.infoLayout.baseBasalIcon.setImageResource(overviewData.temporaryBasalIcon)
binding.infoLayout.basalLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.basal), overviewData.temporaryBasalDialogText) }
}
}
OverviewData.Property.EXTENDED_BOLUS -> {
binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText
binding.infoLayout.extendedLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) }
}
binding.infoLayout.extendedLayout.visibility = (overviewData.extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility()
}
OverviewData.Property.TIME -> {
binding.infoLayout.time.text = dateUtil.timeString(dateUtil.now())
// Status lights
binding.statusLightsLayout.statusLights.visibility = (sp.getBoolean(R.string.key_show_statuslights, true) || config.NSCLIENT).toVisibility()
statusLightHandler.updateStatusLights(binding.statusLightsLayout.cannulaAge, binding.statusLightsLayout.insulinAge, binding.statusLightsLayout.reservoirLevel, binding.statusLightsLayout.sensorAge, null, binding.statusLightsLayout.pbAge, binding.statusLightsLayout.batteryLevel)
processButtonsVisibility()
processAps()
}
OverviewData.Property.IOB_COB -> {
binding.infoLayout.iob.text = overviewData.iobText
binding.infoLayout.iobLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.iob), overviewData.iobDialogText) }
}
// cob
var cobText = overviewData.cobInfo?.displayText(resourceHelper, dateUtil, buildHelper.isEngineeringMode()) ?: resourceHelper.gs(R.string.value_unavailable_short)
val constraintsProcessed = loopPlugin.lastRun?.constraintsProcessed
val lastRun = loopPlugin.lastRun
if (config.APS && constraintsProcessed != null && lastRun != null) {
if (constraintsProcessed.carbsReq > 0) {
//only display carbsreq when carbs have not been entered recently
if (overviewData.lastCarbsTime < lastRun.lastAPSRun) {
cobText += " | " + constraintsProcessed.carbsReq + " " + resourceHelper.gs(R.string.required)
}
if (carbAnimation?.isRunning == false)
carbAnimation?.start()
} else {
carbAnimation?.stop()
carbAnimation?.selectDrawable(0)
}
}
binding.infoLayout.cob.text = cobText
}
OverviewData.Property.TEMPORARY_TARGET -> {
// temp target
if (overviewData.temporaryTarget?.isInProgress(dateUtil) == false) overviewData.temporaryTarget = null
val tempTarget = overviewData.temporaryTarget
if (tempTarget != null) {
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning))
binding.tempTarget.text = Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, resourceHelper)
} else {
// If the target is not the same as set in the profile then oref has overridden it
profileFunction.getProfile()?.let { profile ->
val targetUsed = loopPlugin.lastRun?.constraintsProcessed?.targetBG ?: 0.0
if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) {
aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed")
binding.tempTarget.text = Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units)
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.tempTargetBackground))
} else {
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault))
binding.tempTarget.text = Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)
}
}
}
}
OverviewData.Property.GRAPH -> {
val graphData = GraphData(injector, binding.graphsLayout.bgGraph, overviewData)
val menuChartSettings = overviewMenus.setting
graphData.addInRangeArea(overviewData.fromTime, overviewData.endTime, defaultValueHelper.determineLowLine(), defaultValueHelper.determineHighLine())
graphData.addBgReadings(menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal])
if (buildHelper.isDev()) graphData.addBucketedData()
graphData.addTreatments()
if (menuChartSettings[0][OverviewMenus.CharType.ACT.ordinal])
graphData.addActivity(0.8)
if ((pump.pumpDescription.isTempBasalCapable || config.NSCLIENT) && menuChartSettings[0][OverviewMenus.CharType.BAS.ordinal])
graphData.addBasals()
graphData.addTargetLine()
graphData.addNowLine(dateUtil.now())
// set manual x bounds to have nice steps
graphData.setNumVerticalLabels()
graphData.formatAxis(overviewData.fromTime, overviewData.endTime)
graphData.performUpdate()
// 2nd graphs
prepareGraphsIfNeeded(menuChartSettings.size)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
val now = System.currentTimeMillis()
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], overviewData)
var useABSForScale = false
var useIobForScale = false
var useCobForScale = false
var useDevForScale = false
var useRatioForScale = false
var useDSForScale = false
var useBGIForScale = false
when {
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] -> useBGIForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
}
val alignDevBgiScale = menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] && menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]
if (menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(useABSForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(useIobForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(useCobForScale, if (useCobForScale) 1.0 else 0.5)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(useDevForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(useRatioForScale, if (useRatioForScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(useDSForScale, if(useDSForScale) 1.0 else 0.8, useRatioForScale)
// set manual x bounds to have nice steps
secondGraphData.formatAxis(overviewData.fromTime, overviewData.endTime)
secondGraphData.addNowLine(now)
secondaryGraphsData.add(secondGraphData)
}
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1)
secondaryGraphs[g].visibility = (
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal]
).toVisibility()
secondaryGraphsData[g].performUpdate()
}
}
OverviewData.Property.CALC_PROGRESS -> {
binding.graphsLayout.iobCalculationProgress.text = overviewData.calcProgress
}
OverviewData.Property.SENSITIVITY -> {
if (sp.getBoolean(R.string.key_openapsama_useautosens, false) && constraintChecker.isAutosensModeEnabled().value()) {
binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_swap_vert_black_48dp_green)
} else {
binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_x_swap_vert)
}
binding.infoLayout.sensitivity.text =
overviewData.lastAutosensData?.let { autosensData ->
String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100)
} ?: ""
}
OverviewData.Property.PUMPSTATUS -> {
val status = overviewData.pumpStatus
binding.pumpStatus.text = status
binding.pumpStatusLayout.visibility = (status != "").toVisibility()
} }
} }
} }
@Suppress("UNUSED_PARAMETER")
fun updateGraph(from: String) {
val pump = activePlugin.activePump
val graphData = GraphData(injector, binding.graphsLayout.bgGraph, overviewData)
val menuChartSettings = overviewMenus.setting
graphData.addInRangeArea(overviewData.fromTime, overviewData.endTime, defaultValueHelper.determineLowLine(), defaultValueHelper.determineHighLine())
graphData.addBgReadings(menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal])
if (buildHelper.isDev()) graphData.addBucketedData()
graphData.addTreatments()
if (menuChartSettings[0][OverviewMenus.CharType.ACT.ordinal])
graphData.addActivity(0.8)
if ((pump.pumpDescription.isTempBasalCapable || config.NSCLIENT) && menuChartSettings[0][OverviewMenus.CharType.BAS.ordinal])
graphData.addBasals()
graphData.addTargetLine()
graphData.addNowLine(dateUtil.now())
// set manual x bounds to have nice steps
graphData.setNumVerticalLabels()
graphData.formatAxis(overviewData.fromTime, overviewData.endTime)
graphData.performUpdate()
// 2nd graphs
prepareGraphsIfNeeded(menuChartSettings.size)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
val now = System.currentTimeMillis()
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], overviewData)
var useABSForScale = false
var useIobForScale = false
var useCobForScale = false
var useDevForScale = false
var useRatioForScale = false
var useDSForScale = false
var useBGIForScale = false
when {
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] -> useBGIForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
}
val alignDevBgiScale = menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] && menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]
if (menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(useABSForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(useIobForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(useCobForScale, if (useCobForScale) 1.0 else 0.5)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(useDevForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(useRatioForScale, if (useRatioForScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(
useDSForScale,
if (useDSForScale) 1.0 else 0.8,
useRatioForScale
)
// set manual x bounds to have nice steps
secondGraphData.formatAxis(overviewData.fromTime, overviewData.endTime)
secondGraphData.addNowLine(now)
secondaryGraphsData.add(secondGraphData)
}
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1)
secondaryGraphs[g].visibility = (
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal]
).toVisibility()
secondaryGraphsData[g].performUpdate()
}
}
@Suppress("UNUSED_PARAMETER")
fun updateCalcProgress(from: String) {
binding.graphsLayout.iobCalculationProgress.text = overviewData.calcProgress
}
@Suppress("UNUSED_PARAMETER")
fun updateSensitivity(from: String) {
if (sp.getBoolean(R.string.key_openapsama_useautosens, false) && constraintChecker.isAutosensModeEnabled().value()) {
binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_swap_vert_black_48dp_green)
} else {
binding.infoLayout.sensitivityIcon.setImageResource(R.drawable.ic_x_swap_vert)
}
binding.infoLayout.sensitivity.text =
overviewData.lastAutosensData?.let { autosensData ->
String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100)
} ?: ""
}
@Suppress("UNUSED_PARAMETER")
fun updatePumpStatus(from: String) {
val status = overviewData.pumpStatus
binding.pumpStatus.text = status
binding.pumpStatusLayout.visibility = (status != "").toVisibility()
}
@Suppress("UNUSED_PARAMETER")
fun updateNotification(from: String) {
binding.notifications.let { notificationStore.updateNotifications(it) }
}
} }

View file

@ -24,7 +24,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class OverviewMenus @Inject constructor( class OverviewMenus @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val buildHelper: BuildHelper, private val buildHelper: BuildHelper,
@ -53,7 +53,7 @@ class OverviewMenus @Inject constructor(
fun enabledTypes(graph: Int): String { fun enabledTypes(graph: Int): String {
val r = StringBuilder() val r = StringBuilder()
for (type in CharType.values()) if (_setting[graph][type.ordinal]) { for (type in CharType.values()) if (_setting[graph][type.ordinal]) {
r.append(resourceHelper.gs(type.shortnameId)) r.append(rh.gs(type.shortnameId))
r.append(" ") r.append(" ")
} }
return r.toString() return r.toString()
@ -102,7 +102,7 @@ class OverviewMenus @Inject constructor(
for (g in 0 until numOfGraphs) { for (g in 0 until numOfGraphs) {
if (g != 0 && g < numOfGraphs) { if (g != 0 && g < numOfGraphs) {
val dividerItem = popup.menu.add(Menu.NONE, g, Menu.NONE, "------- ${resourceHelper.gs(R.string.graph_menu_divider_header)} $g -------") val dividerItem = popup.menu.add(Menu.NONE, g, Menu.NONE, "------- ${rh.gs(R.string.graph_menu_divider_header)} $g -------")
dividerItem.isCheckable = true dividerItem.isCheckable = true
dividerItem.isChecked = true dividerItem.isChecked = true
} }
@ -117,10 +117,10 @@ class OverviewMenus @Inject constructor(
if (settingsCopy[g2][m.ordinal]) insert = false if (settingsCopy[g2][m.ordinal]) insert = false
} }
if (insert) { if (insert) {
val item = popup.menu.add(Menu.NONE, m.ordinal + 100 * (g + 1), Menu.NONE, resourceHelper.gs(m.nameId)) val item = popup.menu.add(Menu.NONE, m.ordinal + 100 * (g + 1), Menu.NONE, rh.gs(m.nameId))
val title = item.title val title = item.title
val s = SpannableString(title) val s = SpannableString(title)
s.setSpan(ForegroundColorSpan(resourceHelper.gc(m.colorId)), 0, s.length, 0) s.setSpan(ForegroundColorSpan(rh.gc(m.colorId)), 0, s.length, 0)
item.title = s item.title = s
item.isCheckable = true item.isCheckable = true
item.isChecked = settingsCopy[g][m.ordinal] item.isChecked = settingsCopy[g][m.ordinal]
@ -129,7 +129,7 @@ class OverviewMenus @Inject constructor(
} }
} }
if (numOfGraphs < MAX_GRAPHS) { if (numOfGraphs < MAX_GRAPHS) {
val dividerItem = popup.menu.add(Menu.NONE, numOfGraphs, Menu.NONE, "------- ${resourceHelper.gs(R.string.graph_menu_divider_header)} $numOfGraphs -------") val dividerItem = popup.menu.add(Menu.NONE, numOfGraphs, Menu.NONE, "------- ${rh.gs(R.string.graph_menu_divider_header)} $numOfGraphs -------")
dividerItem.isCheckable = true dividerItem.isCheckable = true
dividerItem.isChecked = false dividerItem.isChecked = false
} }

View file

@ -13,9 +13,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.events.EventLoopInvoked import info.nightscout.androidaps.plugins.aps.events.EventLoopInvoked
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.*
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverview
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.ScaledDataPoint import info.nightscout.androidaps.plugins.general.overview.graphExtensions.ScaledDataPoint
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
@ -41,15 +39,15 @@ class OverviewPlugin @Inject constructor(
private val sp: SP, private val sp: SP,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val config: Config, private val config: Config,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val profileFunction: ProfileFunction,
private val iobCobCalculator: IobCobCalculator, private val iobCobCalculator: IobCobCalculator,
private val repository: AppRepository, private val repository: AppRepository,
private val overviewData: OverviewData, private val overviewData: OverviewData,
private val overviewMenus: OverviewMenus private val overviewMenus: OverviewMenus
) : PluginBase(PluginDescription() ) : PluginBase(
PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment::class.qualifiedName) .fragmentClass(OverviewFragment::class.qualifiedName)
.alwaysVisible(true) .alwaysVisible(true)
@ -59,7 +57,7 @@ class OverviewPlugin @Inject constructor(
.shortName(R.string.overview_shortname) .shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview) .preferencesId(R.xml.pref_overview)
.description(R.string.description_overview), .description(R.string.description_overview),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Overview { ), Overview {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -75,85 +73,97 @@ class OverviewPlugin @Inject constructor(
notificationStore.createNotificationChannel() notificationStore.createNotificationChannel()
disposable += rxBus disposable += rxBus
.toObservable(EventNewNotification::class.java) .toObservable(EventNewNotification::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ n -> .subscribe({ n ->
if (notificationStore.add(n.notification)) if (notificationStore.add(n.notification))
rxBus.send(EventRefreshOverview("EventNewNotification")) rxBus.send(EventUpdateOverviewNotification("EventNewNotification"))
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventDismissNotification::class.java) .toObservable(EventDismissNotification::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ n -> .subscribe({ n ->
if (notificationStore.remove(n.id)) if (notificationStore.remove(n.id))
rxBus.send(EventRefreshOverview("EventDismissNotification")) rxBus.send(EventUpdateOverviewNotification("EventDismissNotification"))
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventIobCalculationProgress::class.java) .toObservable(EventIobCalculationProgress::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ overviewData.calcProgress = it.progress; overviewBus.send(EventUpdateOverview("EventIobCalculationProgress", OverviewData.Property.CALC_PROGRESS)) }, fabricPrivacy::logException) .subscribe({ overviewData.calcProgress = it.progress; overviewBus.send(EventUpdateOverviewCalcProgress("EventIobCalculationProgress")) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventTempBasalChange::class.java) .toObservable(EventTempBasalChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ loadTemporaryBasal("EventTempBasalChange") }, fabricPrivacy::logException) .subscribe({ overviewBus.send(EventUpdateOverviewTemporaryBasal("EventTempBasalChange")) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventExtendedBolusChange::class.java) .toObservable(EventExtendedBolusChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ loadExtendedBolus("EventExtendedBolusChange") }, fabricPrivacy::logException) .subscribe({ overviewBus.send(EventUpdateOverviewExtendedBolus("EventExtendedBolusChange")) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventNewBG::class.java) .toObservable(EventNewBG::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ loadBg("EventNewBG") }, fabricPrivacy::logException) .subscribe({ loadBg("EventNewBG") }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventTempTargetChange::class.java) .toObservable(EventTempTargetChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ loadTemporaryTarget("EventTempTargetChange") }, fabricPrivacy::logException) .subscribe({ loadTemporaryTarget("EventTempTargetChange") }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventTreatmentChange::class.java) .toObservable(EventTreatmentChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
loadIobCobResults("EventTreatmentChange") loadIobCobResults("EventTreatmentChange")
overviewData.prepareTreatmentsData("EventTreatmentChange") overviewData.prepareTreatmentsData("EventTreatmentChange")
overviewBus.send(EventUpdateOverview("EventTreatmentChange", OverviewData.Property.GRAPH)) overviewBus.send(EventUpdateOverviewGraph("EventTreatmentChange"))
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventTherapyEventChange::class.java) .toObservable(EventTherapyEventChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
overviewData.prepareTreatmentsData("EventTherapyEventChange") overviewData.prepareTreatmentsData("EventTherapyEventChange")
overviewBus.send(EventUpdateOverview("EventTherapyEventChange", OverviewData.Property.GRAPH)) overviewBus.send(EventUpdateOverviewGraph("EventTherapyEventChange"))
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventBucketedDataCreated::class.java) .toObservable(EventBucketedDataCreated::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
overviewData.prepareBucketedData("EventBucketedDataCreated") overviewData.prepareBucketedData("EventBucketedDataCreated")
overviewData.prepareBgData("EventBucketedDataCreated") overviewData.prepareBgData("EventBucketedDataCreated")
overviewBus.send(EventUpdateOverview("EventBucketedDataCreated", OverviewData.Property.GRAPH)) overviewBus.send(EventUpdateOverviewGraph("EventBucketedDataCreated"))
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventLoopInvoked::class.java) .toObservable(EventLoopInvoked::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ overviewData.preparePredictions("EventLoopInvoked") }, fabricPrivacy::logException) .subscribe({ overviewData.preparePredictions("EventLoopInvoked") }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventEffectiveProfileSwitchChanged::class.java) .toObservable(EventEffectiveProfileSwitchChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
loadProfile("EventEffectiveProfileSwitchChanged") loadProfile("EventEffectiveProfileSwitchChanged")
overviewData.prepareBasalData("EventEffectiveProfileSwitchChanged") overviewData.prepareBasalData("EventEffectiveProfileSwitchChanged")
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventAutosensCalculationFinished::class.java) .toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
if (it.cause !is EventCustomCalculationFinished) refreshLoop("EventAutosensCalculationFinished") if (it.cause !is EventCustomCalculationFinished) refreshLoop("EventAutosensCalculationFinished")
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus disposable += rxBus
.toObservable(EventPumpStatusChanged::class.java) .toObservable(EventPumpStatusChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
overviewData.pumpStatus = it.getStatus(resourceHelper) overviewData.pumpStatus = it.getStatus(rh)
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event ->
if (event.isChanged(rh, R.string.key_units)) {
overviewData.reset()
overviewData.prepareBucketedData("EventBucketedDataCreated")
overviewData.prepareBgData("EventBucketedDataCreated")
overviewBus.send(EventUpdateOverviewGraph("EventBucketedDataCreated"))
loadAll("EventPreferenceChange")
}
}, fabricPrivacy::logException)
Thread { loadAll("onResume") }.start() Thread { loadAll("onResume") }.start()
} }
@ -166,11 +176,11 @@ class OverviewPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) super.preprocessPreferences(preferenceFragment)
if (config.NSCLIENT) { if (config.NSCLIENT) {
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let { (preferenceFragment.findPreference(rh.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let {
it.isVisible = false it.isVisible = false
it.isEnabled = false it.isEnabled = false
} }
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let { (preferenceFragment.findPreference(rh.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let {
it.isVisible = false it.isVisible = false
it.isEnabled = false it.isEnabled = false
} }
@ -178,58 +188,58 @@ class OverviewPlugin @Inject constructor(
} }
override fun configuration(): JSONObject = override fun configuration(): JSONObject =
JSONObject() JSONObject()
.putInt(R.string.key_units, sp, resourceHelper) .putString(R.string.key_units, sp, rh)
.putString(R.string.key_quickwizard, sp, resourceHelper) .putString(R.string.key_quickwizard, sp, rh)
.putInt(R.string.key_eatingsoon_duration, sp, resourceHelper) .putInt(R.string.key_eatingsoon_duration, sp, rh)
.putDouble(R.string.key_eatingsoon_target, sp, resourceHelper) .putDouble(R.string.key_eatingsoon_target, sp, rh)
.putInt(R.string.key_activity_duration, sp, resourceHelper) .putInt(R.string.key_activity_duration, sp, rh)
.putDouble(R.string.key_activity_target, sp, resourceHelper) .putDouble(R.string.key_activity_target, sp, rh)
.putInt(R.string.key_hypo_duration, sp, resourceHelper) .putInt(R.string.key_hypo_duration, sp, rh)
.putDouble(R.string.key_hypo_target, sp, resourceHelper) .putDouble(R.string.key_hypo_target, sp, rh)
.putDouble(R.string.key_low_mark, sp, resourceHelper) .putDouble(R.string.key_low_mark, sp, rh)
.putDouble(R.string.key_high_mark, sp, resourceHelper) .putDouble(R.string.key_high_mark, sp, rh)
.putDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_cage_warning, sp, rh)
.putDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_cage_critical, sp, rh)
.putDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_iage_warning, sp, rh)
.putDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_iage_critical, sp, rh)
.putDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_sage_warning, sp, rh)
.putDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_sage_critical, sp, rh)
.putDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_sbat_warning, sp, rh)
.putDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_sbat_critical, sp, rh)
.putDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_bage_warning, sp, rh)
.putDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_bage_critical, sp, rh)
.putDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_res_warning, sp, rh)
.putDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_res_critical, sp, rh)
.putDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_bat_warning, sp, rh)
.putDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_bat_critical, sp, rh)
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
configuration configuration
.storeInt(R.string.key_units, sp, resourceHelper) .storeString(R.string.key_units, sp, rh)
.storeString(R.string.key_quickwizard, sp, resourceHelper) .storeString(R.string.key_quickwizard, sp, rh)
.storeInt(R.string.key_eatingsoon_duration, sp, resourceHelper) .storeInt(R.string.key_eatingsoon_duration, sp, rh)
.storeDouble(R.string.key_eatingsoon_target, sp, resourceHelper) .storeDouble(R.string.key_eatingsoon_target, sp, rh)
.storeInt(R.string.key_activity_duration, sp, resourceHelper) .storeInt(R.string.key_activity_duration, sp, rh)
.storeDouble(R.string.key_activity_target, sp, resourceHelper) .storeDouble(R.string.key_activity_target, sp, rh)
.storeInt(R.string.key_hypo_duration, sp, resourceHelper) .storeInt(R.string.key_hypo_duration, sp, rh)
.storeDouble(R.string.key_hypo_target, sp, resourceHelper) .storeDouble(R.string.key_hypo_target, sp, rh)
.storeDouble(R.string.key_low_mark, sp, resourceHelper) .storeDouble(R.string.key_low_mark, sp, rh)
.storeDouble(R.string.key_high_mark, sp, resourceHelper) .storeDouble(R.string.key_high_mark, sp, rh)
.storeDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_cage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_cage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_iage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_iage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sbat_warning, sp, rh)
.storeDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sbat_critical, sp, rh)
.storeDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_res_warning, sp, rh)
.storeDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_res_critical, sp, rh)
.storeDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bat_warning, sp, rh)
.storeDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bat_critical, sp, rh)
} }
@Volatile @Volatile
@ -237,22 +247,23 @@ class OverviewPlugin @Inject constructor(
override fun refreshLoop(from: String) { override fun refreshLoop(from: String) {
if (runningRefresh) return if (runningRefresh) return
runningRefresh = true runningRefresh = true
overviewBus.send(EventUpdateOverviewNotification(from))
loadIobCobResults(from) loadIobCobResults(from)
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.PROFILE)) overviewBus.send(EventUpdateOverviewProfile(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.BG)) overviewBus.send(EventUpdateOverviewBg(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TIME)) overviewBus.send(EventUpdateOverviewTime(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_BASAL)) overviewBus.send(EventUpdateOverviewTemporaryBasal(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.EXTENDED_BOLUS)) overviewBus.send(EventUpdateOverviewExtendedBolus(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_TARGET)) overviewBus.send(EventUpdateOverviewTemporaryTarget(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.SENSITIVITY)) overviewBus.send(EventUpdateOverviewSensitivity(from))
loadAsData(from) loadAsData(from)
overviewData.preparePredictions(from) overviewData.preparePredictions(from)
overviewData.prepareBasalData(from) overviewData.prepareBasalData(from)
overviewData.prepareTemporaryTargetData(from) overviewData.prepareTemporaryTargetData(from)
overviewData.prepareTreatmentsData(from) overviewData.prepareTreatmentsData(from)
overviewData.prepareIobAutosensData(from) overviewData.prepareIobAutosensData(from)
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.GRAPH)) overviewBus.send(EventUpdateOverviewGraph(from))
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.IOB_COB)) overviewBus.send(EventUpdateOverviewIobCob(from))
aapsLogger.debug(LTag.UI, "refreshLoop finished") aapsLogger.debug(LTag.UI, "refreshLoop finished")
runningRefresh = false runningRefresh = false
} }
@ -261,8 +272,6 @@ class OverviewPlugin @Inject constructor(
private fun loadAll(from: String) { private fun loadAll(from: String) {
loadBg(from) loadBg(from)
loadProfile(from) loadProfile(from)
loadTemporaryBasal(from)
loadExtendedBolus(from)
loadTemporaryTarget(from) loadTemporaryTarget(from)
loadIobCobResults(from) loadIobCobResults(from)
loadAsData(from) loadAsData(from)
@ -271,41 +280,31 @@ class OverviewPlugin @Inject constructor(
overviewData.prepareTreatmentsData(from) overviewData.prepareTreatmentsData(from)
// prepareIobAutosensData(from) // prepareIobAutosensData(from)
// preparePredictions(from) // preparePredictions(from)
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.GRAPH)) overviewBus.send(EventUpdateOverviewGraph(from))
aapsLogger.debug(LTag.UI, "loadAll finished") aapsLogger.debug(LTag.UI, "loadAll finished")
} }
private fun loadProfile(from: String) { private fun loadProfile(from: String) {
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.PROFILE)) overviewBus.send(EventUpdateOverviewProfile(from))
}
private fun loadTemporaryBasal(from: String) {
overviewData.temporaryBasal = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_BASAL))
}
private fun loadExtendedBolus(from: String) {
overviewData.extendedBolus = iobCobCalculator.getExtendedBolus(dateUtil.now())
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.EXTENDED_BOLUS))
} }
private fun loadTemporaryTarget(from: String) { private fun loadTemporaryTarget(from: String) {
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) overviewData.temporaryTarget = tempTarget.value if (tempTarget is ValueWrapper.Existing) overviewData.temporaryTarget = tempTarget.value
else overviewData.temporaryTarget = null else overviewData.temporaryTarget = null
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_TARGET)) overviewBus.send(EventUpdateOverviewTemporaryTarget(from))
} }
private fun loadAsData(from: String) { private fun loadAsData(from: String) {
overviewData.lastAutosensData = iobCobCalculator.ads.getLastAutosensData("Overview", aapsLogger, dateUtil) overviewData.lastAutosensData = iobCobCalculator.ads.getLastAutosensData("Overview", aapsLogger, dateUtil)
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.SENSITIVITY)) overviewBus.send(EventUpdateOverviewSensitivity(from))
} }
private fun loadBg(from: String) { private fun loadBg(from: String) {
val gvWrapped = repository.getLastGlucoseValueWrapped().blockingGet() val gvWrapped = repository.getLastGlucoseValueWrapped().blockingGet()
if (gvWrapped is ValueWrapper.Existing) overviewData.lastBg = gvWrapped.value if (gvWrapped is ValueWrapper.Existing) overviewData.lastBg = gvWrapped.value
else overviewData.lastBg = null else overviewData.lastBg = null
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.BG)) overviewBus.send(EventUpdateOverviewBg(from))
} }
private fun loadIobCobResults(from: String) { private fun loadIobCobResults(from: String) {
@ -315,7 +314,7 @@ class OverviewPlugin @Inject constructor(
val lastCarbs = repository.getLastCarbsRecordWrapped().blockingGet() val lastCarbs = repository.getLastCarbsRecordWrapped().blockingGet()
overviewData.lastCarbsTime = if (lastCarbs is ValueWrapper.Existing) lastCarbs.value.timestamp else 0L overviewData.lastCarbsTime = if (lastCarbs is ValueWrapper.Existing) lastCarbs.value.timestamp else 0L
overviewBus.send(EventUpdateOverview(from, OverviewData.Property.IOB_COB)) overviewBus.send(EventUpdateOverviewIobCob(from))
} }
} }

View file

@ -23,7 +23,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class StatusLightHandler @Inject constructor( class StatusLightHandler @Inject constructor(
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -59,7 +59,7 @@ class StatusLightHandler @Inject constructor(
if (!config.NSCLIENT) { if (!config.NSCLIENT) {
if (pump.model() == PumpType.OMNIPOD_DASH) { if (pump.model() == PumpType.OMNIPOD_DASH) {
// Omnipod Dash does not report its battery level // Omnipod Dash does not report its battery level
careportal_battery_level?.text = resourceHelper.gs(R.string.notavailable) careportal_battery_level?.text = rh.gs(R.string.notavailable)
careportal_battery_level?.setTextColor(Color.WHITE) careportal_battery_level?.setTextColor(Color.WHITE)
} else if (pump.model() == PumpType.OMNIPOD_EROS && pump is OmnipodErosPumpPlugin) { // instance of check is needed because at startup, pump can still be VirtualPumpPlugin and that will cause a crash because of the class cast below } else if (pump.model() == PumpType.OMNIPOD_EROS && pump is OmnipodErosPumpPlugin) { // instance of check is needed because at startup, pump can still be VirtualPumpPlugin and that will cause a crash because of the class cast below
// The Omnipod Eros does not report its battery level. However, some RileyLink alternatives do. // The Omnipod Eros does not report its battery level. However, some RileyLink alternatives do.
@ -77,9 +77,9 @@ class StatusLightHandler @Inject constructor(
val therapyEvent = repository.getLastTherapyRecordUpToNow(type).blockingGet() val therapyEvent = repository.getLastTherapyRecordUpToNow(type).blockingGet()
if (therapyEvent is ValueWrapper.Existing) { if (therapyEvent is ValueWrapper.Existing) {
warnColors.setColorByAge(view, therapyEvent.value, warn, urgent) warnColors.setColorByAge(view, therapyEvent.value, warn, urgent)
view?.text = therapyEvent.value.age(resourceHelper.shortTextMode(), resourceHelper, dateUtil) view?.text = therapyEvent.value.age(rh.shortTextMode(), rh, dateUtil)
} else { } else {
view?.text = if (resourceHelper.shortTextMode()) "-" else resourceHelper.gs(R.string.notavailable) view?.text = if (rh.shortTextMode()) "-" else rh.gs(R.string.notavailable)
} }
} }
@ -108,7 +108,7 @@ class StatusLightHandler @Inject constructor(
if (useRileyLinkBatteryLevel) { if (useRileyLinkBatteryLevel) {
handleLevel(view, criticalSetting, criticalDefaultValue, warnSetting, warnDefaultValue, level, units) handleLevel(view, criticalSetting, criticalDefaultValue, warnSetting, warnDefaultValue, level, units)
} else { } else {
view?.text = resourceHelper.gs(R.string.notavailable) view?.text = rh.gs(R.string.notavailable)
view?.setTextColor(Color.WHITE) view?.setTextColor(Color.WHITE)
} }
} }

View file

@ -45,7 +45,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
holder.from.text = dateUtil.timeString(quickWizard[position].validFromDate()) holder.from.text = dateUtil.timeString(quickWizard[position].validFromDate())
holder.to.text = dateUtil.timeString(quickWizard[position].validToDate()) holder.to.text = dateUtil.timeString(quickWizard[position].validToDate())
holder.buttonText.text = quickWizard[position].buttonText() holder.buttonText.text = quickWizard[position].buttonText()
holder.carbs.text = resourceHelper.gs(R.string.format_carbs, quickWizard[position].carbs()) holder.carbs.text = rh.gs(R.string.format_carbs, quickWizard[position].carbs())
} }
override fun getItemCount(): Int = quickWizard.size() override fun getItemCount(): Int = quickWizard.size()

View file

@ -100,19 +100,19 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener {
val toTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> val toTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
toSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt() toSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt()
binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds))
} }
binding.to.setOnClickListener { binding.to.setOnClickListener {
context?.let { context?.let {
TimePickerDialog(it, toTimeSetListener, TimePickerDialog(it, toTimeSetListener,
T.secs(fromSeconds.toLong()).hours().toInt(), T.secs(toSeconds.toLong()).hours().toInt(),
T.secs((fromSeconds % 3600).toLong()).mins().toInt(), T.secs((toSeconds % 3600).toLong()).mins().toInt(),
DateFormat.is24HourFormat(context) DateFormat.is24HourFormat(context)
).show() ).show()
} }
} }
toSeconds = entry.validFrom() toSeconds = entry.validTo()
binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds))
binding.buttonEdit.setText(entry.buttonText()) binding.buttonEdit.setText(entry.buttonText())

View file

@ -1,6 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.plugins.general.overview.OverviewData
class EventUpdateOverview(val from: String, val what: OverviewData.Property) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewBg(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewCalcProgress(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewExtendedBolus(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewGraph(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewIobCob(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewNotification(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewProfile(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewPumpStatus(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewSensitivity(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewTemporaryBasal(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewTemporaryTarget(val from: String) : Event()

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventUpdateOverviewTime(val from: String) : Event()

View file

@ -32,7 +32,7 @@ class GraphData(
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
private var maxY = Double.MIN_VALUE private var maxY = Double.MIN_VALUE
@ -66,7 +66,7 @@ class GraphData(
addSeries(AreaGraphSeries(inRangeAreaDataPoints).also { addSeries(AreaGraphSeries(inRangeAreaDataPoints).also {
it.color = 0 it.color = 0
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = resourceHelper.gc(R.color.inrangebackground) it.backgroundColor = rh.gc(R.color.inrangebackground)
}) })
} }

View file

@ -11,7 +11,7 @@ import javax.inject.Inject
class BolusDataPoint @Inject constructor( class BolusDataPoint @Inject constructor(
val data: Bolus, val data: Bolus,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val defaultValueHelper: DefaultValueHelper private val defaultValueHelper: DefaultValueHelper
) : DataPointWithLabelInterface { ) : DataPointWithLabelInterface {
@ -20,7 +20,7 @@ class BolusDataPoint @Inject constructor(
override fun getX(): Double = data.timestamp.toDouble() override fun getX(): Double = data.timestamp.toDouble()
override fun getY(): Double = if (data.type == Bolus.Type.SMB) defaultValueHelper.determineLowLine() else yValue override fun getY(): Double = if (data.type == Bolus.Type.SMB) defaultValueHelper.determineLowLine() else yValue
override fun getLabel(): String = DecimalFormatter.toPumpSupportedBolus(data.amount, activePlugin.activePump, resourceHelper) override fun getLabel(): String = DecimalFormatter.toPumpSupportedBolus(data.amount, activePlugin.activePump, rh)
override fun getDuration(): Long = 0 override fun getDuration(): Long = 0
override fun getSize(): Float = 2f override fun getSize(): Float = 2f
@ -29,9 +29,9 @@ class BolusDataPoint @Inject constructor(
else PointsWithLabelGraphSeries.Shape.BOLUS else PointsWithLabelGraphSeries.Shape.BOLUS
override fun getColor(): Int = override fun getColor(): Int =
if (data.type == Bolus.Type.SMB) resourceHelper.gc(R.color.tempbasal) if (data.type == Bolus.Type.SMB) rh.gc(R.color.tempbasal)
else if (data.isValid) Color.CYAN else if (data.isValid) Color.CYAN
else resourceHelper.gc(android.R.color.holo_red_light) else rh.gc(android.R.color.holo_red_light)
override fun setY(y: Double) { override fun setY(y: Double) {
yValue = y yValue = y

View file

@ -7,22 +7,22 @@ import javax.inject.Inject
class CarbsDataPoint @Inject constructor( class CarbsDataPoint @Inject constructor(
val data: Carbs, val data: Carbs,
private val resourceHelper: ResourceHelper private val rh: ResourceHelper
) : DataPointWithLabelInterface { ) : DataPointWithLabelInterface {
private var yValue = 0.0 private var yValue = 0.0
override fun getX(): Double = data.timestamp.toDouble() override fun getX(): Double = data.timestamp.toDouble()
override fun getY(): Double = yValue override fun getY(): Double = yValue
override fun getLabel(): String = resourceHelper.gs(R.string.format_carbs, data.amount.toInt()) override fun getLabel(): String = rh.gs(R.string.format_carbs, data.amount.toInt())
override fun getDuration(): Long = 0 override fun getDuration(): Long = 0
override fun getSize(): Float = 2f override fun getSize(): Float = 2f
override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.CARBS override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.CARBS
override fun getColor(): Int = override fun getColor(): Int =
if (data.isValid) resourceHelper.gc(R.color.carbs) if (data.isValid) rh.gc(R.color.carbs)
else resourceHelper.gc(android.R.color.holo_red_light) else rh.gc(android.R.color.holo_red_light)
override fun setY(y: Double) { override fun setY(y: Double) {
yValue = y yValue = y

View file

@ -13,7 +13,7 @@ class GlucoseValueDataPoint @Inject constructor(
val data: GlucoseValue, val data: GlucoseValue,
private val defaultValueHelper: DefaultValueHelper, private val defaultValueHelper: DefaultValueHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val resourceHelper: ResourceHelper private val rh: ResourceHelper
) : DataPointWithLabelInterface { ) : DataPointWithLabelInterface {
fun valueToUnits(units: GlucoseUnit): Double = fun valueToUnits(units: GlucoseUnit): Double =
@ -42,20 +42,20 @@ class GlucoseValueDataPoint @Inject constructor(
val highLine = defaultValueHelper.determineHighLine() val highLine = defaultValueHelper.determineHighLine()
return when { return when {
isPrediction -> predictionColor isPrediction -> predictionColor
valueToUnits(units) < lowLine -> resourceHelper.gc(R.color.low) valueToUnits(units) < lowLine -> rh.gc(R.color.low)
valueToUnits(units) > highLine -> resourceHelper.gc(R.color.high) valueToUnits(units) > highLine -> rh.gc(R.color.high)
else -> resourceHelper.gc(R.color.inrange) else -> rh.gc(R.color.inrange)
} }
} }
val predictionColor: Int val predictionColor: Int
get() { get() {
return when (data.sourceSensor) { return when (data.sourceSensor) {
GlucoseValue.SourceSensor.IOB_PREDICTION -> resourceHelper.gc(R.color.iob) GlucoseValue.SourceSensor.IOB_PREDICTION -> rh.gc(R.color.iob)
GlucoseValue.SourceSensor.COB_PREDICTION -> resourceHelper.gc(R.color.cob) GlucoseValue.SourceSensor.COB_PREDICTION -> rh.gc(R.color.cob)
GlucoseValue.SourceSensor.A_COB_PREDICTION -> -0x7f000001 and resourceHelper.gc(R.color.cob) GlucoseValue.SourceSensor.A_COB_PREDICTION -> -0x7f000001 and rh.gc(R.color.cob)
GlucoseValue.SourceSensor.UAM_PREDICTION -> resourceHelper.gc(R.color.uam) GlucoseValue.SourceSensor.UAM_PREDICTION -> rh.gc(R.color.uam)
GlucoseValue.SourceSensor.ZT_PREDICTION -> resourceHelper.gc(R.color.zt) GlucoseValue.SourceSensor.ZT_PREDICTION -> rh.gc(R.color.zt)
else -> R.color.white else -> R.color.white
} }
} }

View file

@ -11,7 +11,7 @@ import javax.inject.Inject
class InMemoryGlucoseValueDataPoint @Inject constructor( class InMemoryGlucoseValueDataPoint @Inject constructor(
val data: InMemoryGlucoseValue, val data: InMemoryGlucoseValue,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val resourceHelper: ResourceHelper private val rh: ResourceHelper
) : DataPointWithLabelInterface { ) : DataPointWithLabelInterface {
fun valueToUnits(units: GlucoseUnit): Double = fun valueToUnits(units: GlucoseUnit): Double =
@ -24,5 +24,5 @@ class InMemoryGlucoseValueDataPoint @Inject constructor(
override fun getDuration(): Long = 0 override fun getDuration(): Long = 0
override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.BUCKETED_BG override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.BUCKETED_BG
override fun getSize(): Float = 0.3f override fun getSize(): Float = 0.3f
override fun getColor(): Int = resourceHelper.gc(R.color.white) override fun getColor(): Int = rh.gc(R.color.white)
} }

View file

@ -12,7 +12,7 @@ import javax.inject.Inject
class TherapyEventDataPoint @Inject constructor( class TherapyEventDataPoint @Inject constructor(
val data: TherapyEvent, val data: TherapyEvent,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val translator: Translator private val translator: Translator
) : DataPointWithLabelInterface { ) : DataPointWithLabelInterface {
@ -62,10 +62,10 @@ class TherapyEventDataPoint @Inject constructor(
else -> PointsWithLabelGraphSeries.Shape.GENERAL else -> PointsWithLabelGraphSeries.Shape.GENERAL
} }
override fun getSize(): Float = if (resourceHelper.gb(R.bool.isTablet)) 12.0f else 10.0f override fun getSize(): Float = if (rh.gb(R.bool.isTablet)) 12.0f else 10.0f
override fun getColor(): Int = override fun getColor(): Int =
when (data.type) { when (data.type) {
TherapyEvent.Type.ANNOUNCEMENT -> resourceHelper.gc(R.color.notificationAnnouncement) TherapyEvent.Type.ANNOUNCEMENT -> rh.gc(R.color.notificationAnnouncement)
TherapyEvent.Type.NS_MBG -> Color.RED TherapyEvent.Type.NS_MBG -> Color.RED
TherapyEvent.Type.FINGER_STICK_BG_VALUE -> Color.RED TherapyEvent.Type.FINGER_STICK_BG_VALUE -> Color.RED
TherapyEvent.Type.EXERCISE -> Color.BLUE TherapyEvent.Type.EXERCISE -> Color.BLUE

Some files were not shown because too many files have changed in this diff Show more