diff --git a/app/build.gradle b/app/build.gradle index da23b2ff7f..6694ec1639 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -109,7 +109,7 @@ android { defaultConfig { multiDexEnabled true versionCode 1500 - version "2.8.2.8-dev" + version "2.8.2.10-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index c7a4b5b447..0db09d5348 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -113,7 +113,7 @@ class MainActivity : NoSplashAppCompatActivity() { } // 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() { override fun onPageScrollStateChanged(state: 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 - if (!loopPlugin.isEnabled(PluginType.LOOP)) versionCheckerUtils.triggerCheckVersion() + if (!loopPlugin.isEnabled()) versionCheckerUtils.triggerCheckVersion() setUserStats() setupViews() disposable += rxBus @@ -146,7 +146,7 @@ class MainActivity : NoSplashAppCompatActivity() { } androidPermission.notifyForStoragePermission(this) androidPermission.notifyForBatteryOptimizationPermission(this) - androidPermission.notifyForLocationPermissions(this) + if (!config.NSCLIENT) androidPermission.notifyForLocationPermissions(this) if (config.PUMPDRIVERS) { androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin) androidPermission.notifyForSystemWindowPermissions(this) @@ -173,8 +173,8 @@ class MainActivity : NoSplashAppCompatActivity() { override fun onResume() { super.onResume() protectionCheck.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null, - UIRunnable { OKDialog.show(this, "", resourceHelper.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() } }, + UIRunnable { OKDialog.show(this, "", rh.gs(R.string.authorizationfailed)) { finish() } } ) } @@ -184,8 +184,8 @@ class MainActivity : NoSplashAppCompatActivity() { } private fun processPreferenceChange(ev: EventPreferenceChange) { - if (ev.isChanged(resourceHelper, R.string.key_keep_screen_on)) setWakeLock() - if (ev.isChanged(resourceHelper, R.string.key_skin)) recreate() + if (ev.isChanged(rh, R.string.key_keep_screen_on)) setWakeLock() + if (ev.isChanged(rh, R.string.key_skin)) recreate() } private fun setupViews() { @@ -259,7 +259,7 @@ class MainActivity : NoSplashAppCompatActivity() { private fun setPluginPreferenceMenuName() { if (binding.mainPager.currentItem >= 0) { 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 -> { var message = "Build: ${BuildConfig.BUILDVERSION}\n" message += "Flavor: ${BuildConfig.FLAVOR}${BuildConfig.BUILD_TYPE}\n" - message += "${resourceHelper.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.getVersion()}" - if (buildHelper.isEngineeringMode()) message += "\n${resourceHelper.gs(R.string.engineering_mode_enabled)}" - if (!fabricPrivacy.fabricEnabled()) message += "\n${resourceHelper.gs(R.string.fabric_upload_disabled)}" - message += resourceHelper.gs(R.string.about_link_urls) + message += "${rh.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.getVersion()}" + if (buildHelper.isEngineeringMode()) message += "\n${rh.gs(R.string.engineering_mode_enabled)}" + if (!fabricPrivacy.fabricEnabled()) message += "\n${rh.gs(R.string.fabric_upload_disabled)}" + message += rh.gs(R.string.about_link_urls) val messageSpanned = SpannableString(message) Linkify.addLinks(messageSpanned, Linkify.WEB_URLS) AlertDialog.Builder(this) - .setTitle(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION) + .setTitle(rh.gs(R.string.app_name) + " " + BuildConfig.VERSION) .setIcon(iconsProvider.getIcon()) .setMessage(messageSpanned) - .setPositiveButton(resourceHelper.gs(R.string.ok), null) - .setNeutralButton(resourceHelper.gs(R.string.cta_dont_kill_my_app_info)) { _, _ -> DokiActivity.start(context = this@MainActivity) } + .setPositiveButton(rh.gs(R.string.ok), null) + .setNeutralButton(rh.gs(R.string.cta_dont_kill_my_app_info)) { _, _ -> DokiActivity.start(context = this@MainActivity) } .create().apply { show() findViewById(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance() diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt index ebf2360320..74d46d6b39 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt @@ -89,8 +89,8 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { setContentView(binding.root) // 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) - overviewData = OverviewData(injector, aapsLogger, resourceHelper, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, config, loopPlugin, nsDeviceStatus, repository, overviewMenus, iobCobCalculator, translator) + iobCobCalculator = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, rh, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) + overviewData = OverviewData(injector, aapsLogger, rh, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, config, loopPlugin, nsDeviceStatus, repository, overviewMenus, iobCobCalculator, translator) binding.left.setOnClickListener { 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 - 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?.labelVerticalWidth = axisWidth @@ -241,8 +241,8 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) 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.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) + 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 = rh.gc(R.color.graphgrid) graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth @@ -251,7 +251,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { relativeLayout.addView(graph) 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_LEFT) label.layoutParams = layoutParams diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 81190a0769..143919db87 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -62,7 +62,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang private var filter = "" @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var pluginStore: PluginStore @@ -197,21 +197,21 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { rxBus.send(EventPreferenceChange(key)) - if (key == resourceHelper.gs(R.string.key_language)) { + if (key == rh.gs(R.string.key_language)) { rxBus.send(EventRebuildTabs(true)) //recreate() does not update language so better close settings activity?.finish() } - if (key == resourceHelper.gs(R.string.key_short_tabtitles)) { + if (key == rh.gs(R.string.key_short_tabtitles)) { rxBus.send(EventRebuildTabs()) } - if (key == resourceHelper.gs(R.string.key_units)) { + if (key == rh.gs(R.string.key_units)) { activity?.recreate() 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 { - 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) @@ -228,15 +228,15 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang private fun checkForBiometricFallback(key: String) { // Biometric protection activated without set master password - if ((resourceHelper.gs(R.string.key_settings_protection) == key || - resourceHelper.gs(R.string.key_application_protection) == key || - resourceHelper.gs(R.string.key_bolus_protection) == key) && + if ((rh.gs(R.string.key_settings_protection) == key || + rh.gs(R.string.key_application_protection) == key || + rh.gs(R.string.key_bolus_protection) == key) && sp.getString(R.string.key_master_password, "") == "" && sp.getInt(key, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal ) { activity?.let { - val title = resourceHelper.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 title = rh.gs(R.string.unsecure_fallback_biometric) + 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) } } @@ -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 || 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 - 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 { - val title = resourceHelper.gs(R.string.unsecure_fallback_biometric) - val message = resourceHelper.gs(R.string.unsecure_fallback_descriotion_biometric) + val title = rh.gs(R.string.unsecure_fallback_biometric) + val message = rh.gs(R.string.unsecure_fallback_descriotion_biometric) 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 val unitDependent = arrayOf( - resourceHelper.gs(R.string.key_hypo_target), - resourceHelper.gs(R.string.key_activity_target), - resourceHelper.gs(R.string.key_eatingsoon_target), - resourceHelper.gs(R.string.key_high_mark), - resourceHelper.gs(R.string.key_low_mark) + rh.gs(R.string.key_hypo_target), + rh.gs(R.string.key_activity_target), + rh.gs(R.string.key_eatingsoon_target), + rh.gs(R.string.key_high_mark), + rh.gs(R.string.key_low_mark) ) if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) { val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text)) @@ -322,20 +322,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang pref.setSummary(pref.entry) // Preferences // Preferences - if (pref.getKey() == resourceHelper.gs(R.string.key_settings_protection)) { - val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_settings_password)) + if (pref.getKey() == rh.gs(R.string.key_settings_protection)) { + val pass: Preference? = findPreference(rh.gs(R.string.key_settings_password)) if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() } // Application // Application - if (pref.getKey() == resourceHelper.gs(R.string.key_application_protection)) { - val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_application_password)) + if (pref.getKey() == rh.gs(R.string.key_application_protection)) { + val pass: Preference? = findPreference(rh.gs(R.string.key_application_password)) if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() } // Bolus // Bolus - if (pref.getKey() == resourceHelper.gs(R.string.key_bolus_protection)) { - val pass: Preference? = findPreference(resourceHelper.gs(R.string.key_bolus_password)) + if (pref.getKey() == rh.gs(R.string.key_bolus_protection)) { + val pass: Preference? = findPreference(rh.gs(R.string.key_bolus_password)) if (pass != null) pass.isEnabled = pref.value == ProtectionCheck.ProtectionType.CUSTOM_PASSWORD.ordinal.toString() } } @@ -353,10 +353,10 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } val hmacPasswords = arrayOf( - resourceHelper.gs(R.string.key_bolus_password), - resourceHelper.gs(R.string.key_master_password), - resourceHelper.gs(R.string.key_application_password), - resourceHelper.gs(R.string.key_settings_password) + rh.gs(R.string.key_bolus_password), + rh.gs(R.string.key_master_password), + rh.gs(R.string.key_application_password), + rh.gs(R.string.key_settings_password) ) if (pref is Preference) { @@ -364,7 +364,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang if (sp.getString(pref.key, "").startsWith("hmac:")) { pref.summary = "******" } 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 { context?.let { context -> 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.setPassword(context, R.string.master_password, R.string.key_master_password) }) 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) 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) 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) return true } // 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) return true } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt index d209670b01..edff599122 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt @@ -31,7 +31,7 @@ class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompa override fun afterTextChanged(s: Editable) {} }) - title = resourceHelper.gs(R.string.nav_preferences) + title = rh.gs(R.string.nav_preferences) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) myPreferenceFragment = MyPreferenceFragment() diff --git a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt index 9e0bd5db90..eb69d5658f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt @@ -140,7 +140,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { 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()) 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 " + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) .replace(".", "/") @@ -168,7 +168,11 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { 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 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 = 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.DPV_DEFAULT -> resourceHelper.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt()) + ProfileType.MOTOL_DEFAULT -> if (tdd > 0) rh.gs(R.string.formatwithtdd, age, tdd) else rh.gs(R.string.formatwithweight, age, weight) + ProfileType.DPV_DEFAULT -> rh.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt()) ProfileType.CURRENT -> profileFunction.getProfileName() ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString() ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].originalCustomizedName @@ -263,16 +267,16 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { tabSelected = tab 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 binding.profiletype.setText( when (typeSelected[tabSelected]) { - ProfileType.MOTOL_DEFAULT -> resourceHelper.gs(R.string.motoldefaultprofile) - ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.dpvdefaultprofile) - ProfileType.CURRENT -> resourceHelper.gs(R.string.currentprofile) - ProfileType.AVAILABLE_PROFILE -> resourceHelper.gs(R.string.availableprofile) - ProfileType.PROFILE_SWITCH -> resourceHelper.gs(R.string.careportal_profileswitch) + ProfileType.MOTOL_DEFAULT -> rh.gs(R.string.motoldefaultprofile) + ProfileType.DPV_DEFAULT -> rh.gs(R.string.dpvdefaultprofile) + ProfileType.CURRENT -> rh.gs(R.string.currentprofile) + ProfileType.AVAILABLE_PROFILE -> rh.gs(R.string.availableprofile) + ProfileType.PROFILE_SWITCH -> rh.gs(R.string.careportal_profileswitch) }) binding.defaultProfile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility() binding.currentProfile.visibility = (newContent == ProfileType.CURRENT).toVisibility() @@ -293,7 +297,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { } private fun setBackgroundColorOnSelected(tab: Int) { - binding.menu1.setBackgroundColor(resourceHelper.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.menu1.setBackgroundColor(rh.gc(if (tab == 1) R.color.defaultbackground else R.color.tempbasal)) + binding.menu2.setBackgroundColor(rh.gc(if (tab == 0) R.color.defaultbackground else R.color.examinedProfile)) } } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt index 82912e3da3..1ad4bb826f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt @@ -9,6 +9,7 @@ import info.nightscout.androidaps.databinding.ActivityStatsBinding import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.utils.ActivityMonitor 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.TirCalculator import javax.inject.Inject @@ -28,9 +29,9 @@ class StatsActivity : NoSplashAppCompatActivity() { binding = ActivityStatsBinding.inflate(layoutInflater) setContentView(binding.root) - binding.tdds.text = getString(R.string.tdd) + ": " + getString(R.string.calculation_in_progress) - binding.tir.text = getString(R.string.tir) + ": " + getString(R.string.calculation_in_progress) - binding.activity.text = getString(R.string.activitymonitor) + ": " + 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) + ": " + rh.gs(R.string.calculation_in_progress) + binding.activity.text = rh.gs(R.string.activitymonitor) + ": " + rh.gs(R.string.calculation_in_progress) Thread { val tdds = tddCalculator.stats() @@ -47,7 +48,7 @@ class StatsActivity : NoSplashAppCompatActivity() { binding.ok.setOnClickListener { finish() } 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) activityMonitor.reset() recreate() diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TreatmentsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/TreatmentsActivity.kt index 4cd4ab559a..9a68aeaf5f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TreatmentsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/TreatmentsActivity.kt @@ -24,8 +24,8 @@ class TreatmentsActivity : NoSplashAppCompatActivity() { binding = TreatmentsFragmentBinding.inflate(layoutInflater) setContentView(binding.root) - binding.tempBasals.visibility = buildHelper.isEngineeringMode().toVisibility() - binding.extendedBoluses.visibility = (buildHelper.isEngineeringMode() && !activePlugin.activePump.isFakingTempsByExtendedBoluses).toVisibility() + //binding.tempBasals.visibility = buildHelper.isEngineeringMode().toVisibility() + //binding.extendedBoluses.visibility = (buildHelper.isEngineeringMode() && !activePlugin.activePump.isFakingTempsByExtendedBoluses).toVisibility() binding.treatments.setOnClickListener { setFragment(TreatmentsBolusCarbsFragment()) @@ -67,14 +67,14 @@ class TreatmentsActivity : NoSplashAppCompatActivity() { } private fun setBackgroundColorOnSelected(selected: View) { - binding.treatments.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.extendedBoluses.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.tempBasals.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.tempTargets.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.profileSwitches.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.careportal.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.userentry.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - selected.setBackgroundColor(resourceHelper.gc(R.color.tabBgColorSelected)) + binding.treatments.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.extendedBoluses.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.tempBasals.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.tempTargets.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.profileSwitches.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.careportal.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.userentry.setBackgroundColor(rh.gc(R.color.defaultbackground)) + selected.setBackgroundColor(rh.gc(R.color.tabBgColorSelected)) } } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt index e8c653ba33..cbcd80783e 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt @@ -56,7 +56,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @@ -93,7 +93,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { binding.refreshFromNightscout.setOnClickListener { 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) disposable += Completable.fromAction { @@ -116,7 +116,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { } binding.deleteFutureTreatments.setOnClickListener { 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) repository .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() ml.bolus?.let { bolus -> 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.bolusPump.visibility = (bolus.interfaceIDs.pumpId != null).toVisibility() holder.binding.bolusInvalid.visibility = bolus.isValid.not().toVisibility() 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.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 = when (ml.bolus.type) { Bolus.Type.SMB -> "SMB" - Bolus.Type.NORMAL -> resourceHelper.gs(R.string.mealbolus) - Bolus.Type.PRIMING -> resourceHelper.gs(R.string.prime) + Bolus.Type.NORMAL -> rh.gs(R.string.mealbolus) + Bolus.Type.PRIMING -> rh.gs(R.string.prime) } } // Carbs holder.binding.carbsLayout.visibility = (ml.carbs != null && (ml.carbs.isValid || binding.showInvalidated.isChecked)).toVisibility() ml.carbs?.let { carbs -> holder.binding.carbsDate.text = dateUtil.timeString(carbs.timestamp) - holder.binding.carbs.text = resourceHelper.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.carbs.text = rh.gs(R.string.format_carbs, carbs.amount.toInt()) + 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.carbsPump.visibility = (carbs.interfaceIDs.pumpId != null).toVisibility() holder.binding.carbsInvalid.visibility = carbs.isValid.not().toVisibility() @@ -334,10 +334,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { binding.bolusRemove.setOnClickListener { ml -> val bolus = (ml.tag as MealLink?)?.bolus ?: return@setOnClickListener activity?.let { activity -> - val text = resourceHelper.gs(R.string.configbuilder_insulin) + ": " + - resourceHelper.gs(R.string.formatinsulinunits, bolus.amount) + "\n" + - resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(bolus.timestamp) - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { + val text = rh.gs(R.string.configbuilder_insulin) + ": " + + rh.gs(R.string.formatinsulinunits, bolus.amount) + "\n" + + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(bolus.timestamp) + OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable { uel.log( Action.BOLUS_REMOVED, Sources.Treatments, ValueWithUnit.Timestamp(bolus.timestamp), @@ -356,10 +356,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { binding.carbsRemove.setOnClickListener { ml -> val carb = (ml.tag as MealLink?)?.carbs ?: return@setOnClickListener activity?.let { activity -> - val text = resourceHelper.gs(R.string.carbs) + ": " + - resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, carb.amount.toInt()) + "\n" + - resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(carb.timestamp) - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { + val text = rh.gs(R.string.carbs) + ": " + + rh.gs(R.string.carbs) + ": " + rh.gs(R.string.format_carbs, carb.amount.toInt()) + "\n" + + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(carb.timestamp) + OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable { uel.log( Action.CARBS_REMOVED, Sources.Treatments, ValueWithUnit.Timestamp(carb.timestamp), diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt index 188437ed6d..9c6b08ddf3 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt @@ -48,7 +48,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator @Inject lateinit var dateUtil: DateUtil @@ -76,7 +76,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.refreshFromNightscout.setOnClickListener { 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) disposable += Completable.fromAction { repository.deleteAllTherapyEventsEntries() } .subscribeOn(aapsSchedulers.io) @@ -90,9 +90,9 @@ class TreatmentsCareportalFragment : DaggerFragment() { } binding.removeAndroidapsStartedEvents.setOnClickListener { 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) - repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction(resourceHelper.gs(R.string.androidaps_start))) + repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction(rh.gs(R.string.androidaps_start))) .subscribe( { result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated 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.invalid.visibility = therapyEvent.isValid.not().toVisibility() 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.type.text = translator.translate(therapyEvent.type) holder.binding.remove.tag = therapyEvent @@ -182,11 +182,11 @@ class TreatmentsCareportalFragment : DaggerFragment() { binding.remove.setOnClickListener { v: View -> val therapyEvent = v.tag as TherapyEvent activity?.let { activity -> - val text = resourceHelper.gs(R.string.eventtype) + ": " + translator.translate(therapyEvent.type) + "\n" + - resourceHelper.gs(R.string.notes_label) + ": " + (therapyEvent.note + val text = rh.gs(R.string.eventtype) + ": " + translator.translate(therapyEvent.type) + "\n" + + rh.gs(R.string.notes_label) + ": " + (therapyEvent.note ?: "") + "\n" + - resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp) - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(therapyEvent.timestamp) + OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable { uel.log(Action.CAREPORTAL_REMOVED, Sources.Treatments, therapyEvent.note , ValueWithUnit.Timestamp(therapyEvent.timestamp), ValueWithUnit.TherapyEventType(therapyEvent.type)) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt index 7086dad46c..af72a3087c 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt @@ -50,7 +50,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var profileFunction: ProfileFunction @@ -128,18 +128,18 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @SuppressLint("SetTextI18n") if (extendedBolus.isInProgress(dateUtil)) { 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 { holder.binding.date.text = dateUtil.dateAndTimeString(extendedBolus.timestamp) + " - " + dateUtil.timeString(extendedBolus.end) holder.binding.date.setTextColor(holder.binding.insulin.currentTextColor) } val profile = profileFunction.getProfile(extendedBolus.timestamp) ?: return - holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins()) - holder.binding.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.amount) + holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins()) + holder.binding.insulin.text = rh.gs(R.string.formatinsulinunits, extendedBolus.amount) val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile, activePlugin.activeInsulin) - holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iob) - holder.binding.ratio.text = resourceHelper.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) + holder.binding.iob.text = rh.gs(R.string.formatinsulinunits, iob.iob) + holder.binding.ratio.text = rh.gs(R.string.pump_basebasalrate, extendedBolus.rate) + 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 } @@ -153,10 +153,10 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { binding.remove.setOnClickListener { v: View -> val extendedBolus = v.tag as ExtendedBolus 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)} - ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.timestamp)} + ${rh.gs(R.string.extended_bolus)} + ${rh.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.timestamp)} """.trimIndent(), { _: DialogInterface, _: Int -> uel.log(Action.EXTENDED_BOLUS_REMOVED, Sources.Treatments, ValueWithUnit.Timestamp(extendedBolus.timestamp), diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt index 5e6cdc835a..5fce0fc4bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt @@ -52,7 +52,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var sp: SP @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var localProfilePlugin: LocalProfilePlugin - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var dateUtil: DateUtil @Inject lateinit var buildHelper: BuildHelper @@ -80,7 +80,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { binding.refreshFromNightscout.setOnClickListener { 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) disposable += Completable.fromAction { @@ -179,9 +179,9 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { holder.binding.ph.visibility = (profileSwitch is ProfileSealed.EPS).toVisibility() holder.binding.ns.visibility = (profileSwitch.interfaceIDs_backing?.nightscoutId != null).toVisibility() 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 "" - 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) holder.binding.remove.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.clone.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 { @@ -207,9 +207,9 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { binding.remove.setOnClickListener { view -> val profileSwitch = view.tag as ProfileSealed.PS activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), - resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + - "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { + OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), + rh.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + + "\n" + rh.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { uel.log(Action.PROFILE_SWITCH_REMOVED, Sources.Treatments, profileSwitch.profileName, ValueWithUnit.Timestamp(profileSwitch.timestamp)) disposable += repository.runTransactionForResult(InvalidateProfileSwitchTransaction(profileSwitch.id)) @@ -224,7 +224,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { activity?.let { activity -> val profileSwitch = (it.tag as ProfileSealed.PS).value 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, profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"), ValueWithUnit.Timestamp(profileSwitch.timestamp), diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt index b61a7e743f..067b349049 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt @@ -56,7 +56,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator @Inject lateinit var dateUtil: DateUtil @@ -83,7 +83,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.refreshFromNightscout.setOnClickListener { 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) disposable += Completable.fromAction { repository.deleteAllTempTargetEntries() } .subscribeOn(aapsSchedulers.io) @@ -165,14 +165,14 @@ class TreatmentsTempTargetFragment : DaggerFragment() { holder.binding.invalid.visibility = tempTarget.isValid.not().toVisibility() holder.binding.remove.visibility = tempTarget.isValid.toVisibility() 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.high.text = tempTarget.highValueToUnitsToString(units) holder.binding.reason.text = translator.translate(tempTarget.reason) holder.binding.date.setTextColor( when { - tempTarget.id == currentlyActiveTarget?.id -> resourceHelper.gc(R.color.colorActive) - tempTarget.timestamp > dateUtil.now() -> resourceHelper.gc(R.color.colorScheduled) + tempTarget.id == currentlyActiveTarget?.id -> rh.gc(R.color.colorActive) + tempTarget.timestamp > dateUtil.now() -> rh.gc(R.color.colorScheduled) else -> holder.binding.reasonColon.currentTextColor }) holder.binding.remove.tag = tempTarget @@ -188,9 +188,9 @@ class TreatmentsTempTargetFragment : DaggerFragment() { binding.remove.setOnClickListener { v: View -> val tempTarget = v.tag as TemporaryTarget 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)} """.trimIndent(), { _: DialogInterface?, _: Int -> diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt index c0ef52cab0..bf922a55db 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -55,7 +55,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var profileFunction: ProfileFunction @@ -167,24 +167,24 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { holder.binding.ph.visibility = (tempBasal.interfaceIDs.pumpId != null).toVisibility() if (tempBasal.isInProgress) { 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 { holder.binding.date.text = dateUtil.dateAndTimeRangeString(tempBasal.timestamp, tempBasal.end) holder.binding.date.setTextColor(holder.binding.duration.currentTextColor) } - holder.binding.duration.text = resourceHelper.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) - else holder.binding.rate.text = resourceHelper.gs(R.string.format_percent, tempBasal.rate.toInt()) + holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins()) + if (tempBasal.isAbsolute) holder.binding.rate.text = rh.gs(R.string.pump_basebasalrate, tempBasal.rate) + else holder.binding.rate.text = rh.gs(R.string.format_percent, tempBasal.rate.toInt()) val now = dateUtil.now() var iob = IobTotal(now) val profile = profileFunction.getProfile(now) 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.suspendFlag.visibility = (tempBasal.type == TemporaryBasal.Type.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() - 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 } @@ -206,10 +206,10 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { val profile = profileFunction.getProfile(dateUtil.now()) ?: return@setOnClickListener 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)} - ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)} + ${if (isFakeExtended) rh.gs(R.string.extended_bolus) else rh.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, dateUtil)} + ${rh.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)} """.trimIndent(), { _: DialogInterface?, _: Int -> if (isFakeExtended && extendedBolus != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt index b0ca06cfdd..8cb5681995 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt @@ -36,7 +36,7 @@ class TreatmentsUserEntryFragment : DaggerFragment() { @Inject lateinit var repository: AppRepository @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -66,7 +66,7 @@ class TreatmentsUserEntryFragment : DaggerFragment() { binding.recyclerview.layoutManager = LinearLayoutManager(view.context) binding.ueExportToXml.setOnClickListener { 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) importExportPrefs.exportUserEntriesCsv(activity) } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 393b068e07..95f18111f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -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.iob.iobCobCalculator.IobCobCalculatorPlugin 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.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits @@ -74,13 +74,13 @@ open class AppModule { @Provides @Singleton fun provideProfileFunction( - aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, resourceHelper: + aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, rh: ResourceHelper, activePlugin: ActivePlugin, repository: AppRepository, dateUtil: DateUtil, config: Config, hardLimits: HardLimits, aapsSchedulers: AapsSchedulers, fabricPrivacy: FabricPrivacy, deviceStatusData: DeviceStatusData ): ProfileFunction = ProfileFunctionImplementation( - aapsLogger, sp, rxBus, resourceHelper, activePlugin, repository, dateUtil, + aapsLogger, sp, rxBus, rh, activePlugin, repository, dateUtil, config, hardLimits, aapsSchedulers, fabricPrivacy, deviceStatusData ) @@ -89,8 +89,8 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector - @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePlugin - @Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider + @Binds fun bindActivePlugin(pluginStore: PluginStore): ActivePlugin + @Binds fun bindCommandQueue(commandQueue: CommandQueueImplementation): CommandQueue @Binds fun bindConfigInterface(config: ConfigImpl): Config @Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt index 014a8de8e3..56bc21dc49 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt @@ -2,14 +2,14 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.CommandQueueImplementation import info.nightscout.androidaps.queue.commands.* @Module @Suppress("unused") abstract class CommandQueueModule { - @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue + @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueueImplementation @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus @ContributesAndroidInjector abstract fun commandCancelTempBasalInjector(): CommandCancelTempBasal diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index b7b0e32dc9..2a14115056 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -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.openAPSSMB.OpenAPSSMBPlugin 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.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin @@ -294,6 +295,12 @@ abstract class PluginsModule { @IntKey(380) abstract fun bindDstHelperPlugin(plugin: DstHelperPlugin): PluginBase + @Binds + @AllConfigs + @IntoMap + @IntKey(381) + abstract fun bindBgQualityCheckPlugin(plugin: BgQualityCheckPlugin): PluginBase + @Binds @AllConfigs @IntoMap diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt index 5b4c697814..8489ce49df 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -27,7 +27,7 @@ import javax.inject.Inject class CalibrationDialog : DialogFragmentWithDate() { @Inject lateinit var injector: HasAndroidInjector - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var xdripCalibrations: XdripCalibrations @Inject lateinit var uel: UserEntryLogger @@ -63,7 +63,7 @@ class CalibrationDialog : DialogFragmentWithDate() { else binding.bg.setParams(savedInstanceState?.getDouble("bg") ?: 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() { @@ -74,20 +74,20 @@ class CalibrationDialog : DialogFragmentWithDate() { override fun submit(): Boolean { if (_binding == null) return false 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 = LinkedList() 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) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { uel.log(Action.CALIBRATION, Sources.CalibrationDialog, ValueWithUnit.fromGlucoseUnit(bg, units.asText)) xdripCalibrations.sendIntent(bg) }) } } else 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index 6853fedcd5..7a5e116933 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -11,7 +11,6 @@ import com.google.common.base.Joiner import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo -import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TemporaryTarget 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.databinding.DialogCarbsBinding import info.nightscout.androidaps.extensions.formatColor -import info.nightscout.androidaps.interfaces.Constraint -import info.nightscout.androidaps.interfaces.GlucoseUnit -import info.nightscout.androidaps.interfaces.IobCobCalculator -import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -44,7 +39,7 @@ import kotlin.math.max class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var ctx: Context - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction @@ -79,15 +74,15 @@ class CarbsDialog : DialogFragmentWithDate() { val time = binding.time.value.toInt() if (time > 12 * 60 || time < -12 * 60) { 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) { 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) { 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) } - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle?): View { + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View { onCreateViewGeneral() _binding = DialogCarbsBinding.inflate(inflater, container, false) return binding.root @@ -120,33 +117,45 @@ class CarbsDialog : DialogFragmentWithDate() { } } val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() - binding.time.setParams(savedInstanceState?.getDouble("time") - ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) + binding.time.setParams( + 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") - ?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) + binding.duration.setParams( + savedInstanceState?.getDouble("duration") + ?: 0.0, 0.0, 10.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher + ) - binding.carbs.setParams(savedInstanceState?.getDouble("carbs") - ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, binding.okcancel.ok, textWatcher) + binding.carbs.setParams( + 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.setOnClickListener { - binding.carbs.value = max(0.0, binding.carbs.value - + sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT)) + binding.carbs.value = max( + 0.0, binding.carbs.value + + sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT) + ) validateInputs() } binding.plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) binding.plus2.setOnClickListener { - binding.carbs.value = max(0.0, binding.carbs.value - + sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT)) + binding.carbs.value = max( + 0.0, binding.carbs.value + + sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT) + ) validateInputs() } binding.plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) binding.plus3.setOnClickListener { - binding.carbs.value = max(0.0, binding.carbs.value - + sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT)) + binding.carbs.value = max( + 0.0, binding.carbs.value + + sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT) + ) validateInputs() } @@ -190,101 +199,128 @@ class CarbsDialog : DialogFragmentWithDate() { val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() val hypoTT = defaultValueHelper.determineHypoTT() val actions: LinkedList = 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 remindBolus = binding.bolusReminderCheckBox.isChecked val activitySelected = binding.activityTt.isChecked 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 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 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() eventTime -= eventTime % 1000 val time = eventTime + timeOffset * 1000 * 60 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) - 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() 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) { - actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "") + actions.add(rh.gs(R.string.carbs) + ": " + "" + rh.gs(R.string.format_carbs, carbsAfterConstraints) + "") if (carbsAfterConstraints != carbs) - actions.add("" + resourceHelper.gs(R.string.carbsconstraintapplied) + "") + actions.add("" + rh.gs(R.string.carbsconstraintapplied) + "") } val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) + actions.add(rh.gs(R.string.notes_label) + ": " + notes) 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) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { when { - activitySelected -> { - uel.log(Action.TT, Sources.CarbDialog, + activitySelected -> { + uel.log( + Action.TT, Sources.CarbDialog, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.ACTIVITY), ValueWithUnit.fromGlucoseUnit(activityTT, units.asText), - ValueWithUnit.Minute(activityTTDuration)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( - timestamp = System.currentTimeMillis(), - duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()), - reason = TemporaryTarget.Reason.ACTIVITY, - lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(activityTT, 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) - }) + ValueWithUnit.Minute(activityTTDuration) + ) + disposable += repository.runTransactionForResult( + InsertAndCancelCurrentTemporaryTargetTransaction( + timestamp = System.currentTimeMillis(), + duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()), + reason = TemporaryTarget.Reason.ACTIVITY, + lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()), + highTarget = Profile.toMgdl(activityTT, 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) + }) } eatingSoonSelected -> { - uel.log(Action.TT, Sources.CarbDialog, + uel.log( + Action.TT, Sources.CarbDialog, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.EATING_SOON), ValueWithUnit.fromGlucoseUnit(eatingSoonTT, units.asText), - ValueWithUnit.Minute(eatingSoonTTDuration)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( - timestamp = System.currentTimeMillis(), - duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), - reason = TemporaryTarget.Reason.EATING_SOON, - lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(eatingSoonTT, 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) - }) + ValueWithUnit.Minute(eatingSoonTTDuration) + ) + disposable += repository.runTransactionForResult( + InsertAndCancelCurrentTemporaryTargetTransaction( + timestamp = System.currentTimeMillis(), + duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), + reason = TemporaryTarget.Reason.EATING_SOON, + lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), + highTarget = Profile.toMgdl(eatingSoonTT, 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) + }) } - hypoSelected -> { - uel.log(Action.TT, Sources.CarbDialog, + hypoSelected -> { + uel.log( + Action.TT, Sources.CarbDialog, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.HYPOGLYCEMIA), ValueWithUnit.fromGlucoseUnit(hypoTT, units.asText), - ValueWithUnit.Minute(hypoTTDuration)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentTemporaryTargetTransaction( - timestamp = System.currentTimeMillis(), - duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()), - reason = TemporaryTarget.Reason.HYPOGLYCEMIA, - lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(hypoTT, 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) - }) + ValueWithUnit.Minute(hypoTTDuration) + ) + disposable += repository.runTransactionForResult( + InsertAndCancelCurrentTemporaryTargetTransaction( + timestamp = System.currentTimeMillis(), + duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()), + reason = TemporaryTarget.Reason.HYPOGLYCEMIA, + lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()), + highTarget = Profile.toMgdl(hypoTT, 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) + }) } } if (carbsAfterConstraints > 0) { @@ -296,17 +332,17 @@ class CarbsDialog : DialogFragmentWithDate() { detailedBolusInfo.carbsDuration = T.hours(duration.toLong()).msecs() detailedBolusInfo.carbsTimestamp = time uel.log(if (duration == 0) Action.CARBS else Action.EXTENDED_CARBS, Sources.CarbDialog, - notes, - ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, - ValueWithUnit.Gram(carbsAfterConstraints), - ValueWithUnit.Minute(timeOffset).takeIf { timeOffset != 0 }, - ValueWithUnit.Hour(duration).takeIf { duration != 0 }) + notes, + ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }, + ValueWithUnit.Gram(carbsAfterConstraints), + ValueWithUnit.Minute(timeOffset).takeIf { timeOffset != 0 }, + ValueWithUnit.Hour(duration).takeIf { duration != 0 }) commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { carbTimer.removeEatReminder() if (!result.success) { - ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) - } else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus) + ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) + } else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus) bolusTimer.scheduleBolusReminder() } }) @@ -318,7 +354,7 @@ class CarbsDialog : DialogFragmentWithDate() { } } else 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index 15883aaf9e..3c4b6905ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -41,7 +41,7 @@ class CareDialog : DialogFragmentWithDate() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var ctx: Context - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var translator: Translator @Inject lateinit var uel: UserEntryLogger @@ -111,7 +111,7 @@ class CareDialog : DialogFragmentWithDate() { EventType.QUESTION -> R.drawable.ic_cp_question 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.SENSOR_INSERT -> R.string.careportal_cgmsensorinsert EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange @@ -153,11 +153,11 @@ class CareDialog : DialogFragmentWithDate() { } 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") ?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, binding.okcancel.ok, bgTextWatcher) } else { - binding.bgunits.text = resourceHelper.gs(R.string.mgdl) + binding.bgunits.text = rh.gs(R.string.mgdl) binding.bg.setParams(savedInstanceState?.getDouble("bg") ?: 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 else -> TherapyEvent.MeterType.MANUAL } - actions.add(resourceHelper.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.careportal_newnstreatment_glucosetype) + ": " + translator.translate(meterType)) + actions.add(rh.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, binding.bg.value) + " " + rh.gs(unitResId)) therapyEvent.glucoseType = meterType therapyEvent.glucose = binding.bg.value valuesWithUnit.add(ValueWithUnit.fromGlucoseUnit(binding.bg.value.toDouble(), profileFunction.getUnits().asText)) valuesWithUnit.add(ValueWithUnit.TherapyEventMeterType(meterType)) } 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() valuesWithUnit.add(ValueWithUnit.Minute(binding.duration.value.toInt()).takeIf { !binding.duration.value.equals(0.0) } ) } val notes = binding.notesLayout.notes.text.toString() if (notes.isNotEmpty()) { - actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) + actions.add(rh.gs(R.string.notes_label) + ": " + 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 @@ -233,7 +233,7 @@ class CareDialog : DialogFragmentWithDate() { } activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent)) .subscribe( { result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } }, diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index e3ed95451c..ac86d3b982 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.DialogExtendedbolusBinding 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.logging.UserEntryLogger import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker @@ -31,9 +31,9 @@ import kotlin.math.abs class ExtendedBolusDialog : DialogFragmentWithDate() { @Inject lateinit var ctx: Context - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var uel: UserEntryLogger @@ -83,20 +83,20 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val durationInMinutes = binding.duration.value.toInt() val actions: LinkedList = LinkedList() val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() - actions.add(resourceHelper.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.formatinsulinunits, insulinAfterConstraint)) + actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes)) 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 -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { uel.log(Action.EXTENDED_BOLUS, Sources.ExtendedBolusDialog, ValueWithUnit.Insulin(insulinAfterConstraint), ValueWithUnit.Minute(durationInMinutes)) commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { 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) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 398eca586f..ad35ffe612 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction import info.nightscout.androidaps.databinding.DialogFillBinding 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.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger @@ -38,9 +38,9 @@ import kotlin.math.abs class FillDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var ctx: Context - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @@ -111,29 +111,29 @@ class FillDialog : DialogFragmentWithDate() { val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() if (insulinAfterConstraints > 0) { - actions.add(resourceHelper.gs(R.string.fillwarning)) + actions.add(rh.gs(R.string.fillwarning)) 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) - 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 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 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() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) + actions.add(rh.gs(R.string.notes_label) + ": " + notes) eventTime -= eventTime % 1000 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) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { if (insulinAfterConstraints > 0) { uel.log(Action.PRIME_BOLUS, Sources.FillDialog, notes, @@ -175,7 +175,7 @@ class FillDialog : DialogFragmentWithDate() { } } else { 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() @@ -191,7 +191,7 @@ class FillDialog : DialogFragmentWithDate() { commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { 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) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index 51af607860..99bdfacd9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -41,10 +41,10 @@ import kotlin.math.max class InsulinDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var ctx: Context @Inject lateinit var repository: AppRepository @@ -80,11 +80,11 @@ class InsulinDialog : DialogFragmentWithDate() { val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (abs(binding.time.value.toInt()) > 12 * 60) { 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) { 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") ?: 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.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() } - 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.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() } - 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.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() } @@ -153,34 +153,34 @@ class InsulinDialog : DialogFragmentWithDate() { val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val actions: LinkedList = LinkedList() 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 eatingSoonChecked = binding.startEatingSoonTt.isChecked 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) - 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)) - 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 eatingSoonTT = defaultValueHelper.determineEatingSoonTT() 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 time = dateUtil.now() + T.mins(timeOffset.toLong()).msecs() 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() 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) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { if (eatingSoonChecked) { uel.log(Action.TT, Sources.InsulinDialog, notes, @@ -209,8 +209,8 @@ class InsulinDialog : DialogFragmentWithDate() { detailedBolusInfo.timestamp = time if (recordOnlyChecked) { uel.log(Action.BOLUS, Sources.InsulinDialog, - resourceHelper.gs(R.string.record) + if (notes.isNotEmpty()) ": " + notes else "", - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.record)), + rh.gs(R.string.record) + if (notes.isNotEmpty()) ": " + notes else "", + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.record)), ValueWithUnit.Insulin(insulinAfterConstraints), ValueWithUnit.Minute(timeOffset).takeIf { timeOffset!= 0 }) disposable += repository.runTransactionForResult(detailedBolusInfo.insertBolusTransaction()) @@ -227,7 +227,7 @@ class InsulinDialog : DialogFragmentWithDate() { commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { 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 { bolusTimer.removeBolusReminder() } @@ -239,7 +239,7 @@ class InsulinDialog : DialogFragmentWithDate() { } } else 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt index 8542d3dcf6..12b04b97f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt @@ -51,12 +51,12 @@ class LoopDialog : DaggerDialogFragment() { @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var configBuilder: ConfigBuilder @Inject lateinit var uel: UserEntryLogger @Inject lateinit var dateUtil: DateUtil @@ -185,12 +185,12 @@ class LoopDialog : DaggerDialogFragment() { binding.overviewLoop.visibility = View.GONE binding.overviewSuspend.visibility = View.GONE 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.overviewReconnect.visibility = View.VISIBLE } - !loopPlugin.isEnabled(PluginType.LOOP) -> { + !loopPlugin.isEnabled() -> { binding.overviewLoop.visibility = View.VISIBLE binding.overviewEnable.visibility = View.VISIBLE binding.overviewDisable.visibility = View.GONE @@ -202,7 +202,7 @@ class LoopDialog : DaggerDialogFragment() { loopPlugin.isSuspended -> { binding.overviewLoop.visibility = View.GONE 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.overviewResume.visibility = View.VISIBLE binding.overviewPump.visibility = View.GONE @@ -238,12 +238,12 @@ class LoopDialog : DaggerDialogFragment() { } } 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.overviewResume.visibility = View.GONE 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.overviewReconnect.visibility = View.GONE @@ -254,25 +254,25 @@ class LoopDialog : DaggerDialogFragment() { private fun onClickOkCancelEnabled(v: View): Boolean { var description = "" when (v.id) { - R.id.overview_closeloop -> description = resourceHelper.gs(R.string.closedloop) - R.id.overview_lgsloop -> description = resourceHelper.gs(R.string.lowglucosesuspend) - R.id.overview_openloop -> description = resourceHelper.gs(R.string.openloop) - R.id.overview_disable -> description = resourceHelper.gs(R.string.disableloop) - R.id.overview_enable -> description = resourceHelper.gs(R.string.enableloop) - R.id.overview_resume -> description = resourceHelper.gs(R.string.resume) - R.id.overview_reconnect -> description = resourceHelper.gs(R.string.reconnect) - R.id.overview_suspend_1h -> description = resourceHelper.gs(R.string.suspendloopfor1h) - R.id.overview_suspend_2h -> description = resourceHelper.gs(R.string.suspendloopfor2h) - R.id.overview_suspend_3h -> description = resourceHelper.gs(R.string.suspendloopfor3h) - R.id.overview_suspend_10h -> description = resourceHelper.gs(R.string.suspendloopfor10h) - R.id.overview_disconnect_15m -> description = resourceHelper.gs(R.string.disconnectpumpfor15m) - R.id.overview_disconnect_30m -> description = resourceHelper.gs(R.string.disconnectpumpfor30m) - R.id.overview_disconnect_1h -> description = resourceHelper.gs(R.string.disconnectpumpfor1h) - R.id.overview_disconnect_2h -> description = resourceHelper.gs(R.string.disconnectpumpfor2h) - R.id.overview_disconnect_3h -> description = resourceHelper.gs(R.string.disconnectpumpfor3h) + R.id.overview_closeloop -> description = rh.gs(R.string.closedloop) + R.id.overview_lgsloop -> description = rh.gs(R.string.lowglucosesuspend) + R.id.overview_openloop -> description = rh.gs(R.string.openloop) + R.id.overview_disable -> description = rh.gs(R.string.disableloop) + R.id.overview_enable -> description = rh.gs(R.string.enableloop) + R.id.overview_resume -> description = rh.gs(R.string.resume) + R.id.overview_reconnect -> description = rh.gs(R.string.reconnect) + R.id.overview_suspend_1h -> description = rh.gs(R.string.suspendloopfor1h) + R.id.overview_suspend_2h -> description = rh.gs(R.string.suspendloopfor2h) + R.id.overview_suspend_3h -> description = rh.gs(R.string.suspendloopfor3h) + R.id.overview_suspend_10h -> description = rh.gs(R.string.suspendloopfor10h) + R.id.overview_disconnect_15m -> description = rh.gs(R.string.disconnectpumpfor15m) + R.id.overview_disconnect_30m -> description = rh.gs(R.string.disconnectpumpfor30m) + R.id.overview_disconnect_1h -> description = rh.gs(R.string.disconnectpumpfor1h) + R.id.overview_disconnect_2h -> description = rh.gs(R.string.disconnectpumpfor2h) + R.id.overview_disconnect_3h -> description = rh.gs(R.string.disconnectpumpfor3h) } 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) }) } @@ -284,21 +284,21 @@ class LoopDialog : DaggerDialogFragment() { R.id.overview_closeloop -> { uel.log(Action.CLOSED_LOOP_MODE, Sources.LoopDialog) 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 } R.id.overview_lgsloop -> { uel.log(Action.LGS_LOOP_MODE, Sources.LoopDialog) 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 } R.id.overview_openloop -> { uel.log(Action.OPEN_LOOP_MODE, Sources.LoopDialog) 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 } @@ -311,7 +311,7 @@ class LoopDialog : DaggerDialogFragment() { commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { 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() { override fun run() { 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) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 1f0dc67dcd..9d3a9e20da 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -38,10 +38,11 @@ import java.text.DecimalFormat import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject +import kotlin.collections.ArrayList class ProfileSwitchDialog : DialogFragmentWithDate() { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var repository: AppRepository @@ -113,7 +114,17 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { context?.let { context -> val profileStore = activePlugin.activeProfileSource.profile ?: return - val profileList = profileStore.getProfileList() + val profileListToCheck = profileStore.getProfileList() + val profileList = ArrayList() + 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) binding.profile.adapter = adapter // set selected to actual profile @@ -123,19 +134,17 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { for (p in profileList.indices) if (profileList[p] == profileFunction.getOriginalProfileName()) binding.profile.setSelection(p) - } ?: return + } profileFunction.getProfile()?.let { profile -> if (profile is ProfileSealed.EPS) if (profile.value.originalPercentage != 100 || profile.value.originalTimeshift != 0L) { 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.percentage.value = profile.value.originalPercentage.toDouble() binding.timeshift.value = profile.value.originalTimeshift.toDouble() } - } else { - binding.reuselayout.visibility = View.GONE } } binding.ttLayout.visibility = View.GONE @@ -155,75 +164,77 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { val actions: LinkedList = LinkedList() val duration = binding.duration.value?.toInt() ?: return false 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() - actions.add(resourceHelper.gs(R.string.profile) + ": " + profileName) + actions.add(rh.gs(R.string.profile) + ": " + profileName) val percent = binding.percentage.value.toInt() 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() 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() if (notes.isNotEmpty()) - actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) + actions.add(rh.gs(R.string.notes_label) + ": " + notes) 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 target = defaultValueHelper.determineActivityTT() val units = profileFunction.getUnits() 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 -> - val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) - val validity = ProfileSealed.PS(ps).isValid(resourceHelper.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) + val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) ?: return@let + val validity = ProfileSealed.PS(ps).isValid(rh.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, rh, rxBus, hardLimits, false) if (validity.isValid) - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { - profileFunction.createProfileSwitch( - profileStore, - profileName = profileName, - durationInMinutes = duration, - percentage = percent, - timeShiftInHours = timeShift, - 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) + OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + if (profileFunction.createProfileSwitch( + profileStore, + profileName = profileName, + durationInMinutes = duration, + percentage = percent, + timeShiftInHours = timeShift, + 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) + ) + } } }) else { OKDialog.show( activity, - resourceHelper.gs(R.string.careportal_profileswitch), + rh.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(validity.reasons)) ) return false diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index f5c02a69d4..1b6676f8b3 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -29,10 +29,10 @@ import kotlin.math.abs class TempBasalDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var ctx: Context @Inject lateinit var uel: UserEntryLogger @@ -103,23 +103,23 @@ class TempBasalDialog : DialogFragmentWithDate() { if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(binding.basalpercentinput.text) percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() - actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": $percent%") - actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) - if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) + actions.add(rh.gs(R.string.tempbasal_label) + ": $percent%") + actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes)) + if (percent != basalPercentInput) actions.add(rh.gs(R.string.constraintapllied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(binding.basalabsoluteinput.text) absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() - actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": " + resourceHelper.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.tempbasal_label) + ": " + rh.gs(R.string.pump_basebasalrate, absolute)) + actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes)) 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 -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { val callback: Callback = object : Callback() { override fun run() { 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) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index 36c157df72..5e423fa892 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -38,7 +38,7 @@ import javax.inject.Inject class TempTargetDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var defaultValueHelper: DefaultValueHelper @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) 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 context?.let { context -> @@ -95,10 +95,10 @@ class TempTargetDialog : DialogFragmentWithDate() { binding.targetCancel.visibility = View.GONE reasonList = Lists.newArrayList( - resourceHelper.gs(R.string.manual), - resourceHelper.gs(R.string.eatingsoon), - resourceHelper.gs(R.string.activity), - resourceHelper.gs(R.string.hypo) + rh.gs(R.string.manual), + rh.gs(R.string.eatingsoon), + rh.gs(R.string.activity), + rh.gs(R.string.hypo) ) val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) binding.reason.adapter = adapterReason @@ -133,19 +133,19 @@ class TempTargetDialog : DialogFragmentWithDate() { R.id.eating_soon -> { binding.temptarget.value = defaultValueHelper.determineEatingSoonTT() 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 -> { binding.temptarget.value = defaultValueHelper.determineActivityTT() 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 -> { binding.temptarget.value = defaultValueHelper.determineHypoTT() 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 -> { @@ -168,25 +168,25 @@ class TempTargetDialog : DialogFragmentWithDate() { val target = binding.temptarget.value val duration = binding.duration.value.toInt() if (target != 0.0 && duration != 0) { - actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) - actions.add(resourceHelper.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) - actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) + actions.add(rh.gs(R.string.reason) + ": " + reason) + actions.add(rh.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + rh.gs(unitResId)) + actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, duration)) } else { - actions.add(resourceHelper.gs(R.string.stoptemptarget)) - reason = resourceHelper.gs(R.string.stoptemptarget) + actions.add(rh.gs(R.string.stoptemptarget)) + reason = rh.gs(R.string.stoptemptarget) } 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 -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { val units = profileFunction.getUnits() 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)) - 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)) - 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)) - 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)) - resourceHelper.gs(R.string.stoptemptarget) -> uel.log(Action.CANCEL_TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }) + 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)) + 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)) + 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)) + 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)) + rh.gs(R.string.stoptemptarget) -> uel.log(Action.CANCEL_TT, Sources.TTDialog, ValueWithUnit.Timestamp(eventTime).takeIf { eventTimeChanged }) } if (target == 0.0 || duration == 0) { disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(eventTime)) @@ -200,9 +200,9 @@ class TempTargetDialog : DialogFragmentWithDate() { timestamp = eventTime, duration = TimeUnit.MINUTES.toMillis(duration.toLong()), reason = when (reason) { - resourceHelper.gs(R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON - resourceHelper.gs(R.string.activity) -> TemporaryTarget.Reason.ACTIVITY - resourceHelper.gs(R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA + rh.gs(R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON + rh.gs(R.string.activity) -> TemporaryTarget.Reason.ACTIVITY + rh.gs(R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA else -> TemporaryTarget.Reason.CUSTOM }, lowTarget = Profile.toMgdl(target, profileFunction.getUnits()), diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index 060eaff132..2bf693c1e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.DialogTreatmentBinding 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.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger @@ -41,9 +41,9 @@ import kotlin.math.abs class TreatmentDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var ctx: Context @Inject lateinit var config: Config @Inject lateinit var uel: UserEntryLogger @@ -64,11 +64,11 @@ class TreatmentDialog : DialogFragmentWithDate() { val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (SafeParse.stringToInt(binding.carbs.text) > maxCarbs) { 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) { 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() 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) - 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)) - 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) { - 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) - 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) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { + OKDialog.showConfirmation(activity, rh.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { val action = when { insulinAfterConstraints.equals(0.0) -> Action.CARBS carbsAfterConstraints.equals(0) -> Action.BOLUS @@ -149,9 +149,9 @@ class TreatmentDialog : DialogFragmentWithDate() { detailedBolusInfo.carbs = carbsAfterConstraints.toDouble() detailedBolusInfo.context = context 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.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.Gram(carbsAfterConstraints).takeIf { carbsAfterConstraints != 0 }) if (detailedBolusInfo.insulin > 0) @@ -174,7 +174,7 @@ class TreatmentDialog : DialogFragmentWithDate() { commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { 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 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 148681522d..82c3a07da1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -55,7 +55,7 @@ class WizardDialog : DaggerDialogFragment() { @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin @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) 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 binding.ok.setOnClickListener { if (okClicked) { @@ -171,7 +171,7 @@ class WizardDialog : DaggerDialogFragment() { binding.calculationcheckbox.isChecked = showCalc binding.calculationcheckbox.setOnCheckedChangeListener { _, isChecked -> 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.resulttable.visibility = isChecked.toVisibility() } @@ -179,7 +179,7 @@ class WizardDialog : DaggerDialogFragment() { // profile spinner binding.profile.onItemSelectedListener = object : OnItemSelectedListener { 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 } @@ -244,13 +244,13 @@ class WizardDialog : DaggerDialogFragment() { val profileStore = activePlugin.activeProfileSource.profile if (profile == null || profileStore == null) { - ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.noprofile)) + ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.noprofile)) dismiss() return } val profileList: ArrayList = profileStore.getProfileList() - profileList.add(0, resourceHelper.gs(R.string.active)) + profileList.add(0, rh.gs(R.string.active)) context?.let { context -> val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) binding.profile.adapter = adapter @@ -271,8 +271,8 @@ class WizardDialog : DaggerDialogFragment() { val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() - binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -bolusIob.iob) - binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, -basalIob.basaliob) + binding.bolusiobinsulin.text = rh.gs(R.string.formatinsulinunits, -bolusIob.iob) + binding.basaliobinsulin.text = rh.gs(R.string.formatinsulinunits, -basalIob.basaliob) calculateInsulin() @@ -285,7 +285,7 @@ class WizardDialog : DaggerDialogFragment() { return // not initialized yet var profileName = binding.profile.selectedItem.toString() val specificProfile: Profile? - if (profileName == resourceHelper.gs(R.string.active)) { + if (profileName == rh.gs(R.string.active)) { specificProfile = profileFunction.getProfile() profileName = profileFunction.getProfileName() } else @@ -300,7 +300,7 @@ class WizardDialog : DaggerDialogFragment() { val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (abs(carbs - carbsAfterConstraint) > 0.01) { binding.carbsInput.value = 0.0 - ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.carbsconstraintapplied)) return } @@ -330,20 +330,20 @@ class WizardDialog : DaggerDialogFragment() { binding.notes.text.toString(), carbTime) 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.bginsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBG) + 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 = rh.gs(R.string.formatinsulinunits, wizard.insulinFromBG) - binding.carbs.text = String.format(resourceHelper.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) - binding.carbsinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromCarbs) + binding.carbs.text = String.format(rh.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) + binding.carbsinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromCarbs) - binding.bolusiobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBolusIOB) - binding.basaliobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromBasalIOB) + binding.bolusiobinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromBolusIOB) + 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 - binding.sb.text = if (binding.sbcheckbox.isChecked) resourceHelper.gs(R.string.twohours) else "" - binding.sbinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromSuperBolus) + binding.sb.text = if (binding.sbcheckbox.isChecked) rh.gs(R.string.twohours) else "" + binding.sbinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromSuperBolus) // Trend if (binding.bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) { @@ -353,24 +353,24 @@ class WizardDialog : DaggerDialogFragment() { } else { binding.bgtrend.text = "" } - binding.bgtrendinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromTrend) + binding.bgtrendinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromTrend) // COB if (binding.cobcheckbox.isChecked) { - binding.cob.text = String.format(resourceHelper.gs(R.string.format_cob_ic), cob, wizard.ic) - binding.cobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, wizard.insulinFromCOB) + binding.cob.text = String.format(rh.gs(R.string.format_cob_ic), cob, wizard.ic) + binding.cobinsulin.text = rh.gs(R.string.formatinsulinunits, wizard.insulinFromCOB) } else { binding.cob.text = "" binding.cobinsulin.text = "" } if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) { - val insulinText = if (wizard.calculatedTotalInsulin > 0.0) resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" - val carbsText = if (carbsAfterConstraint > 0.0) resourceHelper.gs(R.string.format_carbs, carbsAfterConstraint) else "" - binding.total.text = resourceHelper.gs(R.string.result_insulin_carbs, insulinText, carbsText) + val insulinText = if (wizard.calculatedTotalInsulin > 0.0) rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" + val carbsText = if (carbsAfterConstraint > 0.0) rh.gs(R.string.format_carbs, carbsAfterConstraint) else "" + binding.total.text = rh.gs(R.string.result_insulin_carbs, insulinText, carbsText) binding.ok.visibility = View.VISIBLE } 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 } } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt index 1ae378454e..d5ec4736bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt @@ -19,7 +19,7 @@ import javax.inject.Inject class WizardInfoDialog : DaggerDialogFragment() { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction private lateinit var data: BolusCalculatorResult @@ -51,40 +51,40 @@ class WizardInfoDialog : DaggerDialogFragment() { val units = profileFunction.getUnits() val bgString = Profile.toUnitsString(data.glucoseValue, data.glucoseValue * Constants.MGDL_TO_MMOLL, units) // BG - binding.bg.text = resourceHelper.gs(R.string.format_bg_isf, bgString, data.isf) - binding.bginsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.glucoseInsulin) + binding.bg.text = rh.gs(R.string.format_bg_isf, bgString, data.isf) + binding.bginsulin.text = rh.gs(R.string.formatinsulinunits, data.glucoseInsulin) binding.bgcheckbox.isChecked = data.wasGlucoseUsed binding.ttcheckbox.isChecked = data.wasTempTargetUsed // Trend 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 // COB - binding.cob.text = resourceHelper.gs(R.string.format_cob_ic, data.cob, data.ic) - binding.cobinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.cobInsulin) + binding.cob.text = rh.gs(R.string.format_cob_ic, data.cob, data.ic) + binding.cobinsulin.text = rh.gs(R.string.formatinsulinunits, data.cobInsulin) binding.cobcheckbox.isChecked = data.wasCOBUsed // 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 // 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 // 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 // Carbs - binding.carbs.text = resourceHelper.gs(R.string.format_carbs_ic, data.carbs, data.ic) - binding.carbsinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.carbsInsulin) + binding.carbs.text = rh.gs(R.string.format_carbs_ic, data.carbs, data.ic) + binding.carbsinsulin.text = rh.gs(R.string.formatinsulinunits, data.carbsInsulin) // Correction - binding.correctioninsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.otherCorrection) + binding.correctioninsulin.text = rh.gs(R.string.formatinsulinunits, data.otherCorrection) // Profile binding.profile.text = data.profileName // Notes binding.notes.text = data.note // Percentage - binding.percentUsed.text = resourceHelper.gs(R.string.format_percent, data.percentageCorrection) + binding.percentUsed.text = rh.gs(R.string.format_percent, data.percentageCorrection) // Total - binding.totalinsulin.text = resourceHelper.gs(R.string.formatinsulinunits, data.totalInsulin) + binding.totalinsulin.text = rh.gs(R.string.formatinsulinunits, data.totalInsulin) } override fun onStart() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index 5526cb1b1c..4b6a632913 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt @@ -28,7 +28,7 @@ class LoopFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var dateUtil: DateUtil @@ -51,7 +51,7 @@ class LoopFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) 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() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index 0fbe21ab94..827b8e81b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -75,10 +75,10 @@ class LoopPlugin @Inject constructor( private val sp: SP, config: Config, private val constraintChecker: ConstraintChecker, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val profileFunction: ProfileFunction, private val context: Context, - private val commandQueue: CommandQueueProvider, + private val commandQueue: CommandQueue, private val activePlugin: ActivePlugin, private val virtualPumpPlugin: VirtualPumpPlugin, private val iobCobCalculator: IobCobCalculator, @@ -97,7 +97,7 @@ class LoopPlugin @Inject constructor( .preferencesId(R.xml.pref_loop) .enableByDefault(config.APS) .description(R.string.description_loop), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Loop { private val disposable = CompositeDisposable() @@ -230,7 +230,7 @@ class LoopPlugin @Inject constructor( val loopEnabled = constraintChecker.isLoopInvocationAllowed() if (!loopEnabled.value()) { val message = """ - ${resourceHelper.gs(R.string.loopdisabled)} + ${rh.gs(R.string.loopdisabled)} ${loopEnabled.getReasons(aapsLogger)} """.trimIndent() aapsLogger.debug(LTag.APS, message) @@ -242,28 +242,28 @@ class LoopPlugin @Inject constructor( if (!isEnabled(PluginType.LOOP)) return val profile = profileFunction.getProfile() if (profile == null || !profileFunction.isProfileValid("Loop")) { - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) - rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.noprofileselected))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset)) + rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.noprofileset))) return } // Check if pump info is loaded if (pump.baseBasalRate < 0.01) return val usedAPS = activePlugin.activeAPS - if ((usedAPS as PluginBase).isEnabled(PluginType.APS)) { + if ((usedAPS as PluginBase).isEnabled()) { usedAPS.invoke(initiator, tempBasalFallback) apsResult = usedAPS.lastAPSResult } // Check if we have any result if (apsResult == null) { - rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.noapsselected))) + rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.noapsselected))) return } else rxBus.send(EventLoopInvoked()) if (!isEmptyQueue()) { - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.pumpbusy)) - rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpbusy))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.pumpbusy)) + rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.pumpbusy))) return } @@ -307,13 +307,13 @@ class LoopPlugin @Inject constructor( } if (isSuspended) { - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)) - rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.loopsuspended))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.loopsuspended)) + rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.loopsuspended))) return } if (pump.isSuspended()) { - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.pumpsuspended)) - rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpsuspended))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.pumpsuspended)) + rxBus.send(EventLoopSetLastRunGui(rh.gs(R.string.pumpsuspended))) return } val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() @@ -332,18 +332,18 @@ class LoopPlugin @Inject constructor( val intentAction5m = Intent(context, CarbSuggestionReceiver::class.java) intentAction5m.putExtra("ignoreDuration", 5) 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) intentAction15m.putExtra("ignoreDuration", 15) 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) intentAction30m.putExtra("ignoreDuration", 30) 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) builder.setSmallIcon(R.drawable.notif_icon) - .setContentTitle(resourceHelper.gs(R.string.carbssuggestion)) + .setContentTitle(rh.gs(R.string.carbssuggestion)) .setContentText(resultAfterConstraints.carbsRequiredText) .setAutoCancel(true) .setPriority(Notification.IMPORTANCE_HIGH) @@ -357,9 +357,9 @@ class LoopPlugin @Inject constructor( // mId allows you to update the notification later on. mNotificationManager.notify(Constants.notificationID, builder.build()) - uel.log(Action.CAREPORTAL, Sources.Loop, resourceHelper.gs(R.string.carbsreq, resultAfterConstraints.carbsReq, resultAfterConstraints.carbsReqWithin), - ValueWithUnit.Gram(resultAfterConstraints.carbsReq), - ValueWithUnit.Minute(resultAfterConstraints.carbsReqWithin)) + uel.log(Action.CAREPORTAL, Sources.Loop, rh.gs(R.string.carbsreq, resultAfterConstraints.carbsReq, resultAfterConstraints.carbsReqWithin), + ValueWithUnit.Gram(resultAfterConstraints.carbsReq), + ValueWithUnit.Minute(resultAfterConstraints.carbsReqWithin)) rxBus.send(EventNewOpenLoopNotification()) //only send to wear if Native notifications are turned off @@ -422,7 +422,7 @@ class LoopPlugin @Inject constructor( if (resultAfterConstraints.isChangeRequested && allowNotification) { val builder = NotificationCompat.Builder(context, CHANNEL_ID) builder.setSmallIcon(R.drawable.notif_icon) - .setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion)) + .setContentTitle(rh.gs(R.string.openloop_newsuggestion)) .setContentText(resultAfterConstraints.toString()) .setAutoCancel(true) .setPriority(Notification.IMPORTANCE_HIGH) @@ -516,12 +516,12 @@ class LoopPlugin @Inject constructor( } val pump = activePlugin.activePump 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() return } 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() return } @@ -591,12 +591,12 @@ class LoopPlugin @Inject constructor( return } 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() return } 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() return } @@ -616,7 +616,7 @@ class LoopPlugin @Inject constructor( } private fun allowPercentage(): Boolean { - return virtualPumpPlugin.isEnabled(PluginType.PUMP) + return virtualPumpPlugin.isEnabled() } 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() { override fun run() { 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() { override fun run() { 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() { override fun run() { 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() { override fun run() { 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) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt index e94acfd87a..4d41682fd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt @@ -31,7 +31,7 @@ class OpenAPSAMAFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var dateUtil: DateUtil @@ -101,7 +101,7 @@ class OpenAPSAMAFragment : DaggerFragment() { binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterAMAJS.currentTempParam) try { 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) { aapsLogger.error(LTag.APS, "Unhandled exception", e) @Suppress("SetTextI18n") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index b11d5b8e20..c08479d48d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -35,7 +35,7 @@ class OpenAPSAMAPlugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBus, private val constraintChecker: ConstraintChecker, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val profileFunction: ProfileFunction, private val context: Context, private val activePlugin: ActivePlugin, @@ -54,7 +54,7 @@ class OpenAPSAMAPlugin @Inject constructor( .shortName(R.string.oaps_shortname) .preferencesId(R.xml.pref_openapsama) .description(R.string.description_ama), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), APS { // last values @@ -86,18 +86,18 @@ class OpenAPSAMAPlugin @Inject constructor( val profile = profileFunction.getProfile() val pump = activePlugin.activePump if (profile == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset)) return } if (!isEnabled(PluginType.APS)) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled)) return } if (glucoseStatus == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata)) return } 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 -> inputConstraints.copyReasons(maxIOBAllowedConstraint) }.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 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 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 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], 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], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]) var isTempTarget = false val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { @@ -134,7 +134,7 @@ class OpenAPSAMAPlugin @Inject constructor( if (constraintChecker.isAutosensModeEnabled().value()) { val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") if (autosensData == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata))) return } lastAutosensResult = autosensData.autosensResult diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index bdb1039bd2..6e3a2fb43a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -36,7 +36,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader: @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var activePlugin: ActivePlugin diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index e80614fdea..0e43d90551 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -32,7 +32,7 @@ class OpenAPSSMBFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var dateUtil: DateUtil @@ -101,7 +101,7 @@ class OpenAPSSMBFragment : DaggerFragment() { binding.currenttemp.text = jsonFormatter.format(determineBasalAdapterSMBJS.currentTempParam) try { 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) { aapsLogger.error(LTag.APS, "Unhandled exception", e) @SuppressLint("SetTextI18n") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 42c1700fb8..d611899969 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -35,7 +35,7 @@ class OpenAPSSMBPlugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBus, private val constraintChecker: ConstraintChecker, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val profileFunction: ProfileFunction, private val context: Context, private val activePlugin: ActivePlugin, @@ -55,7 +55,7 @@ class OpenAPSSMBPlugin @Inject constructor( .preferencesId(R.xml.pref_openapssmb) .description(R.string.description_smb) .setDefault(), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), APS, Constraints { // last values @@ -81,9 +81,9 @@ class OpenAPSSMBPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false) - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled + preferenceFragment.findPreference(rh.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled + preferenceFragment.findPreference(rh.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled + preferenceFragment.findPreference(rh.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled } override fun invoke(initiator: String, tempBasalFallback: Boolean) { @@ -93,18 +93,18 @@ class OpenAPSSMBPlugin @Inject constructor( val profile = profileFunction.getProfile() val pump = activePlugin.activePump if (profile == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileset))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileset)) return } if (!isEnabled(PluginType.APS)) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled)) return } if (glucoseStatus == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) - aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata))) + aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata)) return } @@ -119,9 +119,9 @@ class OpenAPSSMBPlugin @Inject constructor( inputConstraints.copyReasons(maxIOBAllowedConstraint) }.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 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 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 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], 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], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1]) var isTempTarget = false val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { @@ -139,7 +139,7 @@ class OpenAPSSMBPlugin @Inject constructor( if (constraintChecker.isAutosensModeEnabled().value()) { val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") if (autosensData == null) { - rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) + rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata))) return } lastAutosensResult = autosensData.autosensResult diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 8071465017..ab93562d4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.configBuilder +import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater @@ -32,13 +33,14 @@ class ConfigBuilderFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var config: Config @Inject lateinit var buildHelper: BuildHelper + @Inject lateinit var ctx: Context private var disposable: CompositeDisposable = CompositeDisposable() private val pluginViewHolders = ArrayList() @@ -125,8 +127,8 @@ class ConfigBuilderFragment : DaggerFragment() { if (plugins.isEmpty()) return @Suppress("InflateParams") val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout - (parent.findViewById(R.id.category_title) as TextView).text = resourceHelper.gs(title) - (parent.findViewById(R.id.category_description) as TextView).text = resourceHelper.gs(description) + (parent.findViewById(R.id.category_title) as TextView).text = rh.gs(title) + (parent.findViewById(R.id.category_description) as TextView).text = rh.gs(description) val pluginContainer = parent.findViewById(R.id.category_plugins) for (plugin in plugins) { val pluginViewHolder = PluginViewHolder(this, pluginType, plugin) @@ -170,7 +172,7 @@ class ConfigBuilderFragment : DaggerFragment() { pluginPreferences.setOnClickListener { fragment.activity?.let { activity -> 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) fragment.startActivity(i) }, null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt index a6e2e35e34..cf9a78194c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt @@ -26,7 +26,7 @@ import javax.inject.Singleton class ConfigBuilderPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val rxBus: RxBus, private val activePlugin: ActivePlugin, @@ -42,7 +42,7 @@ class ConfigBuilderPlugin @Inject constructor( .pluginName(R.string.configbuilder) .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), ConfigBuilder { override fun initialize() { @@ -134,7 +134,7 @@ class ConfigBuilderPlugin @Inject constructor( // Ask when switching to physical pump plugin 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) else if (changedPlugin.getType() == PluginType.PUMP) { performPluginSwitch(changedPlugin, newState, type) @@ -148,12 +148,12 @@ class ConfigBuilderPlugin @Inject constructor( performPluginSwitch(changedPlugin, newState, type) pumpSync.connectNewPump() } 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) pumpSync.connectNewPump() sp.putBoolean("allow_hardware_pump", true) - uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) + uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName), + ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!") }, { rxBus.send(EventConfigBuilderUpdateGui()) @@ -164,12 +164,12 @@ class ConfigBuilderPlugin @Inject constructor( override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) { if(enabled && !changedPlugin.isEnabled()) { - uel.log(Action.PLUGIN_ENABLED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) + uel.log(Action.PLUGIN_ENABLED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName), + ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) } else if(!enabled) { - uel.log(Action.PLUGIN_DISABLED, Sources.ConfigBuilder, resourceHelper.gs(changedPlugin.pluginDescription.pluginName), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) + uel.log(Action.PLUGIN_DISABLED, Sources.ConfigBuilder, rh.gs(changedPlugin.pluginDescription.pluginName), + ValueWithUnit.SimpleString(rh.gsNotLocalised(changedPlugin.pluginDescription.pluginName))) } changedPlugin.setPluginEnabled(type, enabled) changedPlugin.setFragmentVisible(type, enabled) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index 9cf9338901..05afc2fd86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -33,7 +33,7 @@ class ProfileFunctionImplementation @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val activePlugin: ActivePlugin, private val repository: AppRepository, private val dateUtil: DateUtil, @@ -78,13 +78,13 @@ class ProfileFunctionImplementation @Inject constructor( getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true) 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() if (profileSwitch is ValueWrapper.Existing) { profileName = if (customized) profileSwitch.value.originalCustomizedName else profileSwitch.value.originalProfileName if (showRemainingTime && profileSwitch.value.originalDuration != 0L) { - profileName += dateUtil.untilString(profileSwitch.value.originalEnd, resourceHelper) + profileName += dateUtil.untilString(profileSwitch.value.originalEnd, rh) } } return profileName @@ -141,9 +141,8 @@ class ProfileFunctionImplementation @Inject constructor( if (sp.getString(R.string.key_units, Constants.MGDL) == Constants.MGDL) GlucoseUnit.MGDL else GlucoseUnit.MMOL - override fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch { - val pureProfile = profileStore.getSpecificProfile(profileName) - ?: throw InvalidParameterSpecException(profileName) + override fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch? { + val pureProfile = profileStore.getSpecificProfile(profileName) ?: return null return ProfileSwitch( timestamp = timestamp, 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) { - val ps = buildProfileSwitch(profileStore, profileName, durationInMinutes, percentage, timeShiftInHours, timestamp) + 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) ?: return false disposable += repository.runTransactionForResult(InsertOrUpdateProfileSwitch(ps)) .subscribe({ result -> 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) }) + return true } override fun createProfileSwitch(durationInMinutes: Int, percentage: Int, timeShiftInHours: Int): Boolean { val profile = repository.getPermanentProfileSwitch(dateUtil.now()) ?: 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( - resourceHelper.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch), + rh.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch), activePlugin.activePump, config, - resourceHelper, + rh, rxBus, hardLimits, false diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt new file mode 100644 index 0000000000..c20e5f3864 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt @@ -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): Constraint { + 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 + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt index 5295ec4132..3fbc8e009d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -21,18 +21,18 @@ import javax.inject.Singleton class DstHelperPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - private var rxBus: RxBus, - resourceHelper: ResourceHelper, - private var sp: SP, - private var activePlugin: ActivePlugin, - private var loopPlugin: LoopPlugin + private val rxBus: RxBus, + rh: ResourceHelper, + private val sp: SP, + private val activePlugin: ActivePlugin, + private val loopPlugin: LoopPlugin ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .neverVisible(true) .alwaysEnabled(true) .showInList(false) .pluginName(R.string.dst_plugin_name), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { companion object { @@ -41,6 +41,7 @@ class DstHelperPlugin @Inject constructor( } //Return false if time to DST change happened in the last 3 hours. + @Suppress("ReplaceGetOrSet") override fun isLoopInvocationAllowed(value: Constraint): Constraint { val pump = activePlugin.activePump if (pump.canHandleDST()) { @@ -51,10 +52,10 @@ class DstHelperPlugin @Inject constructor( if (willBeDST(cal)) { val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - val notification = NotificationWithAction(injector, Notification.DST_IN_24H, resourceHelper.gs(R.string.dst_in_24h_warning), Notification.LOW) - notification.action(R.string.snooze, Runnable { + val notification = NotificationWithAction(injector, Notification.DST_IN_24H, rh.gs(R.string.dst_in_24h_warning), Notification.LOW) + notification.action(R.string.snooze) { sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs()) - }) + } rxBus.send(EventNewNotification(notification)) } } @@ -66,10 +67,10 @@ class DstHelperPlugin @Inject constructor( if (!loopPlugin.isSuspended) { val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L) if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, resourceHelper.gs(R.string.dst_loop_disabled_warning), Notification.LOW) - notification.action(R.string.snooze, Runnable { + val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, rh.gs(R.string.dst_loop_disabled_warning), Notification.LOW) + notification.action(R.string.snooze) { sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs()) - }) + } rxBus.send(EventNewNotification(notification)) } } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index 1ad1a63571..1054e76d0b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -50,7 +50,7 @@ class ObjectivesFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var receiverStatusStore: ReceiverStatusStore @@ -155,15 +155,15 @@ class ObjectivesFragment : DaggerFragment() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { 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) { holder.binding.objective.visibility = View.VISIBLE - holder.binding.objective.text = resourceHelper.gs(objective.objective) + holder.binding.objective.text = rh.gs(objective.objective) } else holder.binding.objective.visibility = View.GONE if (objective.gate != 0) { holder.binding.gate.visibility = View.VISIBLE - holder.binding.gate.text = resourceHelper.gs(objective.gate) + holder.binding.gate.text = rh.gs(objective.gate) } else holder.binding.gate.visibility = View.GONE if (!objective.isStarted) { @@ -199,7 +199,7 @@ class ObjectivesFragment : DaggerFragment() { if (task.shouldBeIgnored()) continue // name val name = TextView(holder.binding.progress.context) - name.text = "${resourceHelper.gs(task.task)}:" + name.text = "${rh.gs(task.task)}:" name.setTextColor(-0x1) holder.binding.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) // hint @@ -232,7 +232,7 @@ class ObjectivesFragment : DaggerFragment() { 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.verify.setOnClickListener { receiverStatusStore.updateNetworkStatus() @@ -246,27 +246,27 @@ class ObjectivesFragment : DaggerFragment() { // move out of UI thread Thread { 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() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) + rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99)) } else if (success) { if (objective.isCompleted(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) rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.requirementnotmet), 99)) + rxBus.send(EventNtpStatus(rh.gs(R.string.requirementnotmet), 99)) } } else { - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) + rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99)) } } }, receiverStatusStore.isConnected) @@ -285,23 +285,23 @@ class ObjectivesFragment : DaggerFragment() { // move out of UI thread Thread { 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() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) + rxBus.send(EventNtpStatus(rh.gs(R.string.notconnected), 99)) } else if (success) { objective.startedOn = time - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.success), 100)) + rxBus.send(EventNtpStatus(rh.gs(R.string.success), 100)) SystemClock.sleep(1000) rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventSWUpdate(false)) SystemClock.sleep(100) scrollToCurrentObjective() } else { - rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99)) + rxBus.send(EventNtpStatus(rh.gs(R.string.failedretrievetime), 99)) } } }, receiverStatusStore.isConnected) @@ -309,7 +309,7 @@ class ObjectivesFragment : DaggerFragment() { } holder.binding.unstart.setOnClickListener { 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, ValueWithUnit.SimpleInt(position + 1)) objective.startedOn = 0 @@ -329,7 +329,7 @@ class ObjectivesFragment : DaggerFragment() { // 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())) 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.enterbutton.visibility = View.VISIBLE holder.binding.input.visibility = View.VISIBLE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 224a89a888..fb14354044 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -24,7 +24,7 @@ import javax.inject.Singleton class ObjectivesPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val activePlugin: ActivePlugin, private val sp: SP, config: Config, @@ -39,7 +39,7 @@ class ObjectivesPlugin @Inject constructor( .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { var objectives: MutableList = ArrayList() @@ -119,10 +119,10 @@ class ObjectivesPlugin @Inject constructor( sp.putLong("Objectives_" + "auto" + "_started", dateUtil.now()) sp.putLong("Objectives_" + "auto" + "_accomplished", dateUtil.now()) 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) } 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): Constraint { 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 } override fun isLgsAllowed(value: Constraint): Constraint { 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 } override fun isClosedLoopAllowed(value: Constraint): Constraint { 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 } override fun isAutosensModeEnabled(value: Constraint): Constraint { 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 } override fun isSMBModeEnabled(value: Constraint): Constraint { 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 } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { 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 } override fun isAutomationEnabled(value: Constraint): Constraint { 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 } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt index 2170488db3..d04210f2df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt @@ -21,7 +21,7 @@ import javax.inject.Inject class ObjectivesExamDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil companion object { @@ -96,7 +96,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() { context?.let { binding.examHints.addView(h.generate(it)) } } // 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 // Buttons binding.examVerify.isEnabled = !task.answered && task.isEnabledAnswer() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt index 0a0e1477f5..2c5731bef4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt @@ -20,7 +20,7 @@ import kotlin.math.floor abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRes objective: Int, @StringRes gate: Int) { @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil private val spName: String @@ -89,7 +89,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe open fun isCompleted(trueTime: Long): Boolean = isCompleted() 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 { 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 minutes = floor(duration.toDouble() / T.mins(1).msecs()).toInt() return when { - days > 0 -> resourceHelper.gq(R.plurals.days, days, days) - hours > 0 -> resourceHelper.gq(R.plurals.hours, hours, hours) - else -> resourceHelper.gq(R.plurals.minutes, minutes, minutes) + days > 0 -> rh.gq(R.plurals.days, days, days) + hours > 0 -> rh.gq(R.plurals.hours, hours, hours) + else -> rh.gq(R.plurals.minutes, minutes, minutes) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt index c58e0cb355..abb56ccf0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt @@ -39,7 +39,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R } override fun shouldBeIgnored(): Boolean { - return !virtualPumpPlugin.isEnabled(PluginType.PUMP) + return !virtualPumpPlugin.isEnabled() } }) 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) { override fun isCompleted(): Boolean { - return loopPlugin.isEnabled(PluginType.LOOP) + return loopPlugin.isEnabled() } }) tasks.add(object : Task(this, R.string.apsselected) { override fun isCompleted(): Boolean { 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) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective1.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective1.kt index 91fb901033..936065ee0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective1.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective1.kt @@ -33,7 +33,7 @@ class Objective1 @Inject constructor(injector: HasAndroidInjector) : Objective(i }.hint(Hint(R.string.usetemptarget_hint))) tasks.add(object : Task(this, R.string.objectives_useactions) { 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))) tasks.add(object : Task(this, R.string.objectives_useloop) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.kt index 2ccd96f3b3..1808666fad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective3.kt @@ -22,7 +22,7 @@ class Objective3 @Inject constructor(injector: HasAndroidInjector) : Objective(i } 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 }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt index 19dcb7d9fd..8c275cae1f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt @@ -18,7 +18,7 @@ import javax.inject.Singleton class PhoneCheckerPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val context: Context ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -26,7 +26,7 @@ class PhoneCheckerPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.phonechecker), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { var phoneRooted: Boolean = false diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt index e5652e31fa..8e55ff8de9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt @@ -30,7 +30,7 @@ import kotlin.math.floor class SafetyPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val rxBus: RxBus, private val constraintChecker: ConstraintChecker, @@ -50,86 +50,86 @@ class SafetyPlugin @Inject constructor( .showInList(false) .pluginName(R.string.safety) .preferencesId(R.xml.pref_safety), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints, Safety { /** * Constraints interface */ override fun isLoopInvocationAllowed(value: Constraint): Constraint { - 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 } override fun isClosedLoopAllowed(value: Constraint): Constraint { 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 (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)) } - 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 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 } override fun isAutosensModeEnabled(value: Constraint): Constraint { 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 } override fun isSMBModeEnabled(value: Constraint): Constraint { 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() - 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 } override fun isUAMEnabled(value: Constraint): Constraint { val enabled = sp.getBoolean(R.string.key_use_uam, false) - if (!enabled) value[aapsLogger, false, resourceHelper.gs(R.string.uamdisabledinpreferences)] = this - val oref1Enabled = sensitivityOref1Plugin.isEnabled(PluginType.SENSITIVITY) - if (!oref1Enabled) value[aapsLogger, false, resourceHelper.gs(R.string.uamdisabledoref1notselected)] = this + if (!enabled) value[aapsLogger, false, rh.gs(R.string.uamdisabledinpreferences)] = this + val oref1Enabled = sensitivityOref1Plugin.isEnabled() + if (!oref1Enabled) value[aapsLogger, false, rh.gs(R.string.uamdisabledoref1notselected)] = this return value } override fun isAdvancedFilteringEnabled(value: Constraint): Constraint { 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 } override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - 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) { var maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1.0) if (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 val maxBasalMultiplier = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0) 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 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 // check for pump max if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { 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 @@ -149,62 +149,62 @@ class SafetyPlugin @Inject constructor( val pump = activePlugin.activePump 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() - 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) { 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 } override fun applyBolusConstraints(insulin: Constraint): Constraint { - 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) - insulin.setIfSmaller(aapsLogger, maxBolus, String.format(resourceHelper.gs(R.string.limitingbolus), maxBolus, resourceHelper.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, maxBolus, String.format(rh.gs(R.string.limitingbolus), maxBolus, rh.gs(R.string.maxvalueinpreferences)), 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 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 } override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { - 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) - insulin.setIfSmaller(aapsLogger, maxBolus, String.format(resourceHelper.gs(R.string.limitingextendedbolus), maxBolus, resourceHelper.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, maxBolus, String.format(rh.gs(R.string.limitingextendedbolus), maxBolus, rh.gs(R.string.maxvalueinpreferences)), 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 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 } override fun applyCarbsConstraints(carbs: Constraint): Constraint { - 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) - 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 } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { 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) - maxIob.setIfSmaller(aapsLogger, maxIobPref, String.format(resourceHelper.gs(R.string.limitingiob), maxIobPref, resourceHelper.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 (openAPSSMBPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), String.format(resourceHelper.gs(R.string.limitingiob), hardLimits.maxIobSMB(), resourceHelper.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) + 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(rh.gs(R.string.limitingiob), hardLimits.maxIobAMA(), rh.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(rh.gs(R.string.limitingiob), HardLimits.MAX_IOB_LGS, rh.gs(R.string.lowglucosesuspend)), this) return maxIob } override fun configuration(): JSONObject = JSONObject() - .putString(R.string.key_age, sp, resourceHelper) - .putDouble(R.string.key_treatmentssafety_maxbolus, sp, resourceHelper) - .putInt(R.string.key_treatmentssafety_maxcarbs, sp, resourceHelper) + .putString(R.string.key_age, sp, rh) + .putDouble(R.string.key_treatmentssafety_maxbolus, sp, rh) + .putInt(R.string.key_treatmentssafety_maxcarbs, sp, rh) override fun applyConfiguration(configuration: JSONObject) { - configuration.storeString(R.string.key_age, sp, resourceHelper) - configuration.storeDouble(R.string.key_treatmentssafety_maxbolus, sp, resourceHelper) - configuration.storeInt(R.string.key_treatmentssafety_maxcarbs, sp, resourceHelper) + configuration.storeString(R.string.key_age, sp, rh) + configuration.storeDouble(R.string.key_treatmentssafety_maxbolus, sp, rh) + configuration.storeInt(R.string.key_treatmentssafety_maxcarbs, sp, rh) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index 98d8ee8a7f..2fedf66fd5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -35,7 +35,7 @@ import javax.inject.Singleton class SignatureVerifierPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val rxBus: RxBus, private val context: Context @@ -45,7 +45,7 @@ class SignatureVerifierPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.signature_verifier), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { 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() { - 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)) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt index ac46475141..3e1bb68d85 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt @@ -26,7 +26,7 @@ import javax.inject.Singleton class StorageConstraintPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val rxBus: RxBus ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -34,15 +34,15 @@ class StorageConstraintPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.storage), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { override fun isClosedLoopAllowed(value: Constraint): Constraint { val diskFree = availableInternalMemorySize() aapsLogger.debug(LTag.CONSTRAINTS, "Internal storage free (Mb):$diskFree") if (diskFree < Constants.MINIMUM_FREE_SPACE) { - value[aapsLogger, false, resourceHelper.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) + value[aapsLogger, false, rh.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE)] = this + val notification = Notification(Notification.DISK_FULL, rh.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.DISK_FULL)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index 2f38a3152f..d3834719f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -21,7 +21,7 @@ import kotlin.math.roundToInt class VersionCheckerPlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val versionCheckerUtils: VersionCheckerUtils, val rxBus: RxBus, aapsLogger: AAPSLogger, @@ -34,7 +34,7 @@ class VersionCheckerPlugin @Inject constructor( .alwaysEnabled(true) .showInList(false) .pluginName(R.string.versionChecker), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Constraints { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { @@ -59,10 +59,10 @@ class VersionCheckerPlugin @Inject constructor( checkWarning() versionCheckerUtils.triggerCheckVersion() if (isOldVersion(gracePeriod.veryOld.daysToMillis())) - value[aapsLogger, false, resourceHelper.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) + value[aapsLogger, false, rh.gs(R.string.very_old_version)] = this + 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) - value[aapsLogger, false, resourceHelper.gs(R.string.application_expired)] = this + value[aapsLogger, false, rh.gs(R.string.application_expired)] = this return value } @@ -80,7 +80,7 @@ class VersionCheckerPlugin @Inject constructor( sp.putLong(R.string.key_last_versionchecker_plugin_warning, now) //notify - val message = resourceHelper.gs( + val message = rh.gs( R.string.new_version_warning, ((now - sp.getLong(R.string.key_last_time_this_version_detected, now)) / 1L.daysToMillis().toDouble()).roundToInt(), gracePeriod.old, @@ -90,13 +90,13 @@ class VersionCheckerPlugin @Inject constructor( 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)) { // store last notification time sp.putLong(R.string.key_last_versionchecker_plugin_warning, now) //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)) } } @@ -106,7 +106,7 @@ class VersionCheckerPlugin @Inject constructor( override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = 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 maxIob diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index bf8bbd0a37..182b041aed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.activities.HistoryBrowseActivity import info.nightscout.androidaps.diaconn.DiaconnG8Plugin 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.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction @@ -67,12 +67,12 @@ class ActionsFragment : DaggerFragment() { @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var ctx: Context - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var skinProvider: SkinProvider @@ -164,7 +164,7 @@ class ActionsFragment : DaggerFragment() { extendedBolus?.setOnClickListener { activity?.let { activity -> 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 { ExtendedBolusDialog().show(childFragmentManager, "Actions") }, null) @@ -177,7 +177,7 @@ class ActionsFragment : DaggerFragment() { commandQueue.cancelExtended(object : Callback() { override fun run() { 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() { override fun run() { 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.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 extendedBolusCancel?.visibility = View.GONE } else { @@ -283,14 +283,14 @@ class ActionsFragment : DaggerFragment() { extendedBolus?.visibility = View.GONE extendedBolusCancel?.visibility = View.VISIBLE @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 { extendedBolus?.visibility = View.VISIBLE 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 cancelTempBasal?.visibility = View.GONE } else { @@ -299,7 +299,7 @@ class ActionsFragment : DaggerFragment() { setTempBasal?.visibility = View.GONE cancelTempBasal?.visibility = View.VISIBLE @Suppress("SetTextI18n") - cancelTempBasal?.text = resourceHelper.gs(R.string.cancel) + " " + activeTemp.toStringShort() + cancelTempBasal?.text = rh.gs(R.string.cancel) + " " + activeTemp.toStringShort() } else { setTempBasal?.visibility = View.VISIBLE cancelTempBasal?.visibility = View.GONE @@ -318,7 +318,7 @@ class ActionsFragment : DaggerFragment() { if (!config.NSCLIENT) { 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 { statusLightHandler.updateStatusLights(cannulaAge, insulinAge, null, sensorAge, null, pbAge, null) sensorLevelLabel?.text = "" @@ -339,7 +339,7 @@ class ActionsFragment : DaggerFragment() { if (!customAction.isEnabled) continue 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( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f) @@ -357,7 +357,7 @@ class ActionsFragment : DaggerFragment() { buttonsLayout?.addView(btn) - this.pumpCustomActions[resourceHelper.gs(customAction.name)] = customAction + this.pumpCustomActions[rh.gs(customAction.name)] = customAction this.pumpCustomButtons.add(btn) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt index 3fadf5be53..dff25d3ead 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt @@ -15,7 +15,7 @@ import javax.inject.Singleton class ActionsPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) @@ -26,5 +26,5 @@ class ActionsPlugin @Inject constructor( .pluginName(R.string.actions) .shortName(R.string.actions_shortname) .description(R.string.description_actions), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 1ed528c1ff..e4299709a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -34,7 +34,7 @@ import javax.inject.Singleton class DataBroadcastPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val context: Context, private val dateUtil: DateUtil, @@ -57,7 +57,7 @@ class DataBroadcastPlugin @Inject constructor( .alwaysEnabled(true) .neverVisible(true) .showInList(false), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt index cd4e20cb39..7c33102f42 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt @@ -47,7 +47,7 @@ class FoodFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger @@ -75,9 +75,9 @@ class FoodFragment : DaggerFragment() { binding.refreshFromNightscout.setOnClickListener { context?.let { context -> - OKDialog.showConfirmation(context, resourceHelper.gs(R.string.refresheventsfromnightscout) + " ?", { - uel.log(Action.FOOD, Sources.Food, resourceHelper.gs(R.string.refresheventsfromnightscout), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.refresheventsfromnightscout))) + OKDialog.showConfirmation(context, rh.gs(R.string.refresheventsfromnightscout) + " ?", { + uel.log(Action.FOOD, Sources.Food, rh.gs(R.string.refresheventsfromnightscout), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.refresheventsfromnightscout))) disposable += Completable.fromAction { repository.deleteAllFoods() } .subscribeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.main) @@ -172,7 +172,7 @@ class FoodFragment : DaggerFragment() { } // make it unique val categories = ArrayList(catSet) - categories.add(0, resourceHelper.gs(R.string.none)) + categories.add(0, rh.gs(R.string.none)) context?.let { context -> val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) binding.category.adapter = adapterCategories @@ -182,7 +182,7 @@ class FoodFragment : DaggerFragment() { private fun fillSubcategories() { val categoryFilter = binding.category.selectedItem.toString() val subCatSet: MutableSet = HashSet() - if (categoryFilter != resourceHelper.gs(R.string.none)) { + if (categoryFilter != rh.gs(R.string.none)) { for (f in unfiltered) { if (f.category != null && f.category == categoryFilter) { val subCategory = f.subCategory @@ -192,7 +192,7 @@ class FoodFragment : DaggerFragment() { } // make it unique val subcategories = ArrayList(subCatSet) - subcategories.add(0, resourceHelper.gs(R.string.none)) + subcategories.add(0, rh.gs(R.string.none)) context?.let { context -> val adapterSubcategories = ArrayAdapter(context, R.layout.spinner_centered, subcategories) binding.subcategory.adapter = adapterSubcategories @@ -202,14 +202,14 @@ class FoodFragment : DaggerFragment() { private fun filterData() { val textFilter = binding.filter.text.toString() val categoryFilter = binding.category.selectedItem?.toString() - ?: resourceHelper.gs(R.string.none) + ?: rh.gs(R.string.none) val subcategoryFilter = binding.subcategory.selectedItem?.toString() - ?: resourceHelper.gs(R.string.none) + ?: rh.gs(R.string.none) val newFiltered = ArrayList() for (f in unfiltered) { if (f.category == null || f.subCategory == null) continue - if (subcategoryFilter != resourceHelper.gs(R.string.none) && f.subCategory != subcategoryFilter) continue - if (categoryFilter != resourceHelper.gs(R.string.none) && f.category != categoryFilter) continue + if (subcategoryFilter != rh.gs(R.string.none) && f.subCategory != subcategoryFilter) 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 newFiltered.add(f) } @@ -232,12 +232,12 @@ class FoodFragment : DaggerFragment() { holder.binding.nsSign.visibility = (food.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.name.text = food.name holder.binding.portion.text = food.portion.toString() + food.unit - holder.binding.carbs.text = food.carbs.toString() + resourceHelper.gs(R.string.shortgramm) - holder.binding.fat.text = resourceHelper.gs(R.string.shortfat) + ": " + food.fat + resourceHelper.gs(R.string.shortgramm) + holder.binding.carbs.text = food.carbs.toString() + rh.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.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.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.remove.tag = food } @@ -252,7 +252,7 @@ class FoodFragment : DaggerFragment() { binding.remove.setOnClickListener { v: View -> val food = v.tag as Food 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) disposable += repository.runTransactionForResult(InvalidateFoodTransaction(food.id)) .subscribe( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index db617c7f08..79eeb7dab7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -27,7 +27,7 @@ import javax.inject.Singleton class FoodPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper + rh: ResourceHelper ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(FoodFragment::class.java.name) @@ -35,7 +35,7 @@ class FoodPlugin @Inject constructor( .pluginName(R.string.food) .shortName(R.string.food_short) .description(R.string.description_food), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { // cannot be inner class because of needed injection diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt index 7309b0f0f8..be4eba7ac2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt @@ -58,7 +58,7 @@ import kotlin.system.exitProcess @Singleton class ImportExportPrefsImpl @Inject constructor( private var log: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val buildHelper: BuildHelper, private val rxBus: RxBus, @@ -121,7 +121,7 @@ class ImportExportPrefsImpl @Inject constructor( // name provided (hopefully) by user 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 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 -> 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 -> 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 { if (!sp.contains(R.string.key_master_password) || (sp.getString(R.string.key_master_password, "") == "")) { WarningDialog.showWarning(activity, - resourceHelper.gs(wrongPwdTitle), - resourceHelper.gs(R.string.master_password_missing, resourceHelper.gs(R.string.configbuilder_general), resourceHelper.gs(R.string.protection)), + rh.gs(wrongPwdTitle), + rh.gs(R.string.master_password_missing, rh.gs(R.string.configbuilder_general), rh.gs(R.string.protection)), R.string.nav_preferences, { val intent = Intent(activity, PreferencesActivity::class.java).apply { 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)) { if (!assureMasterPasswordSet(activity, R.string.nav_export)) return - TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_export), - resourceHelper.gs(R.string.export_to) + " " + fileToExport.name + " ?", - resourceHelper.gs(R.string.password_preferences_encrypt_prompt), { + TwoMessagesAlertDialog.showAlert(activity, rh.gs(R.string.nav_export), + rh.gs(R.string.export_to) + " " + fileToExport.name + " ?", + rh.gs(R.string.password_preferences_encrypt_prompt), { askForMasterPassIfNeeded(activity, R.string.preferences_export_canceled, then) }, null, R.drawable.ic_header_export) } private fun askToConfirmImport(activity: FragmentActivity, fileToImport: PrefsFile, then: ((password: String) -> Unit)) { if (!assureMasterPasswordSet(activity, R.string.nav_import)) return - TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_import), - resourceHelper.gs(R.string.import_from) + " " + fileToImport.name + " ?", - resourceHelper.gs(R.string.password_preferences_decrypt_prompt), { + TwoMessagesAlertDialog.showAlert(activity, rh.gs(R.string.nav_import), + rh.gs(R.string.import_from) + " " + fileToImport.name + " ?", + rh.gs(R.string.password_preferences_decrypt_prompt), { askForMasterPass(activity, R.string.preferences_import_canceled, then) }, null, R.drawable.ic_header_import) } @@ -224,22 +224,22 @@ class ImportExportPrefsImpl @Inject constructor( encryptedPrefsFormat.savePreferences(newFile, prefs, password) - ToastUtils.okToast(activity, resourceHelper.gs(R.string.exported)) + ToastUtils.okToast(activity, rh.gs(R.string.exported)) } 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) } catch (e: IOException) { ToastUtils.errorToast(activity, e.message) log.error(LTag.CORE, "Unhandled exception", e) } catch (e: PrefFileNotFoundError) { - ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) - + "\n\n" + resourceHelper.gs(R.string.filenotfound) + ToastUtils.Long.errorToast(activity, rh.gs(R.string.preferences_export_canceled) + + "\n\n" + rh.gs(R.string.filenotfound) + ": " + e.message - + "\n\n" + resourceHelper.gs(R.string.needstoragepermission)) + + "\n\n" + rh.gs(R.string.needstoragepermission)) log.error(LTag.CORE, "File system exception", e) } catch (e: PrefIOError) { - ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) - + "\n\n" + resourceHelper.gs(R.string.needstoragepermission) + ToastUtils.Long.errorToast(activity, rh.gs(R.string.preferences_export_canceled) + + "\n\n" + rh.gs(R.string.needstoragepermission) + ": " + e.message) log.error(LTag.CORE, "File system exception", e) } @@ -260,7 +260,7 @@ class ImportExportPrefsImpl @Inject constructor( } catch (e: IllegalArgumentException) { // this exception happens on some early implementations of ActivityResult contracts // 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) } } @@ -298,14 +298,14 @@ class ImportExportPrefsImpl @Inject constructor( restartAppAfterImport(activity) } else { // 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) { - 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) } catch (e: PrefIOError) { log.error(LTag.CORE, "Unhandled exception", e) @@ -326,7 +326,7 @@ class ImportExportPrefsImpl @Inject constructor( private fun restartAppAfterImport(context: Context) { 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) log.debug(LTag.CORE, "Exiting") rxBus.send(EventAppExit()) @@ -354,7 +354,7 @@ class ImportExportPrefsImpl @Inject constructor( @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var repository: AppRepository - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var prefFileList: PrefFileListProvider @Inject lateinit var context: Context @Inject lateinit var userEntryPresentationHelper: UserEntryPresentationHelper @@ -371,9 +371,9 @@ class ImportExportPrefsImpl @Inject constructor( var ret = Result.success() try { saveCsv(newFile, entries) - ToastUtils.okToast(context, resourceHelper.gs(R.string.ue_exported)) + ToastUtils.okToast(context, rh.gs(R.string.ue_exported)) } 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) ret = Result.failure(workDataOf("Error" to "Error FileNotFoundException")) } catch (e: IOException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 064c3c0998..ab892688e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -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.Sources 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.interfaces.DataSyncSelector 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.general.maintenance.activities.LogSettingActivity 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.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers @@ -37,12 +39,15 @@ class MaintenanceFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var importExportPrefs: ImportExportPrefs @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var danaHistoryDatabase: DanaHistoryDatabase @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 dataSyncSelector: DataSyncSelector @Inject lateinit var pumpSync: PumpSync @@ -73,12 +78,15 @@ class MaintenanceFragment : DaggerFragment() { } binding.navResetdb.setOnClickListener { 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( fromAction { repository.clearDatabases() danaHistoryDatabase.clearAllTables() insightDatabase.clearAllTables() + diaconnDatabase.clearAllTables() + erosDatabase.clearAllTables() + dashDatabase.clearAllTables() dataSyncSelector.resetToNextFullSync() pumpSync.connectNewPump() overviewData.reset() @@ -86,12 +94,10 @@ class MaintenanceFragment : DaggerFragment() { iobCobCalculator.clearCache() } .subscribeOn(aapsSchedulers.io) - .observeOn(aapsSchedulers.main) .subscribeBy( onError = { aapsLogger.error("Error clearing databases", it) }, onComplete = { - rxBus.send(EventNewBG(null)) - rxBus.send(EventNewHistoryData(0, true)) + rxBus.send(EventPreferenceChange(rh, R.string.key_units)) } ) ) @@ -116,7 +122,7 @@ class MaintenanceFragment : DaggerFragment() { binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) } binding.exportCsv.setOnClickListener { 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) importExportPrefs.exportUserEntriesCsv(activity) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 4a695b15eb..2437ff645a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -27,7 +27,7 @@ import javax.inject.Singleton class MaintenancePlugin @Inject constructor( injector: HasAndroidInjector, private val context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val nsSettingsStatus: NSSettingsStatus, aapsLogger: AAPSLogger, @@ -46,7 +46,7 @@ class MaintenancePlugin @Inject constructor( .shortName(R.string.maintenance_shortname) .preferencesId(R.xml.pref_maintenance) .description(R.string.description_maintenance), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { 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("you have to do it manually)" + 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()) builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + 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()) - if (buildHelper.isEngineeringMode()) builder.append(resourceHelper.gs(R.string.engineering_mode_enabled)) + builder.append(rh.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator()) + if (buildHelper.isEngineeringMode()) builder.append(rh.gs(R.string.engineering_mode_enabled)) return sendMail(attachmentUri, recipient, subject, builder.toString()) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index ccfa691d6c..54ed71eaf0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -621,7 +621,6 @@ class DataSyncSelectorImplementation @Inject constructor( //private var lastTbrId = -1L //private var lastTbrTime = -1L override fun processChangedTemporaryBasalsCompat(): Boolean { - val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) val lastDbIdWrapped = appRepository.getLastTemporaryBasalIdWrapped().blockingGet() 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) @@ -658,7 +657,7 @@ class DataSyncSelectorImplementation @Inject constructor( tb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", - tb.first.toJson(true, profile, dateUtil, useAbsolute), + tb.first.toJson(true, profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), "$startId/$lastDbId" ) @@ -667,7 +666,7 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbUpdate( "treatments", tb.first.interfaceIDs.nightscoutId, - tb.first.toJson(false, profile, dateUtil, useAbsolute), + tb.first.toJson(false, profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second.id), "$startId/$lastDbId" ) @@ -700,7 +699,6 @@ class DataSyncSelectorImplementation @Inject constructor( //private var lastEbId = -1L //private var lastEbTime = -1L override fun processChangedExtendedBolusesCompat(): Boolean { - val useAbsolute = sp.getBoolean(R.string.key_ns_sync_use_absolute, false) val lastDbIdWrapped = appRepository.getLastExtendedBolusIdWrapped().blockingGet() 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) @@ -737,7 +735,7 @@ class DataSyncSelectorImplementation @Inject constructor( eb.first.interfaceIDs.nightscoutId == null -> nsClientPlugin.nsClientService?.dbAdd( "treatments", - eb.first.toJson(true, profile, dateUtil, useAbsolute), + eb.first.toJson(true, profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), "$startId/$lastDbId" ) @@ -746,7 +744,7 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbUpdate( "treatments", eb.first.interfaceIDs.nightscoutId, - eb.first.toJson(false, profile, dateUtil, useAbsolute), + eb.first.toJson(false, profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second.id), "$startId/$lastDbId" ) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt index f41e57684f..1bfbd3e4e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddAckWorker.kt @@ -1,10 +1,12 @@ package info.nightscout.androidaps.plugins.general.nsclient import android.content.Context +import android.os.SystemClock import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.DeviceStatus 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.receivers.DataWorker import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class NSClientAddAckWorker( @@ -30,6 +33,7 @@ class NSClientAddAckWorker( @Inject lateinit var rxBus: RxBus @Inject lateinit var dataSyncSelector: DataSyncSelector @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var sp: SP override fun doWork(): Result { var ret = Result.success() @@ -37,6 +41,8 @@ class NSClientAddAckWorker( val ack = dataWorker.pickupObject(inputData.getLong(DataWorker.STORE_KEY, -1)) as NSAddAck? ?: 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) { is PairTemporaryTarget -> { val pair = ack.originalObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt index d5ea0d41a7..c63d153c7b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt @@ -28,7 +28,7 @@ class NSClientFragment : DaggerFragment() { @Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -70,8 +70,8 @@ class NSClientFragment : DaggerFragment() { binding.deliverNow.paintFlags = binding.deliverNow.paintFlags or Paint.UNDERLINE_TEXT_FLAG binding.fullSync.setOnClickListener { context?.let { context -> - OKDialog.showConfirmation(context, resourceHelper.gs(R.string.nsclientinternal), - resourceHelper.gs(R.string.full_sync_comment), Runnable { + OKDialog.showConfirmation(context, rh.gs(R.string.nsclientinternal), + rh.gs(R.string.full_sync_comment), Runnable { dataSyncSelector.resetToNextFullSync() }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt index 1b7854a99a..e7255caf3c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt @@ -49,7 +49,7 @@ class NSClientPlugin @Inject constructor( aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val context: Context, private val fabricPrivacy: FabricPrivacy, private val sp: SP, @@ -64,7 +64,7 @@ class NSClientPlugin @Inject constructor( .shortName(R.string.nsclientinternal_shortname) .preferencesId(R.xml.pref_nsclientinternal) .description(R.string.description_ns_client), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() @@ -100,7 +100,7 @@ class NSClientPlugin @Inject constructor( .toObservable(EventNSClientStatus::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventNSClientStatus -> - status = event.getStatus(resourceHelper) + status = event.getStatus(rh) rxBus.send(EventNSClientUpdateGUI()) }, fabricPrivacy::logException) ) @@ -148,17 +148,17 @@ class NSClientPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) if (config.NSCLIENT) { - preferenceFragment.findPreference(resourceHelper.gs(R.string.ns_sync_options))?.isVisible = false + preferenceFragment.findPreference(rh.gs(R.string.ns_sync_options))?.isVisible = false - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_create_announcements_from_errors))?.isVisible = false - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_create_announcements_from_carbs_req))?.isVisible = false - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_sync_use_absolute))?.isVisible = false + preferenceFragment.findPreference(rh.gs(R.string.key_ns_create_announcements_from_errors))?.isVisible = false + preferenceFragment.findPreference(rh.gs(R.string.key_ns_create_announcements_from_carbs_req))?.isVisible = false +// preferenceFragment.findPreference(rh.gs(R.string.key_ns_sync_use_absolute))?.isVisible = false } else { // APS or pumpControl mode - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_receive_profile_switch))?.isVisible = buildHelper.isEngineeringMode() - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_receive_insulin))?.isVisible = buildHelper.isEngineeringMode() - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_receive_carbs))?.isVisible = buildHelper.isEngineeringMode() - preferenceFragment.findPreference(resourceHelper.gs(R.string.key_ns_receive_temp_target))?.isVisible = buildHelper.isEngineeringMode() + preferenceFragment.findPreference(rh.gs(R.string.key_ns_receive_profile_switch))?.isVisible = buildHelper.isEngineeringMode() + preferenceFragment.findPreference(rh.gs(R.string.key_ns_receive_insulin))?.isVisible = buildHelper.isEngineeringMode() + preferenceFragment.findPreference(rh.gs(R.string.key_ns_receive_carbs))?.isVisible = buildHelper.isEngineeringMode() + preferenceFragment.findPreference(rh.gs(R.string.key_ns_receive_temp_target))?.isVisible = buildHelper.isEngineeringMode() } } @@ -217,7 +217,7 @@ class NSClientPlugin @Inject constructor( fun pause(newState: Boolean) { sp.putBoolean(R.string.key_nsclientinternal_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 ?: "" @@ -225,7 +225,7 @@ class NSClientPlugin @Inject constructor( fun handleClearAlarm(originalAlarm: NSAlarm, silenceTimeInMilliseconds: Long) { 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") return } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt index 5cf88e216a..dadb14687c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt @@ -14,7 +14,7 @@ import javax.inject.Singleton @Singleton class NsClientReceiverDelegate @Inject constructor( private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val receiverStatusStore: ReceiverStatusStore ) { @@ -28,12 +28,12 @@ class NsClientReceiverDelegate @Inject constructor( } fun onStatusEvent(ev: EventPreferenceChange) { - if (ev.isChanged(resourceHelper, R.string.key_ns_wifionly) || - ev.isChanged(resourceHelper, R.string.key_ns_wifi_ssids) || - ev.isChanged(resourceHelper, R.string.key_ns_allowroaming)) { + if (ev.isChanged(rh, R.string.key_ns_wifionly) || + ev.isChanged(rh, R.string.key_ns_wifi_ssids) || + ev.isChanged(rh, R.string.key_ns_allowroaming)) { receiverStatusStore.updateNetworkStatus() 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() } } @@ -58,7 +58,7 @@ class NsClientReceiverDelegate @Inject constructor( val newAllowedState = allowedChargingState && allowedNetworkState if (newAllowedState != allowed) { allowed = newAllowedState - rxBus.send(EventPreferenceChange(resourceHelper.gs(R.string.key_nsclientinternal_paused))) + rxBus.send(EventPreferenceChange(rh.gs(R.string.key_nsclientinternal_paused))) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java deleted file mode 100644 index 5f0647bfbc..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java +++ /dev/null @@ -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); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.kt new file mode 100644 index 0000000000..72c6d5bc24 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.kt @@ -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) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt index e18ae5dd9d..5352f7f463 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -77,7 +76,7 @@ import javax.inject.Singleton class NSDeviceStatus @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val nsSettingsStatus: NSSettingsStatus, private val config: Config, private val dateUtil: DateUtil, @@ -158,8 +157,8 @@ class NSDeviceStatus @Inject constructor( //String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"}; val string = StringBuilder() - .append("") - .append(resourceHelper.gs(R.string.pump)) + .append("") + .append(rh.gs(R.string.pump)) .append(": ") // 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("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("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("device")) string.append(device).append(" ") string.append("") // color @@ -195,7 +194,7 @@ class NSDeviceStatus @Inject constructor( if (clock == 0L || deviceStatusData.pumpData != null && clock < deviceStatusData.pumpData!!.clock) return // create new status and process data - var deviceStatusPumpData = DeviceStatusData.PumpData() + val deviceStatusPumpData = DeviceStatusData.PumpData() deviceStatusPumpData.clock = clock 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") @@ -249,8 +248,8 @@ class NSDeviceStatus @Inject constructor( val openApsStatus: Spanned get() { val string = StringBuilder() - .append("") - .append(resourceHelper.gs(R.string.openaps_short)) + .append("") + .append(rh.gs(R.string.openaps_short)) .append(": ") // test warning level @@ -260,7 +259,7 @@ class NSDeviceStatus @Inject constructor( else -> Levels.INFO } string.append("") - 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("") // color return fromHtml(string.toString()) } @@ -269,8 +268,8 @@ class NSDeviceStatus @Inject constructor( get() { val string = StringBuilder() try { - if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockEnacted)).append(" ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("
") - if (deviceStatusData.openAPSData.suggested != null) string.append("").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockSuggested)).append(" ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("
") + if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockEnacted)).append(" ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("
") + if (deviceStatusData.openAPSData.suggested != null) string.append("").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockSuggested)).append(" ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("
") return fromHtml(string.toString()) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) @@ -322,8 +321,8 @@ class NSDeviceStatus @Inject constructor( val uploaderStatusSpanned: Spanned get() { val string = StringBuilder() - string.append("") - string.append(resourceHelper.gs(R.string.uploader_short)) + string.append("") + string.append(rh.gs(R.string.uploader_short)) string.append(": ") val iterator: Iterator<*> = deviceStatusData.uploaderMap.entries.iterator() var minBattery = 100 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt index 4fbe8da0f6..3f66d4d7f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt @@ -118,7 +118,7 @@ import javax.inject.Singleton @Singleton class NSSettingsStatus @Inject constructor( private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val rxBus: RxBus, private val defaultValueHelper: DefaultValueHelper, private val sp: SP, @@ -150,7 +150,7 @@ class NSSettingsStatus @Inject constructor( data = status aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: ${getVersion()}") 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)) } else { rxBus.send(EventDismissNotification(Notification.OLD_NS)) @@ -252,7 +252,7 @@ class NSSettingsStatus @Inject constructor( 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() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt index dfe4ede8d4..c4291de252 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt @@ -4,5 +4,5 @@ import info.nightscout.androidaps.events.EventStatus import info.nightscout.androidaps.utils.resources.ResourceHelper class EventNSClientStatus(var text: String) : EventStatus() { - override fun getStatus(resourceHelper: ResourceHelper): String = text + override fun getStatus(rh: ResourceHelper): String = text } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt index b000688f28..77a09e402e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt @@ -70,7 +70,7 @@ class NSClientService : DaggerService() { @Inject lateinit var nsSettingsStatus: NSSettingsStatus @Inject lateinit var nsDeviceStatus: NSDeviceStatus @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsClientPlugin: NSClientPlugin @@ -119,7 +119,7 @@ class NSClientService : DaggerService() { .toObservable(EventConfigBuilderChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ - if (nsEnabled != nsClientPlugin.isEnabled(PluginType.GENERAL)) { + if (nsEnabled != nsClientPlugin.isEnabled()) { latestDateInReceivedData = 0 destroy() initialize() @@ -130,9 +130,9 @@ class NSClientService : DaggerService() { .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventPreferenceChange -> - if (event.isChanged(resourceHelper, R.string.key_nsclientinternal_url) || - event.isChanged(resourceHelper, R.string.key_nsclientinternal_api_secret) || - event.isChanged(resourceHelper, R.string.key_nsclientinternal_paused)) { + if (event.isChanged(rh, R.string.key_nsclientinternal_url) || + event.isChanged(rh, R.string.key_nsclientinternal_api_secret) || + event.isChanged(rh, R.string.key_nsclientinternal_paused)) { latestDateInReceivedData = 0 destroy() initialize() @@ -199,20 +199,20 @@ class NSClientService : DaggerService() { var connectionStatus = "Authenticated (" if (ack.read) connectionStatus += "R" if (ack.write) connectionStatus += "W" - if (ack.write_treatment) connectionStatus += "T" + if (ack.writeTreatment) connectionStatus += "T" connectionStatus += ')' isConnected = true - hasWriteAuth = ack.write && ack.write_treatment + hasWriteAuth = ack.write && ack.writeTreatment rxBus.send(EventNSClientStatus(connectionStatus)) rxBus.send(EventNSClientNewLog("AUTH", connectionStatus)) if (!ack.write) { rxBus.send(EventNSClientNewLog("ERROR", "Write permission not granted ")) } - if (!ack.write_treatment) { + if (!ack.writeTreatment) { rxBus.send(EventNSClientNewLog("ERROR", "Write treatment permission not granted ")) } 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)) } else { 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)) 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(EventNSClientNewLog("WATCHDOG", "pausing for $WATCHDOG_RECONNECT_IN minutes")) nsClientPlugin.pause(true) @@ -356,7 +356,7 @@ class NSClientService : DaggerService() { } fun readPreferences() { - nsEnabled = nsClientPlugin.isEnabled(PluginType.GENERAL) + nsEnabled = nsClientPlugin.isEnabled() nsURL = sp.getString(R.string.key_nsclientinternal_url, "") nsAPISecret = sp.getString(R.string.key_nsclientinternal_api_secret, "") nsDevice = sp.getString("careportal_enteredby", "") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt index 2cdd860ce3..c831c22f6c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt @@ -38,7 +38,7 @@ import kotlin.math.min class OverviewData @Inject constructor( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val dateUtil: DateUtil, private val sp: SP, private val activePlugin: ActivePlugin, @@ -53,20 +53,6 @@ class OverviewData @Inject constructor( 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 toTime: Long = 0 var fromTime: Long = 0 @@ -76,8 +62,6 @@ class OverviewData @Inject constructor( pumpStatus = "" calcProgress = "" lastBg = null - temporaryBasal = null - extendedBolus = null bolusIob = null basalIob = null cobInfo = null @@ -145,11 +129,11 @@ class OverviewData @Inject constructor( val lastBgColor: Int get() = lastBg?.let { lastBg -> when { - lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> resourceHelper.gc(R.color.low) - lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> resourceHelper.gc(R.color.high) - else -> resourceHelper.gc(R.color.inrange) + lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> rh.gc(R.color.low) + lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> rh.gc(R.color.high) + else -> rh.gc(R.color.inrange) } - } ?: resourceHelper.gc(R.color.inrange) + } ?: rh.gc(R.color.inrange) val isActualBg: Boolean get() = @@ -161,29 +145,28 @@ class OverviewData @Inject constructor( * TEMPORARY BASAL */ - var temporaryBasal: TemporaryBasal? = null - val temporaryBasalText: String get() = profileFunction.getProfile()?.let { profile -> + var temporaryBasal = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) if (temporaryBasal?.isInProgress == false) temporaryBasal = null temporaryBasal?.let { "T:" + it.toStringShort() } - ?: resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()) - } ?: resourceHelper.gs(R.string.notavailable) + ?: rh.gs(R.string.pump_basebasalrate, profile.getBasal()) + } ?: rh.gs(R.string.notavailable) val temporaryBasalDialogText: String get() = profileFunction.getProfile()?.let { profile -> - temporaryBasal?.let { temporaryBasal -> - "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal())}" + - "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil) + iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { temporaryBasal -> + "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}" + + "\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())}" - } ?: resourceHelper.gs(R.string.notavailable) + ?: "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}" + } ?: rh.gs(R.string.notavailable) val temporaryBasalIcon: Int get() = profileFunction.getProfile()?.let { profile -> - temporaryBasal?.let { temporaryBasal -> + iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { temporaryBasal -> val percentRate = temporaryBasal.convertedToPercent(dateUtil.now(), profile) when { percentRate > 100 -> R.drawable.ic_cp_basal_tbr_high @@ -194,27 +177,23 @@ class OverviewData @Inject constructor( } ?: R.drawable.ic_cp_basal_no_tbr val temporaryBasalColor: Int - get() = temporaryBasal?.let { resourceHelper.gc(R.color.basal) } - ?: resourceHelper.gc(R.color.defaulttextcolor) + get() = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { rh.gc(R.color.basal) } + ?: rh.gc(R.color.defaulttextcolor) /* * EXTENDED BOLUS */ - var extendedBolus: ExtendedBolus? = null - val extendedBolusText: String get() = - extendedBolus?.let { extendedBolus -> - if (!extendedBolus.isInProgress(dateUtil)) { - this@OverviewData.extendedBolus = null - "" - } else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate) + iobCobCalculator.getExtendedBolus(dateUtil.now())?.let { extendedBolus -> + if (!extendedBolus.isInProgress(dateUtil)) "" + else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) rh.gs(R.string.pump_basebasalrate, extendedBolus.rate) else "" } ?: "" val extendedBolusDialogText: String - get() = extendedBolus?.toStringFull(dateUtil) ?: "" + get() = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) ?: "" /* * IOB, COB @@ -229,19 +208,19 @@ class OverviewData @Inject constructor( get() = bolusIob?.let { bolusIob -> basalIob?.let { basalIob -> - resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) - } ?: resourceHelper.gs(R.string.value_unavailable_short) - } ?: resourceHelper.gs(R.string.value_unavailable_short) + rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + } ?: rh.gs(R.string.value_unavailable_short) + } ?: rh.gs(R.string.value_unavailable_short) val iobDialogText: String get() = bolusIob?.let { bolusIob -> basalIob?.let { basalIob -> - resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" + - resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" + - resourceHelper.gs(R.string.basal) + ": " + resourceHelper.gs(R.string.formatinsulinunits, basalIob.basaliob) - } ?: resourceHelper.gs(R.string.value_unavailable_short) - } ?: resourceHelper.gs(R.string.value_unavailable_short) + rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" + + rh.gs(R.string.bolus) + ": " + rh.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" + + rh.gs(R.string.basal) + ": " + rh.gs(R.string.formatinsulinunits, basalIob.basaliob) + } ?: rh.gs(R.string.value_unavailable_short) + } ?: rh.gs(R.string.value_unavailable_short) /* * TEMP TARGET @@ -324,8 +303,9 @@ class OverviewData @Inject constructor( for (bg in bgReadingsArray) { if (bg.timestamp < fromTime || bg.timestamp > toTime) continue 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] }) maxBgValue = Profile.fromMgdlToUnits(maxBgValue, profileFunction.getUnits()) if (defaultValueHelper.determineHighLine() > maxBgValue) maxBgValue = defaultValueHelper.determineHighLine() @@ -364,7 +344,7 @@ class OverviewData @Inject constructor( val bgListArray: MutableList = java.util.ArrayList() val predictions: MutableList? = apsResult?.predictions - ?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper) } + ?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh) } ?.toMutableList() if (predictions != null) { predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) } @@ -386,8 +366,9 @@ class OverviewData @Inject constructor( val bucketedListArray: MutableList = java.util.ArrayList() for (inMemoryGlucoseValue in bucketedData) { 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] }) // profiler.log(LTag.UI, "prepareBucketedData() $from", start) } @@ -464,27 +445,27 @@ class OverviewData @Inject constructor( // create series baseBasalGraphSeries = LineGraphSeries(Array(baseBasalArray.size) { i -> baseBasalArray[i] }).also { it.isDrawBackground = true - it.backgroundColor = resourceHelper.gc(R.color.basebasal) + it.backgroundColor = rh.gc(R.color.basebasal) it.thickness = 0 } tempBasalGraphSeries = LineGraphSeries(Array(tempBasalArray.size) { i -> tempBasalArray[i] }).also { it.isDrawBackground = true - it.backgroundColor = resourceHelper.gc(R.color.tempbasal) + it.backgroundColor = rh.gc(R.color.tempbasal) it.thickness = 0 } basalLineGraphSeries = LineGraphSeries(Array(basalLineArray.size) { i -> basalLineArray[i] }).also { it.setCustomPaint(Paint().also { paint -> 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.color = resourceHelper.gc(R.color.basal) + paint.color = rh.gc(R.color.basal) }) } absoluteBasalGraphSeries = LineGraphSeries(Array(absoluteBasalLineArray.size) { i -> absoluteBasalLineArray[i] }).also { it.setCustomPaint(Paint().also { absolutePaint -> absolutePaint.style = Paint.Style.STROKE - absolutePaint.strokeWidth = resourceHelper.getDisplayMetrics().scaledDensity * 2 - absolutePaint.color = resourceHelper.gc(R.color.basal) + absolutePaint.strokeWidth = rh.getDisplayMetrics().scaledDensity * 2 + absolutePaint.color = rh.gc(R.color.basal) }) } // profiler.log(LTag.UI, "prepareBasalData() $from", start) @@ -520,7 +501,7 @@ class OverviewData @Inject constructor( // create series temporaryTargetSeries = LineGraphSeries(Array(targetsSeriesArray.size) { i -> targetsSeriesArray[i] }).also { it.isDrawBackground = false - it.color = resourceHelper.gc(R.color.tempTargetBackground) + it.color = rh.gc(R.color.tempTargetBackground) it.thickness = 2 } // profiler.log(LTag.UI, "prepareTemporaryTargetData() $from", start) @@ -533,14 +514,14 @@ class OverviewData @Inject constructor( maxTreatmentsValue = 0.0 val filteredTreatments: MutableList = java.util.ArrayList() 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 } .forEach { it.y = getNearestBg(it.x.toLong()) filteredTreatments.add(it) } repository.getCarbsDataFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet() - .map { CarbsDataPoint(it, resourceHelper) } + .map { CarbsDataPoint(it, rh) } .forEach { it.y = getNearestBg(it.x.toLong()) filteredTreatments.add(it) @@ -553,7 +534,14 @@ class OverviewData @Inject constructor( // OfflineEvent 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) // Extended bolus @@ -569,7 +557,7 @@ class OverviewData @Inject constructor( // Careportal repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() - .map { TherapyEventDataPoint(it, resourceHelper, profileFunction, translator) } + .map { TherapyEventDataPoint(it, rh, profileFunction, translator) } .filterTimeframe(fromTime, endTime) .forEach { if (it.y == 0.0) it.y = getNearestBg(it.x.toLong()) @@ -680,15 +668,15 @@ class OverviewData @Inject constructor( // DEVIATIONS 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.pastSensitivity == "C") color = resourceHelper.gc(R.color.deviationgrey) - if (autosensData.pastSensitivity == "+") color = resourceHelper.gc(R.color.deviationgreen) - if (autosensData.pastSensitivity == "-") color = resourceHelper.gc(R.color.deviationred) + if (autosensData.pastSensitivity == "C") color = rh.gc(R.color.deviationgrey) + if (autosensData.pastSensitivity == "+") color = rh.gc(R.color.deviationgreen) + if (autosensData.pastSensitivity == "-") color = rh.gc(R.color.deviationred) } else if (autosensData.type == "uam") { - color = resourceHelper.gc(R.color.uam) + color = rh.gc(R.color.uam) } 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)) maxDevValueFound = maxOf(maxDevValueFound, abs(autosensData.deviation), abs(bgi)) @@ -714,14 +702,14 @@ class OverviewData @Inject constructor( // IOB iobSeries = FixedLineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also { it.isDrawBackground = true - it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% - it.color = resourceHelper.gc(R.color.iob) + it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50% + it.color = rh.gc(R.color.iob) it.thickness = 3 } absIobSeries = FixedLineGraphSeries(Array(absIobArray.size) { i -> absIobArray[i] }).also { it.isDrawBackground = true - it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% - it.color = resourceHelper.gc(R.color.iob) + it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50% + it.color = rh.gc(R.color.iob) it.thickness = 3 } @@ -732,14 +720,14 @@ class OverviewData @Inject constructor( val iobPrediction: MutableList = java.util.ArrayList() val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) 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)) } iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] }) val iobPrediction2: MutableList = java.util.ArrayList() val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) 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)) } iobPredictions2Series = PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] }) @@ -753,8 +741,8 @@ class OverviewData @Inject constructor( // COB cobSeries = FixedLineGraphSeries(Array(cobArray.size) { i -> cobArray[i] }).also { it.isDrawBackground = true - it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.cob) //50% - it.color = resourceHelper.gc(R.color.cob) + it.backgroundColor = -0x7f000001 and rh.gc(R.color.cob) //50% + it.color = rh.gc(R.color.cob) it.thickness = 3 } cobMinFailOverSeries = PointsWithLabelGraphSeries(Array(minFailOverActiveList.size) { i -> minFailOverActiveList[i] }) @@ -762,7 +750,7 @@ class OverviewData @Inject constructor( // ACTIVITY activitySeries = FixedLineGraphSeries(Array(actArrayHist.size) { i -> actArrayHist[i] }).also { it.isDrawBackground = false - it.color = resourceHelper.gc(R.color.activity) + it.color = rh.gc(R.color.activity) it.thickness = 3 } activityPredictionSeries = FixedLineGraphSeries(Array(actArrayPrediction.size) { i -> actArrayPrediction[i] }).also { @@ -770,14 +758,14 @@ class OverviewData @Inject constructor( paint.style = Paint.Style.STROKE paint.strokeWidth = 3f paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f) - paint.color = resourceHelper.gc(R.color.activity) + paint.color = rh.gc(R.color.activity) }) } // BGI minusBgiSeries = FixedLineGraphSeries(Array(bgiArrayHist.size) { i -> bgiArrayHist[i] }).also { it.isDrawBackground = false - it.color = resourceHelper.gc(R.color.bgi) + it.color = rh.gc(R.color.bgi) it.thickness = 3 } minusBgiHistSeries = FixedLineGraphSeries(Array(bgiArrayPrediction.size) { i -> bgiArrayPrediction[i] }).also { @@ -785,7 +773,7 @@ class OverviewData @Inject constructor( paint.style = Paint.Style.STROKE paint.strokeWidth = 3f 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 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 } // DEV SLOPE 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 } 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 } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index 36735b856a..924cd778f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -45,15 +45,17 @@ import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.extensions.valueToUnitsString import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification import info.nightscout.androidaps.plugins.bus.RxBus 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.nsclient.data.NSDeviceStatus 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.notifications.NotificationStore 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.source.DexcomPlugin import info.nightscout.androidaps.plugins.source.XdripPlugin -import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper @@ -93,7 +94,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var constraintChecker: ConstraintChecker @@ -122,6 +123,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var overviewData: OverviewData @Inject lateinit var overviewPlugin: OverviewPlugin @Inject lateinit var automationPlugin: AutomationPlugin + @Inject lateinit var bgQualityCheckPlugin: BgQualityCheckPlugin private val disposable = CompositeDisposable() @@ -165,16 +167,16 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList smallHeight = screenHeight <= Constants.SMALL_HEIGHT 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.notifications.setHasFixedSize(false) 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 - 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?.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?.setEnterFadeDuration(1200) @@ -188,8 +190,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overviewData.initRange() overviewData.prepareBucketedData("EventBucketedDataCreated") overviewData.prepareBgData("EventBucketedDataCreated") - updateGUI("rangeChange", OverviewData.Property.GRAPH) - rxBus.send(EventPreferenceChange(resourceHelper, R.string.key_rangetodisplay)) + updateGraph("rangeChange") + rxBus.send(EventPreferenceChange(rh, R.string.key_rangetodisplay)) sp.putBoolean(R.string.key_objectiveusescale, true) false } @@ -225,41 +227,93 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList override fun onResume() { super.onResume() disposable += activePlugin.activeOverview.overviewBus - .toObservable(EventUpdateOverview::class.java) + .toObservable(EventUpdateOverviewTime::class.java) + .debounce(1L, TimeUnit.SECONDS) .observeOn(aapsSchedulers.main) - .subscribe({ updateGUI(it.from, it.what) }, fabricPrivacy::logException) - - disposable.add(rxBus + .subscribe({ updateTime(it.from) }, fabricPrivacy::logException) + disposable += activePlugin.activeOverview.overviewBus + .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) .observeOn(aapsSchedulers.io) .subscribe({ - if (it.now) overviewPlugin.refreshLoop(it.from) - else scheduleUpdateGUI(it.from) - }, fabricPrivacy::logException)) - disposable.add(rxBus + if (it.now) overviewPlugin.refreshLoop(it.from) + else scheduleUpdateGUI(it.from) + }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventAcceptOpenLoopChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ scheduleUpdateGUI("EventAcceptOpenLoopChange") }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventInitializationChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ updateGUI("EventInitializationChanged", OverviewData.Property.TIME) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ updateTime("EventInitializationChanged") }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ scheduleUpdateGUI("EventPreferenceChange") }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ scheduleUpdateGUI("EventPreferenceChange") }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventNewOpenLoopNotification::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }, fabricPrivacy::logException)) + .subscribe({ scheduleUpdateGUI("EventNewOpenLoopNotification") }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) - .delay (30, TimeUnit.MILLISECONDS, aapsSchedulers.main) + .delay(30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .subscribe({ - overviewData.pumpStatus = it.getStatus(resourceHelper) - updateGUI("EventPumpStatusChanged", OverviewData.Property.PUMPSTATUS) - }, fabricPrivacy::logException) + overviewData.pumpStatus = it.getStatus(rh) + updatePumpStatus("EventPumpStatusChanged") + }, fabricPrivacy::logException) refreshLoop = Runnable { overviewPlugin.refreshLoop("refreshLoop") @@ -267,7 +321,17 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } 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 @@ -282,12 +346,27 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (childFragmentManager.isStateSaved) return activity?.let { activity -> when (v.id) { - R.id.treatment_button -> protectionCheck.queryProtection(activity, 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.treatment_button -> protectionCheck.queryProtection( + activity, + 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.carbs_button -> protectionCheck.queryProtection(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.carbs_button -> protectionCheck.queryProtection( + 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 -> { ProfileViewerDialog().also { pvd -> @@ -299,47 +378,47 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } R.id.cgm_button -> { - if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) + if (xdripPlugin.isEnabled()) openCgmApp("com.eveningoutpost.dexdrip") - else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { + else if (dexcomPlugin.isEnabled()) { dexcomMediator.findDexcomPackageName()?.let { 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 -> { - if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) { + if (xdripPlugin.isEnabled()) { CalibrationDialog().show(childFragmentManager, "CalibrationDialog") - } else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { + } else if (dexcomPlugin.isEnabled()) { try { dexcomMediator.findDexcomPackageName()?.let { 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) { - ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.g5appnotdetected)) + ToastUtils.showToastInUiThread(activity, rh.gs(R.string.g5appnotdetected)) } } } R.id.accept_temp_button -> { profileFunction.getProfile() ?: return - if (loopPlugin.isEnabled(PluginType.LOOP)) { + if (loopPlugin.isEnabled()) { handler.post { val lastRun = loopPlugin.lastRun loopPlugin.invoke("Accept temp button", false) if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { 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(), { - uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) - binding.buttonsLayout.acceptTempButton.visibility = View.GONE - (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) - rxBus.send(EventWearInitiateAction("cancelChangeRequest")) - Thread { loopPlugin.acceptChangeRequest() }.run() - }) + uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) + binding.buttonsLayout.acceptTempButton.visibility = View.GONE + (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) + rxBus.send(EventWearInitiateAction("cancelChangeRequest")) + Thread { loopPlugin.acceptChangeRequest() }.run() + }) }) } } @@ -366,7 +445,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList intent.addCategory(Intent.CATEGORY_LAUNCHER) it.startActivity(intent) } 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.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 @@ -408,7 +492,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() activity?.let { 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 } wizard.confirmAndExecute(it) @@ -430,8 +514,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended()) { binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false) - binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + resourceHelper.gs(R.string.format_carbs, quickWizardEntry.carbs()) + - " " + resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) + binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + rh.gs(R.string.format_carbs, quickWizardEntry.carbs()) + + " " + rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) if (wizard.calculatedTotalInsulin <= 0) 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.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.text = "${resourceHelper.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}" + binding.buttonsLayout.acceptTempButton.text = "${rh.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}" } else { binding.buttonsLayout.acceptTempButton.visibility = View.GONE } // **** 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.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() // **** Calibration & CGM buttons **** - val xDripIsBgSource = xdripPlugin.isEnabled(PluginType.BGSOURCE) - val dexcomIsSource = dexcomPlugin.isEnabled(PluginType.BGSOURCE) + val xDripIsBgSource = xdripPlugin.isEnabled() + val dexcomIsSource = dexcomPlugin.isEnabled() 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() @@ -470,18 +558,18 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (event.isEnabled && event.trigger.shouldRun()) context?.let { context -> 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.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.setOnClickListener { OKDialog.showConfirmation( context, - resourceHelper.gs(R.string.run_question, event.title), + rh.gs(R.string.run_question, event.title), { handler.post { automationPlugin.processEvent(event, true) } } ) } @@ -502,30 +590,32 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList when { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { 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 } loopPlugin.isDisconnected -> { 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 } loopPlugin.isEnabled() && loopPlugin.isSuspended -> { 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 } pump.isSuspended() -> { - binding.infoLayout.apsMode.setImageResource(if (pump.model() == PumpType.OMNIPOD_EROS || pump.model() == PumpType.OMNIPOD_DASH) { - // For Omnipod, indicate the pump as disconnected when it's suspended. - // The only way to 'reconnect' it, is through the Omnipod tab - R.drawable.ic_loop_disconnected - } else { - R.drawable.ic_loop_paused - }) + binding.infoLayout.apsMode.setImageResource( + if (pump.model() == PumpType.OMNIPOD_EROS || pump.model() == PumpType.OMNIPOD_DASH) { + // For Omnipod, indicate the pump as disconnected when it's suspended. + // The only way to 'reconnect' it, is through the Omnipod tab + R.drawable.ic_loop_disconnected + } else { + R.drawable.ic_loop_paused + } + ) binding.infoLayout.apsModeText.visibility = View.GONE } @@ -558,15 +648,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList // pump status from ns 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 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 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) { @@ -581,8 +671,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) 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.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) + graph.layoutParams = + 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?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth @@ -591,7 +682,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList relativeLayout.addView(graph) 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_LEFT) label.layoutParams = layoutParams @@ -619,257 +710,283 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList task?.let { handler.postDelayed(it, 500) } } - @Suppress("UNUSED_PARAMETER") @SuppressLint("SetTextI18n") - fun updateGUI(from: String, what: OverviewData.Property) { -// if (what != OverviewData.Property.CALC_PROGRESS) -// 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) } - + @Suppress("UNUSED_PARAMETER") + fun updateBg(from: String) { 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 - when (what) { - OverviewData.Property.BG -> { - binding.infoLayout.bg.text = overviewData.lastBg?.valueToUnitsString(units) - ?: resourceHelper.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) + binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText + binding.infoLayout.extendedLayout.setOnClickListener { + activity?.let { OKDialog.show(it, rh.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) } + } + binding.infoLayout.extendedLayout.visibility = (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() + } - 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) + @Suppress("UNUSED_PARAMETER") + fun updateTime(from: String) { + 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() + } + + @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 { - binding.infoLayout.deltaLarge.text = "" - binding.infoLayout.delta.text = "Δ " + resourceHelper.gs(R.string.notavailable) - binding.infoLayout.avgDelta.text = "" - binding.infoLayout.longAvgDelta.text = "" + binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextDefault)) + binding.tempTarget.setBackgroundColor(rh.gc(R.color.ribbonDefault)) + binding.tempTarget.text = Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units) } - - // 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 = 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 = 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) } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt index f730ac35b6..baf807f31c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt @@ -24,7 +24,7 @@ import javax.inject.Singleton @Singleton class OverviewMenus @Inject constructor( private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val rxBus: RxBus, private val buildHelper: BuildHelper, @@ -53,7 +53,7 @@ class OverviewMenus @Inject constructor( fun enabledTypes(graph: Int): String { val r = StringBuilder() for (type in CharType.values()) if (_setting[graph][type.ordinal]) { - r.append(resourceHelper.gs(type.shortnameId)) + r.append(rh.gs(type.shortnameId)) r.append(" ") } return r.toString() @@ -102,7 +102,7 @@ class OverviewMenus @Inject constructor( for (g in 0 until 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.isChecked = true } @@ -117,10 +117,10 @@ class OverviewMenus @Inject constructor( if (settingsCopy[g2][m.ordinal]) insert = false } 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 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.isCheckable = true item.isChecked = settingsCopy[g][m.ordinal] @@ -129,7 +129,7 @@ class OverviewMenus @Inject constructor( } } 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.isChecked = false } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 22026f31ad..fc41c0c5b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -13,9 +13,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.events.EventLoopInvoked import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification -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.events.* 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.notifications.NotificationStore @@ -41,15 +39,15 @@ class OverviewPlugin @Inject constructor( private val sp: SP, aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val config: Config, private val dateUtil: DateUtil, - private val profileFunction: ProfileFunction, private val iobCobCalculator: IobCobCalculator, private val repository: AppRepository, private val overviewData: OverviewData, private val overviewMenus: OverviewMenus -) : PluginBase(PluginDescription() +) : PluginBase( + PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(OverviewFragment::class.qualifiedName) .alwaysVisible(true) @@ -59,7 +57,7 @@ class OverviewPlugin @Inject constructor( .shortName(R.string.overview_shortname) .preferencesId(R.xml.pref_overview) .description(R.string.description_overview), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Overview { private var disposable: CompositeDisposable = CompositeDisposable() @@ -75,85 +73,97 @@ class OverviewPlugin @Inject constructor( notificationStore.createNotificationChannel() disposable += rxBus - .toObservable(EventNewNotification::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ n -> - if (notificationStore.add(n.notification)) - rxBus.send(EventRefreshOverview("EventNewNotification")) - }, fabricPrivacy::logException) + .toObservable(EventNewNotification::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ n -> + if (notificationStore.add(n.notification)) + rxBus.send(EventUpdateOverviewNotification("EventNewNotification")) + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventDismissNotification::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ n -> - if (notificationStore.remove(n.id)) - rxBus.send(EventRefreshOverview("EventDismissNotification")) - }, fabricPrivacy::logException) + .toObservable(EventDismissNotification::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ n -> + if (notificationStore.remove(n.id)) + rxBus.send(EventUpdateOverviewNotification("EventDismissNotification")) + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventIobCalculationProgress::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ overviewData.calcProgress = it.progress; overviewBus.send(EventUpdateOverview("EventIobCalculationProgress", OverviewData.Property.CALC_PROGRESS)) }, fabricPrivacy::logException) + .toObservable(EventIobCalculationProgress::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ overviewData.calcProgress = it.progress; overviewBus.send(EventUpdateOverviewCalcProgress("EventIobCalculationProgress")) }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventTempBasalChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ loadTemporaryBasal("EventTempBasalChange") }, fabricPrivacy::logException) + .toObservable(EventTempBasalChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ overviewBus.send(EventUpdateOverviewTemporaryBasal("EventTempBasalChange")) }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventExtendedBolusChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ loadExtendedBolus("EventExtendedBolusChange") }, fabricPrivacy::logException) + .toObservable(EventExtendedBolusChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ overviewBus.send(EventUpdateOverviewExtendedBolus("EventExtendedBolusChange")) }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventNewBG::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ loadBg("EventNewBG") }, fabricPrivacy::logException) + .toObservable(EventNewBG::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ loadBg("EventNewBG") }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventTempTargetChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ loadTemporaryTarget("EventTempTargetChange") }, fabricPrivacy::logException) + .toObservable(EventTempTargetChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ loadTemporaryTarget("EventTempTargetChange") }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventTreatmentChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - loadIobCobResults("EventTreatmentChange") - overviewData.prepareTreatmentsData("EventTreatmentChange") - overviewBus.send(EventUpdateOverview("EventTreatmentChange", OverviewData.Property.GRAPH)) - }, fabricPrivacy::logException) + .toObservable(EventTreatmentChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + loadIobCobResults("EventTreatmentChange") + overviewData.prepareTreatmentsData("EventTreatmentChange") + overviewBus.send(EventUpdateOverviewGraph("EventTreatmentChange")) + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventTherapyEventChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - overviewData.prepareTreatmentsData("EventTherapyEventChange") - overviewBus.send(EventUpdateOverview("EventTherapyEventChange", OverviewData.Property.GRAPH)) - }, fabricPrivacy::logException) + .toObservable(EventTherapyEventChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + overviewData.prepareTreatmentsData("EventTherapyEventChange") + overviewBus.send(EventUpdateOverviewGraph("EventTherapyEventChange")) + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventBucketedDataCreated::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - overviewData.prepareBucketedData("EventBucketedDataCreated") - overviewData.prepareBgData("EventBucketedDataCreated") - overviewBus.send(EventUpdateOverview("EventBucketedDataCreated", OverviewData.Property.GRAPH)) - }, fabricPrivacy::logException) + .toObservable(EventBucketedDataCreated::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + overviewData.prepareBucketedData("EventBucketedDataCreated") + overviewData.prepareBgData("EventBucketedDataCreated") + overviewBus.send(EventUpdateOverviewGraph("EventBucketedDataCreated")) + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventLoopInvoked::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ overviewData.preparePredictions("EventLoopInvoked") }, fabricPrivacy::logException) + .toObservable(EventLoopInvoked::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ overviewData.preparePredictions("EventLoopInvoked") }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventEffectiveProfileSwitchChanged::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - loadProfile("EventEffectiveProfileSwitchChanged") - overviewData.prepareBasalData("EventEffectiveProfileSwitchChanged") - }, fabricPrivacy::logException) + .toObservable(EventEffectiveProfileSwitchChanged::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + loadProfile("EventEffectiveProfileSwitchChanged") + overviewData.prepareBasalData("EventEffectiveProfileSwitchChanged") + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - if (it.cause !is EventCustomCalculationFinished) refreshLoop("EventAutosensCalculationFinished") - }, fabricPrivacy::logException) + .toObservable(EventAutosensCalculationFinished::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + if (it.cause !is EventCustomCalculationFinished) refreshLoop("EventAutosensCalculationFinished") + }, fabricPrivacy::logException) disposable += rxBus - .toObservable(EventPumpStatusChanged::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - overviewData.pumpStatus = it.getStatus(resourceHelper) - }, fabricPrivacy::logException) + .toObservable(EventPumpStatusChanged::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + overviewData.pumpStatus = it.getStatus(rh) + }, 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() } @@ -166,11 +176,11 @@ class OverviewPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) 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.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.isEnabled = false } @@ -178,58 +188,58 @@ class OverviewPlugin @Inject constructor( } override fun configuration(): JSONObject = - JSONObject() - .putInt(R.string.key_units, sp, resourceHelper) - .putString(R.string.key_quickwizard, sp, resourceHelper) - .putInt(R.string.key_eatingsoon_duration, sp, resourceHelper) - .putDouble(R.string.key_eatingsoon_target, sp, resourceHelper) - .putInt(R.string.key_activity_duration, sp, resourceHelper) - .putDouble(R.string.key_activity_target, sp, resourceHelper) - .putInt(R.string.key_hypo_duration, sp, resourceHelper) - .putDouble(R.string.key_hypo_target, sp, resourceHelper) - .putDouble(R.string.key_low_mark, sp, resourceHelper) - .putDouble(R.string.key_high_mark, sp, resourceHelper) - .putDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) - .putDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) - .putDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) + JSONObject() + .putString(R.string.key_units, sp, rh) + .putString(R.string.key_quickwizard, sp, rh) + .putInt(R.string.key_eatingsoon_duration, sp, rh) + .putDouble(R.string.key_eatingsoon_target, sp, rh) + .putInt(R.string.key_activity_duration, sp, rh) + .putDouble(R.string.key_activity_target, sp, rh) + .putInt(R.string.key_hypo_duration, sp, rh) + .putDouble(R.string.key_hypo_target, sp, rh) + .putDouble(R.string.key_low_mark, sp, rh) + .putDouble(R.string.key_high_mark, sp, rh) + .putDouble(R.string.key_statuslights_cage_warning, sp, rh) + .putDouble(R.string.key_statuslights_cage_critical, sp, rh) + .putDouble(R.string.key_statuslights_iage_warning, sp, rh) + .putDouble(R.string.key_statuslights_iage_critical, sp, rh) + .putDouble(R.string.key_statuslights_sage_warning, sp, rh) + .putDouble(R.string.key_statuslights_sage_critical, sp, rh) + .putDouble(R.string.key_statuslights_sbat_warning, sp, rh) + .putDouble(R.string.key_statuslights_sbat_critical, sp, rh) + .putDouble(R.string.key_statuslights_bage_warning, sp, rh) + .putDouble(R.string.key_statuslights_bage_critical, sp, rh) + .putDouble(R.string.key_statuslights_res_warning, sp, rh) + .putDouble(R.string.key_statuslights_res_critical, sp, rh) + .putDouble(R.string.key_statuslights_bat_warning, sp, rh) + .putDouble(R.string.key_statuslights_bat_critical, sp, rh) override fun applyConfiguration(configuration: JSONObject) { configuration - .storeInt(R.string.key_units, sp, resourceHelper) - .storeString(R.string.key_quickwizard, sp, resourceHelper) - .storeInt(R.string.key_eatingsoon_duration, sp, resourceHelper) - .storeDouble(R.string.key_eatingsoon_target, sp, resourceHelper) - .storeInt(R.string.key_activity_duration, sp, resourceHelper) - .storeDouble(R.string.key_activity_target, sp, resourceHelper) - .storeInt(R.string.key_hypo_duration, sp, resourceHelper) - .storeDouble(R.string.key_hypo_target, sp, resourceHelper) - .storeDouble(R.string.key_low_mark, sp, resourceHelper) - .storeDouble(R.string.key_high_mark, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) - .storeDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) + .storeString(R.string.key_units, sp, rh) + .storeString(R.string.key_quickwizard, sp, rh) + .storeInt(R.string.key_eatingsoon_duration, sp, rh) + .storeDouble(R.string.key_eatingsoon_target, sp, rh) + .storeInt(R.string.key_activity_duration, sp, rh) + .storeDouble(R.string.key_activity_target, sp, rh) + .storeInt(R.string.key_hypo_duration, sp, rh) + .storeDouble(R.string.key_hypo_target, sp, rh) + .storeDouble(R.string.key_low_mark, sp, rh) + .storeDouble(R.string.key_high_mark, sp, rh) + .storeDouble(R.string.key_statuslights_cage_warning, sp, rh) + .storeDouble(R.string.key_statuslights_cage_critical, sp, rh) + .storeDouble(R.string.key_statuslights_iage_warning, sp, rh) + .storeDouble(R.string.key_statuslights_iage_critical, sp, rh) + .storeDouble(R.string.key_statuslights_sage_warning, sp, rh) + .storeDouble(R.string.key_statuslights_sage_critical, sp, rh) + .storeDouble(R.string.key_statuslights_sbat_warning, sp, rh) + .storeDouble(R.string.key_statuslights_sbat_critical, sp, rh) + .storeDouble(R.string.key_statuslights_bage_warning, sp, rh) + .storeDouble(R.string.key_statuslights_bage_critical, sp, rh) + .storeDouble(R.string.key_statuslights_res_warning, sp, rh) + .storeDouble(R.string.key_statuslights_res_critical, sp, rh) + .storeDouble(R.string.key_statuslights_bat_warning, sp, rh) + .storeDouble(R.string.key_statuslights_bat_critical, sp, rh) } @Volatile @@ -237,22 +247,23 @@ class OverviewPlugin @Inject constructor( override fun refreshLoop(from: String) { if (runningRefresh) return runningRefresh = true + overviewBus.send(EventUpdateOverviewNotification(from)) loadIobCobResults(from) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.PROFILE)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.BG)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TIME)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_BASAL)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.EXTENDED_BOLUS)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_TARGET)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.SENSITIVITY)) + overviewBus.send(EventUpdateOverviewProfile(from)) + overviewBus.send(EventUpdateOverviewBg(from)) + overviewBus.send(EventUpdateOverviewTime(from)) + overviewBus.send(EventUpdateOverviewTemporaryBasal(from)) + overviewBus.send(EventUpdateOverviewExtendedBolus(from)) + overviewBus.send(EventUpdateOverviewTemporaryTarget(from)) + overviewBus.send(EventUpdateOverviewSensitivity(from)) loadAsData(from) overviewData.preparePredictions(from) overviewData.prepareBasalData(from) overviewData.prepareTemporaryTargetData(from) overviewData.prepareTreatmentsData(from) overviewData.prepareIobAutosensData(from) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.GRAPH)) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.IOB_COB)) + overviewBus.send(EventUpdateOverviewGraph(from)) + overviewBus.send(EventUpdateOverviewIobCob(from)) aapsLogger.debug(LTag.UI, "refreshLoop finished") runningRefresh = false } @@ -261,8 +272,6 @@ class OverviewPlugin @Inject constructor( private fun loadAll(from: String) { loadBg(from) loadProfile(from) - loadTemporaryBasal(from) - loadExtendedBolus(from) loadTemporaryTarget(from) loadIobCobResults(from) loadAsData(from) @@ -271,41 +280,31 @@ class OverviewPlugin @Inject constructor( overviewData.prepareTreatmentsData(from) // prepareIobAutosensData(from) // preparePredictions(from) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.GRAPH)) + overviewBus.send(EventUpdateOverviewGraph(from)) aapsLogger.debug(LTag.UI, "loadAll finished") } private fun loadProfile(from: String) { - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.PROFILE)) - } - - 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)) + overviewBus.send(EventUpdateOverviewProfile(from)) } private fun loadTemporaryTarget(from: String) { val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) overviewData.temporaryTarget = tempTarget.value else overviewData.temporaryTarget = null - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.TEMPORARY_TARGET)) + overviewBus.send(EventUpdateOverviewTemporaryTarget(from)) } private fun loadAsData(from: String) { overviewData.lastAutosensData = iobCobCalculator.ads.getLastAutosensData("Overview", aapsLogger, dateUtil) - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.SENSITIVITY)) + overviewBus.send(EventUpdateOverviewSensitivity(from)) } private fun loadBg(from: String) { val gvWrapped = repository.getLastGlucoseValueWrapped().blockingGet() if (gvWrapped is ValueWrapper.Existing) overviewData.lastBg = gvWrapped.value else overviewData.lastBg = null - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.BG)) + overviewBus.send(EventUpdateOverviewBg(from)) } private fun loadIobCobResults(from: String) { @@ -315,7 +314,7 @@ class OverviewPlugin @Inject constructor( val lastCarbs = repository.getLastCarbsRecordWrapped().blockingGet() overviewData.lastCarbsTime = if (lastCarbs is ValueWrapper.Existing) lastCarbs.value.timestamp else 0L - overviewBus.send(EventUpdateOverview(from, OverviewData.Property.IOB_COB)) + overviewBus.send(EventUpdateOverviewIobCob(from)) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index 2fd42278d5..8fe3863db2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -23,7 +23,7 @@ import javax.inject.Singleton @Singleton class StatusLightHandler @Inject constructor( - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val dateUtil: DateUtil, private val activePlugin: ActivePlugin, @@ -59,7 +59,7 @@ class StatusLightHandler @Inject constructor( if (!config.NSCLIENT) { if (pump.model() == PumpType.OMNIPOD_DASH) { // 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) } 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. @@ -77,9 +77,9 @@ class StatusLightHandler @Inject constructor( val therapyEvent = repository.getLastTherapyRecordUpToNow(type).blockingGet() if (therapyEvent is ValueWrapper.Existing) { 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 { - 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) { handleLevel(view, criticalSetting, criticalDefaultValue, warnSetting, warnDefaultValue, level, units) } else { - view?.text = resourceHelper.gs(R.string.notavailable) + view?.text = rh.gs(R.string.notavailable) view?.setTextColor(Color.WHITE) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt index 0b82509cc1..eb56d8067e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt @@ -45,7 +45,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() { holder.from.text = dateUtil.timeString(quickWizard[position].validFromDate()) holder.to.text = dateUtil.timeString(quickWizard[position].validToDate()) 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() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt index 90f6ca5dc9..72e1b46983 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt @@ -100,19 +100,19 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener { val toTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> 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 { context?.let { TimePickerDialog(it, toTimeSetListener, - T.secs(fromSeconds.toLong()).hours().toInt(), - T.secs((fromSeconds % 3600).toLong()).mins().toInt(), + T.secs(toSeconds.toLong()).hours().toInt(), + T.secs((toSeconds % 3600).toLong()).mins().toInt(), DateFormat.is24HourFormat(context) ).show() } } - toSeconds = entry.validFrom() + toSeconds = entry.validTo() binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) binding.buttonEdit.setText(entry.buttonText()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverview.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverview.kt deleted file mode 100644 index 969ed4feed..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverview.kt +++ /dev/null @@ -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() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewBg.kt new file mode 100644 index 0000000000..2bbfb7813c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewBg.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewBg(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewCalcProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewCalcProgress.kt new file mode 100644 index 0000000000..6932500fe3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewCalcProgress.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewCalcProgress(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewExtendedBolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewExtendedBolus.kt new file mode 100644 index 0000000000..51b493acf4 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewExtendedBolus.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewExtendedBolus(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewGraph.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewGraph.kt new file mode 100644 index 0000000000..3f7ad2faad --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewGraph.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewGraph(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewIobCob.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewIobCob.kt new file mode 100644 index 0000000000..75c8d16bac --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewIobCob.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewIobCob(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewNotification.kt new file mode 100644 index 0000000000..7a4ce41eea --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewNotification.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewNotification(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewProfile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewProfile.kt new file mode 100644 index 0000000000..6e4bb95490 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewProfile.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewProfile(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewPumpStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewPumpStatus.kt new file mode 100644 index 0000000000..30ad6b7507 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewPumpStatus.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewPumpStatus(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewSensitivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewSensitivity.kt new file mode 100644 index 0000000000..93c432f507 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewSensitivity.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewSensitivity(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryBasal.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryBasal.kt new file mode 100644 index 0000000000..315bf8d651 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryBasal.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewTemporaryBasal(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryTarget.kt new file mode 100644 index 0000000000..83cafcd664 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTemporaryTarget.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewTemporaryTarget(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTime.kt new file mode 100644 index 0000000000..5da5b72136 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventUpdateOverviewTime.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.events.Event + +class EventUpdateOverviewTime(val from: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index 5aaa5ed402..4d25275a88 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -32,7 +32,7 @@ class GraphData( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper private var maxY = Double.MIN_VALUE @@ -66,7 +66,7 @@ class GraphData( addSeries(AreaGraphSeries(inRangeAreaDataPoints).also { it.color = 0 it.isDrawBackground = true - it.backgroundColor = resourceHelper.gc(R.color.inrangebackground) + it.backgroundColor = rh.gc(R.color.inrangebackground) }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt index 89136b5b69..f0138d70b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt @@ -11,7 +11,7 @@ import javax.inject.Inject class BolusDataPoint @Inject constructor( val data: Bolus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val activePlugin: ActivePlugin, private val defaultValueHelper: DefaultValueHelper ) : DataPointWithLabelInterface { @@ -20,7 +20,7 @@ class BolusDataPoint @Inject constructor( override fun getX(): Double = data.timestamp.toDouble() 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 getSize(): Float = 2f @@ -29,9 +29,9 @@ class BolusDataPoint @Inject constructor( else PointsWithLabelGraphSeries.Shape.BOLUS 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 resourceHelper.gc(android.R.color.holo_red_light) + else rh.gc(android.R.color.holo_red_light) override fun setY(y: Double) { yValue = y diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt index 719533da98..5eece0277f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt @@ -7,22 +7,22 @@ import javax.inject.Inject class CarbsDataPoint @Inject constructor( val data: Carbs, - private val resourceHelper: ResourceHelper + private val rh: ResourceHelper ) : DataPointWithLabelInterface { private var yValue = 0.0 override fun getX(): Double = data.timestamp.toDouble() 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 getSize(): Float = 2f override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.CARBS override fun getColor(): Int = - if (data.isValid) resourceHelper.gc(R.color.carbs) - else resourceHelper.gc(android.R.color.holo_red_light) + if (data.isValid) rh.gc(R.color.carbs) + else rh.gc(android.R.color.holo_red_light) override fun setY(y: Double) { yValue = y diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt index 3c4c6aa367..ea5b79727d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt @@ -13,7 +13,7 @@ class GlucoseValueDataPoint @Inject constructor( val data: GlucoseValue, private val defaultValueHelper: DefaultValueHelper, private val profileFunction: ProfileFunction, - private val resourceHelper: ResourceHelper + private val rh: ResourceHelper ) : DataPointWithLabelInterface { fun valueToUnits(units: GlucoseUnit): Double = @@ -42,20 +42,20 @@ class GlucoseValueDataPoint @Inject constructor( val highLine = defaultValueHelper.determineHighLine() return when { isPrediction -> predictionColor - valueToUnits(units) < lowLine -> resourceHelper.gc(R.color.low) - valueToUnits(units) > highLine -> resourceHelper.gc(R.color.high) - else -> resourceHelper.gc(R.color.inrange) + valueToUnits(units) < lowLine -> rh.gc(R.color.low) + valueToUnits(units) > highLine -> rh.gc(R.color.high) + else -> rh.gc(R.color.inrange) } } val predictionColor: Int get() { return when (data.sourceSensor) { - GlucoseValue.SourceSensor.IOB_PREDICTION -> resourceHelper.gc(R.color.iob) - GlucoseValue.SourceSensor.COB_PREDICTION -> resourceHelper.gc(R.color.cob) - GlucoseValue.SourceSensor.A_COB_PREDICTION -> -0x7f000001 and resourceHelper.gc(R.color.cob) - GlucoseValue.SourceSensor.UAM_PREDICTION -> resourceHelper.gc(R.color.uam) - GlucoseValue.SourceSensor.ZT_PREDICTION -> resourceHelper.gc(R.color.zt) + GlucoseValue.SourceSensor.IOB_PREDICTION -> rh.gc(R.color.iob) + GlucoseValue.SourceSensor.COB_PREDICTION -> rh.gc(R.color.cob) + GlucoseValue.SourceSensor.A_COB_PREDICTION -> -0x7f000001 and rh.gc(R.color.cob) + GlucoseValue.SourceSensor.UAM_PREDICTION -> rh.gc(R.color.uam) + GlucoseValue.SourceSensor.ZT_PREDICTION -> rh.gc(R.color.zt) else -> R.color.white } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt index 04540d9131..dbb04b6f5d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt @@ -11,7 +11,7 @@ import javax.inject.Inject class InMemoryGlucoseValueDataPoint @Inject constructor( val data: InMemoryGlucoseValue, private val profileFunction: ProfileFunction, - private val resourceHelper: ResourceHelper + private val rh: ResourceHelper ) : DataPointWithLabelInterface { fun valueToUnits(units: GlucoseUnit): Double = @@ -24,5 +24,5 @@ class InMemoryGlucoseValueDataPoint @Inject constructor( override fun getDuration(): Long = 0 override fun getShape(): PointsWithLabelGraphSeries.Shape = PointsWithLabelGraphSeries.Shape.BUCKETED_BG override fun getSize(): Float = 0.3f - override fun getColor(): Int = resourceHelper.gc(R.color.white) + override fun getColor(): Int = rh.gc(R.color.white) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt index 7f88e33cd1..4a06f79dd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt @@ -12,7 +12,7 @@ import javax.inject.Inject class TherapyEventDataPoint @Inject constructor( val data: TherapyEvent, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val profileFunction: ProfileFunction, private val translator: Translator ) : DataPointWithLabelInterface { @@ -62,10 +62,10 @@ class TherapyEventDataPoint @Inject constructor( 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 = 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.FINGER_STICK_BG_VALUE -> Color.RED TherapyEvent.Type.EXERCISE -> Color.BLUE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt index 80ee31d783..fa7cdfc9c8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt @@ -14,6 +14,7 @@ import androidx.core.app.NotificationCompat import androidx.recyclerview.widget.RecyclerView import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.OverviewNotificationItemBinding +import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.IconsProvider import info.nightscout.androidaps.interfaces.NotificationHolder import info.nightscout.androidaps.logging.AAPSLogger @@ -33,7 +34,7 @@ class NotificationStore @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val context: Context, private val iconsProvider: IconsProvider, private val alarmSoundServiceHelper: AlarmSoundServiceHelper, @@ -103,7 +104,7 @@ class NotificationStore @Inject constructor( private fun raiseSystemNotification(n: Notification) { val mgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val largeIcon = resourceHelper.decodeResource(iconsProvider.getIcon()) + val largeIcon = rh.decodeResource(iconsProvider.getIcon()) val smallIcon = iconsProvider.getNotificationIcon() val sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM) val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) @@ -116,11 +117,11 @@ class NotificationStore @Inject constructor( .setContentIntent(notificationHolder.openAppIntent(context)) if (n.level == Notification.URGENT) { notificationBuilder.setVibrate(longArrayOf(1000, 1000, 1000, 1000)) - .setContentTitle(resourceHelper.gs(R.string.urgent_alarm)) + .setContentTitle(rh.gs(R.string.urgent_alarm)) .setSound(sound, AudioManager.STREAM_ALARM) } else { notificationBuilder.setVibrate(longArrayOf(0, 100, 50, 100, 50)) - .setContentTitle(resourceHelper.gs(R.string.info)) + .setContentTitle(rh.gs(R.string.info)) } mgr.notify(n.id, notificationBuilder.build()) } @@ -150,7 +151,8 @@ class NotificationStore @Inject constructor( } } - inner class NotificationRecyclerViewAdapter internal constructor(private val notificationsList: List) : RecyclerView.Adapter() { + inner class NotificationRecyclerViewAdapter internal constructor(private val notificationsList: List) : + RecyclerView.Adapter() { override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): NotificationsViewHolder = NotificationsViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.overview_notification_item, viewGroup, false)) @@ -163,11 +165,11 @@ class NotificationStore @Inject constructor( @Suppress("SetTextI18n") holder.binding.text.text = dateUtil.timeString(notification.date) + " " + notification.text when (notification.level) { - Notification.URGENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent)) - Notification.NORMAL -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal)) - Notification.LOW -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow)) - Notification.INFO -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo)) - Notification.ANNOUNCEMENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationAnnouncement)) + Notification.URGENT -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationUrgent)) + Notification.NORMAL -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationNormal)) + Notification.LOW -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationLow)) + Notification.INFO -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationInfo)) + Notification.ANNOUNCEMENT -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationAnnouncement)) } } @@ -182,8 +184,9 @@ class NotificationStore @Inject constructor( init { binding.dismiss.setOnClickListener { val notification = it.tag as Notification - rxBus.send(EventDismissNotification(notification.id)) + notification.contextForAction = itemView.context notification.action?.run() + if (remove(notification.id)) rxBus.send(EventRefreshOverview("NotificationCleared")) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt index 9c60e104c2..075308ec44 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt @@ -18,7 +18,7 @@ class NotificationWithAction constructor( ) : Notification() { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var nsClientPlugin: NSClientPlugin diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index 6d670461aa..7304cffa71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -22,6 +22,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy 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 javax.inject.Inject import javax.inject.Singleton @@ -30,7 +31,7 @@ import javax.inject.Singleton class PersistentNotificationPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val profileFunction: ProfileFunction, private val fabricPrivacy: FabricPrivacy, @@ -42,15 +43,16 @@ class PersistentNotificationPlugin @Inject constructor( private val dummyServiceHelper: DummyServiceHelper, private val iconsProvider: IconsProvider, private val glucoseStatusProvider: GlucoseStatusProvider -) : PluginBase(PluginDescription() - .mainType(PluginType.GENERAL) - .neverVisible(true) - .pluginName(R.string.ongoingnotificaction) - .enableByDefault(true) - .alwaysEnabled(true) - .showInList(false) - .description(R.string.description_persistent_notification), - aapsLogger, resourceHelper, injector +) : PluginBase( + PluginDescription() + .mainType(PluginType.GENERAL) + .neverVisible(true) + .pluginName(R.string.ongoingnotificaction) + .enableByDefault(true) + .alwaysEnabled(true) + .showInList(false) + .description(R.string.description_persistent_notification), + aapsLogger, rh, injector ) { // For Android Auto @@ -63,49 +65,48 @@ class PersistentNotificationPlugin @Inject constructor( // End Android auto private val disposable = CompositeDisposable() + private var channel: NotificationChannel? = null override fun onStart() { super.onStart() - createNotificationChannel() // make sure channels exist before triggering updates through the bus - disposable.add(rxBus + disposable += rxBus .toObservable(EventRefreshOverview::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventTempBasalChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventTreatmentChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventInitializationChanged::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventEffectiveProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventAutosensCalculationFinished::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException)) - triggerNotificationUpdate() + .subscribe({ triggerNotificationUpdate() }, fabricPrivacy::logException) } private fun createNotificationChannel() { val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val channel = NotificationChannel(notificationHolder.channelID, notificationHolder.channelID as CharSequence, NotificationManager.IMPORTANCE_HIGH) - mNotificationManager.createNotificationChannel(channel) + channel = NotificationChannel(notificationHolder.channelID, notificationHolder.channelID as CharSequence, NotificationManager.IMPORTANCE_HIGH) + channel?.let { mNotificationManager.createNotificationChannel(it) } } override fun onStop() { @@ -115,6 +116,8 @@ class PersistentNotificationPlugin @Inject constructor( } private fun triggerNotificationUpdate() { + if (channel == null) + createNotificationChannel() // make sure channels exist before triggering updates through the bus updateNotification() dummyServiceHelper.startService(context) } @@ -139,12 +142,12 @@ class PersistentNotificationPlugin @Inject constructor( line1aa += " " + lastBG.trendArrow.symbol } else { line1 += " " + - resourceHelper.gs(R.string.old_data) + + rh.gs(R.string.old_data) + " " line1aa += "$line1." } } else { - line1aa = resourceHelper.gs(R.string.missed_bg_readings) + line1aa = rh.gs(R.string.missed_bg_readings) line1 = line1aa } val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()) @@ -155,8 +158,16 @@ class PersistentNotificationPlugin @Inject constructor( //IOB val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() - line2 = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() - val line2aa = resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + "." + line2 = + rh.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + rh.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo( + false, + "PersistentNotificationPlugin" + ).generateCOBString() + val line2aa = + rh.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + rh.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo( + false, + "PersistentNotificationPlugin" + ).generateCOBString() + "." line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" var line3aa = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h." line3 += " - " + profileFunction.getProfileName() @@ -167,10 +178,12 @@ class PersistentNotificationPlugin @Inject constructor( .setAction(READ_ACTION) .putExtra(CONVERSATION_ID, notificationHolder.notificationID) .setPackage(PACKAGE) - val msgReadPendingIntent = PendingIntent.getBroadcast(context, + val msgReadPendingIntent = PendingIntent.getBroadcast( + context, notificationHolder.notificationID, msgReadIntent, - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) val msgReplyIntent = Intent() .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) .setAction(REPLY_ACTION) @@ -180,7 +193,8 @@ class PersistentNotificationPlugin @Inject constructor( context, notificationHolder.notificationID, msgReplyIntent, - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) // Build a RemoteInput for receiving voice input from devices val remoteInput = RemoteInput.Builder(EXTRA_VOICE_REPLY).build() // Create the UnreadConversation @@ -192,21 +206,23 @@ class PersistentNotificationPlugin @Inject constructor( unreadConversationBuilder.addMessage(line3aa) /// End Android Auto } else { - line1 = resourceHelper.gs(R.string.noprofileset) + line1 = rh.gs(R.string.noprofileset) } val builder = NotificationCompat.Builder(context, notificationHolder.channelID) builder.setOngoing(true) builder.setOnlyAlertOnce(true) builder.setCategory(NotificationCompat.CATEGORY_STATUS) builder.setSmallIcon(iconsProvider.getNotificationIcon()) - builder.setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) + builder.setLargeIcon(rh.decodeResource(iconsProvider.getIcon())) builder.setContentTitle(line1) if (line2 != null) builder.setContentText(line2) if (line3 != null) builder.setSubText(line3) /// Android Auto if (unreadConversationBuilder != null) { - builder.extend(NotificationCompat.CarExtender() - .setUnreadConversation(unreadConversationBuilder.build())) + builder.extend( + NotificationCompat.CarExtender() + .setUnreadConversation(unreadConversationBuilder.build()) + ) } /// End Android Auto builder.setContentIntent(notificationHolder.openAppIntent(context)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt index a8e22abdf2..0910717c59 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt @@ -4,7 +4,7 @@ import android.os.SystemClock import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword @@ -23,10 +23,10 @@ class AuthRequest internal constructor( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var otp: OneTimePassword @Inject lateinit var dateUtil: DateUtil - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue private var date = 0L private var processed = false @@ -48,7 +48,7 @@ class AuthRequest internal constructor( if (!codeIsValid(codeReceived)) { processed = true aapsLogger.debug(LTag.SMS, "Wrong code") - smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_wrongcode))) + smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, rh.gs(R.string.sms_wrongcode))) return } if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { @@ -62,7 +62,7 @@ class AuthRequest internal constructor( } if (commandQueue.size() != 0) { aapsLogger.debug(LTag.SMS, "Command timed out: " + requester.text) - smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_timeout_while_wating))) + smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, rh.gs(R.string.sms_timeout_while_wating))) return } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 883bab601f..9ef28c1ba5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -65,7 +65,7 @@ import kotlin.math.min class SmsCommunicatorPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val smsManager: SmsManager, private val aapsSchedulers: AapsSchedulers, private val sp: SP, @@ -74,7 +74,7 @@ class SmsCommunicatorPlugin @Inject constructor( private val profileFunction: ProfileFunction, private val fabricPrivacy: FabricPrivacy, private val activePlugin: ActivePlugin, - private val commandQueue: CommandQueueProvider, + private val commandQueue: CommandQueue, private val loop: Loop, private val iobCobCalculator: IobCobCalculator, private val xdripCalibrations: XdripCalibrations, @@ -92,7 +92,7 @@ class SmsCommunicatorPlugin @Inject constructor( .shortName(R.string.smscommunicator_shortname) .preferencesId(R.xml.pref_smscommunicator) .description(R.string.description_sms_communicator), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), SmsCommunicator { private val disposable = CompositeDisposable() @@ -133,28 +133,28 @@ class SmsCommunicatorPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) - val distance = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference? + val distance = preferenceFragment.findPreference(rh.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference? ?: return - val allowedNumbers = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference? + val allowedNumbers = preferenceFragment.findPreference(rh.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference? ?: return if (!areMoreNumbers(allowedNumbers.text)) { - distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance) + ".\n" - + resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { - distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance) distance.isEnabled = true } allowedNumbers.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any -> if (!areMoreNumbers(newValue as String)) { distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString() - distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance) + ".\n" - + resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { - distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance) distance.isEnabled = true } true @@ -165,7 +165,7 @@ class SmsCommunicatorPlugin @Inject constructor( super.updatePreferenceSummary(pref) if (pref is EditTextPreference) { if (pref.getKey().contains("smscommunicator_allowednumbers") && (pref.text == null || TextUtils.isEmpty(pref.text.trim { it <= ' ' }))) { - pref.setSummary(resourceHelper.gs(R.string.smscommunicator_allowednumbers_summary)) + pref.setSummary(rh.gs(R.string.smscommunicator_allowednumbers_summary)) } } } @@ -199,7 +199,7 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun processSettings(ev: EventPreferenceChange?) { - if (ev == null || ev.isChanged(resourceHelper, R.string.key_smscommunicator_allowednumbers)) { + if (ev == null || ev.isChanged(rh, R.string.key_smscommunicator_allowednumbers)) { val settings = sp.getString(R.string.key_smscommunicator_allowednumbers, "") allowedNumbers.clear() val substrings = settings.split(";").toTypedArray() @@ -253,56 +253,56 @@ class SmsCommunicatorPlugin @Inject constructor( when (divided[0].uppercase(Locale.getDefault())) { "BG" -> if (divided.size == 1) processBG(receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "LOOP" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processLOOP(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "NSCLIENT" -> if (divided.size == 2) processNSCLIENT(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "PUMP" -> - if (!remoteCommandsAllowed && divided.size > 1) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed && divided.size > 1) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size <= 3) processPUMP(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "PROFILE" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processPROFILE(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "BASAL" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processBASAL(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "EXTENDED" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processEXTENDED(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "BOLUS" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) - else if (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_another_bolus_in_queue))) - else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed))) - else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) + else if (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_another_bolus_in_queue))) + else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotebolusnotallowed))) + else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.pumpsuspended))) else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "CARBS" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2 || divided.size == 3) processCARBS(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "CAL" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processCAL(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "TARGET" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processTARGET(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "SMS" -> - if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_remotecommandnotallowed))) else if (divided.size == 2) processSMS(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) "HELP" -> if (divided.size == 1 || divided.size == 2) processHELP(divided, receivedSms) - else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) else -> if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) { val execute = messageToConfirm @@ -310,7 +310,7 @@ class SmsCommunicatorPlugin @Inject constructor( execute?.action(divided[0]) } else { messageToConfirm = null - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_unknowncommand))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_unknowncommand))) } } } @@ -323,21 +323,21 @@ class SmsCommunicatorPlugin @Inject constructor( var reply = "" val units = profileFunction.getUnits() if (actualBG != null) { - reply = resourceHelper.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", " + reply = rh.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", " } else if (lastBG != null) { val agoMilliseconds = dateUtil.now() - lastBG.timestamp val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt() - reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", " + reply = rh.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsString(units) + " " + String.format(rh.gs(R.string.sms_minago), agoMin) + ", " } val glucoseStatus = glucoseStatusProvider.glucoseStatusData - if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " + if (glucoseStatus != null) reply += rh.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB") - reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" - + resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " - + resourceHelper.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " - + resourceHelper.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) + reply += (rh.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + + rh.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + + rh.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + + rh.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -347,7 +347,7 @@ class SmsCommunicatorPlugin @Inject constructor( "DISABLE", "STOP" -> { if (loop.enabled) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopdisablereplywithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_loopdisablereplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { @@ -356,49 +356,49 @@ class SmsCommunicatorPlugin @Inject constructor( commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { rxBus.send(EventRefreshOverview("SMS_LOOP_STOP")) - val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + - resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + val replyText = rh.gs(R.string.smscommunicator_loophasbeendisabled) + " " + + rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } }) } }) } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.loopisdisabled))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.loopisdisabled))) receivedSms.processed = true } "ENABLE", "START" -> { if (!loop.enabled) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopenablereplywithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_loopenablereplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { uel.log(Action.LOOP_ENABLED, Sources.SMS) loop.enabled = true - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loophasbeenenabled))) rxBus.send(EventRefreshOverview("SMS_LOOP_START")) } }) } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopisenabled))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loopisenabled))) receivedSms.processed = true } "STATUS" -> { val reply = if (loop.enabled) { - if (loop.isSuspended) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loop.minutesToEndOfSuspend()) - else resourceHelper.gs(R.string.smscommunicator_loopisenabled) + if (loop.isSuspended) String.format(rh.gs(R.string.loopsuspendedfor), loop.minutesToEndOfSuspend()) + else rh.gs(R.string.smscommunicator_loopisenabled) } else - resourceHelper.gs(R.string.loopisdisabled) + rh.gs(R.string.loopisdisabled) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } "RESUME" -> { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopresumereplywithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_loopresumereplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { override fun run() { @@ -413,13 +413,13 @@ class SmsCommunicatorPlugin @Inject constructor( commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) + var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } }) - sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopresumed))) + sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loopresumed))) } }) } @@ -431,11 +431,11 @@ class SmsCommunicatorPlugin @Inject constructor( duration = min(180, duration) if (duration == 0) { receivedSms.processed = true - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_wrongduration))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration))) return } else { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) { override fun run() { @@ -451,11 +451,11 @@ class SmsCommunicatorPlugin @Inject constructor( aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) }) rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) - val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " + - resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + val replyText = rh.gs(R.string.smscommunicator_loopsuspended) + " " + + rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) + var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -466,7 +466,7 @@ class SmsCommunicatorPlugin @Inject constructor( } } - else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else -> sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } } @@ -476,7 +476,7 @@ class SmsCommunicatorPlugin @Inject constructor( sendSMS(Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT")) receivedSms.processed = true } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } private fun processHELP(divided: Array, receivedSms: Sms) { @@ -493,7 +493,7 @@ class SmsCommunicatorPlugin @Inject constructor( } } - else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + else -> sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } } @@ -506,7 +506,7 @@ class SmsCommunicatorPlugin @Inject constructor( val reply = pump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, reply)) } else { - val reply = resourceHelper.gs(R.string.readstatusfailed) + val reply = rh.gs(R.string.readstatusfailed) sendSMS(Sms(receivedSms.phoneNumber, reply)) } } @@ -514,7 +514,7 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true } else if ((divided.size == 2) && (divided[1].equals("CONNECT", ignoreCase = true))) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpconnectwithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_pumpconnectwithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { override fun run() { @@ -522,7 +522,7 @@ class SmsCommunicatorPlugin @Inject constructor( commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_pumpconnectfail))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_pumpconnectfail))) } else { disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now())) .subscribe({ result -> @@ -530,7 +530,7 @@ class SmsCommunicatorPlugin @Inject constructor( }, { aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) }) - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_reconnect))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_reconnect))) rxBus.send(EventRefreshOverview("SMS_PUMP_START")) } } @@ -543,11 +543,11 @@ class SmsCommunicatorPlugin @Inject constructor( duration = min(120, duration) if (duration == 0) { receivedSms.processed = true - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_wrongduration))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration))) return } else { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpdisconnectwithcode), duration, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_pumpdisconnectwithcode), duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { override fun run() { @@ -555,12 +555,12 @@ class SmsCommunicatorPlugin @Inject constructor( val profile = profileFunction.getProfile() ?: return loop.goToZeroTemp(duration, profile, OfflineEvent.Reason.DISCONNECT_PUMP) rxBus.send(EventRefreshOverview("SMS_PUMP_DISCONNECT")) - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_pumpdisconnected))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_pumpdisconnected))) } }) } } else { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) return } } @@ -569,7 +569,7 @@ class SmsCommunicatorPlugin @Inject constructor( val anInterface = activePlugin.activeProfileSource val store = anInterface.profile if (store == null) { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.notconfigured))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.notconfigured))) receivedSms.processed = true return } @@ -578,7 +578,7 @@ class SmsCommunicatorPlugin @Inject constructor( if (divided[1].uppercase(Locale.getDefault()) == "STATUS") { sendSMS(Sms(receivedSms.phoneNumber, profileName)) } else if (divided[1].uppercase(Locale.getDefault()) == "LIST") { - if (list.isEmpty()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.invalidprofile))) + if (list.isEmpty()) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.invalidprofile))) else { var reply = "" for (i in list.indices) { @@ -592,24 +592,29 @@ class SmsCommunicatorPlugin @Inject constructor( val pIndex = SafeParse.stringToInt(divided[1]) var percentage = 100 if (divided.size > 2) percentage = SafeParse.stringToInt(divided[2]) - if (pIndex > list.size) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - else if (percentage == 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - else if (pIndex == 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + if (pIndex > list.size) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) + else if (percentage == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) + else if (pIndex == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) else { val profile = store.getSpecificProfile(list[pIndex - 1] as String) - if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.noprofile))) + if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile))) else { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode), list[pIndex - 1], percentage, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_profilereplywithcode), list[pIndex - 1], percentage, passCode) receivedSms.processed = true val finalPercentage = percentage messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) { override fun run() { - profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now()) - val replyText = resourceHelper.gs(R.string.profileswitchcreated) - sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.PROFILE_SWITCH, Sources.SMS, resourceHelper.gs(R.string.profileswitchcreated), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.profileswitchcreated))) + if (profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())) { + val replyText = rh.gs(R.string.profileswitchcreated) + sendSMS(Sms(receivedSms.phoneNumber, replyText)) + uel.log( + Action.PROFILE_SWITCH, Sources.SMS, rh.gs(R.string.profileswitchcreated), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.profileswitchcreated)) + ) + } else { + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.invalidprofile))) + } } }) } @@ -621,24 +626,24 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processBASAL(divided: Array, receivedSms: Sms) { if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_basalstopreplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { override fun run() { commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled) + var replyText = rh.gs(R.string.smscommunicator_tempbasalcanceled) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled))) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcanceled), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled))) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) + var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalcancelfailed))) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcancelfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcancelfailed))) } } }) @@ -650,38 +655,38 @@ class SmsCommunicatorPlugin @Inject constructor( var duration = 30 if (divided.size > 2) duration = SafeParse.stringToInt(divided[2]) val profile = profileFunction.getProfile() - if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.noprofile))) - else if (tempBasalPct == 0 && divided[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongTbrDuration, durationStep))) + if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile))) + else if (tempBasalPct == 0 && divided[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) + else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep))) else { tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) { override fun run() { commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() { override fun run() { if (result.success) { - var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) + var replyText = if (result.isPercent) String.format(rh.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(rh.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) if (result.isPercent) uel.log(Action.TEMP_BASAL, Sources.SMS, - activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration), - ValueWithUnit.Percent(result.percent), - ValueWithUnit.Minute(result.duration)) + activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration), + ValueWithUnit.Percent(result.percent), + ValueWithUnit.Minute(result.duration)) else uel.log(Action.TEMP_BASAL, Sources.SMS, - activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration), - ValueWithUnit.UnitPerHour(result.absolute), - ValueWithUnit.Minute(result.duration)) + activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration), + ValueWithUnit.UnitPerHour(result.absolute), + ValueWithUnit.Minute(result.duration)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) + var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) } } }) @@ -694,37 +699,37 @@ class SmsCommunicatorPlugin @Inject constructor( var duration = 30 if (divided.size > 2) duration = SafeParse.stringToInt(divided[2]) val profile = profileFunction.getProfile() - if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.noprofile))) - else if (tempBasal == 0.0 && divided[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) - else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongTbrDuration, durationStep))) + if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.noprofile))) + else if (tempBasal == 0.0 && divided[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) + else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep))) else { tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value() val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) { override fun run() { commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() { override fun run() { if (result.success) { - var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) - else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) + var replyText = if (result.isPercent) String.format(rh.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) + else String.format(rh.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) if (result.isPercent) - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration), - ValueWithUnit.Percent(result.percent), - ValueWithUnit.Minute(result.duration)) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration), + ValueWithUnit.Percent(result.percent), + ValueWithUnit.Minute(result.duration)) else - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration), - ValueWithUnit.UnitPerHour(result.absolute), - ValueWithUnit.Minute(result.duration)) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration), + ValueWithUnit.UnitPerHour(result.absolute), + ValueWithUnit.Minute(result.duration)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) + var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) + uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) } } }) @@ -737,62 +742,62 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processEXTENDED(divided: Array, receivedSms: Sms) { if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { override fun run() { commandQueue.cancelExtended(object : Callback() { override fun run() { if (result.success) { - var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcanceled) + var replyText = rh.gs(R.string.smscommunicator_extendedcanceled) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed) + var replyText = rh.gs(R.string.smscommunicator_extendedcancelfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedcanceled), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_extendedcanceled))) + uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedcanceled), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedcanceled))) } } }) } }) } else if (divided.size != 3) { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } else { var extended = SafeParse.stringToDouble(divided[1]) val duration = SafeParse.stringToInt(divided[2]) extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value() - if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) else { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) { override fun run() { commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { override fun run() { if (result.success) { - var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) - if (config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) + var replyText = String.format(rh.gs(R.string.smscommunicator_extendedset), aDouble, duration) + if (config.APS) replyText += "\n" + rh.gs(R.string.loopsuspended) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) if (config.APS) - uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedset, aDouble, duration) + " / " + resourceHelper.gs(R.string.loopsuspended), - ValueWithUnit.Insulin(aDouble ?: 0.0), - ValueWithUnit.Minute(duration), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.loopsuspended))) + uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedset, aDouble, duration) + " / " + rh.gs(R.string.loopsuspended), + ValueWithUnit.Insulin(aDouble ?: 0.0), + ValueWithUnit.Minute(duration), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.loopsuspended))) else - uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedset, aDouble, duration), - ValueWithUnit.Insulin(aDouble ?: 0.0), - ValueWithUnit.Minute(duration)) + uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedset, aDouble, duration), + ValueWithUnit.Insulin(aDouble ?: 0.0), + ValueWithUnit.Minute(duration)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) + var replyText = rh.gs(R.string.smscommunicator_extendedfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_extendedfailed))) + uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedfailed))) } } }) @@ -807,13 +812,13 @@ class SmsCommunicatorPlugin @Inject constructor( val isMeal = divided.size > 2 && divided[2].equals("MEAL", ignoreCase = true) bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value() if (divided.size == 3 && !isMeal) { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } else if (bolus > 0.0) { val passCode = generatePassCode() val reply = if (isMeal) - String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusreplywithcode), bolus, passCode) + String.format(rh.gs(R.string.smscommunicator_mealbolusreplywithcode), bolus, passCode) else - String.format(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode) + String.format(rh.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) { override fun run() { @@ -827,9 +832,9 @@ class SmsCommunicatorPlugin @Inject constructor( override fun run() { if (resultSuccess) { var replyText = if (isMeal) - String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) + String.format(rh.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) else - String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) + String.format(rh.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) replyText += "\n" + activePlugin.activePump.shortStatus(true) lastRemoteBolusTime = dateUtil.now() if (isMeal) { @@ -860,17 +865,17 @@ class SmsCommunicatorPlugin @Inject constructor( val tt = if (currentProfile.units == GlucoseUnit.MMOL) { DecimalFormatter.to1Decimal(eatingSoonTT) } else DecimalFormatter.to0Decimal(eatingSoonTT) - replyText += "\n" + String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered_tt), tt, eatingSoonTTDuration) + replyText += "\n" + String.format(rh.gs(R.string.smscommunicator_mealbolusdelivered_tt), tt, eatingSoonTTDuration) } } sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) uel.log(Action.BOLUS, Sources.SMS, replyText) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed) + var replyText = rh.gs(R.string.smscommunicator_bolusfailed) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_bolusfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_bolusfailed))) + uel.log(Action.BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_bolusfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_bolusfailed))) } } }) @@ -878,7 +883,7 @@ class SmsCommunicatorPlugin @Inject constructor( }) } }) - } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + } else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } private fun toTodayTime(hh_colon_mm: String): Long { @@ -906,15 +911,15 @@ class SmsCommunicatorPlugin @Inject constructor( if (divided.size > 2) { time = toTodayTime(divided[2].uppercase(Locale.getDefault())) if (time == 0L) { - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) return } } grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value() - if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) else { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, dateUtil.timeString(time), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_carbsreplywithcode), grams, dateUtil.timeString(time), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) { override fun run() { @@ -924,17 +929,17 @@ class SmsCommunicatorPlugin @Inject constructor( commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (result.success) { - var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) + var replyText = String.format(rh.gs(R.string.smscommunicator_carbsset), anInteger) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + resourceHelper.gs(R.string.smscommunicator_carbsset, anInteger), - ValueWithUnit.Gram(anInteger ?: 0)) + uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsset, anInteger), + ValueWithUnit.Gram(anInteger ?: 0)) } else { - var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed, anInteger) + var replyText = rh.gs(R.string.smscommunicator_carbsfailed, anInteger) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + resourceHelper.gs(R.string.smscommunicator_carbsfailed, anInteger), - ValueWithUnit.Gram(anInteger ?: 0)) + uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsfailed, anInteger), + ValueWithUnit.Gram(anInteger ?: 0)) } } }) @@ -950,7 +955,7 @@ class SmsCommunicatorPlugin @Inject constructor( val isStop = divided[1].equals("STOP", ignoreCase = true) || divided[1].equals("CANCEL", ignoreCase = true) if (isMeal || isActivity || isHypo) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode), divided[1].uppercase(Locale.getDefault()), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_temptargetwithcode), divided[1].uppercase(Locale.getDefault()), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { @@ -1003,7 +1008,7 @@ class SmsCommunicatorPlugin @Inject constructor( aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) }) val ttString = if (units == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) - val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) + val replyText = String.format(rh.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) uel.log(Action.TT, Sources.SMS, ValueWithUnit.fromGlucoseUnit(tt, units.asText), @@ -1012,7 +1017,7 @@ class SmsCommunicatorPlugin @Inject constructor( }) } else if (isStop) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetcancel), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_temptargetcancel), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { @@ -1022,14 +1027,14 @@ class SmsCommunicatorPlugin @Inject constructor( }, { aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) }) - val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_canceled)) + val replyText = String.format(rh.gs(R.string.smscommunicator_tt_canceled)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.CANCEL_TT, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_tt_canceled), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tt_canceled))) + uel.log(Action.CANCEL_TT, Sources.SMS, rh.gs(R.string.smscommunicator_tt_canceled), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tt_canceled))) } }) } else - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } private fun processSMS(divided: Array, receivedSms: Sms) { @@ -1037,41 +1042,41 @@ class SmsCommunicatorPlugin @Inject constructor( || divided[1].equals("DISABLE", ignoreCase = true)) if (isStop) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_stopsmswithcode), passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_stopsmswithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { sp.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false) - val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_stoppedsms)) + val replyText = String.format(rh.gs(R.string.smscommunicator_stoppedsms)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) - uel.log(Action.STOP_SMS, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_stoppedsms), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_stoppedsms))) + uel.log(Action.STOP_SMS, Sources.SMS, rh.gs(R.string.smscommunicator_stoppedsms), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_stoppedsms))) } }) - } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + } else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } private fun processCAL(divided: Array, receivedSms: Sms) { val cal = SafeParse.stringToDouble(divided[1]) if (cal > 0.0) { val passCode = generatePassCode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode) + val reply = String.format(rh.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) { override fun run() { val result = xdripCalibrations.sendIntent(aDouble!!) val replyText = - if (result) resourceHelper.gs(R.string.smscommunicator_calibrationsent) else resourceHelper.gs(R.string.smscommunicator_calibrationfailed) + if (result) rh.gs(R.string.smscommunicator_calibrationsent) else rh.gs(R.string.smscommunicator_calibrationfailed) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) if (result) - uel.log(Action.CALIBRATION, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_calibrationsent), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_calibrationsent))) + uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationsent), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_calibrationsent))) else - uel.log(Action.CALIBRATION, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_calibrationfailed), - ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_calibrationfailed))) + uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationfailed), + ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_calibrationfailed))) } }) - } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + } else sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat))) } override fun sendNotificationToAllNumbers(text: String): Boolean { @@ -1103,16 +1108,16 @@ class SmsCommunicatorPlugin @Inject constructor( messages.add(sms) } catch (e: IllegalArgumentException) { return if (e.message == "Invalid message body") { - val notification = Notification(Notification.INVALID_MESSAGE_BODY, resourceHelper.gs(R.string.smscommunicator_messagebody), Notification.NORMAL) + val notification = Notification(Notification.INVALID_MESSAGE_BODY, rh.gs(R.string.smscommunicator_messagebody), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) false } else { - val notification = Notification(Notification.INVALID_PHONE_NUMBER, resourceHelper.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL) + val notification = Notification(Notification.INVALID_PHONE_NUMBER, rh.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) false } } catch (e: SecurityException) { - val notification = Notification(Notification.MISSING_SMS_PERMISSION, resourceHelper.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL) + val notification = Notification(Notification.MISSING_SMS_PERMISSION, rh.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) return false } @@ -1121,12 +1126,13 @@ class SmsCommunicatorPlugin @Inject constructor( } private fun generatePassCode(): String = - String.format(resourceHelper.gs(R.string.smscommunicator_code_from_authenticator_for), otp.name()) + String.format(rh.gs(R.string.smscommunicator_code_from_authenticator_for), otp.name()) private fun stripAccents(str: String): String { var s = str s = Normalizer.normalize(s, Normalizer.Form.NFD) s = s.replace("[\\p{InCombiningDiacriticalMarks}]".toRegex(), "") + s = s.replace("ł", "l") // hack for Polish language (bug in libs) return s } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/activities/SmsCommunicatorOtpActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/activities/SmsCommunicatorOtpActivity.kt index f6bc7a230a..f3f7b150bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/activities/SmsCommunicatorOtpActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/activities/SmsCommunicatorOtpActivity.kt @@ -71,25 +71,25 @@ class SmsCommunicatorOtpActivity : NoSplashAppCompatActivity() { binding.otpReset.setOnClickListener { OKDialog.showConfirmation(this, - resourceHelper.gs(R.string.smscommunicator_otp_reset_title), - resourceHelper.gs(R.string.smscommunicator_otp_reset_prompt), + rh.gs(R.string.smscommunicator_otp_reset_title), + rh.gs(R.string.smscommunicator_otp_reset_prompt), Runnable { uel.log(Action.OTP_RESET, Sources.SMS) otp.ensureKey(true) updateGui() - ToastUtils.Long.infoToast(this, resourceHelper.gs(R.string.smscommunicator_otp_reset_successful)) + ToastUtils.Long.infoToast(this, rh.gs(R.string.smscommunicator_otp_reset_successful)) }) } binding.otpProvisioning.setOnLongClickListener { OKDialog.showConfirmation(this, - resourceHelper.gs(R.string.smscommunicator_otp_export_title), - resourceHelper.gs(R.string.smscommunicator_otp_export_prompt), + rh.gs(R.string.smscommunicator_otp_export_title), + rh.gs(R.string.smscommunicator_otp_export_prompt), Runnable { val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("OTP Secret", otp.provisioningSecret()) clipboard.setPrimaryClip(clip) - ToastUtils.Long.infoToast(this, resourceHelper.gs(R.string.smscommunicator_otp_export_successful)) + ToastUtils.Long.infoToast(this, rh.gs(R.string.smscommunicator_otp_export_successful)) uel.log(Action.OTP_EXPORT, Sources.SMS) }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt index 75235ca487..2e73121ce7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt @@ -20,7 +20,7 @@ import javax.inject.Singleton @Singleton class OneTimePassword @Inject constructor( private val sp: SP, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val dateUtil: DateUtil ) { @@ -36,7 +36,7 @@ class OneTimePassword @Inject constructor( * Name of master device (target of OTP) */ fun name(): String { - val defaultUserName = resourceHelper.gs(R.string.patient_name_default) + val defaultUserName = rh.gs(R.string.patient_name_default) var userName = sp.getString(R.string.key_patient_name, defaultUserName).replace(":", "").trim() if (userName.isEmpty()) userName = defaultUserName diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt index d21c0cbd6a..9c4a64c25e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt @@ -43,7 +43,7 @@ import javax.inject.Singleton class TidepoolPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, @@ -60,7 +60,7 @@ class TidepoolPlugin @Inject constructor( .fragmentClass(TidepoolFragment::class.qualifiedName) .preferencesId(R.xml.pref_tidepool) .description(R.string.description_tidepool), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private var disposable: CompositeDisposable = CompositeDisposable() @@ -108,9 +108,9 @@ class TidepoolPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event -> - if (event.isChanged(resourceHelper, R.string.key_tidepool_dev_servers) - || event.isChanged(resourceHelper, R.string.key_tidepool_username) - || event.isChanged(resourceHelper, R.string.key_tidepool_password) + if (event.isChanged(rh, R.string.key_tidepool_dev_servers) + || event.isChanged(rh, R.string.key_tidepool_username) + || event.isChanged(rh, R.string.key_tidepool_password) ) tidepoolUploader.resetInstance() }, fabricPrivacy::logException) @@ -129,7 +129,7 @@ class TidepoolPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) - val tidepoolTestLogin: Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_tidepool_test_login)) + val tidepoolTestLogin: Preference? = preferenceFragment.findPreference(rh.gs(R.string.key_tidepool_test_login)) tidepoolTestLogin?.setOnPreferenceClickListener { preferenceFragment.context?.let { tidepoolUploader.testLogin(it) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt index 0f4ecdce96..8518637177 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt @@ -34,7 +34,7 @@ class TidepoolUploader @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val ctx: Context, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val uploadChunk: UploadChunk, private val activePlugin: ActivePlugin, @@ -130,13 +130,13 @@ class TidepoolUploader @Inject constructor( val call = session.service?.getLogin(it) call?.enqueue(TidepoolCallback(aapsLogger, rxBus, session, "Login", { - OKDialog.show(rootContext, resourceHelper.gs(R.string.tidepool), "Successfully logged into Tidepool.") + OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Successfully logged into Tidepool.") }, { - OKDialog.show(rootContext, resourceHelper.gs(R.string.tidepool), "Failed to log into Tidepool.\nCheck that your user name and password are correct.") + OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Failed to log into Tidepool.\nCheck that your user name and password are correct.") })) } - ?: OKDialog.show(rootContext, resourceHelper.gs(R.string.tidepool), "Cannot do login as user credentials have not been set correctly") + ?: OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Cannot do login as user credentials have not been set correctly") } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 72bcab6b7b..f3a5348a65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -59,7 +59,7 @@ class ActionStringHandler @Inject constructor( private val rxBus: RxBus, private val aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val injector: HasAndroidInjector, private val context: Context, private val constraintChecker: ConstraintChecker, @@ -67,7 +67,7 @@ class ActionStringHandler @Inject constructor( private val loopPlugin: LoopPlugin, private val wearPlugin: WearPlugin, private val fabricPrivacy: FabricPrivacy, - private val commandQueue: CommandQueueProvider, + private val commandQueue: CommandQueue, private val activePlugin: ActivePlugin, private val iobCobCalculator: IobCobCalculator, private val localInsightPlugin: LocalInsightPlugin, @@ -122,24 +122,24 @@ class ActionStringHandler @Inject constructor( else -> return } val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() - rMessage += resourceHelper.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" - if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) + rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" + if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied) rAction += "fill $insulinAfterConstraints" } else if ("fill" == act[0]) { ////////////////////////////////////////////// PRIME/FILL val amount = SafeParse.stringToDouble(act[1]) val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() - rMessage += resourceHelper.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" - if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) + rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" + if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied) rAction += "fill $insulinAfterConstraints" } else if ("bolus" == act[0]) { ////////////////////////////////////////////// BOLUS val insulin = SafeParse.stringToDouble(act[1]) val carbs = SafeParse.stringToInt(act[2]) val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() - rMessage += resourceHelper.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" - rMessage += resourceHelper.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" + rMessage += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" + rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" if (insulinAfterConstraints - insulin != 0.0 || carbsAfterConstraints - carbs != 0) { - rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) + rMessage += "\n" + rh.gs(R.string.constraintapllied) } rAction += "bolus $insulinAfterConstraints $carbsAfterConstraints" } else if ("temptarget" == act[0]) { ///////////////////////////////////////////////////////// TEMPTARGET @@ -280,7 +280,7 @@ class ActionStringHandler @Inject constructor( rMessage = "OLD DATA - " //if pump is not busy: try to fetch data if (activePump.isBusy()) { - rMessage += resourceHelper.gs(R.string.pumpbusy) + rMessage += rh.gs(R.string.pumpbusy) } else { rMessage += "trying to fetch data from pump." commandQueue.loadTDDs(object : Callback() { @@ -306,11 +306,11 @@ class ActionStringHandler @Inject constructor( val duration = SafeParse.stringToInt(act[3]) val starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000 val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() - rMessage += resourceHelper.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" - rMessage += "\n" + resourceHelper.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp) - rMessage += "\n" + resourceHelper.gs(R.string.duration) + ": " + duration + "h" + rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" + rMessage += "\n" + rh.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp) + rMessage += "\n" + rh.gs(R.string.duration) + ": " + duration + "h" if (carbsAfterConstraints - carbs != 0) { - rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) + rMessage += "\n" + rh.gs(R.string.constraintapllied) } if (carbsAfterConstraints <= 0) { sendError("Carbs = 0! No action taken!") @@ -318,7 +318,7 @@ class ActionStringHandler @Inject constructor( } rAction += "ecarbs $carbsAfterConstraints $starttimestamp $duration" } else if ("changeRequest" == act[0]) { ////////////////////////////////////////////// CHANGE REQUEST - rTitle = resourceHelper.gs(R.string.openloop_newsuggestion) + rTitle = rh.gs(R.string.openloop_newsuggestion) rAction = "changeRequest" loopPlugin.lastRun?.let { rMessage += it.constraintsProcessed @@ -472,15 +472,15 @@ class ActionStringHandler @Inject constructor( val usedAPS = activePlugin.activeAPS val result = usedAPS.lastAPSResult ?: return "Last result not available!" ret += if (!result.isChangeRequested) { - resourceHelper.gs(R.string.nochangerequested) + "\n" + rh.gs(R.string.nochangerequested) + "\n" } else if (result.rate == 0.0 && result.duration == 0) { - resourceHelper.gs(R.string.canceltemp) + "\n" + rh.gs(R.string.canceltemp) + "\n" } else { - resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + + rh.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + "(" + DecimalFormatter.to2Decimal(result.rate / activePlugin.activePump.baseBasalRate * 100) + "%)\n" + - resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration.toDouble()) + " min\n" + rh.gs(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration.toDouble()) + " min\n" } - ret += "\n" + resourceHelper.gs(R.string.reason) + ": " + result.reason + ret += "\n" + rh.gs(R.string.reason) + ": " + result.reason return ret } @@ -540,17 +540,17 @@ class ActionStringHandler @Inject constructor( var msg = "" //check for validity if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) { - msg += String.format(resourceHelper.gs(R.string.valueoutofrange), "Profile-Percentage") + "\n" + msg += String.format(rh.gs(R.string.valueoutofrange), "Profile-Percentage") + "\n" } if (timeshift < 0 || timeshift > 23) { - msg += String.format(resourceHelper.gs(R.string.valueoutofrange), "Profile-Timeshift") + "\n" + msg += String.format(rh.gs(R.string.valueoutofrange), "Profile-Timeshift") + "\n" } val profile = profileFunction.getProfile() if (profile == null) { - msg += resourceHelper.gs(R.string.notloadedplugins) + "\n" + msg += rh.gs(R.string.notloadedplugins) + "\n" } if ("" != msg) { - msg += resourceHelper.gs(R.string.valuesnotstored) + msg += rh.gs(R.string.valuesnotstored) val rTitle = "STATUS" val rAction = "statusmessage" wearPlugin.requestActionConfirmation(rTitle, msg, rAction) @@ -605,7 +605,7 @@ class ActionStringHandler @Inject constructor( commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + + sendError(rh.gs(R.string.treatmentdeliveryerror) + "\n" + result.comment) } @@ -642,7 +642,7 @@ class ActionStringHandler @Inject constructor( commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + + sendError(rh.gs(R.string.treatmentdeliveryerror) + "\n" + result.comment) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index afe72dade8..d7666098c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -28,7 +28,7 @@ import javax.inject.Singleton class WearPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val sp: SP, private val ctx: Context, @@ -45,7 +45,7 @@ class WearPlugin @Inject constructor( .shortName(R.string.wear_shortname) .preferencesId(R.xml.pref_wear) .description(R.string.description_wear), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() @@ -88,14 +88,14 @@ class WearPlugin @Inject constructor( .toObservable(EventRefreshOverview::class.java) .observeOn(aapsSchedulers.io) .subscribe({ - if (WatchUpdaterService.shouldReportLoopStatus(loopPlugin.get().isEnabled(PluginType.LOOP))) + if (WatchUpdaterService.shouldReportLoopStatus(loopPlugin.get().isEnabled())) sendDataToWatch(status = true, basals = false, bgValue = false) }, fabricPrivacy::logException)) disposable.add(rxBus .toObservable(EventBolusRequested::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventBolusRequested -> - val status = String.format(resourceHelper.gs(R.string.bolusrequested), event.amount) + val status = String.format(rh.gs(R.string.bolusrequested), event.amount) val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) intent.putExtra("progresspercent", 0) intent.putExtra("progressstatus", status) @@ -107,9 +107,9 @@ class WearPlugin @Inject constructor( .subscribe({ event: EventDismissBolusProgressIfRunning -> if (event.result == null) return@subscribe val status: String = if (event.result!!.success) { - resourceHelper.gs(R.string.success) + rh.gs(R.string.success) } else { - resourceHelper.gs(R.string.nosuccess) + rh.gs(R.string.nosuccess) } val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) intent.putExtra("progresspercent", 100) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index 41c0fc55eb..2583996995 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -67,7 +67,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog @Inject public GlucoseStatusProvider glucoseStatusProvider; @Inject public AAPSLogger aapsLogger; @Inject public WearPlugin wearPlugin; - @Inject public ResourceHelper resourceHelper; + @Inject public ResourceHelper rh; @Inject public SP sp; @Inject public RxBus rxBus; @Inject public ProfileFunction profileFunction; @@ -133,7 +133,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private boolean wearIntegration() { - return wearPlugin.isEnabled(PluginType.GENERAL); + return wearPlugin.isEnabled(); } private void googleApiConnect() { @@ -514,7 +514,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) { List predArray = finalLastRun.getConstraintsProcessed().getPredictions() - .stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) + .stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh)) .collect(Collectors.toList()); if (!predArray.isEmpty()) { @@ -658,7 +658,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (googleApiClient != null && googleApiClient.isConnected()) { Profile profile = profileFunction.getProfile(); - String status = resourceHelper.gs(R.string.noprofile); + String status = rh.gs(R.string.noprofile); String iobSum, iobDetail, cobString, currentBasal, bgiString; iobSum = iobDetail = cobString = currentBasal = bgiString = ""; if (profile != null) { @@ -722,7 +722,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putBoolean(resourceHelper.gs(R.string.key_wear_control), wearcontrol); + dataMapRequest.getDataMap().putBoolean(rh.gs(R.string.key_wear_control), wearcontrol); PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); } else { @@ -736,12 +736,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog String status = ""; if (profile == null) { - status = resourceHelper.gs(R.string.noprofile); + status = rh.gs(R.string.noprofile); return status; } - if (!loopPlugin.isEnabled(PluginType.LOOP)) { - status += resourceHelper.gs(R.string.disabledloop) + "\n"; + if (!loopPlugin.isEnabled()) { + status += rh.gs(R.string.disabledloop) + "\n"; lastLoopStatus = false; } else { lastLoopStatus = true; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index 6ed92ead2b..5eb9ac1c47 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -26,7 +26,7 @@ class StatusLinePlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, private val profileFunction: ProfileFunction, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val context: Context, private val fabricPrivacy: FabricPrivacy, @@ -43,7 +43,7 @@ class StatusLinePlugin @Inject constructor( .neverVisible(true) .preferencesId(R.xml.pref_xdripstatus) .description(R.string.description_xdrip_status_line), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() @@ -66,7 +66,7 @@ class StatusLinePlugin @Inject constructor( super.onStart() disposable += rxBus.toObservable(EventRefreshOverview::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ if (lastLoopStatus != loopPlugin.isEnabled(PluginType.LOOP)) sendStatus() }, fabricPrivacy::logException) + .subscribe({ if (lastLoopStatus != loopPlugin.isEnabled()) sendStatus() }, fabricPrivacy::logException) disposable += rxBus.toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ sendStatus() }, fabricPrivacy::logException) @@ -113,10 +113,10 @@ class StatusLinePlugin @Inject constructor( private fun buildStatusString(profile: Profile): String { var status = "" - if (!loopPlugin.isEnabled(PluginType.LOOP)) { - status += resourceHelper.gs(R.string.disabledloop) + "\n" + if (!loopPlugin.isEnabled()) { + status += rh.gs(R.string.disabledloop) + "\n" lastLoopStatus = false - } else if (loopPlugin.isEnabled(PluginType.LOOP)) { + } else if (loopPlugin.isEnabled()) { lastLoopStatus = true } //Temp basal diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt index 640a0b80be..080fbd41fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt @@ -14,7 +14,7 @@ import javax.inject.Inject class InsulinFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper private var _binding: InsulinFragmentBinding? = null @@ -32,7 +32,7 @@ class InsulinFragment : DaggerFragment() { super.onResume() binding.name.text = activePlugin.activeInsulin.friendlyName binding.comment.text = activePlugin.activeInsulin.comment - binding.dia.text = resourceHelper.gs(R.string.dia) + ": " + resourceHelper.gs(R.string.format_hours, activePlugin.activeInsulin.dia) + binding.dia.text = rh.gs(R.string.dia) + ": " + rh.gs(R.string.format_hours, activePlugin.activeInsulin.dia) binding.graph.show(activePlugin.activeInsulin) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt index dd10210d9a..a2e0b3c2ec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt @@ -14,18 +14,18 @@ import javax.inject.Singleton @Singleton class InsulinLyumjevPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBus, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, rh, profileFunction, rxBus, aapsLogger) { override val id get(): Insulin.InsulinType = Insulin.InsulinType.OREF_LYUMJEV - override val friendlyName get(): String = resourceHelper.gs(R.string.lyumjev) + override val friendlyName get(): String = rh.gs(R.string.lyumjev) override fun configuration(): JSONObject = JSONObject() override fun applyConfiguration(configuration: JSONObject) {} - override fun commentStandardText(): String = resourceHelper.gs(R.string.lyumjev) + override fun commentStandardText(): String = rh.gs(R.string.lyumjev) override val peak = 45 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt index f58f929fa3..e33bcacc93 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -27,7 +27,7 @@ import kotlin.math.pow */ abstract class InsulinOrefBasePlugin( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, val profileFunction: ProfileFunction, val rxBus: RxBus, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() @@ -36,7 +36,7 @@ abstract class InsulinOrefBasePlugin( .pluginIcon(R.drawable.ic_insulin) .shortName(R.string.insulin_shortname) .visibleByDefault(false), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), Insulin { private var lastWarned: Long = 0 @@ -60,7 +60,7 @@ abstract class InsulinOrefBasePlugin( } private val notificationPattern: String - get() = resourceHelper.gs(R.string.dia_too_short) + get() = rh.gs(R.string.dia_too_short) open val userDefinedDia: Double get() { @@ -96,7 +96,7 @@ abstract class InsulinOrefBasePlugin( var comment = commentStandardText() val userDia = userDefinedDia if (userDia < MIN_DIA) { - comment += "\n" + resourceHelper.gs(R.string.dia_too_short, userDia, MIN_DIA) + comment += "\n" + rh.gs(R.string.dia_too_short, userDia, MIN_DIA) } return comment } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index b45fee289c..5a14fed8f9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -21,22 +21,22 @@ import javax.inject.Singleton class InsulinOrefFreePeakPlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, - resourceHelper: ResourceHelper, + rh: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBus, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, rh, profileFunction, rxBus, aapsLogger) { override val id get(): Insulin.InsulinType = Insulin.InsulinType.OREF_FREE_PEAK - override val friendlyName get(): String = resourceHelper.gs(R.string.free_peak_oref) + override val friendlyName get(): String = rh.gs(R.string.free_peak_oref) - override fun configuration(): JSONObject = JSONObject().putInt(R.string.key_insulin_oref_peak, sp, resourceHelper) + override fun configuration(): JSONObject = JSONObject().putInt(R.string.key_insulin_oref_peak, sp, rh) override fun applyConfiguration(configuration: JSONObject) { - configuration.storeInt(R.string.key_insulin_oref_peak, sp, resourceHelper) + configuration.storeInt(R.string.key_insulin_oref_peak, sp, rh) } override fun commentStandardText(): String { - return resourceHelper.gs(R.string.insulin_peak_time) + ": " + peak + return rh.gs(R.string.insulin_peak_time) + ": " + peak } override val peak: Int diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt index 6507b92dc5..9ec79e428c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt @@ -17,18 +17,18 @@ import javax.inject.Singleton @Singleton class InsulinOrefRapidActingPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBus, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, rh, profileFunction, rxBus, aapsLogger) { override val id get(): Insulin.InsulinType = Insulin.InsulinType.OREF_RAPID_ACTING - override val friendlyName get(): String = resourceHelper.gs(R.string.rapid_acting_oref) + override val friendlyName get(): String = rh.gs(R.string.rapid_acting_oref) override fun configuration(): JSONObject = JSONObject() override fun applyConfiguration(configuration: JSONObject) {} - override fun commentStandardText(): String = resourceHelper.gs(R.string.fastactinginsulincomment) + override fun commentStandardText(): String = rh.gs(R.string.fastactinginsulincomment) override val peak = 75 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt index 8f5246fe5f..dfa800291b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -17,18 +17,18 @@ import javax.inject.Singleton @Singleton class InsulinOrefUltraRapidActingPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBus, aapsLogger: AAPSLogger -) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) { +) : InsulinOrefBasePlugin(injector, rh, profileFunction, rxBus, aapsLogger) { override val id get(): Insulin.InsulinType = Insulin.InsulinType.OREF_ULTRA_RAPID_ACTING - override val friendlyName get(): String = resourceHelper.gs(R.string.ultrarapid_oref) + override val friendlyName get(): String = rh.gs(R.string.ultrarapid_oref) override fun configuration(): JSONObject = JSONObject() override fun applyConfiguration(configuration: JSONObject) {} - override fun commentStandardText(): String = resourceHelper.gs(R.string.ultrafastactinginsulincomment) + override fun commentStandardText(): String = rh.gs(R.string.ultrafastactinginsulincomment) override val peak = 55 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index b128ceb34d..fec67d9e5f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -37,6 +37,9 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.json.JSONArray +import java.util.concurrent.Executors +import java.util.concurrent.ScheduledFuture +import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton import kotlin.math.floor @@ -51,7 +54,7 @@ class IobCobCalculatorPlugin @Inject constructor( private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val sp: SP, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val sensitivityOref1Plugin: SensitivityOref1Plugin, @@ -67,7 +70,7 @@ class IobCobCalculatorPlugin @Inject constructor( .showInList(false) .neverVisible(true) .alwaysEnabled(true), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), IobCobCalculator { private val disposable = CompositeDisposable() @@ -102,14 +105,14 @@ class IobCobCalculatorPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event -> - if (event.isChanged(resourceHelper, R.string.key_openapsama_autosens_period) || - event.isChanged(resourceHelper, R.string.key_age) || - event.isChanged(resourceHelper, R.string.key_absorption_maxtime) || - event.isChanged(resourceHelper, R.string.key_openapsama_min_5m_carbimpact) || - event.isChanged(resourceHelper, R.string.key_absorption_cutoff) || - event.isChanged(resourceHelper, R.string.key_openapsama_autosens_max) || - event.isChanged(resourceHelper, R.string.key_openapsama_autosens_min) || - event.isChanged(resourceHelper, R.string.key_insulin_oref_peak) + if (event.isChanged(rh, R.string.key_openapsama_autosens_period) || + event.isChanged(rh, R.string.key_age) || + event.isChanged(rh, R.string.key_absorption_maxtime) || + event.isChanged(rh, R.string.key_openapsama_min_5m_carbimpact) || + event.isChanged(rh, R.string.key_absorption_cutoff) || + event.isChanged(rh, R.string.key_openapsama_autosens_max) || + event.isChanged(rh, R.string.key_openapsama_autosens_min) || + event.isChanged(rh, R.string.key_insulin_oref_peak) ) { resetDataAndRunCalculation("onEventPreferenceChange", event) } @@ -126,12 +129,7 @@ class IobCobCalculatorPlugin @Inject constructor( disposable += rxBus .toObservable(EventNewHistoryData::class.java) .observeOn(aapsSchedulers.io) - .subscribe( - { event -> - newHistoryData(event.oldDataTimestamp, event.reloadBgData, if (event.newestGlucoseValue != null) EventNewBG(event.newestGlucoseValue) else event) - }, - fabricPrivacy::logException - ) + .subscribe({ event -> scheduleHistoryDataChange(event) }, fabricPrivacy::logException) } override fun onStop() { @@ -389,6 +387,44 @@ class IobCobCalculatorPlugin @Inject constructor( } } + // Limit rate of EventNewHistoryData + private val historyWorker = Executors.newSingleThreadScheduledExecutor() + private var scheduledHistoryPost: ScheduledFuture<*>? = null + private var scheduledEvent: EventNewHistoryData? = null + + @Synchronized + private fun scheduleHistoryDataChange(event: EventNewHistoryData) { + // if there is nothing scheduled or asking reload deeper to the past + if (scheduledEvent == null || event.oldDataTimestamp < (scheduledEvent?.oldDataTimestamp) ?: 0L) { + // cancel waiting task to prevent sending multiple posts + scheduledHistoryPost?.cancel(false) + // prepare task for execution in 1 sec + scheduledEvent = event + scheduledHistoryPost = historyWorker.schedule({ + synchronized(this) { + aapsLogger.debug(LTag.DATABASE, "Running newHistoryData") + newHistoryData( + event.oldDataTimestamp, + event.reloadBgData, + if (event.newestGlucoseValue != null) EventNewBG(event.newestGlucoseValue) else event + ) + scheduledEvent = null + scheduledHistoryPost = null + } + }, 1L, TimeUnit.SECONDS) + } else { + // asked reload is newer -> adjust params only + scheduledEvent?.let { + // set reload bg data if was not set + if (!it.reloadBgData) it.reloadBgData = event.reloadBgData + // set Glucose value if newer + event.newestGlucoseValue?.let { gv -> + if (gv.timestamp > (it.newestGlucoseValue?.timestamp ?: 0L)) it.newestGlucoseValue = gv + } + } + } + } + // When historical data is changed (coming from NS etc) finished calculations after this date must be invalidated private fun newHistoryData(oldDataTimestamp: Long, bgDataReload: Boolean, event: Event) { //log.debug("Locking onNewHistoryData"); @@ -522,10 +558,7 @@ class IobCobCalculatorPlugin @Inject constructor( return null } - override fun getTempBasalIncludingConvertedExtended(timestamp: Long): TemporaryBasal? { - - val tb = repository.getTemporaryBasalActiveAt(timestamp).blockingGet() - if (tb is ValueWrapper.Existing) return tb.value + private fun getConvertedExtended(timestamp: Long): TemporaryBasal? { if (activePlugin.activePump.isFakingTempsByExtendedBoluses) { val eb = repository.getExtendedBolusActiveAt(timestamp).blockingGet() val profile = profileFunction.getProfile(timestamp) ?: return null @@ -534,6 +567,22 @@ class IobCobCalculatorPlugin @Inject constructor( return null } + override fun getTempBasalIncludingConvertedExtended(timestamp: Long): TemporaryBasal? { + val tb = repository.getTemporaryBasalActiveAt(timestamp).blockingGet() + if (tb is ValueWrapper.Existing) return tb.value + return getConvertedExtended(timestamp); + } + + override fun getTempBasalIncludingConvertedExtendedForRange(startTime: Long, endTime: Long, calculationStep: Long): Map { + val tempBasals = HashMap(); + val tbs = repository.getTemporaryBasalsDataActiveBetweenTimeAndTime(startTime, endTime).blockingGet() + for (t in startTime until endTime step calculationStep) { + val tb = tbs.firstOrNull { basal -> basal.timestamp <= t && (basal.timestamp + basal.duration) > t } + tempBasals[t] = tb ?: getConvertedExtended(t) + } + return tempBasals; + } + override fun calculateAbsoluteIobFromBaseBasals(toTime: Long): IobTotal { val total = IobTotal(toTime) var i = toTime - range() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt index 7c78cd85bc..4e8bb936bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt @@ -51,7 +51,7 @@ class IobCobOref1Thread internal constructor( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var context: Context @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @@ -67,7 +67,7 @@ class IobCobOref1Thread internal constructor( init { injector.androidInjector().inject(this) - mWakeLock = (context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, resourceHelper.gs(R.string.app_name) + ":iobCobThread") + mWakeLock = (context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, rh.gs(R.string.app_name) + ":iobCobThread") } override fun run() { @@ -161,7 +161,7 @@ class IobCobOref1Thread internal constructor( aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString()) aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString()) //aapsLogger.debug(LTag.AUTOSENS, iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) - val notification = Notification(Notification.SEND_LOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW) + val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break @@ -184,7 +184,7 @@ class IobCobOref1Thread internal constructor( aapsLogger.debug(autosensDataTable.toString()) aapsLogger.debug(bucketedData.toString()) //aapsLogger.debug(iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) - val notification = Notification(Notification.SEND_LOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW) + val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt index 30e86132a2..1561575796 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt @@ -50,7 +50,7 @@ class IobCobThread @Inject internal constructor( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var context: Context @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @@ -66,7 +66,7 @@ class IobCobThread @Inject internal constructor( init { injector.androidInjector().inject(this) - mWakeLock = (context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, resourceHelper.gs(R.string.app_name) + ":iobCobThread") + mWakeLock = (context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, rh.gs(R.string.app_name) + ":iobCobThread") } override fun run() { @@ -160,7 +160,7 @@ class IobCobThread @Inject internal constructor( aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString()) aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString()) //aapsLogger.debug(LTag.AUTOSENS, iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) - val notification = Notification(Notification.SEND_LOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW) + val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break @@ -183,7 +183,7 @@ class IobCobThread @Inject internal constructor( aapsLogger.debug(autosensDataTable.toString()) aapsLogger.debug(bucketedData.toString()) //aapsLogger.debug(iobCobCalculatorPlugin.getBgReadingsDataTable().toString()) - val notification = Notification(Notification.SEND_LOGFILES, resourceHelper.gs(R.string.sendlogfiles), Notification.LOW) + val notification = Notification(Notification.SEND_LOGFILES, rh.gs(R.string.sendlogfiles), Notification.LOW) rxBus.send(EventNewNotification(notification)) sp.putBoolean("log_AUTOSENS", true) break @@ -204,7 +204,7 @@ class IobCobThread @Inject internal constructor( if (previous != null && previous.cob > 0) { // calculate sum of min carb impact from all active treatments var totalMinCarbsImpact = 0.0 - if (sensitivityAAPSPlugin.isEnabled(PluginType.SENSITIVITY) || sensitivityWeightedAveragePlugin.isEnabled(PluginType.SENSITIVITY)) { + if (sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled()) { //when the impact depends on a max time, sum them up as smaller carb sizes make them smaller for (ii in autosensData.activeCarbsList.indices) { val c = autosensData.activeCarbsList[ii] diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt index c842a1dcb7..da88729718 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt @@ -2,5 +2,17 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.events.Event +import org.joda.time.DateTime +import org.joda.time.format.DateTimeFormat +import java.text.DateFormat -class EventNewHistoryData(val oldDataTimestamp: Long, val reloadBgData: Boolean, val newestGlucoseValue : GlucoseValue? = null) : Event() \ No newline at end of file +class EventNewHistoryData(val oldDataTimestamp: Long, var reloadBgData: Boolean, var newestGlucoseValue : GlucoseValue? = null) : Event() { + + override fun toString(): String { + return super.toString() + + " " + + DateFormat.getDateInstance(DateFormat.SHORT).format(oldDataTimestamp) + + " " + + DateTime(oldDataTimestamp).toString(DateTimeFormat.forPattern("HH:mm:ss")) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index 1675d4986b..f799d0ae8e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -39,7 +39,7 @@ class LocalProfileFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var localProfilePlugin: LocalProfilePlugin @@ -55,7 +55,7 @@ class LocalProfileFragment : DaggerFragment() { private val save = Runnable { doEdit() - basalView?.updateLabel(resourceHelper.gs(R.string.basal_label) + ": " + sumLabel()) + basalView?.updateLabel(rh.gs(R.string.basal_label) + ": " + sumLabel()) localProfilePlugin.profile?.getSpecificProfile(spinner?.selectedItem.toString())?.let { binding.basalGraph.show(ProfileSealed.Pure(it)) } @@ -74,7 +74,7 @@ class LocalProfileFragment : DaggerFragment() { private fun sumLabel(): String { val profile = localProfilePlugin.getEditProfile() val sum = profile?.let { ProfileSealed.Pure(profile).baseBasalSum() } ?: 0.0 - return " ∑" + DecimalFormatter.to2Decimal(sum) + resourceHelper.gs(R.string.insulin_unit_shortname) + return " ∑" + DecimalFormatter.to2Decimal(sum) + rh.gs(R.string.insulin_unit_shortname) } private var _binding: LocalprofileFragmentBinding? = null @@ -126,16 +126,16 @@ class LocalProfileFragment : DaggerFragment() { binding.name.removeTextChangedListener(textWatch) binding.name.setText(currentProfile.name) binding.name.addTextChangedListener(textWatch) - binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, binding.save, textWatch) + binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, null, textWatch) binding.dia.tag = "LP_DIA" - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.ic, "IC", resourceHelper.gs(R.string.ic_label), currentProfile.ic, null, hardLimits.minIC(), hardLimits.maxIC(), 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.basal_holder, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, pumpDescription.basalMaximumRate, 0.01, DecimalFormat("0.00"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.ic, "IC", rh.gs(R.string.ic_label), currentProfile.ic, null, hardLimits.minIC(), hardLimits.maxIC(), 0.1, DecimalFormat("0.0"), save) + basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.basal_holder, "BASAL", rh.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, pumpDescription.basalMaximumRate, 0.01, DecimalFormat("0.00"), save) if (units == Constants.MGDL) { - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf, "ISF", resourceHelper.gs(R.string.isf_label), currentProfile.isf, null, HardLimits.MIN_ISF, HardLimits.MAX_ISF, 1.0, DecimalFormat("0"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.target, "TARGET", resourceHelper.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf, "ISF", rh.gs(R.string.isf_label), currentProfile.isf, null, HardLimits.MIN_ISF, HardLimits.MAX_ISF, 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.target, "TARGET", rh.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], HardLimits.VERY_HARD_LIMIT_TARGET_BG[1], 1.0, DecimalFormat("0"), save) } else { - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf, "ISF", resourceHelper.gs(R.string.isf_label), currentProfile.isf, null, Profile.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL), Profile.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL), 0.1, DecimalFormat("0.0"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.target, "TARGET", resourceHelper.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), GlucoseUnit.MMOL), Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), GlucoseUnit.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf, "ISF", rh.gs(R.string.isf_label), currentProfile.isf, null, Profile.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL), Profile.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.target, "TARGET", rh.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[0], GlucoseUnit.MMOL), Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[1], GlucoseUnit.MMOL), 0.1, DecimalFormat("0.0"), save) } // Spinner @@ -154,7 +154,7 @@ class LocalProfileFragment : DaggerFragment() { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (localProfilePlugin.isEdited) { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.doyouwantswitchprofile), { + OKDialog.showConfirmation(activity, rh.gs(R.string.doyouwantswitchprofile), { localProfilePlugin.currentProfileIndex = position build() }, { @@ -173,7 +173,7 @@ class LocalProfileFragment : DaggerFragment() { binding.profileAdd.setOnClickListener { if (localProfilePlugin.isEdited) { - activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.saveorresetchangesfirst)) } + activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) } } else { uel.log(Action.NEW_PROFILE, Sources.LocalProfile) localProfilePlugin.addNewProfile() @@ -183,7 +183,7 @@ class LocalProfileFragment : DaggerFragment() { binding.profileClone.setOnClickListener { if (localProfilePlugin.isEdited) { - activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.saveorresetchangesfirst)) } + activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) } } else { uel.log(Action.CLONE_PROFILE, Sources.LocalProfile, ValueWithUnit.SimpleString(localProfilePlugin.currentProfile()?.name ?: "")) @@ -194,7 +194,7 @@ class LocalProfileFragment : DaggerFragment() { binding.profileRemove.setOnClickListener { activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.deletecurrentprofile), { + OKDialog.showConfirmation(activity, rh.gs(R.string.deletecurrentprofile), { uel.log(Action.PROFILE_REMOVED, Sources.LocalProfile, ValueWithUnit.SimpleString(localProfilePlugin.currentProfile()?.name ?: "")) localProfilePlugin.removeCurrentProfile() @@ -207,7 +207,7 @@ class LocalProfileFragment : DaggerFragment() { // if (!pumpDescription.isTempBasalCapable) binding.basal.visibility = View.GONE @Suppress("SetTextI18n") - binding.units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (currentProfile.mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol)) + binding.units.text = rh.gs(R.string.units_colon) + " " + (if (currentProfile.mgdl) rh.gs(R.string.mgdl) else rh.gs(R.string.mmol)) binding.profileswitch.setOnClickListener { ProfileSwitchDialog() @@ -264,7 +264,7 @@ class LocalProfileFragment : DaggerFragment() { val isValid = localProfilePlugin.isValidEditState(activity) val isEdited = localProfilePlugin.isEdited if (isValid) { - this.view?.setBackgroundColor(resourceHelper.gc(R.color.ok_background)) + this.view?.setBackgroundColor(rh.gc(R.color.ok_background)) if (isEdited) { //edited profile -> save first @@ -275,7 +275,7 @@ class LocalProfileFragment : DaggerFragment() { binding.save.visibility = View.GONE } } else { - this.view?.setBackgroundColor(resourceHelper.gc(R.color.error_background)) + this.view?.setBackgroundColor(rh.gc(R.color.error_background)) binding.profileswitch.visibility = View.GONE binding.save.visibility = View.GONE //don't save an invalid profile } @@ -289,12 +289,12 @@ class LocalProfileFragment : DaggerFragment() { } private fun processVisibilityOnClick(selected: View) { - binding.diaTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.icTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.isfTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.basalTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - binding.targetTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) - selected.setBackgroundColor(resourceHelper.gc(R.color.tabBgColorSelected)) + binding.diaTab.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.icTab.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.isfTab.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.basalTab.setBackgroundColor(rh.gc(R.color.defaultbackground)) + binding.targetTab.setBackgroundColor(rh.gc(R.color.defaultbackground)) + selected.setBackgroundColor(rh.gc(R.color.tabBgColorSelected)) binding.diaPlaceholder.visibility = View.GONE binding.ic.visibility = View.GONE binding.isf.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index 45ffde96b0..830eff3740 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -18,13 +18,12 @@ 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.general.overview.events.EventNewNotification +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.receivers.DataWorker -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.HardLimits -import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.ToastUtils +import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -43,12 +42,13 @@ class LocalProfilePlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBus, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val hardLimits: HardLimits, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.PROFILE) .fragmentClass(LocalProfileFragment::class.java.name) @@ -58,7 +58,7 @@ class LocalProfilePlugin @Inject constructor( .shortName(R.string.localprofile_shortname) .description(R.string.description_profile_local) .setDefault(), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), ProfileSource { private var rawProfile: ProfileStore? = null @@ -109,57 +109,61 @@ class LocalProfilePlugin @Inject constructor( val pumpDescription = activePlugin.activePump.pumpDescription with(profiles[currentProfileIndex]) { if (dia < hardLimits.minDia() || dia > hardLimits.maxDia()) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(info.nightscout.androidaps.core.R.string.profile_dia), dia)) + ToastUtils.errorToast(activity, rh.gs(R.string.value_out_of_hard_limits, rh.gs(info.nightscout.androidaps.core.R.string.profile_dia), dia)) return false } if (name.isNullOrEmpty()){ - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.missing_profile_name)) + ToastUtils.errorToast(activity, rh.gs(R.string.missing_profile_name)) return false } if (blockFromJsonArray(ic, dateUtil)?.any { it.amount < hardLimits.minIC() || it.amount > hardLimits.maxIC() } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_ic_values)) + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_ic_values)) return false } val low = blockFromJsonArray(targetLow, dateUtil) val high = blockFromJsonArray(targetHigh, dateUtil) - if (profileFunction.getUnits() == GlucoseUnit.MGDL) { - if (blockFromJsonArray(isf, dateUtil)?.any { it.amount < HardLimits.MIN_ISF || it.amount > HardLimits.MAX_ISF } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_isf_values)) + if (mgdl) { + if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(it.amount, HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_isf_values)) return false } if (blockFromJsonArray(basal, dateUtil)?.any { it.amount < pumpDescription.basalMinimumRate || it.amount > 10.0 } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_basal_values)) + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_basal_values)) return false } - if (low?.any { it.amount < HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble() || it.amount > HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble() } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) + if (low?.any { hardLimits.isInRange(it.amount, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } - if (high?.any { it.amount < HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble() || it.amount > HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble() } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) + if (high?.any { hardLimits.isInRange(it.amount, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } } else { - if (blockFromJsonArray(isf, dateUtil)?.any { it.amount < Profile.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL) || it.amount > Profile.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL) } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_isf_values)) + if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_isf_values)) return false } if (blockFromJsonArray(basal, dateUtil)?.any { it.amount < pumpDescription.basalMinimumRate || it.amount > 10.0 } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_basal_values)) + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_basal_values)) return false } - if (low?.any { it.amount < Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), GlucoseUnit.MMOL) || it.amount > Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), GlucoseUnit.MMOL) } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) + if (low?.any { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } - if (high?.any { it.amount < Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), GlucoseUnit.MMOL) || it.amount > Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), GlucoseUnit.MMOL) } != false) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) + if (high?.any { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]) } == false) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } } - for (i in low.indices) if (low[i].amount > high[i].amount) { - ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) - return false + low?.let { + high?.let { + for (i in low.indices) if (low[i].amount > high[i].amount) { + ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) + return false + } + } } } return true @@ -212,7 +216,7 @@ class LocalProfilePlugin @Inject constructor( if (name.contains(".")) namesOK = false } if (!namesOK) activity?.let { - OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot)) + OKDialog.show(it, "", rh.gs(R.string.profilenamecontainsdot)) } } @@ -251,10 +255,25 @@ class LocalProfilePlugin @Inject constructor( try { val newProfiles: ArrayList = ArrayList() for (p in store.getProfileList()) { - store.getSpecificProfile(p.toString())?.let { - val sp = copyFrom(it, p.toString()) + val profile = store.getSpecificProfile(p.toString()) + val validityCheck = profile?.let { ProfileSealed.Pure(profile).isValid("NS", activePlugin.activePump, config, rh, rxBus, hardLimits, false) } ?: Profile.ValidityCheck() + if (profile != null && validityCheck.isValid) { + val sp = copyFrom(profile, p.toString()) sp.name = p.toString() newProfiles.add(sp) + } else { + val n = NotificationWithAction( + injector, + Notification.INVALID_PROFILE_NOT_ACCEPTED, + rh.gs(R.string.invalid_profile_not_accepted, p.toString()), + Notification.NORMAL + ) + n.action(R.string.view) { + n.contextForAction?.let { + OKDialog.show(it, rh.gs(R.string.errors), validityCheck.reasons.joinToString(separator = "\n"), null) + } + } + rxBus.send(EventNewNotification(n)) } } if (newProfiles.size > 0) { @@ -458,7 +477,7 @@ class LocalProfilePlugin @Inject constructor( ?: return Result.failure(workDataOf("Error" to "missing input data")) if (sp.getBoolean(R.string.key_ns_receive_profile_store, true) || config.NSCLIENT) { val store = ProfileStore(injector, profileJson, dateUtil) - val createdAt = store.getCreatedAt() + val createdAt = store.getStartDate() val lastLocalChange = sp.getLong(R.string.key_local_profile_last_change, 0) aapsLogger.debug(LTag.PROFILE, "Received profileStore: createdAt: $createdAt Local last modification: $lastLocalChange") @Suppress("LiftReturnOrAssignment") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt index 936f2c007a..d7e1870ca5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt @@ -21,8 +21,8 @@ import javax.inject.Singleton class MDIPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, - commandQueue: CommandQueueProvider, + rh: ResourceHelper, + commandQueue: CommandQueue, private val dateUtil: DateUtil, private val pumpSync: PumpSync ) : PumpPluginBase(PluginDescription() @@ -30,7 +30,7 @@ class MDIPlugin @Inject constructor( .pluginIcon(R.drawable.ic_ict) .pluginName(R.string.mdi) .description(R.string.description_pump_mdi), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ), Pump { override val pumpDescription = PumpDescription() @@ -71,7 +71,7 @@ class MDIPlugin @Inject constructor( result.success = true result.bolusDelivered = detailedBolusInfo.insulin result.carbsDelivered = detailedBolusInfo.carbs - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) if (detailedBolusInfo.insulin > 0) pumpSync.syncBolusWithPumpId( timestamp = detailedBolusInfo.timestamp, @@ -94,7 +94,7 @@ class MDIPlugin @Inject constructor( override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.pumperror) + result.comment = rh.gs(R.string.pumperror) aapsLogger.debug(LTag.PUMPBTCOMM, "Setting temp basal absolute: $result") return result } @@ -102,7 +102,7 @@ class MDIPlugin @Inject constructor( override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.pumperror) + result.comment = rh.gs(R.string.pumperror) aapsLogger.debug(LTag.PUMPBTCOMM, "Settings temp basal percent: $result") return result } @@ -110,7 +110,7 @@ class MDIPlugin @Inject constructor( override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.pumperror) + result.comment = rh.gs(R.string.pumperror) aapsLogger.debug(LTag.PUMPBTCOMM, "Setting extended bolus: $result") return result } @@ -118,7 +118,7 @@ class MDIPlugin @Inject constructor( override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.pumperror) + result.comment = rh.gs(R.string.pumperror) aapsLogger.debug(LTag.PUMPBTCOMM, "Cancel temp basal: $result") return result } @@ -126,7 +126,7 @@ class MDIPlugin @Inject constructor( override fun cancelExtendedBolus(): PumpEnactResult { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.pumperror) + result.comment = rh.gs(R.string.pumperror) aapsLogger.debug(LTag.PUMPBTCOMM, "Canceling extended bolus: $result") return result } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt index b84243b5a3..95bfc25dd7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt @@ -28,7 +28,7 @@ import javax.inject.Inject class VirtualPumpFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin @@ -96,19 +96,19 @@ class VirtualPumpFragment : DaggerFragment() { private fun updateGui() { if (_binding == null) return val profile = profileFunction.getProfile() ?: return - binding.basabasalrate.text = resourceHelper.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate) + binding.basabasalrate.text = rh.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate) binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil.now())?.toStringFull(profile, dateUtil) ?: "" binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) ?: "" - binding.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent) - binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) + binding.battery.text = rh.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent) + binding.reservoir.text = rh.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) virtualPumpPlugin.refreshConfiguration() val pumpType = virtualPumpPlugin.pumpType binding.type.text = pumpType?.description - binding.typeDef.text = pumpType?.getFullDescription(resourceHelper.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals(), resourceHelper) + binding.typeDef.text = pumpType?.getFullDescription(rh.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals(), rh) binding.serialNumber.text = virtualPumpPlugin.serialNumber() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 94f095fc50..8780b8bc1b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -42,12 +42,12 @@ open class VirtualPumpPlugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBus, private var fabricPrivacy: FabricPrivacy, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val sp: SP, private val profileFunction: ProfileFunction, private val iobCobCalculator: IobCobCalculator, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, private val pumpSync: PumpSync, private val config: Config, private val dateUtil: DateUtil @@ -62,7 +62,7 @@ open class VirtualPumpPlugin @Inject constructor( .description(R.string.description_pump_virtual) .setDefault() .neverVisible(config.NSCLIENT), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ), Pump { private val disposable = CompositeDisposable() @@ -108,7 +108,7 @@ open class VirtualPumpPlugin @Inject constructor( disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ event: EventPreferenceChange -> if (event.isChanged(resourceHelper, R.string.key_virtualpump_type)) refreshConfiguration() }, fabricPrivacy::logException) + .subscribe({ event: EventPreferenceChange -> if (event.isChanged(rh, R.string.key_virtualpump_type)) refreshConfiguration() }, fabricPrivacy::logException) refreshConfiguration() } @@ -119,7 +119,7 @@ open class VirtualPumpPlugin @Inject constructor( override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { super.preprocessPreferences(preferenceFragment) - val uploadStatus = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_virtualpump_uploadstatus)) as SwitchPreference? + val uploadStatus = preferenceFragment.findPreference(rh.gs(R.string.key_virtualpump_uploadstatus)) as SwitchPreference? ?: return uploadStatus.isVisible = !config.NSCLIENT } @@ -151,7 +151,7 @@ open class VirtualPumpPlugin @Inject constructor( override fun setNewBasalProfile(profile: Profile): PumpEnactResult { lastDataTime = System.currentTimeMillis() - rxBus.send(EventNewNotification(Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60))) + rxBus.send(EventNewNotification(Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60))) // Do nothing here. we are using database profile return PumpEnactResult(injector).success(true).enacted(true) } @@ -180,18 +180,18 @@ open class VirtualPumpPlugin @Inject constructor( .bolusDelivered(detailedBolusInfo.insulin) .carbsDelivered(detailedBolusInfo.carbs) .enacted(detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) - .comment(resourceHelper.gs(R.string.virtualpump_resultok)) + .comment(rh.gs(R.string.virtualpump_resultok)) val bolusingEvent = EventOverviewBolusProgress var delivering = 0.0 while (delivering < detailedBolusInfo.insulin) { SystemClock.sleep(200) - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, delivering) + bolusingEvent.status = rh.gs(R.string.bolusdelivering, delivering) bolusingEvent.percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) rxBus.send(bolusingEvent) delivering += 0.1 } SystemClock.sleep(200) - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) + bolusingEvent.status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) bolusingEvent.percent = 100 rxBus.send(bolusingEvent) SystemClock.sleep(1000) @@ -226,7 +226,7 @@ open class VirtualPumpPlugin @Inject constructor( result.isTempCancel = false result.absolute = absoluteRate result.duration = durationInMinutes - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) pumpSync.syncTemporaryBasalWithPumpId( timestamp = dateUtil.now(), rate = absoluteRate, @@ -251,7 +251,7 @@ open class VirtualPumpPlugin @Inject constructor( result.isPercent = true result.isTempCancel = false result.duration = durationInMinutes - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) pumpSync.syncTemporaryBasalWithPumpId( timestamp = dateUtil.now(), rate = percent.toDouble(), @@ -276,7 +276,7 @@ open class VirtualPumpPlugin @Inject constructor( result.bolusDelivered = insulin result.isTempCancel = false result.duration = durationInMinutes - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) pumpSync.syncExtendedBolusWithPumpId( timestamp = dateUtil.now(), amount = insulin, @@ -296,7 +296,7 @@ open class VirtualPumpPlugin @Inject constructor( val result = PumpEnactResult(injector) result.success = true result.isTempCancel = true - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) if (pumpSync.expectedPumpState().temporaryBasal != null) { result.enacted = true pumpSync.syncStopTemporaryBasalWithPumpId( @@ -325,7 +325,7 @@ open class VirtualPumpPlugin @Inject constructor( result.success = true result.enacted = true result.isTempCancel = true - result.comment = resourceHelper.gs(R.string.virtualpump_resultok) + result.comment = rh.gs(R.string.virtualpump_resultok) aapsLogger.debug(LTag.PUMP, "Canceling extended bolus: $result") rxBus.send(EventVirtualPumpUpdateGui()) lastDataTime = System.currentTimeMillis() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt index 66b070075d..bfd9630b12 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -20,9 +20,9 @@ abstract class AbstractSensitivityPlugin( pluginDescription: PluginDescription, injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, val sp: SP -) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector), Sensitivity { +) : PluginBase(pluginDescription, aapsLogger, rh, injector), Sensitivity { abstract override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt index b07b2375ab..36bda32853 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -33,7 +33,7 @@ import kotlin.math.roundToInt class SensitivityAAPSPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, sp: SP, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -45,15 +45,15 @@ class SensitivityAAPSPlugin @Inject constructor( .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_aaps), - injector, aapsLogger, resourceHelper, sp + injector, aapsLogger, rh, sp ) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { val age = sp.getString(R.string.key_age, "") var defaultHours = 24 - if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 - if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 - if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 + if (age == rh.gs(R.string.key_adult)) defaultHours = 24 + if (age == rh.gs(R.string.key_teenage)) defaultHours = 4 + if (age == rh.gs(R.string.key_child)) defaultHours = 4 val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) val profile = profileFunction.getProfile() if (profile == null) { @@ -141,10 +141,10 @@ class SensitivityAAPSPlugin @Inject constructor( override fun configuration(): JSONObject { val c = JSONObject() try { - c.put(resourceHelper.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + c.put(rh.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(rh.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) + c.put(rh.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(rh.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) } catch (e: JSONException) { e.printStackTrace() } @@ -153,10 +153,10 @@ class SensitivityAAPSPlugin @Inject constructor( override fun applyConfiguration(configuration: JSONObject) { try { - if (configuration.has(resourceHelper.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_maxtime))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_period))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + if (configuration.has(rh.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(rh.gs(R.string.key_absorption_maxtime))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_period))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min))) } catch (e: JSONException) { e.printStackTrace() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt index d93cd05745..be1816164c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -34,7 +34,7 @@ import kotlin.math.roundToInt class SensitivityOref1Plugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, sp: SP, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -48,7 +48,7 @@ class SensitivityOref1Plugin @Inject constructor( .preferencesId(R.xml.pref_absorption_oref1) .description(R.string.description_sensitivity_oref1) .setDefault(), - injector, aapsLogger, resourceHelper, sp + injector, aapsLogger, rh, sp ) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { @@ -206,10 +206,10 @@ class SensitivityOref1Plugin @Inject constructor( override fun configuration(): JSONObject { val c = JSONObject() try { - c.put(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact), sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)) - c.put(resourceHelper.gs(R.string.key_absorption_cutoff), sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + c.put(rh.gs(R.string.key_openapsama_min_5m_carbimpact), sp.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)) + c.put(rh.gs(R.string.key_absorption_cutoff), sp.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(rh.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(rh.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) } catch (e: JSONException) { e.printStackTrace() } @@ -218,10 +218,10 @@ class SensitivityOref1Plugin @Inject constructor( override fun applyConfiguration(configuration: JSONObject) { try { - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact))) sp.putDouble(R.string.key_openapsama_min_5m_carbimpact, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_min_5m_carbimpact))) - if (configuration.has(resourceHelper.gs(R.string.key_absorption_cutoff))) sp.putDouble(R.string.key_absorption_cutoff, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_cutoff))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + if (configuration.has(rh.gs(R.string.key_openapsama_min_5m_carbimpact))) sp.putDouble(R.string.key_openapsama_min_5m_carbimpact, configuration.getDouble(rh.gs(R.string.key_openapsama_min_5m_carbimpact))) + if (configuration.has(rh.gs(R.string.key_absorption_cutoff))) sp.putDouble(R.string.key_absorption_cutoff, configuration.getDouble(rh.gs(R.string.key_absorption_cutoff))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min))) } catch (e: JSONException) { e.printStackTrace() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt index df1b743f6f..00a5ea432e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -32,7 +32,7 @@ import kotlin.math.roundToInt class SensitivityWeightedAveragePlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, sp: SP, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -44,15 +44,15 @@ class SensitivityWeightedAveragePlugin @Inject constructor( .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_weighted_average), - injector, aapsLogger, resourceHelper, sp + injector, aapsLogger, rh, sp ) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { val age = sp.getString(R.string.key_age, "") var defaultHours = 24 - if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 - if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 - if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 + if (age == rh.gs(R.string.key_adult)) defaultHours = 24 + if (age == rh.gs(R.string.key_teenage)) defaultHours = 4 + if (age == rh.gs(R.string.key_child)) defaultHours = 4 val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) if (ads.autosensDataTable.size() < 4) { aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + ads.lastDataTime(dateUtil)) @@ -161,10 +161,10 @@ class SensitivityWeightedAveragePlugin @Inject constructor( override fun configuration(): JSONObject { val c = JSONObject() try { - c.put(resourceHelper.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) - c.put(resourceHelper.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) + c.put(rh.gs(R.string.key_absorption_maxtime), sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME)) + c.put(rh.gs(R.string.key_openapsama_autosens_period), sp.getInt(R.string.key_openapsama_autosens_period, 24)) + c.put(rh.gs(R.string.key_openapsama_autosens_max), sp.getDouble(R.string.key_openapsama_autosens_max, 1.2)) + c.put(rh.gs(R.string.key_openapsama_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7)) } catch (e: JSONException) { e.printStackTrace() } @@ -173,10 +173,10 @@ class SensitivityWeightedAveragePlugin @Inject constructor( override fun applyConfiguration(configuration: JSONObject) { try { - if (configuration.has(resourceHelper.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(resourceHelper.gs(R.string.key_absorption_maxtime))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_period))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_max))) - if (configuration.has(resourceHelper.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(resourceHelper.gs(R.string.key_openapsama_autosens_min))) + if (configuration.has(rh.gs(R.string.key_absorption_maxtime))) sp.putDouble(R.string.key_absorption_maxtime, configuration.getDouble(rh.gs(R.string.key_absorption_maxtime))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_period))) sp.putDouble(R.string.key_openapsama_autosens_period, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_period))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_max))) sp.getDouble(R.string.key_openapsama_autosens_max, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_max))) + if (configuration.has(rh.gs(R.string.key_openapsama_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min))) } catch (e: JSONException) { e.printStackTrace() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt index 637e9202ec..48b3dbc80e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt @@ -41,7 +41,7 @@ class BGSourceFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @Inject lateinit var repository: AppRepository @@ -50,7 +50,7 @@ class BGSourceFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePlugin private val disposable = CompositeDisposable() - private val millsToThePast = T.hours(12).msecs() + private val millsToThePast = T.hours(36).msecs() private var _binding: BgsourceFragmentBinding? = null @@ -131,7 +131,7 @@ class BGSourceFragment : DaggerFragment() { val glucoseValue = v.tag as GlucoseValue activity?.let { activity -> val text = dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + glucoseValue.valueToUnitsString(profileFunction.getUnits()) - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { + OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), text, Runnable { val source = when((activePlugin.activeBgSource as PluginBase).pluginDescription.pluginName) { R.string.dexcom_app_patched -> Sources.Dexcom R.string.eversense -> Sources.Eversense diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index d744d81340..2f4f7d935e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -34,7 +34,7 @@ import javax.inject.Singleton @Singleton class DexcomPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP, private val dexcomMediator: DexcomMediator, @@ -47,7 +47,7 @@ class DexcomPlugin @Inject constructor( .shortName(R.string.dexcom_short) .preferencesId(R.xml.pref_bgsourcedexcom) .description(R.string.description_source_dexcom), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { init { @@ -83,7 +83,7 @@ class DexcomPlugin @Inject constructor( @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger @@ -94,7 +94,7 @@ class DexcomPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!dexcomPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!dexcomPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val bundle = dataWorker.pickupBundle(inputData.getLong(DataWorker.STORE_KEY, -1)) ?: return Result.failure(workDataOf("Error" to "missing input data")) try { @@ -147,11 +147,11 @@ class DexcomPlugin @Inject constructor( .blockingGet() .also { result -> result.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } result.updated.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Updated bg $it") } result.sensorInsertionsInserted.forEach { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index a6c51cf5de..e1f464f7f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -29,7 +29,7 @@ import javax.inject.Singleton @Singleton class EversensePlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() @@ -40,7 +40,7 @@ class EversensePlugin @Inject constructor( .shortName(R.string.eversense_shortname) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_eversense), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { override var sensorBatteryLevel = -1 @@ -60,7 +60,7 @@ class EversensePlugin @Inject constructor( @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -69,7 +69,7 @@ class EversensePlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!eversensePlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!eversensePlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val bundle = dataWorker.pickupBundle(inputData.getLong(DataWorker.STORE_KEY, -1)) ?: return Result.failure(workDataOf("Error" to "missing input data")) if (bundle.containsKey("currentCalibrationPhase")) aapsLogger.debug(LTag.BGSOURCE, "currentCalibrationPhase: " + bundle.getString("currentCalibrationPhase")) @@ -117,7 +117,7 @@ class EversensePlugin @Inject constructor( .blockingGet() .also { savedValues -> savedValues.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt index a6e0f24821..d23831a413 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt @@ -26,7 +26,7 @@ import javax.inject.Singleton @Singleton class GlimpPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() @@ -36,7 +36,7 @@ class GlimpPlugin @Inject constructor( .pluginName(R.string.Glimp) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_glimp), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { // cannot be inner class because of needed injection @@ -49,7 +49,7 @@ class GlimpPlugin @Inject constructor( @Inject lateinit var glimpPlugin: GlimpPlugin @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -58,7 +58,7 @@ class GlimpPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!glimpPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!glimpPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) aapsLogger.debug(LTag.BGSOURCE, "Received Glimp Data: $inputData}") val glucoseValues = mutableListOf() glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( @@ -77,7 +77,7 @@ class GlimpPlugin @Inject constructor( .blockingGet() .also { savedValues -> savedValues.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt index 728e9c12c9..63da6b8761 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt @@ -28,7 +28,7 @@ import javax.inject.Singleton @Singleton class MM640gPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() @@ -37,7 +37,7 @@ class MM640gPlugin @Inject constructor( .pluginIcon(R.drawable.ic_generic_cgm) .pluginName(R.string.MM640g) .description(R.string.description_source_mm640g), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { // cannot be inner class because of needed injection @@ -52,7 +52,7 @@ class MM640gPlugin @Inject constructor( @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -61,7 +61,7 @@ class MM640gPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!mM640gPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success() + if (!mM640gPlugin.isEnabled()) return Result.success() val collection = inputData.getString("collection") ?: return Result.failure(workDataOf("Error" to "missing collection")) if (collection == "entries") { val data = inputData.getString("data") @@ -93,7 +93,7 @@ class MM640gPlugin @Inject constructor( .blockingGet() .also { savedValues -> savedValues.all().forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index 9d82c48014..0069586498 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -34,7 +34,7 @@ import javax.inject.Singleton @Singleton class NSClientSourcePlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, config: Config ) : PluginBase(PluginDescription() @@ -44,7 +44,7 @@ class NSClientSourcePlugin @Inject constructor( .pluginName(R.string.nsclientbg) .shortName(R.string.nsclientbgshort) .description(R.string.description_source_ns_client), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { private var lastBGTimeStamp: Long = 0 @@ -91,7 +91,7 @@ class NSClientSourcePlugin @Inject constructor( @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin @@ -116,7 +116,7 @@ class NSClientSourcePlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!nsClientSourcePlugin.isEnabled() && !sp.getBoolean(R.string.key_ns_receive_cgm, true) && !dexcomPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Sync not enabled")) + if (!nsClientSourcePlugin.isEnabled() && !sp.getBoolean(R.string.key_ns_receive_cgm, false)) return Result.success(workDataOf("Result" to "Sync not enabled")) val sgvs = dataWorker.pickupJSONArray(inputData.getLong(DataWorker.STORE_KEY, -1)) ?: return Result.failure(workDataOf("Error" to "missing input data")) @@ -148,12 +148,12 @@ class NSClientSourcePlugin @Inject constructor( .blockingGet() .also { result -> result.updated.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) nsClientSourcePlugin.detectSource(it) aapsLogger.debug(LTag.DATABASE, "Updated bg $it") } result.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) nsClientSourcePlugin.detectSource(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index fa7e0a278a..d17bef33e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -28,7 +28,7 @@ import javax.inject.Singleton @Singleton class PoctechPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() @@ -38,7 +38,7 @@ class PoctechPlugin @Inject constructor( .pluginName(R.string.poctech) .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_poctech), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { // cannot be inner class because of needed injection @@ -51,7 +51,7 @@ class PoctechPlugin @Inject constructor( @Inject lateinit var poctechPlugin: PoctechPlugin @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -60,7 +60,7 @@ class PoctechPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!poctechPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!poctechPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) aapsLogger.debug(LTag.BGSOURCE, "Received Poctech Data $inputData") try { val glucoseValues = mutableListOf() @@ -86,7 +86,7 @@ class PoctechPlugin @Inject constructor( .blockingGet() .also { savedValues -> savedValues.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index 06c7822036..66cf7f43ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -13,11 +13,8 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable @@ -31,23 +28,21 @@ import kotlin.math.sin @Singleton class RandomBgPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, - private val virtualPumpPlugin: VirtualPumpPlugin, - private val buildHelper: BuildHelper, private val sp: SP, - private val dateUtil: DateUtil, private val repository: AppRepository, private val xDripBroadcast: XDripBroadcast -) : PluginBase(PluginDescription() - .mainType(PluginType.BGSOURCE) - .fragmentClass(BGSourceFragment::class.java.name) - .pluginIcon(R.drawable.ic_dice) - .pluginName(R.string.randombg) - .shortName(R.string.randombg_short) - .preferencesId(R.xml.pref_bgsource) - .description(R.string.description_source_randombg), - aapsLogger, resourceHelper, injector +) : PluginBase( + PluginDescription() + .mainType(PluginType.BGSOURCE) + .fragmentClass(BGSourceFragment::class.java.name) + .pluginIcon(R.drawable.ic_dice) + .pluginName(R.string.randombg) + .shortName(R.string.randombg_short) + .preferencesId(R.xml.pref_bgsource) + .description(R.string.description_source_randombg), + aapsLogger, rh, injector ), BgSource { private val loopHandler: Handler = Handler(HandlerThread(RandomBgPlugin::class.java.simpleName + "Handler").also { it.start() }.looper) @@ -58,7 +53,7 @@ class RandomBgPlugin @Inject constructor( const val interval = 5L // minutes const val min = 70 // mgdl const val max = 190 // mgdl - const val period = 90.0 // minutes + const val period = 120.0 // minutes } init { @@ -89,20 +84,23 @@ class RandomBgPlugin @Inject constructor( } override fun specialEnableCondition(): Boolean { -// return isRunningTest() || virtualPumpPlugin.isEnabled(PluginType.PUMP) && buildHelper.isEngineeringMode() +// return isRunningTest() || virtualPumpPlugin.isEnabled() && buildHelper.isEngineeringMode() return true } private fun handleNewData() { - if (!isEnabled(PluginType.BGSOURCE)) return + if (!isEnabled()) return val cal = GregorianCalendar() - val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60 + val currentMinute = cal[Calendar.MINUTE] + (cal[Calendar.HOUR_OF_DAY] % 2) * 60 val bgMgdl = min + ((max - min) + (max - min) * sin(currentMinute / period * 2 * PI)) / 2 + cal[Calendar.MILLISECOND] = 0 + cal[Calendar.SECOND] = 0 + cal[Calendar.MINUTE] -= cal[Calendar.MINUTE] % 5 val glucoseValues = mutableListOf() glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( - timestamp = dateUtil.now(), + timestamp = cal.timeInMillis, value = bgMgdl, raw = 0.0, noise = null, @@ -111,11 +109,11 @@ class RandomBgPlugin @Inject constructor( ) disposable += repository.runTransactionForResult(CgmSourceTransaction(glucoseValues, emptyList(), null)) .subscribe({ savedValues -> - savedValues.inserted.forEach { - xDripBroadcast(it) - aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") - } - }, { aapsLogger.error(LTag.DATABASE, "Error while saving values from Random plugin", it) } + savedValues.inserted.forEach { + xDripBroadcast.send(it) + aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") + } + }, { aapsLogger.error(LTag.DATABASE, "Error while saving values from Random plugin", it) } ) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index 52773e1d76..fd0eeb48dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -24,7 +24,7 @@ import javax.inject.Singleton @Singleton class TomatoPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP ) : PluginBase(PluginDescription() @@ -35,7 +35,7 @@ class TomatoPlugin @Inject constructor( .preferencesId(R.xml.pref_bgsource) .shortName(R.string.tomato_short) .description(R.string.description_source_tomato), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { // cannot be inner class because of needed injection @@ -49,7 +49,7 @@ class TomatoPlugin @Inject constructor( @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var repository: AppRepository - @Inject lateinit var broadcastToXDrip: XDripBroadcast + @Inject lateinit var xDripBroadcast: XDripBroadcast init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -59,7 +59,7 @@ class TomatoPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!tomatoPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!tomatoPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val glucoseValues = mutableListOf() glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( timestamp = inputData.getLong("com.fanqies.tomatofn.Extras.Time", 0), @@ -77,7 +77,7 @@ class TomatoPlugin @Inject constructor( .blockingGet() .also { savedValues -> savedValues.inserted.forEach { - broadcastToXDrip(it) + xDripBroadcast.send(it) aapsLogger.debug(LTag.DATABASE, "Inserted bg $it") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt index bbb8b2c7e1..80a656b82f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt @@ -24,7 +24,7 @@ import javax.inject.Singleton @Singleton class XdripPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) @@ -32,7 +32,7 @@ class XdripPlugin @Inject constructor( .pluginIcon((R.drawable.ic_blooddrop_48)) .pluginName(R.string.xdrip) .description(R.string.description_source_xdrip), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ), BgSource { private var advancedFiltering = false @@ -73,7 +73,7 @@ class XdripPlugin @Inject constructor( override fun doWork(): Result { var ret = Result.success() - if (!xdripPlugin.isEnabled(PluginType.BGSOURCE)) return Result.success(workDataOf("Result" to "Plugin not enabled")) + if (!xdripPlugin.isEnabled()) return Result.success(workDataOf("Result" to "Plugin not enabled")) val bundle = dataWorker.pickupBundle(inputData.getLong(DataWorker.STORE_KEY, -1)) ?: return Result.failure(workDataOf("Error" to "missing input data")) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt similarity index 90% rename from app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt rename to app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt index 3bbc5eca43..2f3fa6d9ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt @@ -49,12 +49,12 @@ import javax.inject.Singleton @OpenForTesting @Singleton -class CommandQueue @Inject constructor( +class CommandQueueImplementation @Inject constructor( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val aapsSchedulers: AapsSchedulers, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val constraintChecker: ConstraintChecker, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, @@ -65,7 +65,7 @@ class CommandQueue @Inject constructor( private val repository: AppRepository, private val fabricPrivacy: FabricPrivacy, private val config: Config -) : CommandQueueProvider { +) : CommandQueue { private val disposable = CompositeDisposable() @@ -88,9 +88,8 @@ class CommandQueue @Inject constructor( setProfile(ProfileSealed.Pure(nonCustomized), it.interfaceIDs.nightscoutId != null, object : Callback() { override fun run() { if (!result.success) { - ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.failedupdatebasalprofile), R.raw.boluserror) - } - if (result.enacted) { + ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.failedupdatebasalprofile), R.raw.boluserror) + } else { repository.createEffectiveProfileSwitch( EffectiveProfileSwitch( timestamp = dateUtil.now(), @@ -177,7 +176,7 @@ class CommandQueue @Inject constructor( @Synchronized fun notifyAboutNewCommand() { waitForFinishedThread() if (thread == null || thread!!.state == Thread.State.TERMINATED) { - thread = QueueThread(this, context, aapsLogger, rxBus, activePlugin, resourceHelper, sp) + thread = QueueThread(this, context, aapsLogger, rxBus, activePlugin, rh, sp) thread!!.start() aapsLogger.debug(LTag.PUMPQUEUE, "Starting new thread") } else { @@ -196,9 +195,9 @@ class CommandQueue @Inject constructor( override fun independentConnect(reason: String, callback: Callback?) { aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue") - val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, - constraintChecker, profileFunction, activePlugin, context, sp, - buildHelper, dateUtil, repository, fabricPrivacy, config) + val tempCommandQueue = CommandQueueImplementation(injector, aapsLogger, rxBus, aapsSchedulers, rh, + constraintChecker, profileFunction, activePlugin, context, sp, + buildHelper, dateUtil, repository, fabricPrivacy, config) tempCommandQueue.readStatus(reason, callback) tempCommandQueue.disposable.clear() } @@ -222,27 +221,36 @@ class CommandQueue @Inject constructor( // Check if pump store carbs // If not, it's not necessary add command to the queue and initiate connection // Assuming carbs in the future and carbs with duration are NOT stores anyway + + var carbsRunnable = Runnable { } + val originalCarbs = detailedBolusInfo.carbs if ((detailedBolusInfo.carbs > 0) && (!activePlugin.activePump.pumpDescription.storesCarbInfo || detailedBolusInfo.carbsDuration != 0L || (detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil.now()) ) { - disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) - .subscribeBy( - onSuccess = { result -> - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } - callback?.result(PumpEnactResult(injector).enacted(false).success(true))?.run() + carbsRunnable = Runnable { + detailedBolusInfo.carbs = originalCarbs + disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) + .subscribeBy( + onSuccess = { result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } + callback?.result(PumpEnactResult(injector).enacted(false).success(true))?.run() - }, - onError = { - aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) - callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() - } - ) + }, + onError = { + aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) + callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() + } + ) + } // Do not process carbs anymore detailedBolusInfo.carbs = 0.0 // if no insulin just exit - if (detailedBolusInfo.insulin == 0.0) return true + if (detailedBolusInfo.insulin == 0.0) { + carbsRunnable.run() // store carbs + return true + } } var type = if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) CommandType.SMB_BOLUS else CommandType.BOLUS @@ -278,10 +286,10 @@ class CommandQueue @Inject constructor( if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) { add(CommandSMBBolus(injector, detailedBolusInfo, callback)) } else { - add(CommandBolus(injector, detailedBolusInfo, callback, type)) + add(CommandBolus(injector, detailedBolusInfo, callback, type, carbsRunnable)) if (type == CommandType.BOLUS) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, // not when the Bolus command is starting. The command closes the dialog upon completion). - showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context) + showBolusProgressDialog(detailedBolusInfo) // Notify Wear about upcoming bolus rxBus.send(EventBolusRequested(detailedBolusInfo.insulin)) } @@ -308,7 +316,7 @@ class CommandQueue @Inject constructor( @Synchronized override fun cancelAllBoluses() { if (!isRunning(CommandType.BOLUS)) { - rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false))) + rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false), null)) } removeAll(CommandType.BOLUS) removeAll(CommandType.SMB_BOLUS) @@ -399,7 +407,7 @@ class CommandQueue @Inject constructor( val basalValues = profile.getBasalValues() for (basalValue in basalValues) { if (basalValue.value < activePlugin.activePump.pumpDescription.basalMinimumRate) { - val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, resourceHelper.gs(R.string.basalvaluebelowminimum), Notification.URGENT) + val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, rh.gs(R.string.basalvaluebelowminimum), Notification.URGENT) rxBus.send(EventNewNotification(notification)) callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(R.string.basalvaluebelowminimum))?.run() return false @@ -574,14 +582,16 @@ class CommandQueue @Inject constructor( return result } - private fun showBolusProgressDialog(insulin: Double, ctx: Context?) { - if (ctx != null) { + private fun showBolusProgressDialog(detailedBolusInfo: DetailedBolusInfo) { + if (detailedBolusInfo.context != null) { val bolusProgressDialog = BolusProgressDialog() - bolusProgressDialog.setInsulin(insulin) - bolusProgressDialog.show((ctx as AppCompatActivity).supportFragmentManager, "BolusProgress") + bolusProgressDialog.setInsulin(detailedBolusInfo.insulin) + bolusProgressDialog.setTimestamp(detailedBolusInfo.timestamp) + bolusProgressDialog.show((detailedBolusInfo.context as AppCompatActivity).supportFragmentManager, "BolusProgress") } else { val i = Intent() - i.putExtra("insulin", insulin) + i.putExtra("insulin", detailedBolusInfo.insulin) + i.putExtra("timestamp", detailedBolusInfo.timestamp) i.setClass(context, BolusProgressHelperActivity::class.java) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt index 1501fcd23b..1bdbdc7d64 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt @@ -18,12 +18,12 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP class QueueThread internal constructor( - private val queue: CommandQueue, + private val queue: CommandQueueImplementation, context: Context, private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val activePlugin: ActivePlugin, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP ) : Thread() { @@ -32,7 +32,7 @@ class QueueThread internal constructor( private var mWakeLock: PowerManager.WakeLock? = null init { - mWakeLock = (context.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, resourceHelper.gs(R.string.app_name) + ":QueueThread") + mWakeLock = (context.getSystemService(Context.POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, rh.gs(R.string.app_name) + ":QueueThread") } override fun run() { @@ -46,8 +46,8 @@ class QueueThread internal constructor( val secondsElapsed = (System.currentTimeMillis() - connectionStartTime) / 1000 val pump = activePlugin.activePump if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { - rxBus.send(EventDismissBolusProgressIfRunning(null)) - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.connectiontimedout))) + rxBus.send(EventDismissBolusProgressIfRunning(null, null)) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.connectiontimedout))) aapsLogger.debug(LTag.PUMPQUEUE, "timed out") pump.stopConnecting() diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt index 15a0cee52c..0de6850a6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.kt @@ -15,7 +15,8 @@ class CommandBolus( injector: HasAndroidInjector, private val detailedBolusInfo: DetailedBolusInfo, callback: Callback?, - type: CommandType + type: CommandType, + private val carbsRunnable: Runnable ) : Command(injector, type, callback) { @Inject lateinit var rxBus: RxBus @@ -23,14 +24,15 @@ class CommandBolus( override fun execute() { val r = activePlugin.activePump.deliverTreatment(detailedBolusInfo) + if (r.success) carbsRunnable.run() BolusProgressDialog.bolusEnded = true - rxBus.send(EventDismissBolusProgressIfRunning(r)) + rxBus.send(EventDismissBolusProgressIfRunning(r, detailedBolusInfo.timestamp)) aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") callback?.result(r)?.run() } override fun status(): String { - return (if (detailedBolusInfo.insulin > 0) "BOLUS " + resourceHelper.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin) else "") + - if (detailedBolusInfo.carbs > 0) "CARBS " + resourceHelper.gs(R.string.format_carbs, detailedBolusInfo.carbs.toInt()) else "" + return (if (detailedBolusInfo.insulin > 0) "BOLUS " + rh.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin) else "") + + if (detailedBolusInfo.carbs > 0) "CARBS " + rh.gs(R.string.format_carbs, detailedBolusInfo.carbs.toInt()) else "" } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index eaac269a71..6fc51058b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -37,5 +37,5 @@ class CommandSMBBolus( callback?.result(r)?.run() } - override fun status(): String = "SMB BOLUS ${resourceHelper.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin)}" + override fun status(): String = "SMB BOLUS ${rh.gs(R.string.formatinsulinunits, detailedBolusInfo.insulin)}" } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt index 7759448f6f..fdf3fb28fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.ValueWrapper 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.PluginType import info.nightscout.androidaps.interfaces.Profile @@ -25,7 +25,7 @@ class CommandSetProfile constructor( @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var dateUtil: DateUtil - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var config: Config override fun execute() { @@ -40,8 +40,8 @@ class CommandSetProfile constructor( // Send SMS notification if ProfileSwitch is coming from NS val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() if (profileSwitch is ValueWrapper.Existing && r.enacted && hasNsId && !config.NSCLIENT) { - if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) - smsCommunicatorPlugin.sendNotificationToAllNumbers(resourceHelper.gs(R.string.profile_set_ok)) + if (smsCommunicatorPlugin.isEnabled()) + smsCommunicatorPlugin.sendNotificationToAllNumbers(rh.gs(R.string.profile_set_ok)) } } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt index 259ae91b5f..d4b559edd6 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.kt @@ -21,7 +21,11 @@ class CommandTempBasalPercent( @Inject lateinit var activePlugin: ActivePlugin override fun execute() { - val r = activePlugin.activePump.setTempBasalPercent(percent, durationInMinutes, profile, enforceNew, tbrType) + val r = + if (percent == 100) + activePlugin.activePump.cancelTempBasal(enforceNew) + else + activePlugin.activePump.setTempBasalPercent(percent, durationInMinutes, profile, enforceNew, tbrType) aapsLogger.debug(LTag.PUMPQUEUE, "Result percent: $percent durationInMinutes: $durationInMinutes success: ${r.success} enacted: ${r.enacted}") callback?.result(r)?.run() } diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index 94d75d342b..47460541f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.extensions.buildDeviceStatus import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger @@ -69,7 +69,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { @Inject lateinit var runningConfiguration: RunningConfiguration @Inject lateinit var receiverStatusStore: ReceiverStatusStore @Inject lateinit var rxBus: RxBus - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var maintenancePlugin: MaintenancePlugin diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt index 9880ffe8e9..e79221c2c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt @@ -41,12 +41,12 @@ class SWDefinition @Inject constructor( injector: HasAndroidInjector, private val rxBus: RxBus, private val context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, private val localProfilePlugin: LocalProfilePlugin, private val activePlugin: ActivePlugin, - private val commandQueue: CommandQueueProvider, + private val commandQueue: CommandQueue, private val objectivesPlugin: ObjectivesPlugin, private val configBuilder: ConfigBuilder, private val loopPlugin: LoopPlugin, @@ -110,7 +110,7 @@ class SWDefinition @Inject constructor( private val screenPermissionWindow = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfoText(injector) - .label(resourceHelper.gs(R.string.needsystemwindowpermission))) + .label(rh.gs(R.string.needsystemwindowpermission))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) @@ -121,7 +121,7 @@ class SWDefinition @Inject constructor( private val screenPermissionBattery = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfoText(injector) - .label(resourceHelper.gs(R.string.needwhitelisting, resourceHelper.gs(R.string.app_name)))) + .label(rh.gs(R.string.needwhitelisting, rh.gs(R.string.app_name)))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) @@ -132,7 +132,7 @@ class SWDefinition @Inject constructor( private val screenPermissionBt = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfoText(injector) - .label(resourceHelper.gs(R.string.needlocationpermission))) + .label(rh.gs(R.string.needlocationpermission))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) @@ -143,7 +143,7 @@ class SWDefinition @Inject constructor( private val screenPermissionStore = SWScreen(injector, R.string.permission) .skippable(false) .add(SWInfoText(injector) - .label(resourceHelper.gs(R.string.needstoragepermission))) + .label(rh.gs(R.string.needstoragepermission))) .add(SWBreak(injector)) .add(SWButton(injector) .text(R.string.askforpermission) @@ -170,7 +170,7 @@ class SWDefinition @Inject constructor( configBuilder.performPluginSwitch(nsClientPlugin, true, PluginType.GENERAL) rxBus.send(EventSWUpdate(true)) } - .visibility { !nsClientPlugin.isEnabled(PluginType.GENERAL) }) + .visibility { !nsClientPlugin.isEnabled() }) .add(SWEditUrl(injector) .preferenceId(R.string.key_nsclientinternal_url) .updateDelay(5) @@ -257,7 +257,7 @@ class SWDefinition @Inject constructor( .add(SWFragment(injector, this) .add(LocalProfileFragment())) .validator { - localProfilePlugin.profile?.getDefaultProfile()?.let { ProfileSealed.Pure(it).isValid("StartupWizard", activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false).isValid } + localProfilePlugin.profile?.getDefaultProfile()?.let { ProfileSealed.Pure(it).isValid("StartupWizard", activePlugin.activePump, config, rh, rxBus, hardLimits, false).isValid } ?: false } .visibility { localProfilePlugin.isEnabled() } @@ -343,9 +343,9 @@ class SWDefinition @Inject constructor( configBuilder.performPluginSwitch(loopPlugin, true, PluginType.LOOP) rxBus.send(EventSWUpdate(true)) } - .visibility { !loopPlugin.isEnabled(PluginType.LOOP) }) - .validator { loopPlugin.isEnabled(PluginType.LOOP) } - .visibility { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS } + .visibility { !loopPlugin.isEnabled() }) + .validator { loopPlugin.isEnabled() } + .visibility { !loopPlugin.isEnabled() && config.APS } private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity) .skippable(false) .add(SWInfoText(injector) diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt index e0326133f1..2b4d667758 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.kt @@ -30,9 +30,9 @@ class SWEventListener constructor( .toObservable(clazz) .observeOn(aapsSchedulers.main) .subscribe { event: Any -> - status = (event as EventStatus).getStatus(resourceHelper) + status = (event as EventStatus).getStatus(rh) @SuppressLint("SetTextI18n") - textView?.text = (if (textLabel != 0) resourceHelper.gs(textLabel) else "") + " " + status + textView?.text = (if (textLabel != 0) rh.gs(textLabel) else "") + " " + status } ) } @@ -57,7 +57,7 @@ class SWEventListener constructor( val context = layout.context textView = TextView(context) textView?.id = View.generateViewId() - textView?.text = (if (textLabel != 0) resourceHelper.gs(textLabel) else "") + " " + status + textView?.text = (if (textLabel != 0) rh.gs(textLabel) else "") + " " + status layout.addView(textView) } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt index 377aedaed4..c840b0c38a 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt @@ -8,7 +8,7 @@ import javax.inject.Inject class SWScreen(val injector: HasAndroidInjector, private var header: Int) { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper var items: MutableList = ArrayList() var validator: SWValidator? = null @@ -20,7 +20,7 @@ class SWScreen(val injector: HasAndroidInjector, private var header: Int) { } fun getHeader(): String { - return resourceHelper.gs(header) + return rh.gs(header) } fun skippable(skippable: Boolean): SWScreen { diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt index 7e964ab77d..2239207183 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt @@ -145,13 +145,13 @@ class SetupWizardActivity : NoSplashAppCompatActivity() { } override fun onBackPressed() { - if (currentWizardPage == 0) OKDialog.showConfirmation(this, resourceHelper.gs(R.string.exitwizard)) { finish() } else showPreviousPage(null) + if (currentWizardPage == 0) OKDialog.showConfirmation(this, rh.gs(R.string.exitwizard)) { finish() } else showPreviousPage(null) } @Suppress("UNUSED_PARAMETER") fun exitPressed(view: View?) { sp.putBoolean(R.string.key_setupwizard_processed, true) - OKDialog.showConfirmation(this, resourceHelper.gs(R.string.exitwizard)) { finish() } + OKDialog.showConfirmation(this, rh.gs(R.string.exitwizard)) { finish() } } @Suppress("UNUSED_PARAMETER") diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.kt index 90647b51cf..1f3d938bbb 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.kt @@ -38,7 +38,7 @@ class SWEditUrl(injector: HasAndroidInjector) : SWItem(injector, Type.URL) { editText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { - if (Patterns.WEB_URL.matcher(s).matches()) save(s.toString(), updateDelay) else rxBus.send(EventSWLabel(resourceHelper.gs(R.string.error_url_not_valid))) + if (Patterns.WEB_URL.matcher(s).matches()) save(s.toString(), updateDelay) else rxBus.send(EventSWLabel(rh.gs(R.string.error_url_not_valid))) } override fun afterTextChanged(s: Editable) {} diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt index 6793bd0cc7..f2d7a42aff 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt @@ -24,7 +24,7 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var passwordCheck: PasswordCheck @@ -75,7 +75,7 @@ open class SWItem(val injector: HasAndroidInjector, var type: Type) { override fun run() { aapsLogger.debug(LTag.CORE, "Firing EventPreferenceChange") - rxBus.send(EventPreferenceChange(resourceHelper, preferenceId)) + rxBus.send(EventPreferenceChange(rh, preferenceId)) rxBus.send(EventSWUpdate(false)) scheduledEventPost = null } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWRadioButton.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWRadioButton.kt index 979bfe52fc..7a8113a435 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWRadioButton.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWRadioButton.kt @@ -20,11 +20,11 @@ class SWRadioButton(injector: HasAndroidInjector) : SWItem(injector, Type.RADIOB } private fun labels(): Array { - return resourceHelper.gsa(labelsArray) + return rh.gsa(labelsArray) } fun values(): Array { - return resourceHelper.gsa(valuesArray) + return rh.gsa(valuesArray) } override fun generateDialog(layout: LinearLayout) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt index 8f45f00b98..52f7f9a20f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt @@ -15,7 +15,7 @@ import javax.inject.Singleton @Singleton class ActivityMonitor @Inject constructor( private var aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val sp: SP, private val dateUtil: DateUtil ) : Application.ActivityLifecycleCallbacks { @@ -64,16 +64,16 @@ class ActivityMonitor @Inject constructor( if (key.startsWith("Monitor") && key.endsWith("total")) { val v = if (value is Long) value else SafeParse.stringToLong(value as String) val activity = key.split("_")[1].replace("Activity", "") - val duration = dateUtil.niceTimeScalar(v as Long, resourceHelper) + val duration = dateUtil.niceTimeScalar(v as Long, rh) val start = sp.getLong(key.replace("total", "start"), 0) val days = T.msecs(dateUtil.now() - start).days() - result += resourceHelper.gs(R.string.activitymonitorformat, activity, duration, days) + result += rh.gs(R.string.activitymonitorformat, activity, duration, days) } return result } fun stats(): Spanned { - return HtmlHelper.fromHtml("
" + resourceHelper.gs(R.string.activitymonitor) + ":
" + toText()) + return HtmlHelper.fromHtml("
" + rh.gs(R.string.activitymonitor) + ":
" + toText()) } fun reset() { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt index 9f5e36b545..90f9af31c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt @@ -29,7 +29,7 @@ import javax.inject.Singleton @Singleton class AndroidPermission @Inject constructor( - val resourceHelper: ResourceHelper, + val rh: ResourceHelper, val rxBus: RxBus, val injector: HasAndroidInjector ) { @@ -58,7 +58,7 @@ class AndroidPermission @Inject constructor( activity.callForBatteryOptimization.launch(null) } catch (e: ActivityNotFoundException) { permissionBatteryOptimizationFailed = true - OKDialog.show(activity, resourceHelper.gs(R.string.permission), resourceHelper.gs(R.string.alert_dialog_permission_battery_optimization_failed)) { activity.recreate() } + OKDialog.show(activity, rh.gs(R.string.permission), rh.gs(R.string.alert_dialog_permission_battery_optimization_failed)) { activity.recreate() } } } } @@ -79,9 +79,9 @@ class AndroidPermission @Inject constructor( @Synchronized fun notifyForSMSPermissions(activity: FragmentActivity, smsCommunicatorPlugin: SmsCommunicatorPlugin) { - if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) { + if (smsCommunicatorPlugin.isEnabled()) { if (permissionNotGranted(activity, Manifest.permission.RECEIVE_SMS)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_SMS, resourceHelper.gs(R.string.smscommunicator_missingsmspermission), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_SMS, rh.gs(R.string.smscommunicator_missingsmspermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS, @@ -91,7 +91,7 @@ class AndroidPermission @Inject constructor( } else rxBus.send(EventDismissNotification(Notification.PERMISSION_SMS)) // Following is a bug in Android 8 if (permissionNotGranted(activity, Manifest.permission.READ_PHONE_STATE)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_PHONE_STATE, resourceHelper.gs(R.string.smscommunicator_missingphonestatepermission), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_PHONE_STATE, rh.gs(R.string.smscommunicator_missingphonestatepermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.READ_PHONE_STATE)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_PHONE_STATE)) @@ -101,7 +101,7 @@ class AndroidPermission @Inject constructor( @Synchronized fun notifyForBatteryOptimizationPermission(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_BATTERY, String.format(resourceHelper.gs(R.string.needwhitelisting), resourceHelper.gs(R.string.app_name)), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_BATTERY, String.format(rh.gs(R.string.needwhitelisting), rh.gs(R.string.app_name)), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_BATTERY)) @@ -109,7 +109,7 @@ class AndroidPermission @Inject constructor( @Synchronized fun notifyForStoragePermission(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_STORAGE, resourceHelper.gs(R.string.needstoragepermission), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_STORAGE, rh.gs(R.string.needstoragepermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) @@ -120,7 +120,7 @@ class AndroidPermission @Inject constructor( @Synchronized fun notifyForLocationPermissions(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_LOCATION, resourceHelper.gs(R.string.needlocationpermission), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_LOCATION, rh.gs(R.string.needlocationpermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_LOCATION)) @@ -130,7 +130,7 @@ class AndroidPermission @Inject constructor( // Check if Android Q or higher if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { if (!Settings.canDrawOverlays(activity)) { - val notification = NotificationWithAction(injector, Notification.PERMISSION_SYSTEM_WINDOW, resourceHelper.gs(R.string.needsystemwindowpermission), Notification.URGENT) + val notification = NotificationWithAction(injector, Notification.PERMISSION_SYSTEM_WINDOW, rh.gs(R.string.needsystemwindowpermission), Notification.URGENT) notification.action(R.string.request) { // Check if Android Q or higher if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt index a137794222..3d8f75f2ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt @@ -19,13 +19,13 @@ import javax.inject.Singleton @Singleton class BolusTimer @Inject constructor( private val injector: HasAndroidInjector, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val automationPlugin: AutomationPlugin, ) { fun scheduleBolusReminder() { val event = AutomationEvent(injector).apply { - title = resourceHelper.gs(R.string.bolusreminder) + title = rh.gs(R.string.bolusreminder) readOnly = true systemAction = true autoRemove = true @@ -35,12 +35,12 @@ class BolusTimer @Inject constructor( list.add(TriggerBg(injector, 70.0, GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_GREATER)) list.add( TriggerDelta( - injector, InputDelta(resourceHelper, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare + injector, InputDelta(rh, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare .IS_GREATER ) ) } - actions.add(ActionAlarm(injector, resourceHelper.gs(R.string.time_to_bolus))) + actions.add(ActionAlarm(injector, rh.gs(R.string.time_to_bolus))) } automationPlugin.addIfNotExists(event) @@ -48,7 +48,7 @@ class BolusTimer @Inject constructor( fun removeBolusReminder() { val event = AutomationEvent(injector).apply { - title = resourceHelper.gs(R.string.bolusreminder) + title = rh.gs(R.string.bolusreminder) } automationPlugin.removeIfExists(event) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt b/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt index 0f61366226..8d2229c74a 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt @@ -19,17 +19,17 @@ import javax.inject.Singleton @Singleton class CarbTimer @Inject constructor( private val injector: HasAndroidInjector, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val automationPlugin: AutomationPlugin, private val timerUtil: TimerUtil ) { fun scheduleReminder(time: Long, text: String? = null) = - timerUtil.scheduleReminder(time, text ?: resourceHelper.gs(R.string.timetoeat)) + timerUtil.scheduleReminder(time, text ?: rh.gs(R.string.timetoeat)) fun scheduleEatReminder() { val event = AutomationEvent(injector).apply { - title = resourceHelper.gs(R.string.bolusadvisor) + title = rh.gs(R.string.bolusadvisor) readOnly = true systemAction = true autoRemove = true @@ -38,23 +38,23 @@ class CarbTimer @Inject constructor( // Bg under 180 mgdl and dropping by 15 mgdl list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 180.0, GlucoseUnit.MGDL, Comparator.Compare.IS_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, -15.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, -8.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, -15.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, -8.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) // Bg under 160 mgdl and dropping by 9 mgdl list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 160.0, GlucoseUnit.MGDL, Comparator.Compare.IS_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, -9.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, -5.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, -9.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, -5.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) // Bg under 145 mgdl and dropping list.add(TriggerConnector(injector, TriggerConnector.Type.AND).apply { list.add(TriggerBg(injector, 145.0, GlucoseUnit.MGDL, Comparator.Compare.IS_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) - list.add(TriggerDelta(injector, InputDelta(resourceHelper, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.DELTA), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) + list.add(TriggerDelta(injector, InputDelta(rh, 0.0, -360.0, 360.0, 1.0, DecimalFormat("0"), InputDelta.DeltaType.SHORT_AVERAGE), GlucoseUnit.MGDL, Comparator.Compare.IS_EQUAL_OR_LESSER)) }) } - actions.add(ActionAlarm(injector, resourceHelper.gs(R.string.time_to_eat))) + actions.add(ActionAlarm(injector, rh.gs(R.string.time_to_eat))) } automationPlugin.addIfNotExists(event) @@ -62,7 +62,7 @@ class CarbTimer @Inject constructor( fun removeEatReminder() { val event = AutomationEvent(injector).apply { - title = resourceHelper.gs(R.string.bolusadvisor) + title = rh.gs(R.string.bolusadvisor) } automationPlugin.removeIfExists(event) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt index d6169b307c..1e8cf7d3b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt @@ -36,7 +36,7 @@ class LocalAlertUtils @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val activePlugin: ActivePlugin, private val profileFunction: ProfileFunction, private val smsCommunicatorPlugin: SmsCommunicatorPlugin, @@ -63,13 +63,13 @@ class LocalAlertUtils @Inject constructor( if (sp.getBoolean(R.string.key_enable_pump_unreachable_alert, true)) { aapsLogger.debug(LTag.CORE, "Generating pump unreachable alarm. lastConnection: " + dateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: " + isStatusOutdated) sp.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()) - rxBus.send(EventNewNotification(Notification(Notification.PUMP_UNREACHABLE, resourceHelper.gs(R.string.pump_unreachable), Notification.URGENT).also { it.soundId = R.raw.alarm })) - uel.log(Action.CAREPORTAL, Sources.Aaps, resourceHelper.gs(R.string.pump_unreachable), ValueWithUnit.TherapyEventType(TherapyEvent.Type.ANNOUNCEMENT)) + rxBus.send(EventNewNotification(Notification(Notification.PUMP_UNREACHABLE, rh.gs(R.string.pump_unreachable), Notification.URGENT).also { it.soundId = R.raw.alarm })) + uel.log(Action.CAREPORTAL, Sources.Aaps, rh.gs(R.string.pump_unreachable), ValueWithUnit.TherapyEventType(TherapyEvent.Type.ANNOUNCEMENT)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) - disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.pump_unreachable))).subscribe() + disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(rh.gs(R.string.pump_unreachable))).subscribe() } if (sp.getBoolean(R.string.key_smscommunicator_report_pump_ureachable, true)) - smsCommunicatorPlugin.sendNotificationToAllNumbers(resourceHelper.gs(R.string.pump_unreachable)) + smsCommunicatorPlugin.sendNotificationToAllNumbers(rh.gs(R.string.pump_unreachable)) } if (!isStatusOutdated && !alarmTimeoutExpired) rxBus.send(EventDismissNotification(Notification.PUMP_UNREACHABLE)) } @@ -122,11 +122,11 @@ class LocalAlertUtils @Inject constructor( && bgReading.timestamp + missedReadingsThreshold() < System.currentTimeMillis() && sp.getLong("nextMissedReadingsAlarm", 0L) < System.currentTimeMillis() ) { - val n = Notification(Notification.BG_READINGS_MISSED, resourceHelper.gs(R.string.missed_bg_readings), Notification.URGENT) + val n = Notification(Notification.BG_READINGS_MISSED, rh.gs(R.string.missed_bg_readings), Notification.URGENT) n.soundId = R.raw.alarm sp.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()) rxBus.send(EventNewNotification(n)) - uel.log(Action.CAREPORTAL, Sources.Aaps, resourceHelper.gs(R.string.missed_bg_readings), ValueWithUnit.TherapyEventType(TherapyEvent.Type.ANNOUNCEMENT)) + uel.log(Action.CAREPORTAL, Sources.Aaps, rh.gs(R.string.missed_bg_readings), ValueWithUnit.TherapyEventType(TherapyEvent.Type.ANNOUNCEMENT)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { n.text?.let { disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(it)).subscribe() } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt b/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt index 0ff3cab9ec..d669ef8bc3 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt @@ -14,14 +14,17 @@ import org.json.JSONObject import java.text.SimpleDateFormat import java.util.* import javax.inject.Inject +import javax.inject.Singleton -@Suppress("SpellCheckingInspection") class XDripBroadcast @Inject constructor( +@Suppress("SpellCheckingInspection") +@Singleton +class XDripBroadcast @Inject constructor( private val context: Context, private val aapsLogger: AAPSLogger, private val sp: SP ) { - operator fun invoke(glucoseValue: GlucoseValue) { + fun send(glucoseValue: GlucoseValue) { if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US) try { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt index 133a03187a..a0b9d0af1c 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt @@ -17,7 +17,7 @@ import javax.inject.Singleton @Singleton class XdripCalibrations @Inject constructor( private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val context: Context, private val profileFunction: ProfileFunction ) { @@ -33,12 +33,12 @@ class XdripCalibrations @Inject constructor( context.sendBroadcast(intent) val q = context.packageManager.queryBroadcastReceivers(intent, 0) return if (q.size < 1) { - ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.xdripnotinstalled)) - aapsLogger.debug(resourceHelper.gs(R.string.xdripnotinstalled)) + ToastUtils.showToastInUiThread(context, rh.gs(R.string.xdripnotinstalled)) + aapsLogger.debug(rh.gs(R.string.xdripnotinstalled)) false } else { - ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.calibrationsent)) - aapsLogger.debug(resourceHelper.gs(R.string.calibrationsent)) + ToastUtils.showToastInUiThread(context, rh.gs(R.string.calibrationsent)) + aapsLogger.debug(rh.gs(R.string.calibrationsent)) true } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt index 4fda9e5fd8..1599cddb79 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt @@ -17,7 +17,7 @@ import javax.inject.Singleton @Singleton class NotificationHolderImpl @Inject constructor( - resourceHelper: ResourceHelper, + rh: ResourceHelper, context: Context, iconsProvider: IconsProvider ) : NotificationHolder { @@ -29,8 +29,8 @@ class NotificationHolderImpl @Inject constructor( .setOnlyAlertOnce(true) .setCategory(NotificationCompat.CATEGORY_STATUS) .setSmallIcon(iconsProvider.getNotificationIcon()) - .setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) - .setContentTitle(resourceHelper.gs(R.string.loading)) + .setLargeIcon(rh.decodeResource(iconsProvider.getIcon())) + .setContentTitle(rh.gs(R.string.loading)) .setContentIntent(openAppIntent(context)) .build() .also { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt index 5f67236055..6b688c15cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt @@ -21,7 +21,7 @@ class TIR(val date: Long, val lowThreshold: Double, val highThreshold: Double) { private fun inRangePct() = if (count > 0) 100 - belowPct() - abovePct() else 0 private fun abovePct() = if (count > 0) (above.toDouble() / count * 100.0).roundToInt() else 0 - fun toText(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = resourceHelper.gs(R.string.tirformat, dateUtil.dateStringShort(date), belowPct(), inRangePct(), abovePct()) + fun toText(rh: ResourceHelper, dateUtil: DateUtil): String = rh.gs(R.string.tirformat, dateUtil.dateStringShort(date), belowPct(), inRangePct(), abovePct()) - fun toText(resourceHelper: ResourceHelper, days: Int): String = resourceHelper.gs(R.string.tirformat, "%02d".format(days) + " " + resourceHelper.gs(R.string.days), belowPct(), inRangePct(), abovePct()) + fun toText(rh: ResourceHelper, days: Int): String = rh.gs(R.string.tirformat, "%02d".format(days) + " " + rh.gs(R.string.days), belowPct(), inRangePct(), abovePct()) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index f00d391026..cfe0eeeaec 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -22,7 +22,7 @@ import javax.inject.Inject class TddCalculator @Inject constructor( private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val activePlugin: ActivePlugin, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, @@ -50,10 +50,12 @@ class TddCalculator @Inject constructor( result.put(midnight, tdd) } - for (t in startTime until endTime step T.mins(5).msecs()) { + val calculationStep = T.mins(5).msecs() + val tempBasals = iobCobCalculator.getTempBasalIncludingConvertedExtendedForRange(startTime, endTime, calculationStep) + for (t in startTime until endTime step calculationStep) { val midnight = MidnightTime.calc(t) val tdd = result[midnight] ?: TotalDailyDose(timestamp = midnight) - val tbr = iobCobCalculator.getTempBasalIncludingConvertedExtended(t) + val tbr = tempBasals[t] val profile = profileFunction.getProfile(t) ?: continue val absoluteRate = tbr?.convertedToAbsolute(t, profile) ?: profile.getBasal(t) tdd.basalAmount += absoluteRate / 60.0 * 5.0 @@ -94,10 +96,10 @@ class TddCalculator @Inject constructor( val tdds = calculate(7) val averageTdd = averageTDD(tdds) return HtmlHelper.fromHtml( - "" + resourceHelper.gs(R.string.tdd) + ":
" + + "" + rh.gs(R.string.tdd) + ":
" + toText(tdds, true) + - "" + resourceHelper.gs(R.string.average) + ":
" + - averageTdd.toText(resourceHelper, tdds.size(), true) + "" + rh.gs(R.string.average) + ":
" + + averageTdd.toText(rh, tdds.size(), true) ) } @@ -105,7 +107,7 @@ class TddCalculator @Inject constructor( private fun toText(tdds: LongSparseArray, includeCarbs: Boolean): String { var t = "" for (i in 0 until tdds.size()) { - t += "${tdds.valueAt(i).toText(resourceHelper, dateUtil, includeCarbs)}
" + t += "${tdds.valueAt(i).toText(rh, dateUtil, includeCarbs)}
" } return t } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt index b2c476f729..58ec13ab54 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt @@ -17,7 +17,7 @@ import javax.inject.Singleton @Singleton class TirCalculator @Inject constructor( - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, private val repository: AppRepository @@ -78,21 +78,21 @@ class TirCalculator @Inject constructor( val tit30 = calculate(30, lowTitMgdl, highTitMgdl) val averageTit30 = averageTIR(tit30) return HtmlHelper.fromHtml( - "
" + resourceHelper.gs(R.string.tir) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):
" + - toText(resourceHelper, tir7) + - "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):
" + - averageTir7.toText(resourceHelper, tir7.size()) + "
" + - averageTir30.toText(resourceHelper, tir30.size()) + - "
" + resourceHelper.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTitMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTitMgdl) + "):
" + - averageTit7.toText(resourceHelper, tit7.size()) + "
" + - averageTit30.toText(resourceHelper, tit30.size()) + "
" + rh.gs(R.string.tir) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):
" + + toText(rh, tir7) + + "
" + rh.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + "):
" + + averageTir7.toText(rh, tir7.size()) + "
" + + averageTir30.toText(rh, tir30.size()) + + "
" + rh.gs(R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTitMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTitMgdl) + "):
" + + averageTit7.toText(rh, tit7.size()) + "
" + + averageTit30.toText(rh, tit30.size()) ) } - fun toText(resourceHelper: ResourceHelper, tirs: LongSparseArray): String { + fun toText(rh: ResourceHelper, tirs: LongSparseArray): String { var t = "" for (i in 0 until tirs.size()) { - t += "${tirs.valueAt(i).toText(resourceHelper, dateUtil)}
" + t += "${tirs.valueAt(i).toText(rh, dateUtil)}
" } return t } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 2b5e11342d..ccdef22e95 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -45,13 +45,13 @@ class BolusWizard @Inject constructor( ) { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var dateUtil: DateUtil @@ -283,31 +283,31 @@ class BolusWizard @Inject constructor( val actions: LinkedList = LinkedList() if (insulinAfterConstraints > 0) { val pct = if (percentageCorrection != 100) " ($percentageCorrection%)" else "" - actions.add(resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraints).formatColor(resourceHelper, R.color.bolus) + pct) + actions.add(rh.gs(R.string.bolus) + ": " + rh.gs(R.string.formatinsulinunits, insulinAfterConstraints).formatColor(rh, R.color.bolus) + pct) } if (carbs > 0 && !advisor) { var timeShift = "" if (carbTime > 0) { - timeShift += " (+" + resourceHelper.gs(R.string.mins, carbTime) + ")" + timeShift += " (+" + rh.gs(R.string.mins, carbTime) + ")" } else if (carbTime < 0) { - timeShift += " (" + resourceHelper.gs(R.string.mins, carbTime) + ")" + timeShift += " (" + rh.gs(R.string.mins, carbTime) + ")" } - actions.add(resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, carbs).formatColor(resourceHelper, R.color.carbs) + timeShift) + actions.add(rh.gs(R.string.carbs) + ": " + rh.gs(R.string.format_carbs, carbs).formatColor(rh, R.color.carbs) + timeShift) } if (insulinFromCOB > 0) { - actions.add(resourceHelper.gs(R.string.cobvsiob) + ": " + resourceHelper.gs(R.string.formatsignedinsulinunits, insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG).formatColor(resourceHelper, R.color.cobAlert)) + actions.add(rh.gs(R.string.cobvsiob) + ": " + rh.gs(R.string.formatsignedinsulinunits, insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG).formatColor(rh, R.color.cobAlert)) val absorptionRate = iobCobCalculator.ads.slowAbsorptionPercentage(60) if (absorptionRate > .25) - actions.add(resourceHelper.gs(R.string.slowabsorptiondetected, resourceHelper.gc(R.color.cobAlert), (absorptionRate * 100).toInt())) + actions.add(rh.gs(R.string.slowabsorptiondetected, rh.gc(R.color.cobAlert), (absorptionRate * 100).toInt())) } if (abs(insulinAfterConstraints - calculatedTotalInsulin) > activePlugin.activePump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarn, calculatedTotalInsulin, insulinAfterConstraints).formatColor(resourceHelper, R.color.warning)) + actions.add(rh.gs(R.string.bolusconstraintappliedwarn, calculatedTotalInsulin, insulinAfterConstraints).formatColor(rh, R.color.warning)) if (config.NSCLIENT && insulinAfterConstraints > 0) - 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 (useAlarm && !advisor && carbs > 0 && carbTime > 0) - actions.add(resourceHelper.gs(R.string.alarminxmin, carbTime).formatColor(resourceHelper, R.color.info)) + actions.add(rh.gs(R.string.alarminxmin, carbTime).formatColor(rh, R.color.info)) if (advisor) - actions.add(resourceHelper.gs(R.string.advisoralarm).formatColor(resourceHelper, R.color.info)) + actions.add(rh.gs(R.string.advisoralarm).formatColor(rh, R.color.info)) return HtmlHelper.fromHtml(Joiner.on("
").join(actions)) } @@ -324,7 +324,7 @@ class BolusWizard @Inject constructor( if (carbs > 0.0) carbTimer.removeEatReminder() if (sp.getBoolean(R.string.key_usebolusadvisor, false) && Profile.toMgdl(bg, profile.units) > 180 && carbs > 0 && carbTime >= 0) - OKDialog.showYesNoCancel(ctx, resourceHelper.gs(R.string.bolusadvisor), resourceHelper.gs(R.string.bolusadvisormessage), + OKDialog.showYesNoCancel(ctx, rh.gs(R.string.bolusadvisor), rh.gs(R.string.bolusadvisormessage), { bolusAdvisorProcessing(ctx) }, { commonProcessing(ctx) } ) @@ -335,7 +335,7 @@ class BolusWizard @Inject constructor( private fun bolusAdvisorProcessing(ctx: Context) { val confirmMessage = confirmMessageAfterConstraints(advisor = true) - OKDialog.showConfirmation(ctx, resourceHelper.gs(R.string.boluswizard), confirmMessage, { + OKDialog.showConfirmation(ctx, rh.gs(R.string.boluswizard), confirmMessage, { DetailedBolusInfo().apply { eventType = DetailedBolusInfo.EventType.CORRECTION_BOLUS insulin = insulinAfterConstraints @@ -354,7 +354,7 @@ class BolusWizard @Inject constructor( commandQueue.bolus(this, object : Callback() { override fun run() { 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 carbTimer.scheduleEatReminder() } @@ -369,11 +369,11 @@ class BolusWizard @Inject constructor( val pump = activePlugin.activePump val confirmMessage = confirmMessageAfterConstraints(advisor = false) - OKDialog.showConfirmation(ctx, resourceHelper.gs(R.string.boluswizard), confirmMessage, { + OKDialog.showConfirmation(ctx, rh.gs(R.string.boluswizard), confirmMessage, { if (insulinAfterConstraints > 0 || carbs > 0) { if (useSuperBolus) { uel.log(Action.SUPERBOLUS_TBR, Sources.WizardDialog) - if (loopPlugin.isEnabled(PluginType.LOOP)) { + if (loopPlugin.isEnabled()) { loopPlugin.goToZeroTemp(2 * 60, profile, OfflineEvent.Reason.SUPER_BOLUS) rxBus.send(EventRefreshOverview("WizardDialog")) } @@ -382,7 +382,7 @@ class BolusWizard @Inject constructor( commandQueue.tempBasalAbsolute(0.0, 120, true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() { override fun run() { 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) } } }) @@ -393,7 +393,7 @@ class BolusWizard @Inject constructor( val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra(ErrorHelperActivity.SOUND_ID, R.raw.boluserror) i.putExtra(ErrorHelperActivity.STATUS, result.comment) - i.putExtra(ErrorHelperActivity.TITLE, resourceHelper.gs(R.string.tempbasaldeliveryerror)) + i.putExtra(ErrorHelperActivity.TITLE, rh.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } @@ -426,7 +426,7 @@ class BolusWizard @Inject constructor( commandQueue.bolus(this, object : Callback() { override fun run() { 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) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index c1784ca4ff..f2217d20ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -132,7 +132,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec fun validFrom(): Int = safeGetInt(storage, "validFrom") - private fun validTo(): Int = safeGetInt(storage, "validTo") + fun validTo(): Int = safeGetInt(storage, "validTo") fun useBG(): Int = safeGetInt(storage, "useBG", YES) diff --git a/app/src/main/res/drawable/ic_baseline_warning_24_red.xml b/app/src/main/res/drawable/ic_baseline_warning_24_red.xml new file mode 100644 index 0000000000..f01f6df79d --- /dev/null +++ b/app/src/main/res/drawable/ic_baseline_warning_24_red.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_baseline_warning_24_yellow.xml b/app/src/main/res/drawable/ic_baseline_warning_24_yellow.xml new file mode 100644 index 0000000000..2eededf7fc --- /dev/null +++ b/app/src/main/res/drawable/ic_baseline_warning_24_yellow.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/drawable/ic_loop_reconnect.xml b/app/src/main/res/drawable/ic_loop_reconnect.xml index d90927a081..f61d0f97b1 100644 --- a/app/src/main/res/drawable/ic_loop_reconnect.xml +++ b/app/src/main/res/drawable/ic_loop_reconnect.xml @@ -5,8 +5,8 @@ android:viewportHeight="24"> + android:fillColor="@color/loopClosed"/> + android:fillColor="@color/loopClosed"/> diff --git a/app/src/main/res/layout/dialog_profileswitch.xml b/app/src/main/res/layout/dialog_profileswitch.xml index 9cb45b96d8..e563f7b0fe 100644 --- a/app/src/main/res/layout/dialog_profileswitch.xml +++ b/app/src/main/res/layout/dialog_profileswitch.xml @@ -77,7 +77,7 @@ android:layout_height="wrap_content" android:gravity="center_horizontal" android:orientation="horizontal" - android:visibility="visible"> + android:visibility="gone"> diff --git a/app/src/main/res/layout/overview_info_layout.xml b/app/src/main/res/layout/overview_info_layout.xml index 7ec4d562ee..20f5e775de 100644 --- a/app/src/main/res/layout/overview_info_layout.xml +++ b/app/src/main/res/layout/overview_info_layout.xml @@ -19,6 +19,14 @@ app:layout_constraintTop_toTopOf="parent" tools:ignore="HardcodedText" /> + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
https://androidaps.readthedocs.io/en/latest/EN/Module/module.html https://androidaps.readthedocs.io/en/latest/EN/Module/module.html + Отбележете всички правилни отговори. https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting https://www.facebook.com/groups/AndroidAPSUsers/ https://gitter.im/MilosKozak/AndroidAPS Fiasp® https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin + Отбележете всички правилни отговори. https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-to-carb-ratio-ic-g-u https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml index 8c4e00b7b0..9d60fcda5e 100644 --- a/app/src/main/res/values-bg-rBG/strings.xml +++ b/app/src/main/res/values-bg-rBG/strings.xml @@ -677,6 +677,7 @@ Възстанови настройките по подразбиране Грешка в NSClient. Рестартирайте Nightscout и NSClient времево отместване + Напомни за болус по-късно Предпочитаният режим на APS Общо Калк @@ -715,6 +716,7 @@ Проверка на версията стара версия много стара версия + Прилагането изтече Има нова версия от най-малко %1$d дни! Ще спре подаването на инсулин след %2$d дни, цикълът ще бъде изключен след %3$d дни Dexcom приложение (модифицирано) @@ -842,6 +844,10 @@ Използвай напомняне за старт на хранене вместо съветника по време на висока гликемия (\"пре-болус\") Време за ядене!\nИзпълнете болус съветника и направете изчисления отново. Време е за ядене + Болус подсещане + Включи подсещането за болус + Използвай подсещане за болус по-късно със съветник (\"след-болус\") + Време е за болус!\nВключи болус съветника и направи изчисление отново. Качването на данни за проблеми е забранено!(Fabric) Графика Меню на графиката @@ -849,6 +855,7 @@ Стрелка тенденция Канюла Потербителска настройка + Използвай стойностите от вашето най-голямо хранен, с което обикновено се храните Тази електронна поща ще бъде добавена към репорта за да можем да се свържем с вас в случай на нужда. Не е задължително. Електронна поща Настройки за поверителност @@ -876,6 +883,7 @@ Приемай постояни данни от сензора идващи от NS Изтичане на времето на предишна комуникация с помпата В момента се обработва друг болус. Моля опитай по-късни. + Калкулация в прогресс Липсва име на профила Грешка в стойността на ВЧ (IC) Грешка в базалните стойности diff --git a/app/src/main/res/values-ca-rES/exam.xml b/app/src/main/res/values-ca-rES/exam.xml index 3ea04e700d..0250b67387 100644 --- a/app/src/main/res/values-ca-rES/exam.xml +++ b/app/src/main/res/values-ca-rES/exam.xml @@ -1,2 +1,178 @@ - + + Què és cert sobre la DIA (Durada de l\'Acció de la Insulina)? + Durada de l\'Acció de la Insulina (DIA) + Heu de configurar el valor de la DIA al vostre perfil. + El mínim permès son 5 hores. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin + Si esteu satisfets amb el valor de la DIA que fèieu servir a la bomba abans d\'utilitzar AndroidAPS, no cal canviar-la quan comenceu amb el llaç. + Heu de determinar vosaltres mateixos el valor apropiat per la DIA. + Objectiu temporal hipo + Quin seria el motiu principal per fixar un objectiu temporal hipo? + Corregir hipos causades per configuracions incorrectes de la ràtio basal. + Evitar que AndroidAPS corregeixi excessivament quan hi ha un augment de glucèmia provocat pels carbohidrats d\'absorció ràpida consumits per tractar una hipo. + Corregir una hipo provocada per fer esport. + Evitar que la glucèmia baixi més del compte quan ja hi ha una basal temporal activa del 0%. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html + Quin perfil pot ser utilitzat i configurat sense connexió a Internet? + Tema: Perfil fora de línia + El perfil NS es pot fer servir, però no configurar. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile + Motius per aplicar \"Desconnectar bomba\" a AndroidAPS + Què cal fer al desconnectar la bomba? + No cal fer res, ja que a l\'estar la bomba físicament desconnectada, no es lliurarà insulina. + Evita que AndroidAPS tingui en compte la insulina que no es lliura mentre la bomba està físicament desconnectada. + Si la bomba continua connectada, no deixarà de lliurar insulina. + Posarà AndroidAPS en mode llaç obert. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings + Configuració AndroidAPS + Configuració AndroidAPS + Quines son les bones pràctiques respecte a fer còpia de seguretat de la configuració? + No cal exportar la configuració si la teniu anotada a algun lloc. + Exporteu la configuració cada vegada que completeu un objectiu. + Exporteu la configuració cada vegada que canvieu algun paràmetre. + Exporteu la configuració un cop feta la configuració inicial i haver establert les vostres preferències. + Exporteu la configuració localment des del menú de manteniment. + El fitxer de configuració es troba a la carpeta Internal Storage/AAPS/preferences del vostre telèfon. + Copieu el fitxer de configuració a una ubicació segura fora del telèfon (p.ex. al núvol, connectant un cable a un ordinador, correu electrònic, etc.) + Si el vostre telèfon està avariat o perdut, és fàcil recuperar la vostra configuració remotament sense una còpia de seguretat. + https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me + Lectures CGM sorolloses + Què cal fer si les dades del CGM son sorolloses? + No cal fer res, AndroidAPS se n\'encarregarà. + Desactivar el llaç tancat per evitar dosi massa altes o baixes. + Substituir els sensors constantment sorollosos o inexactes. + Comprovar que la vostra app de CGM proporciona dades suavitzades. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data + Esport i perfils + Com es poden utilitzar els perfils per ajudar el sistema a gestionar l\'esport aeròbic? + Fer un canvi de perfil a menys del 100%. + Fer un canvi de perfil a més del 100%. + Deixar el perfil al 100%. + Aturar el llaç. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target + Esport i objectius temporals + Com es poden utilitzar els objectius temporals per ajudar el sistema a gestionar l\'esport aeròbic? + Establir un objectiu glucèmic d\'activitat, prou temps abans de començar l\'esport. + Establir un objectiu glucèmic d\'activitat un cop acabat l\'esport. + Deixar l\'objectiu glucèmic com està. + Esperar que la glucèmia baixi per sota del vostre objectiu temporal d\'hipoglucèmia i llavors prendre 15g de carbohidrats d\'acció ràpida. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target + Llaç desactivat/aturat + Rebo insulina quan el llaç està desactivat/aturat? + Sí, la insulina basal es continua lliurant. + No, s\'atura el lliurament d\'insulina. + Basal, ISF (Factor Sensibilitat Insulina) i proves I:C (ràtio insulina/carbohidrats) + Quan s\'haurien de validar aquests valors? + Abans de començar amb el llaç. + Quan es produeixen sovint glucèmies altes i baixes. + Almenys un cop per setmana. + Un cop configurats i validats, aquests valors no haurien de canviar amb el temps. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings + Prerequisits + Què seria essencial per configurar i utilitzar AndroidAPS? + Informació del perfil validada (basal, ràtio I:C, ISF, DIA). + Un ordinador amb Android Studio instal·lat i configurat. + Un telèfon compatible. + Una bomba d\'insulina compatible, si és que voleu acabar fent servir un llaç tancat. + Nightscout, per tenir un registre amb totes els dades i poder revisar la configuració. + Un compte Tidepool. + Un compte Google. + Un compte Github. + Experiència en programació o edició de codi. + Una bomba MiniMed 670G. + https://androidaps.readthedocs.io/en/latest/EN/Module/module.html + Un smartwatch (rellotge intel·ligent). + Un CGM (Monitor Continu de Glucosa) compatible. + Requisits previs + Què seria essencial per configurar i utilitzar AndroidAPS? + Informació validada per poder configurar un perfil (ISF, ràtio I:C, basals, DIA, etc.). + Un dispositiu Android compatible (p.ex. telèfon mòbil, rellotge Android o tauleta). + AndroidAPS necessita una connexió a internet per poder funcionar en mode llaç tancat. + Un CGM (monitor continu de glucosa) compatible i l\'app adequada per rebre al telèfon/dispositiu els valors de glucèmia que proporciona. + https://androidaps.readthedocs.io/en/latest/EN/Module/module.html + Actualitzant AndroidAPS + Marqueu totes les respostes correctes. + Cal tenir Git instal·lat i configurat al vostre ordinador. + Quan es lliuren versions actualitzades d\'AndroidAPS, les versions anteriors poden ser limitades remotament al cap d\'un temps, en una data determinada. + Haurieu de desar i anotar la ubicació del vostre \"keystore\" i utilitzar la mateixa clau de signatura per la instal·lació anterior que per les noves actualitzacions. + No actualitzeu mai si el sistema està funcionant correctament. + Si teniu problemes en compilar l\'apk (aplicació), podeu instal·lar una apk que hagi estat compilada per una amiga. + https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch + Resolució de problemes + A on es pot cercar ajuda relacionada amb AndroidAPS? + Demanant consell al grup de Facebook d\'usuaris d\'AndroidAPS. + Llegint (i rellegint) la documentació d\'AndroidAPS. + Demanant consell i enregistrant problemes tècnics o errors de funcionament a la sala AndroidAPS de Gitter. + Preguntant a la clínica on us porten la diabetis o a la vostra endocrinòloga. + https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting + https://www.facebook.com/groups/AndroidAPSUsers/ + https://gitter.im/MilosKozak/AndroidAPS + Plugins d\'insulina + Quina insulina s\'ha de fer servir amb el plugin Ultra-Rapid Oref? + Fiasp® + NovoRapid®/Novolog® + Humalog® + Actrapid®/Humalin R®/insulina humana \"estàndard\". + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin + Plugins de sensibilitat + Marqueu totes les respostes correctes. + Els plugins de sensibilitat permeten AndroidAPS ajustar-se davant de canvis temporals o breus de sensibilitat a l\'insulina (per exemple canvis hormonals o problemes d\'absorció al lloc d\'infusió). + Els plugins de sensibilitat ofereixen l\'usuari suggeriments de canvi de les basals, ràtios I:C (insulina:carbohidrats) i ISF (factor de sensibilitat a l\'insulina) que poden ser utilitzats per editar el perfil. + L\'enregistrament d\'un canvi de cànula restableix la ràtio Autosens, deixant-lo de nou a un 100%. + Algunes de les opcions de plugins es poden configurar segons rangs horaris que poden ser definits per l\'usuari. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html + Errors d\'entrada de carbohidrats + Què cal fer si feu una entrada incorrecta de carbohidrats? + Elimineu la entrada incorrecta a Tractaments i introduïu el valor correcte de carbohidrats. + Bolus amb insulina utilitzant el menú d\'encebat del set d\'infusió. + Res - AndroidAPS ja farà els ajustos apropiats. + Bolus amb insulina utilitzant el botó d\'Insulina (bolus) de la pantalla \"Inici\". + Errors de lliurament/registre d\'insulina + Què cal fer si rebeu menys insulina de la que suggereix l\'historial de la bomba, p.ex. degut a una oclusió, a una cànula que no funciona o un oblit de reconnexió de la bomba després d\'una dutxa? + Eliminar dades d\'insulina del portal de cures Nightscout per eliminar-les de l\'historial de la bomba. + Compara els valors entre AndroidAps i l’historial de la bomba (si la bomba ho admet). + Lliurar un bolus amb part de la insulina que falta utilitzant una jeringa/ploma o el menú d\'encebat. + No fer res i permetre que AndroidAPS corregeixi els possibles valors alts de glucèmia que es produeixin. + Insulina \"a bord\" (IOB) + Marqueu totes les respostes correctes. + El valor d\'IOB es veu afectat per les basals temporals lliurades. + Una basal temporal alta no serà lliurada si la glucèmia està per sota de l\'objectiu. + Un valor d\'IOB positiu durant un període de temps important suggereix resistència a la insulina o àpats no anunciats. + Entrada de carbohidrats i bolus + A l\'hora d\'estimar i registrar els carbohidrats consumits, només s\'han de fer servir grams. + Els carbohidrats consumits poden registrar-se utilitzant un sistema d\'intercanvi apropiat (p.ex. intercanvis DAFNE \"CHO\" o les \"Unitats de pa\" europees). + AndroidAPS fa servir un model dinàmic per estimar com \"decauen\" els carbohidrats i calcular els COB. + Si els valors de glucèmia estan fora dels valors acceptats (massa alts o massa baixos) la calculadora de bolus es pot fer servir per obtenir suggeriments de carbohidrats o correccions amb insulina. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-to-carb-ratio-ic-g-u + e-carbs + Per a què poden ser utilitzats els e-carbs (carbohidrats estesos)? + Per programar carbs del futur, possiblement distribuïts durant un interval de temps (similar a un bolus estès distribuint insulina durant un interval). + Per registrar carbohidrats d\'esport \"lliures\" que volgueu ocultar a AndroidAPS. + els e-carbs (distribuïts en el futur) poden ajudar AndroidAPS a gestionar àpats rics en greix/proteïnes. + Per registrar els carbohidrats de rescat que s\'utilitzen per tractar hipoglucèmies. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html + Monitorització a distància + Com podeu monitoritzar AndroidAPS (per exemple per la vostra filla) a distància? + Les aplicacions NS Client i Nightscout, així com la web Nightscout us permeten fer un seguiment d\'AndroidAPS a distància. + Altres aplicacions (p.ex. Dexcom follow, xDrip en mode seguiment) us permeten monitoritzar alguns paràmetres (p.ex. glucèmia/valors sensor) de forma remota, però fan servir algoritmes diferents, per tant poden tenir valors d\'IOB o COB inexactes. + Per seguir AndroidAPS a distància, ambdos dispositius han de tenir accés a internet (p.ex. via Wi-Fi o dades de la xarxa mòbil). + L\'NS Client utilitzat com a seguidor remot, permet tant monitoritzar AndroidAPS com controlar-lo totalment. + https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html + Factor de Sensibilitat a la Insulina (ISF) + Augmentar o disminuir l\'ISF no afecta la quantitat d\'insulina a lliurar quan els valors de glucèmia estan per sota de l\'objectiu. + Cal introduir l\'ISF a la configuració d\'AndroidAPS. + Modificar el valor d\'ISF al perfil és suficient per aplicar el canvi. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u + https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html + Podeu fer servir més d\'un valor per la relació I:C al vostre perfil. + Si modifiqueu l\'ISF al vostre perfil haureu de modificar també sempre el vostre ràtio I:C. + Ràtio Insulina:Carbohidrats (I:C ràtio) + Ràtios I:C elevades fan que es lliuri menys insulina per una quantitat de carbohidrats determinada. + Ràtios I:C baixes fan que es lliuri menys insulina per una quantitat de carbohidrats determinada. + Si teniu 0 COB, modificar la ràtio I: C farà que es lliuri una quantitat d\'insulina diferent per corregir un valor de glucèmia determinat. + La ràtio I:C serà diferent si compteu una unitat de carbohidrats com 10g o 12g. + Significat d\'I:C: Quantes unitats d\'hidrats de carboni estan cobertes amb 1U d\'insulina. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u + diff --git a/app/src/main/res/values-cs-rCZ/strings.xml b/app/src/main/res/values-cs-rCZ/strings.xml index b1acfd9974..d1dc1b6dd8 100644 --- a/app/src/main/res/values-cs-rCZ/strings.xml +++ b/app/src/main/res/values-cs-rCZ/strings.xml @@ -893,4 +893,8 @@ Chyba v hodnotách cílové gl. Chyba v hodnotách inz. citlivosti Spustit %s? + Neplatný profil %1$s nebyl přijat z NS + Zobrazit + Chyby + Zpomalit odesílání diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml index 4aebbcbaaf..533463a4d7 100644 --- a/app/src/main/res/values-de-rDE/strings.xml +++ b/app/src/main/res/values-de-rDE/strings.xml @@ -887,4 +887,5 @@ Unerwartetes Verhalten.
Fehler in den Basalwerten Fehler in den Zielwerten Fehler in ISF-Werten + Hochladen verlangsamen diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index a10bd7cb54..a939f23e58 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -45,14 +45,14 @@ Control remoto de AndroidAPS mediante comandos SMS. Insulina: Carbohidratos: - IOB (Insulina Activa): - IOB (Insulina Activa): + IOB: + IOB: IOB total: Actividad total IOB: Dur: Relación: Ins: - IOB (Insulina Activa): + IOB: IOB Total: BG OT @@ -402,8 +402,8 @@ Sensor Insulina Batería de la bomba - edad: - nivel: + Edad: + Nivel: Opciones alarma Crear notificaciones de alarmas NS Crear notificaciones de avisos de NS @@ -452,7 +452,7 @@ Cambio de tiempo Objetivo temporal por defecto duración comiendopronto - objectivo comiendopronto + objetivo ComiendoPronto duración actividad objetivo actividad Duración Hipo @@ -517,7 +517,6 @@ Habilitar SMB con COB Habilitar SMB cuando hay Carbohidratos Activo COB. Habilitar SMB con Objetivos Temporales - Habilitar SMB cuando hay un Objetivo Temporal (TT) activo (ComerPronto, Actividad) Habilitar SMB con Objetivo Temporal Alto Habilitar SMB cuando hay un objetivo temporal alto activo (ejercicio, superior a 100 mg/dl o 5.5 mmol/l) Insulina @@ -547,7 +546,6 @@ Actualice su aplicación Dexcom a una versión compatible La aplicación Dexcom no está instalada. Inicio OT Actividad - Inicio OT ComiendoPronto OT No administrar Bolo, solo anotar Categoría @@ -559,7 +557,7 @@ Sensibilidad Desviaciones Carbohidratos activos COB - Insulina activa IOB + Insulina activa Basales Ninguna acción seleccionada, nada sucederá Inicio OT Hipo @@ -743,7 +741,7 @@ Limpieza iniciada ¿Desea reiniciar el objetivo? Puedes perder tu progreso. Seleccione las unidades en las que desea visualizar los valores - DIA (Duración Insulina Activa) + DIA IC ISF TARG @@ -844,6 +842,7 @@ Utilice un recordatorio para empezar a comer más tarde en lugar del resultado del asistente durante la glicemia alta (\"pre-bolo\") ¡Hora de comer!\nEjecutar el asistente de bolo y cálcular de nuevo. Hora de comer + Recordatorio de bolo ¡Carga de registros de errores desactivada! Gráfico Menú gráfico @@ -882,4 +881,5 @@ Hay otro bolo en cola. Inténtalo de nuevo más tarde. Cálculo en curso Error en valores IC + Ralentizar subidas diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml index 27600d2205..0a31a3d8e5 100644 --- a/app/src/main/res/values-fr-rFR/strings.xml +++ b/app/src/main/res/values-fr-rFR/strings.xml @@ -892,4 +892,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Erreur dans les valeurs de basal Erreur dans les valeurs cibles Erreur dans les valeurs de SI + Exécuter %s? + Profil %1$s non valide, refusé par NS + Vue + Erreurs diff --git a/app/src/main/res/values-hu-rHU/exam.xml b/app/src/main/res/values-hu-rHU/exam.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/app/src/main/res/values-hu-rHU/exam.xml @@ -0,0 +1,2 @@ + + diff --git a/app/src/main/res/values-hu-rHU/objectives.xml b/app/src/main/res/values-hu-rHU/objectives.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/app/src/main/res/values-hu-rHU/objectives.xml @@ -0,0 +1,2 @@ + + diff --git a/app/src/main/res/values-hu-rHU/strings.xml b/app/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..718d414505 --- /dev/null +++ b/app/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml index 508a8f6256..15c6082fd3 100644 --- a/app/src/main/res/values-it-rIT/strings.xml +++ b/app/src/main/res/values-it-rIT/strings.xml @@ -678,6 +678,7 @@ Ripristina valori predefiniti Malfunzionamento NSClient. Considera il riavvio di NS e NSClient. Offset + Ricorda di fare il bolo Modalità APS preferita Totale Calc @@ -844,6 +845,11 @@ Usa un promemoria per iniziare a mangiare invece del risultato del calcolatore durante la glicemia alta (\"pre-bolo\") Tempo di mangiare!\nEsegui il calcolatore e fai di nuovi i calcoli. Tempo di mangiare + Promemoria bolo + Abilita promemoria bolo + Usa promemoria bolo con calcolatore + (\"post-bolo\") + Tempo di fare un bolo!\nEsegui il calcolatore e fai di nuovi i calcoli. Caricamento log dei crash disabilitato! Grafico Menu grafico @@ -886,4 +892,9 @@ Errore nei valori della basale Errore nei valori del target Errore nei valori ISF + Eseguire %s? + Profilo %1$s non valido - non accettato da NS + Vista + Errori + Rallenta caricamenti diff --git a/app/src/main/res/values-iw-rIL/strings.xml b/app/src/main/res/values-iw-rIL/strings.xml index fdc076afae..9dba64ee69 100644 --- a/app/src/main/res/values-iw-rIL/strings.xml +++ b/app/src/main/res/values-iw-rIL/strings.xml @@ -86,22 +86,22 @@ איזה אלגוריתם של APS יבצע התאמות טיפול? כללי מס\' תוספים כלליים שעשויים להיות יעילים. - אילו הגבלות פעילות? + אילו מגבלות פעילות? מגבלות לולאה השתמשו באפשרות זו כדי להפעיל את לולאת AndroidAPS. אלגוריתם APS - הגבלות לאחר עיבוד + מגבלות לאחר עיבוד מינון בזאלי זמני שהוגדר במשאבה לא נבחרה או סופקה תוצאה ע\"י APS בטיחות התוסף אינו זמין - הפרת הגבלות + הפרת מגבלות שגיאה במתן בולוס אשר בזאלי זמני חדש: טיפול מחשבון - ההגבלה הוחלה! + מגבלה הוחלה! בולוס: אינסולין בזאלי אינסולין בזאלי: @@ -247,7 +247,7 @@ Wear שלח מחדש את כל הנתונים פתיחת הגדרות Wear - ערכים בזאליים: + מינונים בזאליים: ערך הבסיס מתחת למינימום. פרופיל אינו מוגדר! ערכי סוכר בדם: ערכי סוכר אחרונים: @@ -892,4 +892,9 @@ שגיאה בערכי המינון הבזאלי שגיאה בערכי המטרה שגיאה בערכי יחס התיקון + להפעיל %s? + הפרופיל הבלתי חוקי %1$s מ-Nightscout לא מאושר + תצוגה + שגיאות + האט העלאות diff --git a/app/src/main/res/values-nl-rNL/strings.xml b/app/src/main/res/values-nl-rNL/strings.xml index 7b3de291e1..ee604c3bf2 100644 --- a/app/src/main/res/values-nl-rNL/strings.xml +++ b/app/src/main/res/values-nl-rNL/strings.xml @@ -432,7 +432,7 @@ Afbreken Niet alle profielen zijn geladen! Waarden niet opgeslagen! - Schakel lokaal data delen naar andere apps (zoals xDrip) in. Schakel dit niet in als je NSClient of meer dan één installatie van AAPS op je telefoon hebt staan! + Schakel lokaal data delen met andere apps (zoals xDrip) in. Schakel dit niet in als er meer dan één installatie van AAPS of NSClient zijn geinstalleerd! Activeer locaal delen. OpenAPS SMB Activeer UAM @@ -678,6 +678,7 @@ Terug naar standaardinstellingen NSClient werkt niet goed. Overweg een herstart van NS en NSClient. Tijdverschuiving + Herinner later te bolussen Voorkeur APS-modus Totaal Calc @@ -844,6 +845,11 @@ Gebruik bij een hoge bloedglucose niet het resultaat van de wizard, maar een herinnering om later met eten te beginnen (\"pre-bolus\") Tijd om te eten!\nVoer de boluswizard opnieuw uit. Tijd om te eten + Bolus herinnering + Bolus herinnering inschakelen + Gebruik herinnering om later te bolussen met de wizard + (\"post-bolus\") + Tijd om te bolussen!\nVoer de boluswizard uit en maak de berekening opnieuw. Upload van crashrapporten is uitgeschakeld! Grafiek Grafiek menu diff --git a/app/src/main/res/values-no-rNO/strings.xml b/app/src/main/res/values-no-rNO/strings.xml index 9631c5f0c7..bf9f84aea9 100644 --- a/app/src/main/res/values-no-rNO/strings.xml +++ b/app/src/main/res/values-no-rNO/strings.xml @@ -12,7 +12,6 @@ Nullstill databasene Vil du virkelig nullstille databasene? Avslutt - Bruk alltid absolutte verdier for basal Det ser ikke ut som mobilen støtter registrering av apper som unntas fra batterioptimalisering - du kan oppleve ytelsesproblemer. Knapper for rask tilgang til ofte brukte funksjoner Brukt for innstilling av aktive plugin @@ -678,6 +677,7 @@ Gjenopprett standardinnstillinger NSClient feil. Vurder omstart av NS og NSClient. Tidsforskyvning + Påminnelse til å gi bolus senere Foretrukket APS modus Total Kalkyle @@ -844,6 +844,11 @@ Bruk en påminnelse om å spise senere enn kalkulator resultatet fra wizard ved høyt blodsukker (\"pre-bolus\") Nå må du spise!\Bruk bolus veiviseren og beregn på nytt. Nå må du spise + Bolus påminnelse + Aktiver bolus påminnelse + Bruk påminnelse for å sette bolus dosen senere med veiviseren + («post bolus») + Tid for bolus!\nStart bolus-veiviser og gjør beregning på nytt. Opplast av krasj logger er deaktivert! Graf Diagram meny @@ -886,4 +891,12 @@ Feil i basalverdiene Feil i BS mål verdiene Feil i IF verdien + Kjør %s? + Ugyldig profil %1$s ikke akseptert fra NS + Visning + Feil + Reduser opplastingshastighet + BS data status + Rekalkulerte siste data + BS for nær:\n%1$s\n%2$s diff --git a/app/src/main/res/values-pl-rPL/strings.xml b/app/src/main/res/values-pl-rPL/strings.xml index 6126d8012b..57ca6fe2a0 100644 --- a/app/src/main/res/values-pl-rPL/strings.xml +++ b/app/src/main/res/values-pl-rPL/strings.xml @@ -12,7 +12,6 @@ Zresetuj bazy danych Na pewno chcesz zresetować bazy danych? Wyjście - Zawsze używaj wartości bezwzględnych bazy To urządzenie nie obsługuje białej listy optymalizacji baterii - mogą wystąpić problemy z wydajnością. Niektóre przyciski umożliwiające szybki dostęp do typowych funkcji Konfiguracja aktywnych modułów systemu @@ -57,15 +56,15 @@ BG TT Węglow - Korekta - Bolus IOB + Poprawka + IOB z bolusów Uruchom teraz POMPA WIRTUALNA Ostatnie działanie Parametry wejściowe Stan glukozy Obecna tymczasowa - IOB data + Dane IOB Profil Dane posiłku Rezultat @@ -117,7 +116,7 @@ Dostępna nowa sugestia Sugestia węglowodanów Niewspierana wersja Nightscout - Bazowa IOB + IOB z bazy Ograniczenia bolusa wprowadzone Ograniczenie stosowania węglowodanów Inne @@ -678,6 +677,7 @@ Przywróć ustawienia domyślne Usterka NSClient. Spróbuj zrestartować NS i NSClient. Przesunięcie czasu + Przypomnij o bolusie Preferowany tryb APS Razem Kalk @@ -716,6 +716,7 @@ Kontroler wersji stara wersja bardzo stara wersja + Aplikacja wygasła Nowa wersja dostępna co najmniej %1$d dni! Powrót do LGS (zawieszania podawania bazy przy niskim poziomie) po %2$d dniach, pętla zostanie wyłączona po %3$d dniach 2 h Apka Dexcom (spatchowana) @@ -843,6 +844,10 @@ Użyj przypomnienia, aby rozpocząć jedzenie później podczas wysokiej glikemii (\"pre-bolus\") Czas jeść!\nUruchom kreatora bolusa i zrób obliczenia ponownie. Czas na jedzenie + Przypomnienie bolusa + Włącz przypomnienie bolusa + Użyj przypomnienia o potrzebie obliczenia i podania bolusa kalkulatorem (\"opóźniony bolus\") + Czas na bolus!\nUruchom Kalkulator bolusa aby ponownie wykonać obliczenia. Przesyłanie dzienników awarii jest wyłączone! Wykres Menu wykresu @@ -855,6 +860,8 @@ Adres e-mail Ustawienia prywatności Możesz opcjonalnie podać adres e-mail, jeśli chcesz otrzymywać powiadomienia o awariach aplikacji. To nie jest usługa zautomatyzowana. W niebezpiecznych sytuacjach deweloperzy skontaktują się z Tobą. + Pełna synchronizacja + Wykonać pełną synchronizację? Może ona potrwać wiele godzin i aż do jej zakończenia nie zobaczysz nowych danych w NS. Wypełnianie Synchronizacja Profile, bolusy, węglowodany, tymczasowe bazy są przesyłane do NS @@ -878,4 +885,17 @@ Przekroczono limit czasu oczekiwania na zakończenie poprzedniej komunikacji z pompą W kolejce oczekuje inny bolus. Spróbuj ponownie później. Trwa obliczanie + Brak nazwy profilu + Błąd w przelicznikach IC + Błąd w wartościach bazy + Błąd w wartościach docelowych + Błąd w wartościach ISF + Uruchomić %s? + Błędny profil %1$s nie został zaakceptowany z NS + Podgląd + Błędy + Wysyłaj dane wolniej + Stan danych glikemii + Użyto przeliczonych wartości + Zbyt bliskie pomiary glikemii:\n%1$s\n%2$s diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml index 1cc7cc1048..0e637b38f1 100644 --- a/app/src/main/res/values-ro-rRO/strings.xml +++ b/app/src/main/res/values-ro-rRO/strings.xml @@ -678,6 +678,7 @@ Resetare la setările implicite Funcționare incorectă a NSClient. Aveți în vedere un restart al NS și al NSClient. Decalaj + Amintește-mi sa fac bolus mai târziu Modul APS preferat Total Calc @@ -844,6 +845,11 @@ Folosește o alarma de reamintire pentru a începe sa mănânci mai târziu în loc de alerta de la calculatorul de bolus din timpul hiperglicemiei (\"pre-bolus\") Timpul sa mănânci!\nRuleaza Calculatorul de Bolus pentru a face calculele din nou. Timpul sa mănânci + Memento bolus + Activează memento bolus + Folosește memento pentru a bolusa mai târziu cu asistentul + (\"post-bolus\") + Timpul sa faci bolus!\nRuleaza Calculatorul de Bolus pentru a face calculele din nou. Încărcarea jurnalelor de erori este dezactivata! Grafic Meniu diagramă @@ -886,4 +892,9 @@ Eroare in valorile ratei bazale Eroare in valorile tinta Eroare in valorile ISF + Executați %s? + Profilul invalid din NS %1$s nu este acceptat + Vizualizare + Erori + Încarcă mai lent diff --git a/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/values-ru-rRU/strings.xml index ae429b6f3c..da7505a0c9 100644 --- a/app/src/main/res/values-ru-rRU/strings.xml +++ b/app/src/main/res/values-ru-rRU/strings.xml @@ -893,4 +893,9 @@ Context | Edit Context
Ошибка в величине базала Ошибка в целевых значениях Ошибка в значении фактора чувствительности к инсулину ISF + Запустить %s? + Неверный профиль %1$s не принят из NS + Вид + Ошибки + Замедлить выгрузку diff --git a/app/src/main/res/values-sk-rSK/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml index 2ab79361b1..88321f70a5 100644 --- a/app/src/main/res/values-sk-rSK/strings.xml +++ b/app/src/main/res/values-sk-rSK/strings.xml @@ -892,4 +892,9 @@ Chyba v hodnotách bazálu Chyba v cieľových hodnotách Chyba v hodnotách citlivosti + Spustiť %s? + Neplatný profil %1$s nebol akceptovaný z NS + Zobraziť + Chyby + Spomaliť nahrávanie diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml index 37a8f65935..f6ea5725a7 100644 --- a/app/src/main/res/values-sv-rSE/strings.xml +++ b/app/src/main/res/values-sv-rSE/strings.xml @@ -679,6 +679,7 @@ Eversense-appen.
Återställ standardinställningar Fel på NSClient. Överväg att starta om NSClient och Nightscout-webbplatsen. KH-tid + Påminn om bolus senare Föredraget APS-läge Total Kalkyl @@ -845,6 +846,11 @@ Eversense-appen.
Få en påminnelse om att börja äta senare (istället för kalkylatorns resultat) om du ligger högt i BG Dags att äta!\nKör bolusguiden igen för ny beräkning. Dags att äta + Boluspåminnelse + Aktivera boluspåminnelse + Använd påminnelse för att ge bolus senare + (\"post-bolus\") + Dags för bolus!\nKör Bolusguiden och gör beräkningar igen. Uppladdning av kraschloggar inaktiverad! Graf Diagrammeny @@ -882,4 +888,14 @@ Eversense-appen.
Föregående pumpkommunikation har inte bekräftats/avslutats i tid Det finns en annan bolus i kö. Försök igen senare. Beräkning pågår + Profilnamn saknas + Fel i KH-kvoter + Fel i basaldoser + Fel i målvärden + Fel i korrektionskvoter + Kör %s? + Ogiltig profil %1$s från NS accepteras inte + Visa + Fel + Långsamma uppladdningar diff --git a/app/src/main/res/values-tr-rTR/exam.xml b/app/src/main/res/values-tr-rTR/exam.xml index 3ea04e700d..e257adfd90 100644 --- a/app/src/main/res/values-tr-rTR/exam.xml +++ b/app/src/main/res/values-tr-rTR/exam.xml @@ -1,2 +1,215 @@ - + + İES (DIA) hakkında doğru olan nedir? + İnsülin Etki Süresi (İES) + Profilinizde İES değerini ayarlamalısınız. + İzin verilen minimum değer 5 saattir. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin + AndroidAPS\'den önce pompanızda kullandığınız İES değerinin doğru olduğundan eminseniz, döngüye başladığınızda bunu değiştirmenize gerek yoktur. + İES için uygun değeri kendiniz belirlemelisiniz. + Hipo Geçici-Hedef + Hipo geçici hedef belirlemenin birincil nedeni nedir? + Yanlış bazal oranı ayarlarından kaynaklanan hipoları düzeltmek için. + Hipo tedavisinde kullanılan hızlı etkili karbonhidratların neden olduğu kan şekeri artışında, AndroidAPS\'in aşırı düzeltme yapmasını önlemek. + Egzersizin bir sonucu olarak tetiklenen hipoyu düzeltmek için. + Halihazırda %0 geçici bazal oran çalışıyorsa, kan şekerinin düşmesini önlemek için. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html + Hangi profil çevrimdışı kullanılabilir ve yapılandırılabilir? + Konu: Çevrimdışı profiller + NS Profili kullanılabilir ancak yapılandırılamaz. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile + AndroidAPS\'de Pompa bağlantısını kesme nedenleri + Pompa bağlantısı kesilirken ne yapılmalı? + Pompanın fiziksel olarak bağlantısı kesilirse insülin iletilmeyeceğinden bu gereksizdir. + AndroidAPS\'nin, pompa fiziksel olarak bağlı değilken iletilmeyen insülini hesaba katmasını önler. + Pompa bağlı kalırsa insülin iletimini durdurmaz. + AndroidAPS\'yi açık döngü moduna gönderir. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings + AndroidAPS Ayarları + AndroidAPS Ayarları + Ayarlarınızı yedeklemek için en sağlıklı yöntemler nelerdir? + Ayarlarınızı not etmeniz şartıyla ayarları dışa aktarmanıza gerek yoktur. + Bir görevi tamamlamayı bitirdikten sonra ayarlarınızı dışa aktarın. + Ayarlarınızdan herhangi birini değiştirdikten sonra ayarlarınızı dışa aktarın. + İlk kurulumunuzu tamamladıktan ve Tercihlerinizi belirledikten sonra ayarlarınızı dışa aktarın. + Bakım menüsünü kullanarak ayarlarınızı yerel olarak dışa aktarın. + Ayar dosyanız, telefonunuzdaki Dahili Depolama/AAPS/tercihler klasöründe bulunur. + Tercihler dosyanızı telefonunuzun dışındaki güvenli bir konuma kopyalayın (ör. bulut sürücüsü kullanarak, bilgisayara kablo bağlayarak, e-posta vb.) + Telefonunuz hasar görürse veya kaybolursa, ayarlarınızı yedeklemeden uzaktan kurtarmanın kolay yolları vardır. + https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me + Gürültülü CGM Okumaları + CGM (dexcom, miaomaio vs.) verileri gürültülü ise ne yapılmalı? + Hiçbir şey yapmayın - AndroidAPS bununla ilgilenecektir. + Olası aşırı veya düşük dozdan kaçınmak için kapalı döngüyü devre dışı bırakın. + Sürekli gürültülü veya hatalı sensörleri değiştirin. + CGM uygulamanızın sorunsuz veriler sağladığını doğrulayın. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data + Egzersiz ve Profiller + Aerobik egzersiz yaparken sistemin size en iyi şekilde yardımcı olması için profilleri nasıl kullanırsınız? + %100\'ün altında bir profil geçişi yapın. + %100\'den fazla bir profil geçişi yapın. + Profili %100 olarak bırakın. + Döngüyü askıya alın. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target + Egzersiz ve Geçici Hedefler + Aerobik egzersiz yaparken sistemin size en iyi şekilde yardımcı olması için geçici hedefleri nasıl kullanırsınız? + Egzersize başlamadan önce uygun bir zamandan başlayarak aktivite kan şekeri hedefi belirleyin. + Egzersizi bitirdikten sonra bir aktivite kan şekeri hedefi belirleyin. + Kan şekeri hedefinizi değiştirmeden bırakın. + Kan şekeri, hipo geçici hedefinizin altına düşene kadar bekleyin ve ardından 15 g hızlı etkili karbonhidrat yiyin. + https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target + Döngüyü Devre Dışı bırakma/Askıya alma + Döngü devre dışı bırakıldığında/askıya alındığında insülin alır mıyım? + Evet, bazal insülin verilmeye devam ediyor. + Hayır, insülin iletimi durdurulur. + Bazal, ISF ve I:C Testi + Bu değerler ne zaman doğrulanmalıdır? + Döngüye başlamadan önce. + Sık sık yüksek veya düşük kan şekeri yaşarken. + Haftada en az bir kez. + Bir kez ayarlanıp onaylandıktan sonra bu değerler zaman içinde değişmemelidir. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings + Önkoşullar + AndroidAPS\'i kurmak ve kullanmak için ne gereklidir? + Doğrulanmış profil bilgileri (Basal, IC, ISF, DIA). + Android Studio\'nun kurulu ve yapılandırılmış olduğu bir bilgisayar. + Desteklenen bir telefon. + Kapalı devre çalıştırmayı planlıyorsanız uyumlu bir insülin pompası. + Tüm verilerin kaydını tutmak ve ayarları gözden geçirmek için Nightscout sitesi + Tidepool hesabı. + Google hesabı. + Github hesabı. + Programlama veya kod düzenleme konusunda deneyim. + MiniMed 670G pompa. + https://androidaps.readthedocs.io/en/latest/EN/Module/module.html + Akıllı saat. + Desteklenen bir CGM. + Önkoşullar + AndroidAPS\'yi kurmak ve kullanmak için ne gereklidir? + Profil oluşturmak için doğrulanmış bilgiler (ISF, I:C oranı, bazal oranlar, DIA vb.). + Uyumlu bir Android cihaz (ör. cep telefonu, Android saat veya tablet). + AndroidAPS\'in kapalı döngüde çalışması için internet bağlantısı gerekir. + Telefonda/cihazda kan şekeri değerlerini almak için desteklenen bir CGM ve uygulama. + https://androidaps.readthedocs.io/en/latest/EN/Module/module.html + AndroidAPS\'i güncelleme + Tüm doğru cevapları kontrol edin. + Git\'in bilgisayarınızda kurulu ve yapılandırılmış olması gerekir. + AndroidAPS\'nin güncellenmiş sürümleri yayınlandığında, önceki sürümler belirli bir süre sonra uzaktan sınırlandırılabilir. + Anahtar deponuzun konumunu kaydetmeli ve not etmeli ve önceki yüklemenizde olduğu gibi güncellemeler için aynı imzalama anahtarını kullanmalısınız. + Sistem iyi çalışıyorsa asla güncelleme yapmayın. + Apk oluşturmakta zorluk çekiyorsanız, bir arkadaşınız tarafından oluşturulmuş bir apk yükleyebilirsiniz. + https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch + Sorun giderme + AndroidAPS ile ilgili nereden yardım alabilirsiniz? + AndroidAPS Kullanıcıları Facebook grubundan tavsiye isteyebilirsiniz. + AndroidAPS belgelerini okumalısınız (ve yeniden okumalısınız). + AndroidAPS Gitter odasından tavsiye isteyebilir ve teknik problemleri veya sorunları not edebilirsiniz. + Diyabet kliniğinize/endokrinoloğunuza sormalısınız. + https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting + https://www.facebook.com/groups/AndroidAPSUsers/ + https://gitter.im/MilosKozak/AndroidAPS + İnsülin Eklentileri + Ultra-Hızlı Oref eklentisi ile hangi insülini kullanmalısınız? + Fiasp® + NovoRapid®/Novolog® + Humalog® + Actrapid®/Humulin R®/ insan insülini. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin + Duyarlılık Eklentileri + Tüm doğru cevapları kontrol edin. + Duyarlılık eklentileri, AndroidAPS\'nin insülin duyarlılığındaki geçici veya kısa süreli değişiklikleri (örneğin hormonal değişiklikler veya infüzyon bölgesinde emilim sorunları) ayarlamasına olanak tanır. + Duyarlılık eklentileri, kullanıcıya profili düzenlemek için kullanılabilecek bazal oranlar, I:C oranları ve ISF için önerilen değişiklikleri sağlar. + Bir kanül değişikliğinin kaydedilmesi, Otoduyarlılık oranını %100\'e sıfırlayacaktır. + Eklenti seçeneklerinden bazıları, kullanıcı tarafından ayarlanabilen yapılandırılabilir zaman aralıklarına sahiptir. + https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html + Karbonhidrat Giriş Hataları + Yanlış bir karbonhidrat girişi yaptıysanız ne yapmalısınız? + Tedavilerdeki yanlış girişi siler ve doğru karbonhidrat değerini girerim. + İnfüzyon seti başlatma menüsünü kullanarak insülin gönderme. + Hiçbir şey yapmayın – AndroidAPS uygun ayarlamaları yapacaktır. + Genel Bakış\'ta İnsülin (bolus) düğmesini kullanarak insülin gönderme. + İnsülin gönderme/giriş hataları + Tıkanma, başarısız bir kanül veya duştan sonra pompayı tekrar takmayı unutma v.s. nedeniyle, pompa geçmişinin önerdiğinden daha az insülin aldıysanız ne yapmalısınız? + Pompa geçmişinden çıkarmak için insülin verilerini Nightscout Careportal\'dan silerim. + AndroidAPS ve pompa geçmişindeki değerleri karşılaştırın (pompa bunu destekliyorsa). + Şırınga/kalem veya başlatma kullanarak hesaplanan \"eksik\" insülininizi bolus olarak karşılayın. + Hiçbir şey yapmayın ve AndroidAPS\'in ortaya çıkabilecek yüksek kan şekeri seviyesini düzeltmesine müsade edin. + Aktif İnsülin (IOB) + Tüm doğru cevapları kontrol edin. + IOB değeri, verilen geçici bazallardan etkilenir. + Kan şekeriniz hedefin altına düştüğünde yüksek geçici bazal verilmeyecektir. + Egzersiz yapmadığınız halde uzun bir dönem için negatif IOB, profilinizin çok güçlü olduğunu ve ayarlarınızda daha az insüline ihtiyaç duyulduğunu gösterir. + Önemli bir süre için pozitif IOB, insülin direncini veya habersiz öğünleri gösterir. + Karbonhidrat girişi ve boluslar + Tüketilen karbonhidratları tahmin etmek ve kaydetmek için sadece gram kullanılmalıdır. + Tüketilen karbonhidratlar uygun bir değişim sistemi kullanılarak kaydedilebilir (örn. DAFNE \"CHO\" değişimleri veya Avrupa \"Ekmek Birimleri\"). + AndroidAPS, karbonhidrat \"çözünmesini\" tahmin etmek ve COB\'ı hesaplamak için dinamik bir model kullanır. + Kan şekeri seviyeleri kabul edilebilir değerlerin dışındaysa (çok düşük veya çok yüksek), karbonhidrat veya insülin düzeltmeleri için öneriler sağlamak için bolus hesaplayıcı kullanılabilir. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-to-carb-ratio-ic-g-u + yayma-karbonhidratlar + Y-karbonhidratları (yayma karbonhidratlar) ne için kullanabilirsiniz? + Gelecekte karbonhidratları planlamak için, muhtemelen bir aralığa dağıtılır (bir aralıkta insülin dağıtan yayma bolusa benzer). + AndroidAPS\'den gizlemek istediğiniz \'ücretsiz\' egzersiz karbonhidratlarını kaydetmek için. + y-karbonhidratlar (gelecekte dağıtılacak) AndroidAPS\'nin yüksek yağ/proteinli öğünlerle uğraşmasına yardımcı olabilir. + Düşük kan şekerini tedavi etmede kullandığınız kurtarma karbonhidratlarını kaydetmek için. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html + Uzaktan İzleme + AndroidAPS\'i (örneğin çocuğunuz için) uzaktan nasıl izleyebilirsiniz? + NS Client uygulaması, Nightscout uygulaması ve Nightscout web sayfasının tümü, AndroidAPS\'i uzaktan takip etmenize olanak tanır. + Diğer uygulamalar (ör. Dexcom takip, xDrip) bazı parametreleri (ör. kan şekeri/sensör değerleri) uzaktan takip etmenize izin verir, ancak farklı algoritma kullanımı, hatalı IOB veya COB değerlerine sebep olabilir. + AndroidAPS\'yi uzaktan takip etmek için her iki cihazın da internet erişimine sahip olması gerekir (ör. Wi-Fi veya mobil/hücresel ağ verileri aracılığıyla). + Uzak takipçi olarak kullanılan NS İstemcisi, AndroidAPS\'i hem izleyecek hem de tam kontrol sağlayacaktır. + https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html + İnsülin Duyarlılık Faktörü (ISF) + ISF değerlerini yükseltmek, belirli bir karbonhidrat miktarını karşılamak için daha fazla insülin verilmesine yol açacaktır. + ISF değerinin düşürülmesi, hedeflenen kan şekerinin üzerinde bir düzeltme için daha fazla insülin verilmesine yol açar. + Kan şekeri seviyeleri hedefin altında olduğunda ISF\'yi yükseltmenin veya düşürmenin insülin iletimi üzerinde hiçbir etkisi yoktur. + ISF, AndroidAPS Tercihlerinize girilmelidir. + Profilinizdeki ISF değerini değiştirmeniz değişikliği uygulamak için yeterlidir. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u + https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html + Profilinizde I:C oranı için birden fazla değer kullanabilirsiniz. + Profilinizde ISF\'nizi değiştirirseniz, her zaman I:C oranınızı da değiştirmelisiniz. + İnsülin/Karbonhidrat Oranı (I:C oranı) + Daha yüksek I:C oranları, belirli bir miktarda karbonhidrat için daha az insülin verilmesine yol açar. + Daha düşük I:C oranları, belirli bir miktarda karbonhidrat için daha az insülin verilmesine yol açar. + 0 COB\'niz varsa, IC oranını değiştirmek, belirli bir KŞ değerini düzeltmek için farklı insülin miktarına sebep olur. + Ekmek (değişim) birimini 10g veya 12g olarak sayarsanız IC farklı olacaktır. + IC anlamı şudur: 1Ü insülin kaç ekmek birimi (değişim) kapsar. + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u + Profil Değiştirme + %90\'lık bir profil değişimi belirlediğinizde hangi yanıtlar doğrudur? + Bazal oranlar %10 daha düşük olacaktır. + ISF %10 daha yüksek olacaktır. + I:C oranının değeri %10 daha düşük bir sayı olacaktır. + ISF ve I:C oranları değişmeyecektir. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch + Profil Değiştirme + %120 profil değişimi belirlediğinizde hangi yanıtlar doğrudur? + Hedef kan şekeri %20 daha yüksek olacaktır. + Bazal oranlar %20 daha yüksek olacaktır. + Hedef kan şekeri değişmeyecektir. + ISF %20 daha yüksek olacaktır. + Profil Değiştirme + Normalden 2 saat önce kalkarsanız, zaman değişikliğini AndroidAPS\'e nasıl bildirmelisiniz? + 2 saatlik bir zaman kayması ile bir profil değişikliği başlatın + -2saatlik bir zaman kayması ile bir profil değişikliği başlatın + Yakında yemek geçici hedefi belirleyin. + %100\'den fazla bir profil değişikliği yapın. + https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift + Profillerdeki değişiklikler + Profillerde bazal oranlar, ISF, I:C oranları vb. ayarlanmalıdır. + Nightscout Profilinizdeki değişiklikleri etkinleştirmek, AndroidAPS kurulu telefonunuzun internete bağlı olmasını gerektirir. + Değerleri değiştirmek için profi düzenlemek, yapılan değişiklikleri yürürlüğe koymak için yeterlidir. + Değişen koşullara (ör. hormonal değişiklikler, vardiyalı çalışma, hafta içi/hafta sonu yaşam tarzı) uyum sağlamak için birden fazla profil ayarlanabilir ve seçilebilir. + https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy + Bazal oranlarla ilgili yardım + Bazal oranlar vb. ile ilgili yardım için nereye gitmeli? + Diyabet ekibiniz + Google + Facebook + Diğer ilaçlarla etkileşim. Lütfen aşağıdaki beyanı okuyun ve ardından kabul etmek için kutuyu işaretleyin. + AndroidAPS, kan şekerini yükseltmek için bazal oranları düşürür veya insülin iletimini askıya alır. SGLT2 inhibitörleri (gliflozinler) sınıfındaki ilaçlar kan şekerindeki artışları önleyebilir ve bu nedenle DKA\'ya (Diyabetik ketoasidoz) yol açan tehlikeli bir insülin eksikliğine yol açabilir. +\nYaygın marka isimleri şunlardır: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nAndroidAPS kullanırken bu tür ilaçları almayacağıma veya bu tür ilaçları kullanmadan önce döngüyü devre dışı bırakacağıma söz veriyorum. + diff --git a/app/src/main/res/values-tr-rTR/objectives.xml b/app/src/main/res/values-tr-rTR/objectives.xml index 3ea04e700d..8ffcbd83a6 100644 --- a/app/src/main/res/values-tr-rTR/objectives.xml +++ b/app/src/main/res/values-tr-rTR/objectives.xml @@ -1,2 +1,55 @@ - + + Başlat + Doğrulayın + %1$d. Görev + Görev %1$d başlanmadı + Görev %1$d tamamlanmadı + Nightscout üzerinden izlemeyi ve görselleştirmeyi yapılandırın, bazalları ve oranlarını analiz edin + Nightscout\'ta KŞ\'nin bulunduğunu ve insülin verilerinin yüklenmekte olduğunu doğrulayın + Açık Döngü modu başlatılıyor + Birkaç gün boyunca Açık Döngü modunda çalıştırın ve birçok geçici bazalı el yordamı ile girin. Geçici ve varsayılan geçici hedefleri düzenleyin ve kullanın (örn. egzersiz ve hipo-tedaviyi desteklemek için) + Geçici bazal tavsiyeleri de dahil olmak üzere Açık Döngüyü anlamak + Bu deneyime dayanarak, max bazalın ne olması gerektiğine karar vermeli ve bunu pompa ve tercihlere koymalısınız + Kapalı Döngü, (LGS) Düşük Kan Şekerinde Duraklatma modunda başlatılıyor + Çok sayıda LGS (düşük KŞ) olmadan birkaç gün boyunca maksimum IOB = 0 (Aktif insülin) Kapalı Döngü\'de deneyin + Kapalı Döngü\'de ince ayarlar, maksimum (IOB) Aktif İnsülinin 0\'ın üzerine yükseltme ve yavaş yavaş KŞ hedeflerini aşağıya çekme + KŞ hedefini azaltmadan önce birkaç gün ve en az bir gece düşük KŞ (Hipo) alarmı olmadan deneyin + Gerekirse, bazal ve oranları ayarlayın ve sonra auto-sens\'i etkinleştirin + Bir hafta boyunca düzenli Karbonhidrad girdileri yaparak gün boyunca Kapalı Döngüyü çalıştırın + SMB (Super Micro Bolus) gibi gündüz kullanımı için ek özelliklerin etkinleştirilmesi + Otomasyonu etkinleştirme + (Super Micro Bolus) SMB\'lerın iyi çalışabilmesi için wiki\'yi okumalısınız ve maxIOB\'u yükseltmelisiniz! İyi bir başlangıç için maxIOB = ortalama yemek bolusu + 3 x max günlük bazaldır + Otomasyonun nasıl çalıştığına dair dokümanları okuyun. İlk basit kurallarınızı belirleyin. Eylem yerine AAPS\'in yalnızca bildirim göndermesine izin verin. Otomasyonun doğru zamanda tetiklendiğinden emin olduğunuzda, bildirimi gerçek eylemle değiştirin. (https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html) + KŞ NS\'ta mevcut + Pompa durumu NS mevcut + Manuel eylemler + Başarıldı: %1$s + AndroidAPS\'i nasıl kontrol edeceğinizi öğrenin + AndroidAPS\'de farklı eylemler gerçekleştirin + Profili 10 dakika boyunca %90 olarak ayarla (Ana sayfada profil adına uzun basın) + Duşu simüle edin. 1 saat boyunca pompanın bağlantısını kesin (Açık Döngü işaretine Uzun Basın) + ... ve aynı şekilde tekrar bağlanın + 10 dakika süreyle geçici hedef oluşturun (Mevcut hedefinize uzun basın) + Konfigürasyon oluşturucuda, Eylemler eklentisini etkinleştirin, görünür yapın ve içeriğini üst menüden görüntüleyin + Döngü eklentisinin içeriğini görüntüle + KŞ tablosuna uzun basarak ölçeği değiştirebilirsiniz + Giriş + Diğer sistemlerde en az 3 aylık kapalı döngü deneyiminiz varsa, hedefleri atlamak için bir kod almaya hak kazanabilirsiniz. Ayrıntılar için https://androidaps.readthedocs.io/en/latest/EN/Usage/Objectives.html#skip-objectives adresine bakın. + Kod kabul edildi + Geçersiz kod + Bilginizi sınayın + Sorulara çalışın. Her soru için size dört olası cevap verilir. Birden fazla doğru cevap olabilir. Lütfen doğru olanların hepsini kontrol edin ve DOĞRULA\'yı seçin. + Yanıtlama devre dışı bırakıldı: %1$s + Yanlış Cevap! + Tamamlanmayan bir sonraki + Kod: %1$s + (tüm doğru cevapları kontrol edin) + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder + https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen + İnternete bağlı değil + Geri almada hata + Görev gereksinimleri karşılanmadı + diff --git a/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/values-tr-rTR/strings.xml index 3ceb963da9..f07dd6a72c 100644 --- a/app/src/main/res/values-tr-rTR/strings.xml +++ b/app/src/main/res/values-tr-rTR/strings.xml @@ -3,21 +3,24 @@ - Tedavilerin güvenlik ayarları + Tedavi güvenliği Max izin verilen bolus [U] Max izin verilen karbonhidrat [g] + %1$s Tercihler Tercihler NS\'tan tedavileri güncelle Veritabanlarını sıfırla Veritabanlarını gerçekten sıfırlamak istiyor musunuz? Çıkış Her zaman bazal mutlak değerleri kullan + Bu cihaz, program için pil optimizasyonunu desteklemiyor gibi görünüyor - performans sorunları yaşayabilirsiniz. Ortak özelliklere hızlıca erişmek için bazı düğmeler Aktif eklentileri yapılandırmak için kullanılan Eğitim programı Nightscout\'ta tanımlanan gıda ön ayarlarını gösterir Humalog ve NovoRapid / NovoLog için İnsülin Profili Fiasp için insülim Profili + Lyumjev için insülin ayarı İnsülin aktivitesinin zirvesini tanımlamanıza ve sadece ileri düzey kullanıcılar tarafından kullanılmasına izin verir Döngüyü tetikleyen uygulamayı etkinleştirin veya devre dışı bırakın. Nightscout ile verilerinizi senkronize eder @@ -25,13 +28,17 @@ İleri düzey kullanıcılar için en yeni algoritma En yaygın eylemler için Döngü ve düğmelerinizin geçerli durumunu görüntüler Döngünün şu anda ne yaptığını hızlıca gözden geçirerek sürekli bir bildirim gösterir + Çevrimdışı kullanılabilen bir profil tanımlayın. Diyabet tedavisi için günde birden fazla enjeksiyon yapan kişiler için pompa entegrasyonu Henüz herhangi bir sürücüye sahip olmayan pompalar için pompa entegrasyonu (Açık Döngü) Duyarlılık, Oref0 gibi aynı şekilde hesaplanır ancak geçmiş zaman çerçevesi belirtebilirsiniz. Minimal karbonhidrat emilimi, tercihlerden maksimum karbonhidrat emilim süresinden hesaplanır. + Duyarlılık, geçmişteki 8 veya 24 saatlik verilerden (hangisi daha hassas ise) hesaplanır. Karbonhidratlar (emilmemişse) tercihlerde belirtilen süreden sonra kesilir. Eklenti ayrıca UAM\'ı da (bildirilmemiş yemekler) hesaplar. Duyarlılık, sapmalardan ağırlıklı ortalama olarak hesaplanır. Daha yeni sapmalar daha ağırdır. Minimal karbonhidrat emilimi, tercihlerden maksimum karbon emilim süresinden hesaplanır. Bu algoritma, aşağıdaki duyarlılık değişikliklerinden daha hızlıdır. + Yamalı Eversense uygulamasından KŞ değerleri alır. Glimp\'ten KŞ değerleri alır. - 600SeriesAndroidUploader\'dan KŞ değerleri alın. + 600SeriesAndroidUploader\'dan KŞ değerleri alır. Nightscout\'tan KŞ verilerini yükler + XDrip+\'ten KŞ değerlerini alır. Yapılan tüm tedavileri kaydet WearOS saatinizi kullanarak AndroidAPS\'yi izleyin ve kontrol edin. Döngü\'yle ilgili bilgileri xDrip+ watchface\'inizde gösterin. @@ -62,6 +69,7 @@ Profil Yemek Verisi Sonuç + Sonuç: %1$s %2$s Glikoz verisi yok İstek Delta @@ -100,11 +108,14 @@ Girişinizi değiştirin! KŞ kaynağı AndroidAPS verilerini nereden alsın? + xDrip+ APS modu Kapalı Döngü Açık Döngü + Düşük Glikoz Askıya alma Döngü devre dışı Yeni öneri mevcut + Karbonhidrat Önerisi Nightscout\'un desteklenmeyen sürümü Bazal IOB Bolus kısıtlaması uygulandı @@ -119,16 +130,35 @@ Geçici Bazal Yayım Bolus Nightscout sürümü: + %1$d g eksik Tercihler dışa aktarıldı + Kullanıcı Girişleri dışa aktarıldı Ayarları aktar Ayarları içe aktar Ayarlar içe aktarıldı Dosya bulunamadı Dışarı aktarma ayarları İçe aktarma ayarları + Max Ü/s geçici Bazal ayarlanabilir Bu değer OpenAPS\'te \"max bazal\" olarak adlandırılır OpenAPS\'nin vermesine izin verilen maksimum bazal IOB (Aktif insülin) [U] Bu değere OpenAPS bağlamında Max IOB denir.\nAPS\'de [U] bir kerede verilen maksimum insülin. + Dışa aktarılan tercihleri şifrelemek için kullanılacak ana parola sorulacaktır. + İçe aktarılan tercihlerin şifresini çözmek için gerekli olan ana parola sorulacaktır. + Aktarım iptal edildi! Tercihler dışa aktarılmadı! + Aktarım iptal edildi! Tercihler içe aktarılmadı! + Tercihler içe aktarılamıyor! + Lütfen ana ekrana dönün ve tekrar deneyin. + Eski Ana Parola + Bu dosya dışa aktarılmış ve farklı bir parola ile şifrelenmiş. Dosyanın şifresini çözmek için eski parolayı bulun. + Başarılı içe aktarma işleminin sonucu olarak mevcut ana parola, eski ana parola ile DEĞİŞTİRİLECEKTİR! + Lütfen içe aktarmadan önce tercihleri kontrol edin: + Tercihler içe aktarılamaz! + Tercihler içe aktarılmamalıdır! + İçe aktarım sorunlarını açıkla… + İçe aktarım sorun detayları + İçe aktarma + Yine de içe aktar (TEHLİKELİ!) Son Kullanıcı Lisans Sözleşmesi TIBBİ KARAR VERMEK İÇİN KULLANILMAMALIDIR. UYGULANABİLİR YASANIN İZİN VERDİĞİ ÖLÇÜDE, PROGRAM İÇİN GARANTİ YOKTUR. TELİF HAKKI SAHİPLERİNİN VE / VEYA DİĞER TARAFLARIN YAZILI OLMASINA YÖNELİK BAŞKA HİÇBİR ŞEKİLDE BELİRTİLEN VEYA BELİRLİ BİR AMACA UYGUNLUK İLE İLGİLİ ZIMNİ GARANTİLER DE DAHİL OLMAK ÜZERE ANCAK BUNLARLA SINIRLI OLMAMAK ÜZERE AÇIK VEYA ZIMNİ HİÇBİR GARANTİ OLMAKSIZIN “OLDUĞU GİBİ” SAĞLAMAKTADIR. PROGRAMIN KALİTESİ VE PERFORMANSI İLE İLGİLİ TÜM RİSK SİZE AİTTİR. PROGRAMIN HASARLI OLMASI DURUMUNDA, TÜM GEREKLİ SERVİS, ONARIM VEYA DÜZELTME MALİYETİNİ KABUL ETMİŞ OLURSUNUZ. BEN ANLADIM VE KABUL EDİYORUM @@ -138,18 +168,56 @@ İzinli telefon numaraları +XXXXXXXXXX;+YYYYYYYYYY Bolus %1$.2fU gönderilecek, kod ile cevap ver %2$s + %1$.2fU Yemek bolusu göndermek için %2$s koduyla yanıt verin + Geçici Hedefi %1$s yapmak için %2$s koduyla yanıt verin + Geçici Hedefi iptal etmek için %1$s koduyla yanıt verin + SMS Uzak Hizmet desteğini devre dışı bırakmak için %1$s koduyla yanıt verin.\n\nBu hizmeti yalnızca AAPS yüklü ana telefondan yeniden etkinleştirebileceğinizi unutmayın. + SMS Uzak Hizmeti durduruldu. Yeniden etkinleştirmek için ana telefondaki APPS\'i kullanın. Kalibrasyon %1$.2f gönderilecek, kod ile cevap ver %2$s Bolus başarısız oldu + Bir sms bolusu ile bir sonraki bolus arasında geçmesi gereken minimum dakika sayısı + Bir sms bolus gönderimi ile bir sonraki bolus arasında en az kaç dakika geçsin? + Güvenliğiniz için en az 2 telefon numarası eklemeniz gerekir. + %1$.2f U gönderilecek + %1$.2f U Bolus başarıyla gönderildi + %1$.2f U Yemek Bolusu başarıyla gönderildi + Hedef %2$d dakika boyunca %1$s + Hedef %2$d dakika boyunca %1$s olarak başarıyla ayarlandı + Geçici Hedef başarıyla iptal edildi SMS ile uzaktan komutlara izin ver Döngü devre dışı bırakıldı Döngü etkinleştirildi Döngü etkin + Pompaya bağlanmak için %1$s koduyla yanıt verin + Pompa bağlantısı başarısız + Pompanın bağlantısını %1$d dakika boyunca kesmek için %2$s koduyla yanıtlayın + Pompa bağlantısı kesildi + Pompa yeniden bağlandı Uzaktan komuta izin verilmez + Uzaktan bolus mevcut değil. Daha sonra tekrar deneyin. + %2$d dk boyunca bazalı %1$.2f U/h yapmak için %3$s koduyla yanıtlayın + Profili %1$s %2$d%% olarak değiştirmek için %3$s koduyla yanıtlayın + %2$d dakika boyunca %1$.2f U yayma bolus başlatmak için %3$s koduyla yanıtlayın + %2$s\'de %1$dg girmek için %3$s koduyla yanıtlayın + %2$d dk boyunca bazal %1$d%% başlatmak için %3$s koduyla yanıtlayın %1$d dakika için Döngü\'yü askıya almak için %2$s kodunu yanıtla + Döngüye devam etmek için %1$s koduyla yanıtlayın + Döngüyü etkinleştirmek için %1$s koduyla yanıtlayın + Döngüyü iptal etmek için %1$s koduyla yanıtlayın Geçici bazal %1$.2fÜ/s %2$d dakika için başarıyla başlatıldı + %1$.2fU yayma bolus %2$d dakika boyunca başarıyla başlatıldı + %1$d g karbonhidrat başarıyla sisteme girildi + %1$d g karbonhidrat girilemedi + %2$d dakikalık geçici bazal %1$d%% başarıyla başlatıldı Temp bazal başlatma başarısız oldu + Yayma bolus başlatma başarısız oldu + Geçici bazalı durdurmak için %1$s kodunu gir + Yayma bolusu durdurmak için %1$s koduyla yanıtlayın Geçici bazal iptal + Yayma bolus iptal edildi Geçici bazal iptali hata verdi + Yayma bolus iptal edilemedi + Bilinmeyen komut veya yanlış cevap Kurulum Sihirbazı Kurulum Sihirbazı Ayarları Düğme Metni: @@ -160,12 +228,18 @@ Ögün Düzeltme Eylemler + (DEVRE DIŞI BIRAKILMASI TEHLİKELİ) Yalnızca NS yüklemelerinde + Yalnızca NS yüklemesi (senkronizasyon devre dışı). xDrip+ gibi yerel bir kaynak seçilmediği sürece SGV üzerinde etkili değildir. NS-Profili kullanılırken Profiller üzerinde etkili değildir.\n!!! UYARI !!! Bileşenlerinizden herhangi biri (AAPS, NS, xDrip+) yanlış yapılandırılmışsa, bu seçeneğin devre dışı bırakılması arızalara ve aşırı insülin dozuna neden olabilir. AAPS tarafından görüntülenen verilerin pompa durumuyla eşleşip eşleşmediğini dikkatlice izleyin! Pompa başlatılmamış! Hazırla/doldur Lütfen miktarın infüzyon setinizin özelliklerine uygun olduğundan emin olun! + Hazırla/doldur standart insülin miktarları Düğme 1 Düğme 2 Düğme 3 + Ünite: + Ünite + İES Görselleştirme Aralığı Genel bakış ve akıllı saat göstergesi için yüksek ve düşük değerler DÜŞÜK işareti @@ -182,10 +256,13 @@ Sürekli Bildirim ESKİ VERİ %1$ddak önce + Profil OpenAPS AMA %1$d öğelerin dizisi.\nGerçek değer: Autosens verileri Skriptte hata ayıkla + Otoduyarlılık özelliğini kullan + NS\'tan yenile Gelecekte tedavileri sil ACT KONF @@ -200,10 +277,13 @@ SMS Kısa tab başlıkları Her zaman basit delta yerine kısa ortalama delta kullan + xDrip+ gibi filtrelenmemiş kaynaklardan gelen veriler gürültülü olduğunda kullanışlıdır. Profil Varsayılan değer: 3 Bu OpenAPS için önemli bir güvenlik ayarıdır. Maksimum bazal Iob\'u, en büyük bazal oranınızın üç katı (varsayılan olarak) ile sınırlar. Genel olarak, bu değeri değiştirmemelisiniz. Ama \"3x max günlük, 4x şuan\" ın bir güvenlik ayarı olarak ne anlama geldiğini bilmelisiniz. Varsayılan ayar: 4 Bu, OpenAPS güvenlik ayarlarının diğer yarısı ve \"3x max günlük, 4x akım\" güvenlik korumasının diğer yarısıdır. Bu, başlangıç değerinizin, pompada ayarlanan taban maksimum değerinizden bağımsız olarak, mevcut bazal seviyenin bu sayısından daha yüksek olamayacağı anlamına gelir. Bu, insanların, algoritmanın nasıl çalıştığını anlamadan temel çizgiyi büyük ölçüde artırarak kendilerini tehlikeli durumlarda bulmalarını engellemektir. Varsayılan ayar 4x\'dir; Çoğu insan bu ayarları asla değiştirmek zorunda kalmayacak, ancak bu güvenlik sınırına yakınsa diğer terapi ayarlarını ayarlamalıdırlar. - Varsayılan değer: 0.7\nBu autosens için diğer güvenlik önlemidir. Bazal oranların ne kadar düştüğünü ve İnsülin Duyarlılık Faktörü ve KŞ hedeflerini ne kadar yüksek tutabileceğini gösterir. + Varsayılan değer: 1.2\nOtoduyarlılık (yakında otoayar) çarpanı. Varsayılan değere %20 maksimum limit atamak, otoduyarlılığın bazalları ne kadar yüksek ayarlayabileceğini, ISF ve KŞ hedefini de ne kadar düşük ayarlayabileceğini belirler. + Varsayılan değer: 0.7\nBu otoduyarlılık için diğer güvenlik önlemidir. Otoduyarlılığın bazal oranlarını ne kadar düşürebileceğini ve İnsülin Duyarlılık Faktörü ve KŞ hedeflerini ne kadar yüksek tutabileceğini gösterir. + Otoduyarlılık, hedefleri de ayarlar Varsayılan değer: true\nBu autosens in İnsülin Duyarlılık Faktörü ve bazallara ek olarak KŞ hedeflerinin ayarlanmasında kullanılır. Varsayılan değer: 2\nEğer sadece öğününüzü yerseniz, öğün bolusu alındıktan sonra bolus ertelemesi devreye girer, bu şekilde Döngü karşı bir tetbir olarak geçici bazal oranını azaltmasın diye. Buaradaki örnekte olduğu gibi varsayılan 2; 3 saat DIA olacak şekilde bolus ertelemesi kademeli olarak 1,5 saat üzeri (3DIA/2=1,5). Varsayılan değer: 3.0 (AMA) Gelişmiş Yemek Asistanı veya 8.0 (SMB) Super Micro Bolus. Bu 5 dakika başına varsayılan karbonhidrat emilimi için bir ayardır. Standart değer AMA için 3mg/dl/5dk aynı şekilde SMB 8mg/dl/5dk dir. @@ -212,6 +292,9 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Geçersiz SMS telefon numarası Kalibrasyon xDrip+ uygulaması yüklenmemiş + Kalibrasyon xDrip+ a gönderildi + Kalibrasyon gönderildi. Alma xDrip+\'ta etkinleştirilmelidir. + xDrip+ kalibrasyonları almıyor Pompa durduldu Yürütülüyor Sanal pompa ayarları @@ -238,22 +321,37 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Ayrıntılı IOB göster Watchface üzerinde IOB\'yi bolus ve bazal IOB\'ye ayırın başarısız - lütfen telefonu kontrol edin + n/a + Hasta tipi Çocuk Ergen Yetişkin Yetişkin İnsülin direnci + Hamile + Güvenlik limitlerini ayarlamak için lütfen hasta tipini seçin + Hasta Adı + Lütfen çoklu kurulumlar arasında ayrım yapmak için hasta adı veya takma ad belirleyin + Kullanıcı Glimp + %1$s, düzgün bir şekilde çalışması için pil optimizasyonu yapılmalıdır Döngü durduldu Askıya alındı (%1$d m) Döngü 1s\'liğine askıya alındı Döngü 2s\'liğine askıya alındı Döngü 3s\'liğine askıya alındı Döngü 10s\'liğine askıya alındı + Pompayı ayırın 15 dakika boyunca pompayı ayırın 30 dakika boyunca pompayı ayırın 1 saat boyunca pompayı ayırın 2 saat boyunca pompayı ayırın 3 saat boyunca pompayı ayırın + 15 Dk. + 30 Dk. + 1 Saat + 2 Saat + 3 Saat + 10 Saat Devam et Pompayı tekrar bağla Yanlış süre @@ -270,17 +368,49 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d INS SuperBolus sihirbazını etkinleştir Kurulum sihirbazında superbolus işlevselliğini etkinleştirin. Gerçekten ne yaptığınızı öğrenene kadar etkinleştirmeyin. BİLİNÇSİZ KULLANILDIĞINDA AŞIRI DOS İNSÜLIN VERİLEBİLİR! + Ana ekranda durum ışıklarını göster + Kanül ömrü uyarısı belirle (saat) [h] + Kritik kanül ömrü (saat) [h] + İnsülin ömrü uyarısı belirle (saat) [h] + Kritik insülin ömrü (saat) [h] + Sensör ömrü uyarısı (saat) [h] + Kritik sensör ömrü (saat) [h] + Sensör pili seviye uyarısı [%] + Kritik sensör pili [%] + Pompa pil ömrü uyarısı (saat) [h] + Kritik pompa pili (saat) [h] + Rezervuar seviye uyarısı (ünite) [U] + Kritik rezervuar seviyesi (ünite) [U] + Pompa pil seviye uyarısı [%] + Kritik pompa pili seviyesi [%] + TAHMİN + BAZAL + SAPMA + EYLEM + KŞE + ABS + EĞİMSAPMA Hakkında SMS izni eksik Kayıp telefon durum yetkilendirmesi + xDrip+ Durumu (saat) + xDrip+ Durum Çizgisi (saat) xds BGI göster BGI\'yı durum satırına ekle Yayma Bolusu iptal et + Profil Değişimi Yap + Sensör + İnsülin + Pompa pili + ömür: + seviye: Alarm türleri + NS alarmlarından bildirimler oluşturun + NS duyurularından bildirimler oluşturun Eski veri eşiği [min] Acil durum verileri eşiği [min] - Autosens [h] için aralık + Otoduyarlılık süresi [h] Duyarlılık tespiti için geçmişte geçen saat miktarı (karbonhidrat emilim süresi hariç) OpenAPS Aktar @@ -303,6 +433,7 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Vazgeç Tüm profiller yüklenmedi! Değerler saklanmadı! + Diğer uygulamalara (xDrip+ gibi) yayınları etkinleştirin. Yüklü birden fazla APPS veya NSClient örneğiniz varsa etkinleştirmeyin! Yerel yayınları etkinleştirin. OpenAPS SMB UAM etkinleştir @@ -314,6 +445,7 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Free-Peak Oref Hızlı etkili Oref Hızlı Oref + Lyumjev DIA %1$f çok kısa - bunun yerine %2$f kullanıyor! Profili etkinleştir GEÇERSİZ @@ -326,6 +458,7 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d eğzersiz hedefi hipo süresi hipo hedefi + %1$d%% %2$dh\'yi yeniden kullan Saat tarafından kontrol Tedavileri ve Geçici hedefleri saat tarafından girin. Yiyecek @@ -339,19 +472,29 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Komut şu anda çalıştırıldı Kaçırılan KŞ Okumaları Uyarılar ve bildirimler için sistem bildirimlerini kullan + Uyarılar ve bildirimler için ses seviyesini kademeli olarak artırın Yerel uyarıları KŞ bilgisi alınmadığında uyar Pompa ulaşılamıyorsa uyar Kritik eşik pompaya erişilemiyor [min] + Karbonhidrat gerekliyse uyar Acil önemli Alarm INFO + Eversense App (yamalı) KŞ verilerini NighScout\'a yükle + KŞ yükleme ayarları Ayrıntılı delta göster Bir ondalık basamakla deltayı göster + Kaç dakikada bir SMB verilebilecek SMB\'yi sınırlamak için maksimum bazal dakika + UAM SMB maks. dakika ayarı + UAM da SMB\'yi sınırlamak için maksimum bazal dakika + Gerekli Minimum Karbonhidrat Önerisi + Bir karbonhidrat öneri uyarısı görüntülemek için minimum karbonhidrat gramı. Bu sayının altındaki karbonhidrat önerileri bildirilmeyecektir. XDrip+\'a KŞ verilerini gönder Xdrip+ içerisinde 640g/Eversense veri kaynağı seç Nightscout Client KŞ + NS KŞ KŞ Hesaplaması Bolus IOB (Aktif İnsülin) hesaplaması Bazal IOB hesaplaması @@ -377,6 +520,7 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Geçici hedeflerle SMB\'yi (Super Micro Bolus) etkinleştir Geçici hedef aktif olduğunda SMB\'yi etkinleştir (yakında yeme, egzersiz) Yüksek geçici bazal oran hedefleriyle SMB\'yi etkinleştir + Yüksek geçici hedef aktif olduğunda SMB\'yi etkinleştirin (egzersiz, 100 mg/dl veya 5.5 mmol/l\'nin üzerinde) İnsülin Tuşlar xDrip+ \'ya bir kalibrasyon gönderir veya G5 kalibrasyon iletişim kutusunu açar @@ -385,23 +529,34 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Düğmeye basıldığında eklenecek insülin miktarı CGM uygulaması başlatılamadı. Yüklendiğinden emin olun. CGM + 5dk yoksay + 15dk yoksay + 30dk yoksay + iht. Geçmiş SMB\'ye (Super Micro Bolus) bildir Saatte SMB\'yi (Super Micro Bolus) standart bir bolus gibi göster. Hatalardan duyurular oluştur + Karbonhidrat gerekli uyarılarından duyurular oluşturun Hata diyalogları ve yerel uyarılar için Nightscout anonsu oluşturun (Tedaviler altında Careportal\'da da görüntülenebilir) + Karbonhidrat gerekli uyarılarından Nightscout duyuruları oluşturun Watchface üzerindeki tahminleri göster. Tahminler Veri seçenekleri Fabric Upload Geliştiricilere, fabric.io hizmeti aracılığıyla otomatik kilitlenme raporlaması ve özellik kullanım verilerinin gönderilmesine izin verir. + Lütfen Dexcom uygulamanızı desteklenen sürüme güncelleyin + Dexcom uygulaması yüklü değil. Eğzersiz başlat TT Yakında Yemeğe Başla TT TT Bolusu sadece kayıt altına al Kategori Alt kategori + Bolus yalnızca kaydedilecektir (pompa ile iletilmez) SMB (Supermicroboluses) pompa tarafından verildi + Aktivite + Kan Şekeri Etkisi Duyarlılık Sapma Aktiv Karbonhidrat @@ -414,7 +569,7 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Profildeğiştir kayıp. Lütfen bir profil değiştir seçin veya YerelPorfil\'de \"Profili Etkinleştir\" düğmesine basın. Pompa geçici bazal yetenekli değil Kapalı Döngü tercihlerde devre dışı bırakıldı - Autosens tercihlerde devre dışı bırakıldı + Otoduyarlılık tercihlerde devre dışı bırakıldı SMB tercihleri devre dışı UAM (UnAnnounced Meals) tercihlerde devre dışı bırakıldı UAM (UnAnnounced Meals), Oref1 duyarlılık eklentisine bağlı olduğu için devre dışı bırakıldı @@ -476,11 +631,17 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d AndroidAPS\'ın bazal değişiklikleri önerme/yapmasını sağlamak için aşağıdaki düğmeye basın Duyarlılık eklentisi, duyarlılık tespiti ve COB hesaplaması için kullanılır. Daha fazla bilgi için ziyaret edin: https://github.com/MilosKozak/AndroidAPS/wiki/Sensitivity-detection-and-COB + NSClient, Nightscout\'a bağlantıyı sağlar. Şimdi bu kısmı atlayabilirsiniz, ancak ayarlamadan görevleri geçemezsiniz. Lütfen unutmayın: yeni insülin profilleri en az 5 saat DIA gerektirir. Yeni profildeki DIA 5–6 saat, eski insülin profillerinde DIA 3saat\'e eşittir. Mevcut algoritmalardan birini seçin. En eskiden en yeniye ayrılırlar. Yeni algoritma genellikle daha güçlü ve daha agresiftir. Böylece eğer yeni bir Döngü\'cü iseniz, muhtemelen AMA ile başlayabilirsin, en sonuncusuyla değil. OpenAPS belgelerini okumayı ve kullanmadan önce yapılandırmayı unutmayın. + Lütfen aşağıda RileyLink\'inizi yapılandırın. Bir RileyLink seçtikten sonra, RileyLink durumu \"Bağlandı\" olduğunda kuruluma devam etmek mümkün olacaktır. Bu bir dakika sürebilir.\n + Not: Pompa kurulduktan sonra kuruluma devam edebilirsiniz.\n İlk hedefinize başlayın Yetki İzin için sorunuz + Uygulama, bildirimler için sistem iznine ihtiyaç duyuyor + Uygulamanın BT taraması ve WiFi tanımlaması için konum iznine ihtiyacı var + Uygulamanın, günlük dosyalarını saklayabilmesi ve ayarları dışa aktarabilmesi için depolama iznine ihtiyacı var İstek Navigasyonu aç Navigasyonu kapat @@ -495,11 +656,16 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d = 100]]> Düşük geçici hedefler duyarlılığı azaltır + Direnç hedefi düşürür + Direnç tespit edildiğinde KŞ hedefini düşürün + Duyarlılık hedefi yükseltir + Hassasiyet tespit edildiğinde, KŞ hedefini yükseltin Temiz AndroidAPS başladı Saklanan ayarlar bulundu Dikkat: Eğer bir donanım pompasını etkinleştirir ve bağlarsanız, AndroidAPS, bazal ayarları profilden pompaya aktaracaktır ve pompada kayıtlı mevcut bazal oranlarının üzerine yazacaktır. AndroidAPS\'de doğru ayarların olduğundan emin olun. Emin değilseniz veya pompanızdaki bazal ayarların üzerine yazmak istemiyorsanız, iptal tuşuna basın ve daha sonra tekrar deneyin. Tedavi verileri eksik Bakım ayarları + E-Posta alıcısı Gönderilecek loglar Yok Bakım BAKIM @@ -513,13 +679,223 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d Varsayılanlara sıfırla NSClient arızası. NS ve NSClient yeniden başlatmayı düşünün. Saat farkı + Bolusu daha sonra hatırlat Tercih edilen APS modu Toplam Hesap Bu günün log dosyalarını bu zamana göre geliştiricilere gönder. Beklenmedik bir durum. Minimum istek değişikliği [%] + Açık Döngü, yalnızca değişiklik % cinsinden bu değerden büyükse yeni değişiklik isteğini açar. Varsayılan değer %20\'dir == ∑ %1$s U + Sensör değişimlerini NS\'a kaydet + Sensör başlangıcında otomatik olarak NS\'de \"Sensör Değişimi\" etkinliği oluştur Tomato (MiaoMiao) Tomato + Tidepool oturum açma kullanıcı adınız, normalde e-posta adresiniz + Kullanıcı adınınız + Tidepool şifreniz + Giriş Parolası + Tidepool girişini test et + Etkinleştirilirse, yüklemeler https://app.tidepool.org/ yerine https://int-app.tidepool.org adresine gider + Entegrasyon (test) sunucularını kullanın + Tidepool + TDP + Tidepool\'a veri yükler + SGİ (CGM) verilerini yükle + Tedavileri yükleyin (insülin, karbonhidratlar) + Geçici bazalları yükleyin + Profil değişimlerini, geçici hedefleri yükleyin + KŞ testlerini yükleyin + 24 saat veya daha kısa süre içinde yaz saati değişikliği + Yaz Saati Uygulaması 3 saatten daha kısa bir süre önce değişti - Kapalı döngü devre dışı + dahili depolama birimi + Dahili depolama biriminden en az %1$d MB yer kaldı! Döngü devre dışı! + Yanlış Format + Geçici Bazal Oranı süresi %1$d dakikanın katı ve 0\'dan büyük olmalıdır. + Hatalı kod. Komut iptal edildi. + Yapılandırılmadı + Profil değiştirme yapıldı + Sürüm Kontrolcüsü + eski sürüm + çok eski sürüm + Uygulamanın süresi doldu + En az %1$d gündür yeni sürüm mevcut! %2$d gün sonra LGS\'ye (Düşük Glukoz gönderimine) dönülecek, %3$d gün sonra da döngü devre dışı bırakılacaktır + 2sa + Dexcom Uygulaması (yamalı) + DXCM + Yamalı Dexcom uygulamasından KŞ değerleri alır. + COB vs IOB + Bolus kısıtlaması uygulandı: %1$.2f Ü ile %2$.2f Ü + !!!!! Yavaş karbonhidrat emilimi tespit edildi: zamanın %2$d%\'si. Hesaplamanızı iki kez kontrol edin. Aktif Karbonhidrat (COB) olduğundan fazla tahmin edilebilir, bu nedenle daha fazla insülin verilebilir !!!!!]]> + Bolus sihirbazı sonucunun bu bölümünü ilet [%] + Bolus sihirbazı hesaplamayı gerçekleştirir ancak hesaplanan insülinin yalnızca bu kısmı iletilir. SMB algoritması ile kullanışlıdır. + Ertele + Profilinizdeki maksimum bazal değeriniz düşük olduğu için maksimum bazal değeri artırma + Geçersiz mesaj + %1$s ISF: %2$.1f + %1$.0fg IC: %2$.1f + %1$.1fg IC: %2$.1f + %1$d%% + dk. + Profil adı: + Seçildi: + Ünite + Profili değiştirmek ve mevcut profilde yapılan değişiklikleri gözardı etmek istiyor musunuz? + Silme tamamlandı + Silme başladı + Görevleri sıfırlamak istiyor musunuz? Tüm yaptıklarınızı kaybedeceksiniz. + Değerleri görüntülemek istediğiniz birimleri seçin + İES İnsülin Etki Süresi + IC Karbonhidrat İnsülin Oranı + IDF İnsülin Duyarlılık Faktörü + HDF + Klon + Önce mevcut değişiklikleri kaydedin veya sıfırlayın + Mevcut profil silinsin mi? + Bu profilden yeni profil oluşturulsun mu? + Profil adı noktalar içeriyor.\nBu NS tarafından desteklenmiyor.\n Profil NS\'a yüklenmez. + Aralıktan daha düşük değer (sadece görüntüle) + Aralıktan daha yüksek değer (Sadece görüntüle) + Yaş: + Kilo: + Kimlik: + Sunum + En yaygın profil: + Not: Yalnızca bu ekranda görünen veriler anonim olarak yüklenecektir. Bu AndroidAPS kurulumunda kimlik atanır. Ana profiliniz değişirse verileri tekrar gönderebilir, ancak sonuçların zaman içinde görünür olması için en az bir hafta çalışmasına izin verebilirsiniz. Yardımın takdire değer. + Geçersiz yaş girişi + Geçersiz ağırlık girişi + Geçersiz % giriş + %1$s: Düşük: %2$02d%% İçinde: %3$02d%% Yüksek: %4$02d%%]]> + Ortalama + TIR + Aktivite monitörü + Etkinlik istatistiklerini sıfırlamak istiyor musunuz? + İstatistikler + Rastgele KŞ + Rastgele KŞ verileri oluşturun (Yalnızca demo modunda) + + Araçlar + Hesaplamayı göster + Kaldırılanları göster + Kuyruk temizlensin mi? Kuyruktaki tüm veriler kaybedilecek! + Yayma bolus özelliğinin kullanılması, yayma bolus çalıştırıldığı süre boyunca kapalı döngü modunu durduracaktır. Gerçekten istiyor musunuz? + Yayma bolus çalıştığı için kapalı döngü devre dışı bırakıldı + \"Telefon Denetleyicisi\" + Grafik menüsü + SMB (Super Micro Bolus) zamanı + SMB (Super Micro Bolus) uygulama süresi + Geçici bazal zamanı + Geçici bazal uygulama süresi + authenticator uygulamasından %1$s için PIN girin + İlave zorunlu şifre (PIN) + Oluşturulan Her Tek Kullanımlık Şifrenin sonunda ezberlenmesi ve yapıştırılması gereken ek şifre + Kimlik doğrulayıcı (OTP-Authenticator) kurulumu + Kontrol edilecek kod: + OTP + PIN + Doğrulama kodu, Authenticator uygulaması (OTP olarak bilinir) tarafından görüntülenen 6 haneden ve ardından 3 veya daha fazla zorunlu PIN hanesinden oluşur. + Kimlik Doğrulayıcıları (OTP) Sıfırla + Kimlik Doğrulayıcı Anahtarını Sıfırla + Kimlik Doğrulayıcı (Authenticator) anahtarını sıfırlamak istediğinizden emin misiniz? Şu anda yapılandırılmış tüm Kimlik Doğrulayıcıları geçersiz kılar ve bunları yeniden ayarlamanız gerekir. + Yeni Kimlik Doğrulayıcı (Authenticator) Anahtarı oluşturuldu! Kimlik doğrulayıcıları için lütfen güncellenmiş QRCode\'u kullanın. + OTP dışa aktarma + OTP secret panoya kopyalamak istediğinizden emin misiniz?\n\nYalnızca kimlik doğrulama uygulamanızın QRCode\'u tarama sorunları varsa, bunu elle girmek veya uygulamayı kullanarak OTP donanımı yapılandırmak istiyorsanız buna ihtiyacınız olabilir. + OTP secret (Base32 formatında) dışa aktarıldı ve panoya kopyalandı. Doğrulayıcıya veya OTP donanım yazıcısına yapıştırın! + 1. Doğrulayıcıyı (Authenticator) yükleyin + 2. AndroidAPS OTP kod kurulumu için QR kodu tarayın + 3. Tek Kullanımlık Parolayı (OTP) Test Edin + Doğrulayıcıları (Authenticators) Sıfırla + Her takipçi telefonunda, RFC 6238 TOTP belirteçlerini destekleyen Kimlik Doğrulayıcı uygulamasını yükleyin. Popüler ücretsiz uygulamalar şunlardır:\n • Authy\n • Google Authenticator\n • LastPass Authenticator\n • FreeOTP Authenticator + Doğrulayıcıyı (Authenticator) sıfırlayarak, önceden sağlanmış tüm doğrulayıcıları geçersiz kılarsınız. Onları tekrar kurmanız gerekecek! + Tahminler + Sapma eğimi + Yetkilendirme başarısız oldu + Mutlak insülin + Ana parola, yedekleme şifrelemesi ve uygulamanın güvenliği için kullanılır. Bu parolayı unutmayın ve güvenli bir yerde saklayın. + Geçerli ana parola + Durum ışıkları + Ayarları NS\'den kopyala + NS ayarları kopyalansın mı (varsa)? + Orjinal tema + Düşük çözünürlüklü tema + Düğmeler her zaman ekranın altında görüntülenir + Büyük ekran + Tema + Profilleri karşılaştırın + Profil yardımcısı + Varsayılan profil + Mevcut profil + Kullanılabilir profil + Profil tipi + Yaş: %1$.0f Top.Gün.Doz: %2$.0f Ü + Yaş: %1$.0f Top.Gün.Doz: %2$.0f Ü %3$d%% + Yaş: %1$.0f Ağırlık: %2$.0f kg + % bazalın + DPV Varsayılan profil + RileyLink durumu: + Filtre + Profil oluşturulamıyor. Profil geçersiz. + Uygulamamı öldürme? + Pompa ulaşılamazsa SMS gönder + Pompaya ulaşılamadığını bildir + Yemek zamanı alarmı çalıştır + Alarmı %1$d dakika içinde çalıştır + Bolus danışmanı + Yüksek glisemiksiniz. Şimdi yemek yemek yerine daha iyi glisemi beklemeniz önerilir. Şimdi bir düzeltme bolusu yapmak ve yemek zamanı geldiğinde size hatırlatmak ister misiniz? Bu durumda karbonhidrat kaydı yapılmaz ve size hatırlattığımızda sihirbazı tekrar kullanmanız gerekir. + Bolus danışmanını etkinleştir + Yüksek glisemi sırasında sihirbaz sonucu yerine daha sonra yemeye başlamak için hatırlatıcı kullanın (\"pre-bolus\") + Yemek zamanı!\nBolus sihirbazını çalıştırın ve yeniden hesaplama yapın. + Yemek zamanı + Bolus hatırlatıcısı + Bolus hatırlatıcıyı etkinleştir + Sihirbazla daha sonra bolus için hatırlatıcı kullanın + (\"bolus sonrası\") + Bolus zamanı!\nBolus sihirbazını çalıştırın ve yeniden hesaplama yapın. + Çökme günlükleri yükleme devre dışı bırakıldı! + Grafik + Grafik menüsü + Filtreyi temizle + Trend oku + Kanül + Kullanıcı girişi + Genellikle yediğiniz en büyük yiyeceğin değerlerini kullanın\n + Bu e-posta adresi, acil durumlarda sizinle iletişim kurabilmemiz için çökme raporlarına eklenecektir. (İsteğe bağlı.) + E-posta adresi + Gizlilik ayarı + Uygulama çökmeleri hakkında bilgilendirilmek istiyorsanız isteğe bağlı e-posta adresi sağlayabilirsiniz. Bu otomatik bir hizmet değildir. Tehlikeli durumlarda geliştiriciler sizinle iletişime geçecektir. + Tam senkronizasyon + Tam senkronizasyon? Birkaç saat sürebilir ve bitene kadar NS\'ta yeni veriler göremeyeceksiniz. + Doldur + Senkronizasyon + Profiller, boluslar, karbonhidratlar, geçici bazallar NS\'a yüklenir + Verileri NS\'a yükleyin + Profil deposunu al + NS profil düzenleyicisinden profilleri senkronize edin + Geçici hedefleri al + NS veya NSClient aracılığıyla girilen geçici hedefleri kabul edin + Profil değişimlerini al + NS veya NSClient aracılığıyla girilen profil değişimlerini kabul edin + APS çevrimdışı olaylarını alın + NS veya NSClient aracılığıyla girilen APS çevrimdışı olaylarını kabul edin + İnsülinleri alın + NS veya NSClient aracılığıyla girilen insülini kabul edin (iletilmez, yalnızca aktif insüline göre (IOB) hesaplanır) + Karbonhidratları alın + NS veya NSClient aracılığıyla girilen karbonhidratları kabul edin + Terapi etkinlikleri alın + NS veya NSClient aracılığıyla girilen tedavi olaylarını (kanül, insülin, pil değişimi vb.) kabul edin + SGİ (CGM) verilerini alma/doldurma + NS\'tan SGİ (CGM) verilerini kabul edin + Önceki pompa iletişiminin bitmesini beklerken zaman aşımı + Sırada başka bir bolus var. Daha sonra tekrar deneyin. + Hesaplanıyor + Profil adı eksik + IC değerinde hata + Bazal değerlerde hata + Hedef değerlerde hata + ISF değerinde hata + Yürüt %s? + Geçersiz profil %1$s NS tarafından kabul edilmiyor + Görünüm + Hatalar + Yüklemeleri yavaşlat diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 015695e7c0..0453fe87bb 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -92,9 +92,10 @@ Generic AAPS - Accu-Chek Spirit Accu-Chek Combo + Accu-Chek Spirit Accu-Chek Insight + Accu-Chek Solo Animas Ping Animas Vibe Cellnovo @@ -102,13 +103,16 @@ DanaR Korean DanaRS DanaRv2 - Insulet Omnipod + DanaI + Diaconn G8 Medtronic 512/712 Medtronic 515/715 Medtronic 522/722 Medtronic 523/723 (Revel) Medtronic 554/754 (Veo) Medtronic 640G + Omnipod Dash + Omnipod Eros Tandem t:slim Tandem t:flex Tandem t:slim G4 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ee00a2eab8..4d24ca2e1d 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -54,6 +54,7 @@ ns_offline_event_last_synced_id ns_profile_store_last_synced_timestamp local_profile_last_change + ns_sync_slow Treatments safety Max allowed bolus [U] @@ -65,7 +66,6 @@ Reset Databases Do you really want to reset the databases? Exit - Always use basal absolute values This device does not appear to support battery optimization whitelisting - you may experience performance issues. Some buttons to quickly access common features @@ -1125,5 +1125,12 @@ Error in target values Error in ISF values Run %s? + Invalid profile %1$s not accepted from NS + View + Errors + Slow down uploads + BG data status + Recalculated data used + BG too close:\n%1$s\n%2$s diff --git a/app/src/main/res/xml/pref_nsclientinternal.xml b/app/src/main/res/xml/pref_nsclientinternal.xml index c9dbe2d1e5..208bb66168 100644 --- a/app/src/main/res/xml/pref_nsclientinternal.xml +++ b/app/src/main/res/xml/pref_nsclientinternal.xml @@ -156,7 +156,7 @@ + android:key="@string/key_ns_sync_slow" + android:title="@string/ns_sync_slow" /> diff --git a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 3d859d6c34..358e9b1299 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -24,7 +24,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @@ -44,7 +44,9 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" dateUtil = DateUtil(context) validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) effectiveProfileSwitch = EffectiveProfileSwitch( @@ -72,4 +74,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index 0e086f2957..68dd9ae32c 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -47,7 +47,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var sp: SP - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @Mock lateinit var glimpPlugin: GlimpPlugin @@ -79,45 +79,45 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { it.dateUtil = dateUtil } if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } @Before fun prepare() { - `when`(resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.") - `when`(resourceHelper.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences") - `when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") - `when`(resourceHelper.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences") - `when`(resourceHelper.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") - `when`(resourceHelper.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences") - `when`(resourceHelper.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier") - `when`(resourceHelper.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s") - `when`(resourceHelper.gs(R.string.hardlimit)).thenReturn("hard limit") - `when`(resourceHelper.gs(R.string.key_child)).thenReturn("child") - `when`(resourceHelper.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s") - `when`(resourceHelper.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s") - `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") - `when`(resourceHelper.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") - `when`(resourceHelper.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") - `when`(resourceHelper.gs(R.string.limitingpercentrate, 0, "it must be positive value")).thenReturn("") - `when`(resourceHelper.gs(R.string.limitingbolus, 3.0, "pump limit")).thenReturn("") - `when`(resourceHelper.gs(R.string.limitingbolus, 6.0, "pump limit")).thenReturn("") - `when`(resourceHelper.gs(R.string.limitingbasalratio, 0.8, "pump limit")).thenReturn("") - `when`(resourceHelper.gs(R.string.limitingpercentrate, 200, "pump limit")).thenReturn("") - `when`(resourceHelper.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 9)).thenReturn("Objective 9 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 8)).thenReturn("Objective 8 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 6)).thenReturn("Objective 6 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 1)).thenReturn("Objective 1 not started") + `when`(rh.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.") + `when`(rh.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences") + `when`(rh.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") + `when`(rh.gs(R.string.autosensdisabledinpreferences)).thenReturn("Autosens disabled in preferences") + `when`(rh.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") + `when`(rh.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences") + `when`(rh.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier") + `when`(rh.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %.1f U because of %s") + `when`(rh.gs(R.string.hardlimit)).thenReturn("hard limit") + `when`(rh.gs(R.string.key_child)).thenReturn("child") + `when`(rh.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %d g because of %s") + `when`(rh.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %.1f U because of %s") + `when`(rh.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") + `when`(rh.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") + `when`(rh.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") + `when`(rh.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") + `when`(rh.gs(R.string.limitingpercentrate, 0, "it must be positive value")).thenReturn("") + `when`(rh.gs(R.string.limitingbolus, 3.0, "pump limit")).thenReturn("") + `when`(rh.gs(R.string.limitingbolus, 6.0, "pump limit")).thenReturn("") + `when`(rh.gs(R.string.limitingbasalratio, 0.8, "pump limit")).thenReturn("") + `when`(rh.gs(R.string.limitingpercentrate, 200, "pump limit")).thenReturn("") + `when`(rh.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") + `when`(rh.gs(R.string.objectivenotstarted, 9)).thenReturn("Objective 9 not started") + `when`(rh.gs(R.string.objectivenotstarted, 8)).thenReturn("Objective 8 not started") + `when`(rh.gs(R.string.objectivenotstarted, 6)).thenReturn("Objective 6 not started") + `when`(rh.gs(R.string.objectivenotstarted, 1)).thenReturn("Objective 1 not started") // RS constructor `when`(sp.getString(R.string.key_danars_address, "")).thenReturn("") @@ -130,15 +130,15 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { insightDbHelper = InsightDbHelper(insightDatabaseDao) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) - hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, ConfigImpl(), dateUtil, uel) - comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, pumpSync, dateUtil) - danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) - danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) - insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, insightDbHelper, pumpSync) - openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) - openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) - safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, + hardLimits = HardLimits(aapsLogger, rxBus, sp, rh, context, repository) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, activePlugin, sp, ConfigImpl(), dateUtil, uel) + comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, rh, profileFunction, sp, commandQueue, context, pumpSync, dateUtil) + danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) + danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) + insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, rh, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, insightDbHelper, pumpSync) + openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) + openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) + safetyPlugin = SafetyPlugin(injector, aapsLogger, rh, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelperImpl(ConfigImpl(), fileListProvider), iobCobCalculator, ConfigImpl(), dateUtil) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index ba72feb5a1..50f7692b8d 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -30,10 +30,10 @@ class LoopPluginTest : TestBase() { @Mock lateinit var sp: SP private val rxBus: RxBus = RxBus(aapsSchedulers, aapsLogger) @Mock lateinit var constraintChecker: ConstraintChecker - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var context: Context - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var iobCobCalculator: IobCobCalculator @@ -50,15 +50,15 @@ class LoopPluginTest : TestBase() { val injector = HasAndroidInjector { AndroidInjector { } } @Before fun prepareMock() { - loopPlugin = LoopPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, ConfigImpl(), constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, virtualPumpPlugin, iobCobCalculator, receiverStatusStore, fabricPrivacy, dateUtil, uel, repository, runningConfiguration) + loopPlugin = LoopPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, ConfigImpl(), constraintChecker, rh, profileFunction, context, commandQueue, activePlugin, virtualPumpPlugin, iobCobCalculator, receiverStatusStore, fabricPrivacy, dateUtil, uel, repository, runningConfiguration) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(context.getSystemService(Context.NOTIFICATION_SERVICE)).thenReturn(notificationManager) } @Test fun testPluginInterface() { - `when`(resourceHelper.gs(R.string.loop)).thenReturn("Loop") - `when`(resourceHelper.gs(R.string.loop_shortname)).thenReturn("LOOP") + `when`(rh.gs(R.string.loop)).thenReturn("Loop") + `when`(rh.gs(R.string.loop_shortname)).thenReturn("LOOP") `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed") val pumpDescription = PumpDescription() `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) @@ -71,13 +71,13 @@ class LoopPluginTest : TestBase() { Assert.assertEquals(R.xml.pref_loop.toLong(), loopPlugin.preferencesId.toLong()) // Plugin is disabled by default - Assert.assertEquals(false, loopPlugin.isEnabled(PluginType.LOOP)) + Assert.assertEquals(false, loopPlugin.isEnabled()) loopPlugin.setPluginEnabled(PluginType.LOOP, true) - Assert.assertEquals(true, loopPlugin.isEnabled(PluginType.LOOP)) + Assert.assertEquals(true, loopPlugin.isEnabled()) // No temp basal capable pump should disable plugin virtualPumpPlugin.pumpDescription.isTempBasalCapable = false - Assert.assertEquals(false, loopPlugin.isEnabled(PluginType.LOOP)) + Assert.assertEquals(false, loopPlugin.isEnabled()) virtualPumpPlugin.pumpDescription.isTempBasalCapable = true // Fragment is hidden by default diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt index f3ed85f757..4d198b4dd0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt @@ -16,7 +16,7 @@ import org.mockito.Mock class ConfigBuilderPluginTest : TestBase() { @Mock lateinit var sp: SP - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var uel: UserEntryLogger @Mock lateinit var pumpSync: PumpSync @@ -32,6 +32,6 @@ class ConfigBuilderPluginTest : TestBase() { @Before fun prepareMock() { - configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, resourceHelper, sp, RxBus(aapsSchedulers, aapsLogger), activePlugin, uel, pumpSync) + configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, rh, sp, RxBus(aapsSchedulers, aapsLogger), activePlugin, uel, pumpSync) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt new file mode 100644 index 0000000000..5cc254333c --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt @@ -0,0 +1,196 @@ +package info.nightscout.androidaps.plugins.constraints.bgQualityCheck + +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R +import info.nightscout.androidaps.TestBase +import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.IobCobCalculator +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.Mock +import org.mockito.Mockito +import java.util.* + +class BgQualityCheckPluginTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var iobCobCalculator: IobCobCalculator + @Mock lateinit var fabricPrivacy: FabricPrivacy + + private lateinit var plugin: BgQualityCheckPlugin + + val injector = HasAndroidInjector { AndroidInjector { } } + private val autosensDataStore = AutosensDataStore() + + @Before + fun mock() { + plugin = BgQualityCheckPlugin(injector, aapsLogger, rh, RxBus(aapsSchedulers, aapsLogger), iobCobCalculator, aapsSchedulers, fabricPrivacy) + Mockito.`when`(iobCobCalculator.ads).thenReturn(autosensDataStore) + } + + @Test + fun runTest() { + autosensDataStore.lastUsed5minCalculation = null + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.UNKNOWN, plugin.state) + Assert.assertEquals(0, plugin.icon()) + autosensDataStore.lastUsed5minCalculation = true + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.FIVE_MIN_DATA, plugin.state) + Assert.assertEquals(0, plugin.icon()) + autosensDataStore.lastUsed5minCalculation = false + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.RECALCULATED, plugin.state) + Assert.assertEquals(R.drawable.ic_baseline_warning_24_yellow, plugin.icon()) + + val superData: MutableList = ArrayList() + superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + autosensDataStore.bgReadings = superData + + autosensDataStore.lastUsed5minCalculation = true + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.FIVE_MIN_DATA, plugin.state) + autosensDataStore.lastUsed5minCalculation = false + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.RECALCULATED, plugin.state) + + val duplicatedData: MutableList = ArrayList() + duplicatedData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + duplicatedData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(20).msecs() + 1, + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + duplicatedData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + duplicatedData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + duplicatedData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + autosensDataStore.bgReadings = duplicatedData + + autosensDataStore.lastUsed5minCalculation = true + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.DOUBLED, plugin.state) + Assert.assertEquals(R.drawable.ic_baseline_warning_24_red, plugin.icon()) + + val identicalData: MutableList = ArrayList() + identicalData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + identicalData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + identicalData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + identicalData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + identicalData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + autosensDataStore.bgReadings = identicalData + + autosensDataStore.lastUsed5minCalculation = false + plugin.processBgData() + Assert.assertEquals(BgQualityCheckPlugin.State.DOUBLED, plugin.state) + } + + @Test + fun isLoopInvocationAllowedTest() { + plugin.state = BgQualityCheckPlugin.State.UNKNOWN + Assert.assertEquals(true, plugin.isLoopInvocationAllowed(Constraint(true)).value()) + plugin.state = BgQualityCheckPlugin.State.FIVE_MIN_DATA + Assert.assertEquals(true, plugin.isLoopInvocationAllowed(Constraint(true)).value()) + plugin.state = BgQualityCheckPlugin.State.RECALCULATED + Assert.assertEquals(true, plugin.isLoopInvocationAllowed(Constraint(true)).value()) + plugin.state = BgQualityCheckPlugin.State.DOUBLED + Assert.assertEquals(false, plugin.isLoopInvocationAllowed(Constraint(true)).value()) + } + +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt index acfdc4d068..69a9563dbb 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt @@ -18,7 +18,7 @@ import java.util.* class DstHelperPluginTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var loopPlugin: LoopPlugin @@ -29,7 +29,7 @@ class DstHelperPluginTest : TestBase() { @Before fun mock() { - plugin = DstHelperPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), resourceHelper, + plugin = DstHelperPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), rh, sp, activePlugin, loopPlugin) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt index 795a677695..f8a24417d2 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt @@ -20,7 +20,7 @@ import org.mockito.Mockito.`when` class ObjectivesPluginTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var sp: SP @Mock lateinit var dateUtil: DateUtil @@ -32,19 +32,19 @@ class ObjectivesPluginTest : TestBase() { AndroidInjector { if (it is Objective) { it.sp = sp - it.resourceHelper = resourceHelper + it.rh = rh it.dateUtil = dateUtil } } } @Before fun prepareMock() { - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, ConfigImpl(), dateUtil, uel) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, activePlugin, sp, ConfigImpl(), dateUtil, uel) objectivesPlugin.onStart() - `when`(resourceHelper.gs(R.string.objectivenotstarted, 9)).thenReturn("Objective 9 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 8)).thenReturn("Objective 8 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 6)).thenReturn("Objective 6 not started") - `when`(resourceHelper.gs(R.string.objectivenotstarted, 1)).thenReturn("Objective 1 not started") + `when`(rh.gs(R.string.objectivenotstarted, 9)).thenReturn("Objective 9 not started") + `when`(rh.gs(R.string.objectivenotstarted, 8)).thenReturn("Objective 8 not started") + `when`(rh.gs(R.string.objectivenotstarted, 6)).thenReturn("Objective 6 not started") + `when`(rh.gs(R.string.objectivenotstarted, 1)).thenReturn("Objective 1 not started") } @Test fun notStartedObjectivesShouldLimitLoopInvocation() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt index bc54c57e09..566db83f18 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -46,30 +46,30 @@ class SafetyPluginTest : TestBaseWithProfile() { @Before fun prepare() { - `when`(resourceHelper.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %1\$.1f U because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %1\$.1f U because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %1\$d g because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") - `when`(resourceHelper.gs(R.string.pumpisnottempbasalcapable)).thenReturn("Pump is not temp basal capable") - `when`(resourceHelper.gs(R.string.increasingmaxbasal)).thenReturn("Increasing max basal value because setting is lower than your max basal in profile") - `when`(resourceHelper.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences") - `when`(resourceHelper.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences") - `when`(resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.") - `when`(resourceHelper.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") - `when`(resourceHelper.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode") - `when`(resourceHelper.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences") - `when`(resourceHelper.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier") - `when`(resourceHelper.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier") - `when`(resourceHelper.gs(R.string.hardlimit)).thenReturn("hard limit") - `when`(resourceHelper.gs(R.string.key_child)).thenReturn("child") + `when`(rh.gs(R.string.limitingbolus)).thenReturn("Limiting bolus to %1\$.1f U because of %2\$s") + `when`(rh.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") + `when`(rh.gs(R.string.limitingiob)).thenReturn("Limiting IOB to %1\$.1f U because of %2\$s") + `when`(rh.gs(R.string.limitingcarbs)).thenReturn("Limiting carbs to %1\$d g because of %2\$s") + `when`(rh.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") + `when`(rh.gs(R.string.pumpisnottempbasalcapable)).thenReturn("Pump is not temp basal capable") + `when`(rh.gs(R.string.increasingmaxbasal)).thenReturn("Increasing max basal value because setting is lower than your max basal in profile") + `when`(rh.gs(R.string.smbdisabledinpreferences)).thenReturn("SMB disabled in preferences") + `when`(rh.gs(R.string.closedmodedisabledinpreferences)).thenReturn("Closed loop mode disabled in preferences") + `when`(rh.gs(R.string.closed_loop_disabled_on_dev_branch)).thenReturn("Running dev version. Closed loop is disabled.") + `when`(rh.gs(R.string.itmustbepositivevalue)).thenReturn("it must be positive value") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.smbalwaysdisabled)).thenReturn("SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") + `when`(rh.gs(R.string.smbnotallowedinopenloopmode)).thenReturn("SMB not allowed in open loop mode") + `when`(rh.gs(R.string.maxvalueinpreferences)).thenReturn("max value in preferences") + `when`(rh.gs(R.string.maxbasalmultiplier)).thenReturn("max basal multiplier") + `when`(rh.gs(R.string.maxdailybasalmultiplier)).thenReturn("max daily basal multiplier") + `when`(rh.gs(R.string.hardlimit)).thenReturn("hard limit") + `when`(rh.gs(R.string.key_child)).thenReturn("child") `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) - hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) - safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, iobCobCalculator, ConfigImpl(), dateUtil) + hardLimits = HardLimits(aapsLogger, rxBus, sp, rh, context, repository) + safetyPlugin = SafetyPlugin(injector, aapsLogger, rh, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, buildHelper, iobCobCalculator, ConfigImpl(), dateUtil) } @Test fun pumpDescriptionShouldLimitLoopInvocation() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt index 16ba83983b..abc82bdbe4 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt @@ -13,7 +13,7 @@ import org.mockito.Mock class SignatureVerifierPluginTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var context: Context private val rxBus = RxBus(aapsSchedulers, aapsLogger) @@ -22,7 +22,7 @@ class SignatureVerifierPluginTest : TestBase() { @Test fun singleCharUnMapTest() { - val plugin = SignatureVerifierPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, context) + val plugin = SignatureVerifierPlugin(injector, aapsLogger, rh, sp, rxBus, context) val key = "2ΙšÄΠΒϨÒÇeЄtЄЗž-*Ж*ZcHijЊÄœ<|x\"Ε" val unmapped = plugin.singleCharUnMap(key) Assert.assertEquals("32:99:61:C4:A0:92:E8:D2:C7:65:04:74:04:17:7E:2D:2A:16:2A:5A:63:48:69:6A:0A:C4:53:3C:7C:78:22:95", unmapped) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt index c1a5a94e37..770cb6153b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt @@ -17,29 +17,29 @@ import org.mockito.Mockito.anyLong class StorageConstraintPluginTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper private val rxBusWrapper = RxBus(aapsSchedulers, aapsLogger) private lateinit var storageConstraintPlugin: StorageConstraintPlugin @Before fun prepareMock() { - storageConstraintPlugin = StorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) - `when`(resourceHelper.gs(anyInt(), anyLong())).thenReturn("") + storageConstraintPlugin = StorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, rh, rxBusWrapper) + `when`(rh.gs(anyInt(), anyLong())).thenReturn("") } class MockedStorageConstraintPlugin constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, rxBus: RxBus - ) : StorageConstraintPlugin(injector, aapsLogger, resourceHelper, rxBus) { + ) : StorageConstraintPlugin(injector, aapsLogger, rh, rxBus) { var memSize = 150L override fun availableInternalMemorySize(): Long = memSize } @Test fun isLoopInvocationAllowedTest() { - val mocked = MockedStorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, resourceHelper, rxBusWrapper) + val mocked = MockedStorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, rh, rxBusWrapper) // Set free space under 200(Mb) to disable loop mocked.memSize = 150L Assert.assertEquals(false, mocked.isClosedLoopAllowed(Constraint(true)).value()) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersionsTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersionsTest.kt index 7c5706b7ca..1b14ba64d0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersionsTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersionsTest.kt @@ -23,7 +23,10 @@ class AllowedVersionsTest { @Test fun findByVersionTest() { - val definition = AllowedVersions().generateSupportedVersions() + //val definition = AllowedVersions().generateSupportedVersions() + val definition = "[{\"minAndroid\":1,\"maxAndroid\":23},{\"minAndroid\":24,\"maxAndroid\":25,\"supported\":\"2.6.2\"},{\"minAndroid\":26,\"maxAndroid\":27,\"supported\":\"2.8.2\"},{\"minAndroid\":28,\"maxAndroid\":99,\"supported\":\"2.8.2\"},{\"endDate\":\"2021-11-07\",\"version\":\"2.9.0-beta1\"},{\"endDate\":\"2021-11-02\",\"version\":\"3.0-beta1\"},{\"endDate\":\"2021-11-04\",\"version\":\"3.0-beta2\"},{\"endDate\":\"2021-11-10\",\"version\":\"3.0-beta3\"},{\"endDate\":\"2021-11-14\",\"version\":\"3.0-beta4\"}\n" + + " ,{\"endDate\":\"2021-11-16\",\"version\":\"3.0-beta5\"}\n" + + "]" assertNull(AllowedVersions().findByVersion(definition, "2.6.0")) assertTrue(AllowedVersions().findByVersion(definition, "2.9.0-beta1")?.has("endDate") ?: false) assertEquals("2021-11-07", AllowedVersions().findByVersion(definition, "2.9.0-beta1")?.getString("endDate")) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt index 14ab61d104..fbf57cd467 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt @@ -19,7 +19,7 @@ class MaintenancePluginTest : TestBase() { @Mock lateinit var injector: HasAndroidInjector @Mock lateinit var context: Context - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var nsSettingsStatus: NSSettingsStatus @Mock lateinit var buildHelper: BuildHelper @@ -30,7 +30,7 @@ class MaintenancePluginTest : TestBase() { @Before fun mock() { - sut = MaintenancePlugin(injector, context, resourceHelper, sp, nsSettingsStatus, aapsLogger, buildHelper, ConfigImpl(), fileListProvider, loggerUtils) + sut = MaintenancePlugin(injector, context, rh, sp, nsSettingsStatus, aapsLogger, buildHelper, ConfigImpl(), fileListProvider, loggerUtils) `when`(loggerUtils.suffix).thenReturn(".log.zip") `when`(loggerUtils.logDirectory).thenReturn("src/test/res/logger") `when`(fileListProvider.ensureTempDirExists()).thenReturn(File("src/test/res/logger")) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt index 19733459a3..c9e688baa7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt @@ -23,7 +23,7 @@ class NsClientReceiverDelegateTest : TestBase() { @Mock lateinit var context: Context @Mock lateinit var sp: SP - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper lateinit var receiverStatusStore: ReceiverStatusStore val rxBus = RxBus(aapsSchedulers, aapsLogger) @@ -37,7 +37,7 @@ class NsClientReceiverDelegateTest : TestBase() { `when`(sp.getInt(anyInt(), anyInt())).thenReturn(0) `when`(sp.getString(anyInt(), anyString())).thenReturn("") - sut = NsClientReceiverDelegate(rxBus, resourceHelper, sp, receiverStatusStore) + sut = NsClientReceiverDelegate(rxBus, rh, sp, receiverStatusStore) } @Test fun testCalculateStatusChargingState() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt index 228c4aa802..8d44fc6677 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt @@ -22,7 +22,7 @@ import org.mockito.stubbing.Answer class AuthRequestTest : TestBase() { @Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var otp: OneTimePassword @Mock lateinit var dateUtil: DateUtil @@ -30,7 +30,7 @@ class AuthRequestTest : TestBase() { AndroidInjector { if (it is AuthRequest) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.smsCommunicatorPlugin = smsCommunicatorPlugin it.otp = otp it.dateUtil = dateUtil @@ -42,7 +42,7 @@ class AuthRequestTest : TestBase() { private var actionCalled = false @Before fun prepareTests() { - `when`(resourceHelper.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.") + `when`(rh.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.") doAnswer(Answer { invocation: InvocationOnMock -> sentSms = invocation.getArgument(0) null diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index a56824dd4c..186c7a4465 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -50,7 +50,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { @Mock lateinit var sp: SP @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var activePlugin: ActivePlugin - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var loopPlugin: LoopPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var localProfilePlugin: LocalProfilePlugin @@ -65,12 +65,12 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } if (it is AuthRequest) { it.aapsLogger = aapsLogger it.smsCommunicatorPlugin = smsCommunicatorPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.otp = otp it.dateUtil = dateUtil it.commandQueue = commandQueue @@ -98,7 +98,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { })) val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtilMocked) - smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, ConfigImpl(), dateUtilMocked, uel, glucoseStatusProvider, repository) + smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, rh, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, ConfigImpl(), dateUtilMocked, uel, glucoseStatusProvider, repository) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) Mockito.doAnswer { invocation: InvocationOnMock -> val callback = invocation.getArgument(1) @@ -160,77 +160,78 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { `when`(otp.name()).thenReturn("User") `when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.OK) - `when`(resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") - `when`(resourceHelper.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.") - `when`(resourceHelper.gs(R.string.sms_iob)).thenReturn("IOB:") - `when`(resourceHelper.gs(R.string.sms_lastbg)).thenReturn("Last BG:") - `when`(resourceHelper.gs(R.string.sms_minago)).thenReturn("%1\$dmin ago") - `when`(resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") - `when`(resourceHelper.gs(R.string.smscommunicator_stopsmswithcode)).thenReturn("To disable the SMS Remote Service reply with code %1\$s.\\n\\nKeep in mind that you\\'ll able to reactivate it directly from the AAPS master smartphone only.") - `when`(resourceHelper.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2\$s.") - `when`(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode)).thenReturn("To set the Temp Target %1\$s reply with code %2\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_temptargetcancel)).thenReturn("To cancel Temp Target reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") - `when`(resourceHelper.gs(R.string.smscommunicator_tt_set)).thenReturn("Target %1\$s for %2\$d minutes set successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully") - `when`(resourceHelper.gs(R.string.loopsuspendedfor)).thenReturn("Suspended (%1\$d m)") - `when`(resourceHelper.gs(R.string.loopisdisabled)).thenReturn("Loop is disabled") - `when`(resourceHelper.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled") - `when`(resourceHelper.gs(R.string.wrongformat)).thenReturn("Wrong format") - `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.wrongTbrDuration), ArgumentMatchers.any())).thenAnswer { i: InvocationOnMock -> "TBR duration must be a multiple of " + i.arguments[1] + " minutes and greater than 0." } - `when`(resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled") - `when`(resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled") - `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled") - `when`(resourceHelper.gs(R.string.smscommunicator_loopresumed)).thenReturn("Loop resumed") - `when`(resourceHelper.gs(R.string.smscommunicator_wrongduration)).thenReturn("Wrong duration") - `when`(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode)).thenReturn("To suspend loop for %1\$d minutes reply with code %2\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_loopsuspended)).thenReturn("Loop suspended") - `when`(resourceHelper.gs(R.string.smscommunicator_unknowncommand)).thenReturn("Unknown command or wrong reply") - `when`(resourceHelper.gs(R.string.notconfigured)).thenReturn("Not configured") - `when`(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode)).thenReturn("To switch profile to %1\$s %2\$d%% reply with code %3\$s") - `when`(resourceHelper.gs(R.string.profileswitchcreated)).thenReturn("Profile switch created") - `when`(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode)).thenReturn("To stop temp basal reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode)).thenReturn("To start basal %1\$d%% for %2\$d min reply with code %3\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent)).thenReturn("Temp basal %1\$d%% for %2\$d min started successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode)).thenReturn("To start basal %1$.2fU/h for %2\$d min reply with code %3\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_tempbasalset)).thenReturn("Temp basal %1$.2fU/h for %2\$d min started successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode)).thenReturn("To stop extended bolus reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_extendedcanceled)).thenReturn("Extended bolus canceled") - `when`(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode)).thenReturn("To start extended bolus %1$.2fU for %2\$d min reply with code %3\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_extendedset)).thenReturn("Extended bolus %1$.2fU for %2\$d min started successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode)).thenReturn("To deliver bolus %1$.2fU reply with code %2\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_bolusdelivered)).thenReturn("Bolus %1$.2fU delivered successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed)).thenReturn("Remote bolus not available. Try again later.") - `when`(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode)).thenReturn("To send calibration %1$.2f reply with code %2\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip.") - `when`(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode)).thenReturn("To enter %1\$dg at %2\$s reply with code %3\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_carbsset)).thenReturn("Carbs %1\$dg entered successfully") - `when`(resourceHelper.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") - `when`(resourceHelper.gs(R.string.pumpsuspended)).thenReturn("Pump suspended") - `when`(resourceHelper.gs(R.string.sms_delta)).thenReturn("Delta:") - `when`(resourceHelper.gs(R.string.sms_bolus)).thenReturn("Bolus:") - `when`(resourceHelper.gs(R.string.sms_basal)).thenReturn("Basal:") - `when`(resourceHelper.gs(R.string.cob)).thenReturn("COB") - `when`(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered)).thenReturn("Meal Bolus %1\$.2fU delivered successfully") - `when`(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered_tt)).thenReturn("Target %1\$s for %2\$d minutes") - `when`(resourceHelper.gs(R.string.sms_actualbg)).thenReturn("BG:") - `when`(resourceHelper.gs(R.string.sms_lastbg)).thenReturn("Last BG:") - `when`(resourceHelper.gs(R.string.smscommunicator_loopdisablereplywithcode)).thenReturn("To disable loop reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_loopenablereplywithcode)).thenReturn("To enable loop reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_loopresumereplywithcode)).thenReturn("To resume loop reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_pumpdisconnectwithcode)).thenReturn("To disconnect pump for %1d minutes reply with code %2\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_pumpconnectwithcode)).thenReturn("To connect pump reply with code %1\$s") - `when`(resourceHelper.gs(R.string.smscommunicator_reconnect)).thenReturn("Pump reconnected") - `when`(resourceHelper.gs(R.string.smscommunicator_pumpconnectfail)).thenReturn("Connection to pump failed") - `when`(resourceHelper.gs(R.string.smscommunicator_pumpdisconnected)).thenReturn("Pump disconnected") - `when`(resourceHelper.gs(R.string.smscommunicator_code_from_authenticator_for)).thenReturn("from Authenticator app for: %1\$s followed by PIN") - `when`(resourceHelper.gs(R.string.patient_name_default)).thenReturn("User") - `when`(resourceHelper.gsNotLocalised(R.string.loopsuspended)).thenReturn("Loop suspended") - `when`(resourceHelper.gsNotLocalised(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") - `when`(resourceHelper.gsNotLocalised(R.string.profileswitchcreated)).thenReturn("Profile switch created") - `when`(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled") - `when`(resourceHelper.gsNotLocalised(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip+.") - `when`(resourceHelper.gsNotLocalised(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully") + `when`(rh.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") + `when`(rh.gs(R.string.sms_wrongcode)).thenReturn("Wrong code. Command cancelled.") + `when`(rh.gs(R.string.sms_iob)).thenReturn("IOB:") + `when`(rh.gs(R.string.sms_lastbg)).thenReturn("Last BG:") + `when`(rh.gs(R.string.sms_minago)).thenReturn("%1\$dmin ago") + `when`(rh.gs(R.string.smscommunicator_remotecommandnotallowed)).thenReturn("Remote command is not allowed") + `when`(rh.gs(R.string.smscommunicator_stopsmswithcode)).thenReturn("To disable the SMS Remote Service reply with code %1\$s.\\n\\nKeep in mind that you\\'ll able to reactivate it directly from the AAPS master smartphone only.") + `when`(rh.gs(R.string.smscommunicator_mealbolusreplywithcode)).thenReturn("To deliver meal bolus %1$.2fU reply with code %2\$s.") + `when`(rh.gs(R.string.smscommunicator_temptargetwithcode)).thenReturn("To set the Temp Target %1\$s reply with code %2\$s") + `when`(rh.gs(R.string.smscommunicator_temptargetcancel)).thenReturn("To cancel Temp Target reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") + `when`(rh.gs(R.string.smscommunicator_tt_set)).thenReturn("Target %1\$s for %2\$d minutes set successfully") + `when`(rh.gs(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully") + `when`(rh.gs(R.string.loopsuspendedfor)).thenReturn("Suspended (%1\$d m)") + `when`(rh.gs(R.string.loopisdisabled)).thenReturn("Loop is disabled") + `when`(rh.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled") + `when`(rh.gs(R.string.wrongformat)).thenReturn("Wrong format") + `when`(rh.gs(ArgumentMatchers.eq(R.string.wrongTbrDuration), ArgumentMatchers.any())).thenAnswer { i: InvocationOnMock -> "TBR duration must be a multiple of " + i.arguments[1] + " minutes and greater than 0." } + `when`(rh.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled") + `when`(rh.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled") + `when`(rh.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled") + `when`(rh.gs(R.string.smscommunicator_loopresumed)).thenReturn("Loop resumed") + `when`(rh.gs(R.string.smscommunicator_wrongduration)).thenReturn("Wrong duration") + `when`(rh.gs(R.string.smscommunicator_suspendreplywithcode)).thenReturn("To suspend loop for %1\$d minutes reply with code %2\$s") + `when`(rh.gs(R.string.smscommunicator_loopsuspended)).thenReturn("Loop suspended") + `when`(rh.gs(R.string.smscommunicator_unknowncommand)).thenReturn("Unknown command or wrong reply") + `when`(rh.gs(R.string.notconfigured)).thenReturn("Not configured") + `when`(rh.gs(R.string.smscommunicator_profilereplywithcode)).thenReturn("To switch profile to %1\$s %2\$d%% reply with code %3\$s") + `when`(rh.gs(R.string.profileswitchcreated)).thenReturn("Profile switch created") + `when`(rh.gs(R.string.smscommunicator_basalstopreplywithcode)).thenReturn("To stop temp basal reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_basalpctreplywithcode)).thenReturn("To start basal %1\$d%% for %2\$d min reply with code %3\$s") + `when`(rh.gs(R.string.smscommunicator_tempbasalset_percent)).thenReturn("Temp basal %1\$d%% for %2\$d min started successfully") + `when`(rh.gs(R.string.smscommunicator_basalreplywithcode)).thenReturn("To start basal %1$.2fU/h for %2\$d min reply with code %3\$s") + `when`(rh.gs(R.string.smscommunicator_tempbasalset)).thenReturn("Temp basal %1$.2fU/h for %2\$d min started successfully") + `when`(rh.gs(R.string.smscommunicator_extendedstopreplywithcode)).thenReturn("To stop extended bolus reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_extendedcanceled)).thenReturn("Extended bolus canceled") + `when`(rh.gs(R.string.smscommunicator_extendedreplywithcode)).thenReturn("To start extended bolus %1$.2fU for %2\$d min reply with code %3\$s") + `when`(rh.gs(R.string.smscommunicator_extendedset)).thenReturn("Extended bolus %1$.2fU for %2\$d min started successfully") + `when`(rh.gs(R.string.smscommunicator_bolusreplywithcode)).thenReturn("To deliver bolus %1$.2fU reply with code %2\$s") + `when`(rh.gs(R.string.smscommunicator_bolusdelivered)).thenReturn("Bolus %1$.2fU delivered successfully") + `when`(rh.gs(R.string.smscommunicator_remotebolusnotallowed)).thenReturn("Remote bolus not available. Try again later.") + `when`(rh.gs(R.string.smscommunicator_calibrationreplywithcode)).thenReturn("To send calibration %1$.2f reply with code %2\$s") + `when`(rh.gs(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip.") + `when`(rh.gs(R.string.smscommunicator_carbsreplywithcode)).thenReturn("To enter %1\$dg at %2\$s reply with code %3\$s") + `when`(rh.gs(R.string.smscommunicator_carbsset)).thenReturn("Carbs %1\$dg entered successfully") + `when`(rh.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") + `when`(rh.gs(R.string.pumpsuspended)).thenReturn("Pump suspended") + `when`(rh.gs(R.string.sms_delta)).thenReturn("Delta:") + `when`(rh.gs(R.string.sms_bolus)).thenReturn("Bolus:") + `when`(rh.gs(R.string.sms_basal)).thenReturn("Basal:") + `when`(rh.gs(R.string.cob)).thenReturn("COB") + `when`(rh.gs(R.string.smscommunicator_mealbolusdelivered)).thenReturn("Meal Bolus %1\$.2fU delivered successfully") + `when`(rh.gs(R.string.smscommunicator_mealbolusdelivered_tt)).thenReturn("Target %1\$s for %2\$d minutes") + `when`(rh.gs(R.string.sms_actualbg)).thenReturn("BG:") + `when`(rh.gs(R.string.sms_lastbg)).thenReturn("Last BG:") + `when`(rh.gs(R.string.smscommunicator_loopdisablereplywithcode)).thenReturn("To disable loop reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_loopenablereplywithcode)).thenReturn("To enable loop reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_loopresumereplywithcode)).thenReturn("To resume loop reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_pumpdisconnectwithcode)).thenReturn("To disconnect pump for %1d minutes reply with code %2\$s") + `when`(rh.gs(R.string.smscommunicator_pumpconnectwithcode)).thenReturn("To connect pump reply with code %1\$s") + `when`(rh.gs(R.string.smscommunicator_reconnect)).thenReturn("Pump reconnected") + `when`(rh.gs(R.string.smscommunicator_pumpconnectfail)).thenReturn("Connection to pump failed") + `when`(rh.gs(R.string.smscommunicator_pumpdisconnected)).thenReturn("Pump disconnected") + `when`(rh.gs(R.string.smscommunicator_code_from_authenticator_for)).thenReturn("from Authenticator app for: %1\$s followed by PIN") + `when`(rh.gs(R.string.patient_name_default)).thenReturn("User") + `when`(rh.gs(R.string.invalidprofile)).thenReturn("Invalid profile !!!") + `when`(rh.gsNotLocalised(R.string.loopsuspended)).thenReturn("Loop suspended") + `when`(rh.gsNotLocalised(R.string.smscommunicator_stoppedsms)).thenReturn("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.") + `when`(rh.gsNotLocalised(R.string.profileswitchcreated)).thenReturn("Profile switch created") + `when`(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled") + `when`(rh.gsNotLocalised(R.string.smscommunicator_calibrationsent)).thenReturn("Calibration sent. Receiving must be enabled in xDrip+.") + `when`(rh.gsNotLocalised(R.string.smscommunicator_tt_canceled)).thenReturn("Temp Target canceled successfully") } @@ -464,7 +465,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) //NSCLIENT RESTART - `when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + `when`(loopPlugin.isEnabled()).thenReturn(true) `when`(loopPlugin.isSuspended).thenReturn(false) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT RESTART") @@ -474,7 +475,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("NSCLIENT RESTART")) //NSCLIENT BLA BLA - `when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + `when`(loopPlugin.isEnabled()).thenReturn(true) `when`(loopPlugin.isSuspended).thenReturn(false) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT BLA BLA") @@ -484,7 +485,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) //NSCLIENT BLABLA - `when`(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true) + `when`(loopPlugin.isEnabled()).thenReturn(true) `when`(loopPlugin.isSuspended).thenReturn(false) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "NSCLIENT BLABLA") @@ -707,6 +708,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("To switch profile to someProfile 100% reply with code")) //PROFILE 1 90(OK) + `when`(profileFunction.createProfileSwitch(anyObject(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt(), anyLong())).thenReturn(true) smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "PROFILE 1 90") smsCommunicatorPlugin.processSms(sms) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt index b00e3ffa9e..0fb0290810 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt @@ -25,7 +25,7 @@ class InsulinLyumjevPluginTest { private lateinit var sut: InsulinLyumjevPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var aapsLogger: AAPSLogger @@ -37,7 +37,7 @@ class InsulinLyumjevPluginTest { @Before fun setup() { - sut = InsulinLyumjevPlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) + sut = InsulinLyumjevPlugin(injector, rh, profileFunction, rxBus, aapsLogger) } @Test @@ -52,13 +52,13 @@ class InsulinLyumjevPluginTest { @Test fun commentStandardTextTest() { - `when`(resourceHelper.gs(eq(R.string.lyumjev))).thenReturn("Lyumjev") + `when`(rh.gs(eq(R.string.lyumjev))).thenReturn("Lyumjev") assertEquals("Lyumjev", sut.commentStandardText()) } @Test fun getFriendlyNameTest() { - `when`(resourceHelper.gs(eq(R.string.lyumjev))).thenReturn("Lyumjev") + `when`(rh.gs(eq(R.string.lyumjev))).thenReturn("Lyumjev") assertEquals("Lyumjev", sut.friendlyName) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt index 73e23dbd0e..dcd01949cd 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt @@ -30,12 +30,12 @@ class InsulinOrefBasePluginTest { inner class InsulinBaseTest( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, profileFunction: ProfileFunction, rxBus: RxBus, aapsLogger: AAPSLogger ) : InsulinOrefBasePlugin( - injector, resourceHelper, profileFunction, rxBus, aapsLogger + injector, rh, profileFunction, rxBus, aapsLogger ) { override fun sendShortDiaNotification(dia: Double) { @@ -61,7 +61,7 @@ class InsulinOrefBasePluginTest { private lateinit var sut: InsulinBaseTest @Mock lateinit var defaultValueHelper: DefaultValueHelper - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var rxBus: RxBus @Mock lateinit var aapsLogger: AAPSLogger @@ -74,7 +74,7 @@ class InsulinOrefBasePluginTest { @Before fun setUp() { - sut = InsulinBaseTest(injector, resourceHelper, profileFunction, rxBus, aapsLogger) + sut = InsulinBaseTest(injector, rh, profileFunction, rxBus, aapsLogger) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt index 11fba81c92..dfe7937972 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -26,7 +26,7 @@ class InsulinOrefFreePeakPluginTest : TestBase() { lateinit var sut: InsulinOrefFreePeakPlugin @Mock lateinit var sp: SP - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var profileFunction: ProfileFunction @@ -40,7 +40,7 @@ class InsulinOrefFreePeakPluginTest : TestBase() { sut = InsulinOrefFreePeakPlugin( injector, sp, - resourceHelper, + rh, profileFunction, rxBus, aapsLogger) @@ -60,13 +60,13 @@ class InsulinOrefFreePeakPluginTest : TestBase() { @Test fun commentStandardTextTest() { `when`(sp.getInt(eq(R.string.key_insulin_oref_peak), anyInt())).thenReturn(90) - `when`(resourceHelper.gs(eq(R.string.insulin_peak_time))).thenReturn("Peak Time [min]") + `when`(rh.gs(eq(R.string.insulin_peak_time))).thenReturn("Peak Time [min]") assertEquals("Peak Time [min]: 90", sut.commentStandardText()) } @Test fun getFriendlyNameTest() { - `when`(resourceHelper.gs(eq(R.string.free_peak_oref))).thenReturn("Free-Peak Oref") + `when`(rh.gs(eq(R.string.free_peak_oref))).thenReturn("Free-Peak Oref") assertEquals("Free-Peak Oref", sut.friendlyName) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt index 8c0b05e603..fcd6de648e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt @@ -25,7 +25,7 @@ class InsulinOrefRapidActingPluginTest { private lateinit var sut: InsulinOrefRapidActingPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var aapsLogger: AAPSLogger @@ -37,7 +37,7 @@ class InsulinOrefRapidActingPluginTest { @Before fun setup() { - sut = InsulinOrefRapidActingPlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) + sut = InsulinOrefRapidActingPlugin(injector, rh, profileFunction, rxBus, aapsLogger) } @Test @@ -52,13 +52,13 @@ class InsulinOrefRapidActingPluginTest { @Test fun commentStandardTextTest() { - `when`(resourceHelper.gs(eq(R.string.fastactinginsulincomment))).thenReturn("Novorapid, Novolog, Humalog") + `when`(rh.gs(eq(R.string.fastactinginsulincomment))).thenReturn("Novorapid, Novolog, Humalog") assertEquals("Novorapid, Novolog, Humalog", sut.commentStandardText()) } @Test fun getFriendlyNameTest() { - `when`(resourceHelper.gs(eq(R.string.rapid_acting_oref))).thenReturn("Rapid-Acting Oref") + `when`(rh.gs(eq(R.string.rapid_acting_oref))).thenReturn("Rapid-Acting Oref") assertEquals("Rapid-Acting Oref", sut.friendlyName) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt index f8da0bc1fc..88ecff887f 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt @@ -25,7 +25,7 @@ class InsulinOrefUltraRapidActingPluginTest { private lateinit var sut: InsulinOrefUltraRapidActingPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var aapsLogger: AAPSLogger @@ -37,7 +37,7 @@ class InsulinOrefUltraRapidActingPluginTest { @Before fun setup() { - sut = InsulinOrefUltraRapidActingPlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) + sut = InsulinOrefUltraRapidActingPlugin(injector, rh, profileFunction, rxBus, aapsLogger) } @Test @@ -52,13 +52,13 @@ class InsulinOrefUltraRapidActingPluginTest { @Test fun commentStandardTextTest() { - `when`(resourceHelper.gs(eq(R.string.ultrafastactinginsulincomment))).thenReturn("Fiasp") + `when`(rh.gs(eq(R.string.ultrafastactinginsulincomment))).thenReturn("Fiasp") assertEquals("Fiasp", sut.commentStandardText()) } @Test fun getFriendlyNameTest() { - `when`(resourceHelper.gs(eq(R.string.ultrarapid_oref))).thenReturn("Ultra-Rapid Oref") + `when`(rh.gs(eq(R.string.ultrarapid_oref))).thenReturn("Ultra-Rapid Oref") assertEquals("Ultra-Rapid Oref", sut.friendlyName) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt index c0c1c2b21e..3545c1e258 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.virtual import dagger.android.AndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.PumpSync @@ -24,11 +24,11 @@ class VirtualPumpPluginUTest : TestBase() { private val rxBus = RxBus(aapsSchedulers, aapsLogger) @Mock lateinit var fabricPrivacy: FabricPrivacy - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var iobCobCalculator: IobCobCalculator - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var dateUtil: DateUtil @Mock lateinit var pumpSync: PumpSync @@ -36,7 +36,7 @@ class VirtualPumpPluginUTest : TestBase() { @Before fun prepareMocks() { - virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, resourceHelper, aapsSchedulers, sp, profileFunction, iobCobCalculator, commandQueue, pumpSync, ConfigImpl(), dateUtil) + virtualPumpPlugin = VirtualPumpPlugin({ AndroidInjector { } }, aapsLogger, rxBus, fabricPrivacy, rh, aapsSchedulers, sp, profileFunction, iobCobCalculator, commandQueue, pumpSync, ConfigImpl(), dateUtil) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt index a35ff07f17..724e4f567a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -18,10 +18,10 @@ import org.mockito.Mock class AbstractSensitivityPluginTest : TestBase() { @Mock lateinit var pluginDescription: PluginDescription - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP - private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, HasAndroidInjector { AndroidInjector { } }, aapsLogger, resourceHelper, sp) { + private inner class SensitivityTestClass(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, rh: ResourceHelper, sp: SP) : AbstractSensitivityPlugin(pluginDescription, HasAndroidInjector { AndroidInjector { } }, aapsLogger, rh, sp) { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { return AutosensResult() @@ -37,7 +37,7 @@ class AbstractSensitivityPluginTest : TestBase() { @Test fun fillResultTest() { - val sut = SensitivityTestClass(pluginDescription, aapsLogger, resourceHelper, sp) + val sut = SensitivityTestClass(pluginDescription, aapsLogger, rh, sp) var ar = sut.fillResult(1.0, 1.0, "1", "1.2", "1", 12, 0.7, 1.2) Assert.assertEquals(1.0, ar.ratio, 0.01) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt index 882f754d6d..e6282c23c3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt @@ -14,12 +14,12 @@ class GlimpPluginTest : TestBase() { private lateinit var glimpPlugin: GlimpPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Before fun setup() { - glimpPlugin = GlimpPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger, sp) + glimpPlugin = GlimpPlugin(HasAndroidInjector { AndroidInjector { } }, rh, aapsLogger, sp) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt index a1c98901c8..e1c4662fd9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt @@ -14,12 +14,12 @@ class MM640GPluginTest : TestBase() { private lateinit var mM640gPlugin: MM640gPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Before fun setup() { - mM640gPlugin = MM640gPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger, sp) + mM640gPlugin = MM640gPlugin(HasAndroidInjector { AndroidInjector { } }, rh, aapsLogger, sp) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt index 0a1211596e..981c343bff 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt @@ -14,12 +14,12 @@ class NSClientPluginTest : TestBase() { private lateinit var nsClientSourcePlugin: NSClientSourcePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Before fun setup() { - nsClientSourcePlugin = NSClientSourcePlugin({ AndroidInjector { } }, resourceHelper, aapsLogger, ConfigImpl()) + nsClientSourcePlugin = NSClientSourcePlugin({ AndroidInjector { } }, rh, aapsLogger, ConfigImpl()) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt index 8b49149b3d..120bbcd235 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt @@ -13,11 +13,11 @@ class XdripPluginTest : TestBase() { private lateinit var xdripPlugin: XdripPlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Before fun setup() { - xdripPlugin = XdripPlugin(HasAndroidInjector { AndroidInjector { } }, resourceHelper, aapsLogger) + xdripPlugin = XdripPlugin(HasAndroidInjector { AndroidInjector { } }, rh, aapsLogger) } @Test fun advancedFilteringSupported() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt index a8c38819de..d097a38721 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt @@ -26,12 +26,12 @@ class TreatmentsPluginTest : TestBaseWithProfile() { @Before fun prepare() { - insulinOrefRapidActingPlugin = InsulinOrefRapidActingPlugin(profileInjector, resourceHelper, profileFunction, rxBus, aapsLogger) + insulinOrefRapidActingPlugin = InsulinOrefRapidActingPlugin(profileInjector, rh, profileFunction, rxBus, aapsLogger) `when`(profileFunction.getProfile(ArgumentMatchers.anyLong())).thenReturn(validProfile) `when`(activePluginProvider.activeInsulin).thenReturn(insulinOrefRapidActingPlugin) - sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, databaseHelper, repository) + sot = TreatmentsPlugin(profileInjector, aapsLogger, rxBus, aapsSchedulers, rh, context, sp, profileFunction, activePluginProvider, nsUpload, fabricPrivacy, dateUtil, databaseHelper, repository) sot.service = treatmentService } diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt similarity index 94% rename from app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt rename to app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt index 33ff47b5c4..4830daa3c8 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt @@ -39,7 +39,7 @@ import org.mockito.Mockito.`when` import org.mockito.Mockito.anyLong import java.util.* -class CommandQueueTest : TestBaseWithProfile() { +class CommandQueueImplementationTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var activePlugin: ActivePlugin @@ -53,7 +53,7 @@ class CommandQueueTest : TestBaseWithProfile() { aapsLogger: AAPSLogger, rxBus: RxBus, aapsSchedulers: AapsSchedulers, - resourceHelper: ResourceHelper, + rh: ResourceHelper, constraintChecker: ConstraintChecker, profileFunction: ProfileFunction, activePlugin: ActivePlugin, @@ -64,8 +64,8 @@ class CommandQueueTest : TestBaseWithProfile() { repository: AppRepository, fabricPrivacy: FabricPrivacy, config: Config - ) : CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, - activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy, config) { + ) : CommandQueueImplementation(injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, + activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy, config) { override fun notifyAboutNewCommand() {} @@ -75,7 +75,7 @@ class CommandQueueTest : TestBaseWithProfile() { AndroidInjector { if (it is Command) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh } if (it is CommandTempBasalPercent) { it.activePlugin = activePlugin @@ -94,17 +94,17 @@ class CommandQueueTest : TestBaseWithProfile() { it.activePlugin = activePlugin } if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } - private lateinit var commandQueue: CommandQueue + private lateinit var commandQueue: CommandQueueImplementation private lateinit var testPumpPlugin: TestPumpPlugin @Before fun prepare() { - commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, + commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelperImpl(ConfigImpl(), fileListProvider), dateUtil, repository, fabricPrivacy, config) @@ -133,15 +133,15 @@ class CommandQueueTest : TestBaseWithProfile() { `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(rateConstraint) val percentageConstraint = Constraint(0) `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint) - `when`(resourceHelper.gs(R.string.connectiontimedout)).thenReturn("Connection timed out") + `when`(rh.gs(R.string.connectiontimedout)).thenReturn("Connection timed out") } @Test fun commandIsPickedUp() { - val commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, - constraintChecker, profileFunction, activePlugin, context, sp, - BuildHelperImpl(ConfigImpl(), fileListProvider), dateUtil, repository, - fabricPrivacy, config) + val commandQueue = CommandQueueImplementation(injector, aapsLogger, rxBus, aapsSchedulers, rh, + constraintChecker, profileFunction, activePlugin, context, sp, + BuildHelperImpl(ConfigImpl(), fileListProvider), dateUtil, repository, + fabricPrivacy, config) // start with empty queue Assert.assertEquals(0, commandQueue.size()) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt index 7944588efd..9c6688791d 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt @@ -37,7 +37,7 @@ class QueueThreadTest : TestBaseWithProfile() { AndroidInjector { if (it is Command) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh } if (it is CommandTempBasalAbsolute) { it.activePlugin = activePlugin @@ -46,14 +46,14 @@ class QueueThreadTest : TestBaseWithProfile() { } private lateinit var pumpPlugin: TestPumpPlugin - private lateinit var commandQueue: CommandQueue + private lateinit var commandQueue: CommandQueueImplementation private lateinit var sut: QueueThread @Before fun prepare() { pumpPlugin = TestPumpPlugin(injector) - commandQueue = CommandQueue( - injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, + commandQueue = CommandQueueImplementation( + injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelperImpl(ConfigImpl(), fileListProvider), dateUtil, repository, fabricPrivacy, config ) @@ -76,7 +76,7 @@ class QueueThreadTest : TestBaseWithProfile() { Mockito.`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())) .thenReturn(percentageConstraint) - sut = QueueThread(commandQueue, context, aapsLogger, rxBus, activePlugin, resourceHelper, sp) + sut = QueueThread(commandQueue, context, aapsLogger, rxBus, activePlugin, rh, sp) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt index 383e283d9d..3a3c67cdfa 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt @@ -26,12 +26,12 @@ class BolusWizardTest : TestBase() { private val pumpBolusStep = 0.1 - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var context: Context @Mock lateinit var activePlugin: ActivePlugin - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var loopPlugin: LoopPlugin @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @@ -42,7 +42,7 @@ class BolusWizardTest : TestBase() { AndroidInjector { if (it is BolusWizard) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.rxBus = RxBus(aapsSchedulers, aapsLogger) it.profileFunction = profileFunction it.constraintChecker = constraintChecker diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt index 07ac5924d2..c372d1d216 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt @@ -47,6 +47,7 @@ class AutomationEvent(private val injector: HasAndroidInjector) { fun areActionsValid(): Boolean { var result = true for (action in actions) result = result && action.isValid() + if (!result) isEnabled = false return result } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt index 47c41918ee..6fd6d4a2c7 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt @@ -46,7 +46,7 @@ import javax.inject.Inject class AutomationFragment : DaggerFragment(), OnStartDragListener { @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var automationPlugin: AutomationPlugin @@ -160,14 +160,14 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { private fun addImage(@DrawableRes res: Int, context: Context, layout: LinearLayout) { val iv = ImageView(context) iv.setImageResource(res) - iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24)) + iv.layoutParams = LinearLayout.LayoutParams(rh.dpToPx(24), rh.dpToPx(24)) layout.addView(iv) } @SuppressLint("ClickableViewAccessibility") override fun onBindViewHolder(holder: ViewHolder, position: Int) { val event = automationPlugin.at(position) - holder.binding.rootLayout.setBackgroundColor(resourceHelper.gc( + holder.binding.rootLayout.setBackgroundColor(rh.gc( if (event.userAction) R.color.mdtp_line_dark else if (event.areActionsValid()) R.color.ribbonDefault else R.color.errorAlertBackground) @@ -186,8 +186,8 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { // arrow icon val iv = ImageView(holder.context) iv.setImageResource(R.drawable.ic_arrow_forward_white_24dp) - iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24)) - iv.setPadding(resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4), 0) + iv.layoutParams = LinearLayout.LayoutParams(rh.dpToPx(24), rh.dpToPx(24)) + iv.setPadding(rh.dpToPx(4), 0, rh.dpToPx(4), 0) holder.binding.iconLayout.addView(iv) // action icons val actionIcons = HashSet() @@ -221,7 +221,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { } // remove event holder.binding.iconTrash.setOnClickListener { - OKDialog.showConfirmation(requireContext(), resourceHelper.gs(R.string.removerecord) + " " + automationPlugin.at(position).title, + OKDialog.showConfirmation(requireContext(), rh.gs(R.string.removerecord) + " " + automationPlugin.at(position).title, { uel.log(Action.AUTOMATION_REMOVED, Sources.Automation, automationPlugin.at(position).title) automationPlugin.removeAt(position) @@ -246,7 +246,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { activity?.let { activity -> OKDialog.showConfirmation( activity, - resourceHelper.gs(R.string.removerecord) + " " + automationPlugin.at(position).title, + rh.gs(R.string.removerecord) + " " + automationPlugin.at(position).title, { uel.log(Action.AUTOMATION_REMOVED, Sources.Automation, automationPlugin.at(position).title) automationPlugin.removeAt(position) @@ -262,7 +262,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { override fun onItemSelected() = itemView.setBackgroundColor(Color.LTGRAY) - override fun onItemClear() = itemView.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) + override fun onItemClear() = itemView.setBackgroundColor(rh.gc(R.color.ribbonDefault)) } } } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index f8cd61486c..fafa93d117 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -43,7 +43,7 @@ import kotlin.collections.ArrayList @Singleton class AutomationPlugin @Inject constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val context: Context, private val sp: SP, private val fabricPrivacy: FabricPrivacy, @@ -67,7 +67,7 @@ class AutomationPlugin @Inject constructor( .alwaysEnabled(!config.APS) .preferencesId(R.xml.pref_automation) .description(R.string.automation_description), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private var disposable: CompositeDisposable = CompositeDisposable() @@ -105,7 +105,7 @@ class AutomationPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.io) .subscribe({ e -> - if (e.isChanged(resourceHelper, R.string.key_location)) { + if (e.isChanged(rh, R.string.key_location)) { locationServiceHelper.stopService(context) locationServiceHelper.startService(context) } @@ -189,7 +189,7 @@ class AutomationPlugin @Inject constructor( if (config.APS) { if (loopPlugin.isSuspended || !(loopPlugin as PluginBase).isEnabled()) { aapsLogger.debug(LTag.AUTOMATION, "Loop deactivated") - executionLog.add(resourceHelper.gs(R.string.loopisdisabled)) + executionLog.add(rh.gs(R.string.loopisdisabled)) userEventsEnabled = false } val enabled = constraintChecker.isAutomationEnabled() diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt index 69b3dc8346..26c9c5365b 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt @@ -6,6 +6,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONException import org.json.JSONObject import javax.inject.Inject @@ -13,6 +14,7 @@ import javax.inject.Inject abstract class Action(val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rh: ResourceHelper var precondition: Trigger? = null diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt index eb23d81e31..92f9064948 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt @@ -15,13 +15,11 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.TimerUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionAlarm(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var context: Context @Inject lateinit var dateUtil: DateUtil @@ -34,14 +32,14 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) { } override fun friendlyName(): Int = R.string.alarm - override fun shortDescription(): String = resourceHelper.gs(R.string.alarm_message, text.value) + override fun shortDescription(): String = rh.gs(R.string.alarm_message, text.value) @DrawableRes override fun icon(): Int = R.drawable.ic_access_alarm_24dp override fun isValid(): Boolean = true // empty alarm will show app name override fun doAction(callback: Callback) { timerUtil.scheduleReminder(dateUtil.now() + T.secs(10L).msecs(), text.value.takeIf { it.isNotBlank() } - ?: resourceHelper.gs(R.string.app_name)) + ?: rh.gs(R.string.app_name)) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } @@ -63,7 +61,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.alarm_short), "", text)) + .add(LabelWithElement(rh, rh.gs(R.string.alarm_short), "", text)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEvent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEvent.kt index 29bda8f6fc..5e3f3669eb 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEvent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEvent.kt @@ -13,13 +13,16 @@ import info.nightscout.androidaps.extensions.fromConstant import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger -import info.nightscout.androidaps.plugins.general.automation.elements.* +import info.nightscout.androidaps.plugins.general.automation.elements.InputCarePortalMenu +import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration +import info.nightscout.androidaps.plugins.general.automation.elements.InputString +import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement +import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign @@ -28,7 +31,6 @@ import javax.inject.Inject class ActionCarePortalEvent(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var repository: AppRepository @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @@ -41,15 +43,15 @@ class ActionCarePortalEvent(injector: HasAndroidInjector) : Action(injector) { var note = InputString() var duration = InputDuration(0, InputDuration.TimeUnit.MINUTES) - var cpEvent = InputCarePortalMenu(resourceHelper) + var cpEvent = InputCarePortalMenu(rh) private var valuesWithUnit = mutableListOf() private constructor(injector: HasAndroidInjector, actionCPEvent: ActionCarePortalEvent) : this(injector) { - cpEvent = InputCarePortalMenu(resourceHelper, actionCPEvent.cpEvent.value) + cpEvent = InputCarePortalMenu(rh, actionCPEvent.cpEvent.value) } override fun friendlyName(): Int = R.string.careportal - override fun shortDescription(): String = resourceHelper.gs(cpEvent.value.stringResWithValue, note.value) + override fun shortDescription(): String = rh.gs(cpEvent.value.stringResWithValue, note.value) @DrawableRes override fun icon(): Int = cpEvent.value.drawableRes @@ -110,8 +112,8 @@ class ActionCarePortalEvent(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() .add(cpEvent) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.duration_min_label), "", duration)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.notes_label), "", note)) + .add(LabelWithElement(rh, rh.gs(R.string.duration_min_label), "", duration)) + .add(LabelWithElement(rh, rh.gs(R.string.notes_label), "", note)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt index 9a22b5867c..0a4866c298 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisable.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.events.EventRefreshOverview -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.ConfigBuilder import info.nightscout.androidaps.interfaces.Loop import info.nightscout.androidaps.interfaces.PluginBase @@ -15,19 +15,18 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class ActionLoopDisable(injector: HasAndroidInjector) : Action(injector) { + @Inject lateinit var loopPlugin: Loop - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var configBuilder: ConfigBuilder - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var rxBus: RxBus @Inject lateinit var uel: UserEntryLogger override fun friendlyName(): Int = R.string.disableloop - override fun shortDescription(): String = resourceHelper.gs(R.string.disableloop) + override fun shortDescription(): String = rh.gs(R.string.disableloop) @DrawableRes override fun icon(): Int = R.drawable.ic_stop_24dp override fun doAction(callback: Callback) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt index e07f7b2b74..fef97824bd 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnable.kt @@ -14,19 +14,17 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class ActionLoopEnable(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var loopPlugin: Loop @Inject lateinit var configBuilder: ConfigBuilder @Inject lateinit var rxBus: RxBus @Inject lateinit var uel: UserEntryLogger override fun friendlyName(): Int = R.string.enableloop - override fun shortDescription(): String = resourceHelper.gs(R.string.enableloop) + override fun shortDescription(): String = rh.gs(R.string.enableloop) @DrawableRes override fun icon(): Int = R.drawable.ic_play_circle_outline_24dp override fun doAction(callback: Callback) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt index 812d05c5c7..bafd2e21ad 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt @@ -16,13 +16,12 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import javax.inject.Inject class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var loopPlugin: Loop @Inject lateinit var configBuilder: ConfigBuilder @Inject lateinit var rxBus: RxBus @@ -31,7 +30,7 @@ class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var dateUtil: DateUtil override fun friendlyName(): Int = R.string.resumeloop - override fun shortDescription(): String = resourceHelper.gs(R.string.resumeloop) + override fun shortDescription(): String = rh.gs(R.string.resumeloop) @DrawableRes override fun icon(): Int = R.drawable.ic_replay_24dp val disposable = CompositeDisposable() @@ -40,10 +39,10 @@ class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) { if (loopPlugin.isSuspended) { disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now())) .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } + }, { + aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) + }) rxBus.send(EventRefreshOverview("ActionLoopResume")) uel.log(UserEntry.Action.RESUME, Sources.Automation, title) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt index 486f22e1df..a1c568b6a9 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.kt @@ -17,12 +17,11 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var loopPlugin: Loop @Inject lateinit var rxBus: RxBus @Inject lateinit var uel: UserEntryLogger @@ -30,15 +29,17 @@ class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { var minutes = InputDuration(30, InputDuration.TimeUnit.MINUTES) override fun friendlyName(): Int = R.string.suspendloop - override fun shortDescription(): String = resourceHelper.gs(R.string.suspendloopforXmin, minutes.getMinutes()) + override fun shortDescription(): String = rh.gs(R.string.suspendloopforXmin, minutes.getMinutes()) @DrawableRes override fun icon(): Int = R.drawable.ic_pause_circle_outline_24dp override fun doAction(callback: Callback) { if (!loopPlugin.isSuspended) { loopPlugin.suspendLoop(minutes.getMinutes()) rxBus.send(EventRefreshOverview("ActionLoopSuspend")) - uel.log(UserEntry.Action.SUSPEND, Sources.Automation, title + ": " + resourceHelper.gs(R.string.suspendloopforXmin, minutes.getMinutes()), - ValueWithUnit.Minute(minutes.getMinutes())) + uel.log( + UserEntry.Action.SUSPEND, Sources.Automation, title + ": " + rh.gs(R.string.suspendloopforXmin, minutes.getMinutes()), + ValueWithUnit.Minute(minutes.getMinutes()) + ) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended))?.run() @@ -63,7 +64,7 @@ class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.duration_min_label), "", minutes)) + .add(LabelWithElement(rh, rh.gs(R.string.duration_min_label), "", minutes)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt index 865044bf3f..488b21608e 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt @@ -16,7 +16,6 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.json.JSONObject @@ -24,7 +23,6 @@ import javax.inject.Inject class ActionNotification(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var repository: AppRepository @@ -33,7 +31,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) { var text = InputString() override fun friendlyName(): Int = R.string.notification - override fun shortDescription(): String = resourceHelper.gs(R.string.notification_message, text.value) + override fun shortDescription(): String = rh.gs(R.string.notification_message, text.value) @DrawableRes override fun icon(): Int = R.drawable.ic_notifications override fun doAction(callback: Callback) { @@ -62,7 +60,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.message_short), "", text)) + .add(LabelWithElement(rh, rh.gs(R.string.message_short), "", text)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt index 38985b833a..83119e47a8 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt @@ -9,8 +9,8 @@ import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement @@ -18,21 +18,20 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuil import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger - var inputProfileName: InputProfileName = InputProfileName(resourceHelper, activePlugin, "") + var inputProfileName: InputProfileName = InputProfileName(rh, activePlugin, "") override fun friendlyName(): Int = R.string.profilename - override fun shortDescription(): String = resourceHelper.gs(R.string.changengetoprofilename, inputProfileName.value) + override fun shortDescription(): String = rh.gs(R.string.changengetoprofilename, inputProfileName.value) @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch override fun doAction(callback: Callback) { @@ -59,16 +58,18 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { callback.result(PumpEnactResult(injector).success(false).comment(R.string.notexists))?.run() return } - uel.log(UserEntry.Action.PROFILE_SWITCH, Sources.Automation, title, + uel.log( + UserEntry.Action.PROFILE_SWITCH, Sources.Automation, title, ValueWithUnit.SimpleString(inputProfileName.value), - ValueWithUnit.Percent(100)) - profileFunction.createProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, dateUtil.now()) - callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() + ValueWithUnit.Percent(100) + ) + val result = profileFunction.createProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, dateUtil.now()) + callback.result(PumpEnactResult(injector).success(result).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.profilename), "", inputProfileName)) + .add(LabelWithElement(rh, rh.gs(R.string.profilename), "", inputProfileName)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt index 0634021564..353f91ce27 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt @@ -19,13 +19,11 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuil import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var uel: UserEntryLogger @@ -34,8 +32,8 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector override fun friendlyName(): Int = R.string.profilepercentage override fun shortDescription(): String = - if (duration.value == 0) resourceHelper.gs(R.string.startprofileforever, pct.value.toInt()) - else resourceHelper.gs(R.string.startprofile, pct.value.toInt(), duration.value) + if (duration.value == 0) rh.gs(R.string.startprofileforever, pct.value.toInt()) + else rh.gs(R.string.startprofile, pct.value.toInt(), duration.value) @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch @@ -48,20 +46,21 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector uel.log( UserEntry.Action.PROFILE_SWITCH, Sources.Automation, - title + ": " + resourceHelper.gs(R.string.startprofile, pct.value.toInt(), duration.value), + title + ": " + rh.gs(R.string.startprofile, pct.value.toInt(), duration.value), ValueWithUnit.Percent(pct.value.toInt()), ValueWithUnit.Minute(duration.value) ) + callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } else { aapsLogger.error(LTag.AUTOMATION, "Final profile not valid") + callback.result(PumpEnactResult(injector).success(false).comment(R.string.ok))?.run() } - callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.percent_u), "", pct)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.duration_min_label), "", duration)) + .add(LabelWithElement(rh, rh.gs(R.string.percent_u), "", pct)) + .add(LabelWithElement(rh, rh.gs(R.string.duration_min_label), "", duration)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt index 446eeb4cee..4c96e33784 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt @@ -10,19 +10,17 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import javax.inject.Inject class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var smsCommunicatorPlugin: SmsCommunicator var text = InputString() override fun friendlyName(): Int = R.string.sendsmsactiondescription - override fun shortDescription(): String = resourceHelper.gs(R.string.sendsmsactionlabel, text.value) + override fun shortDescription(): String = rh.gs(R.string.sendsmsactionlabel, text.value) override fun icon(): Int = R.drawable.ic_notifications override fun doAction(callback: Callback) { @@ -50,7 +48,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.sendsmsactiontext), "", text)) + .add(LabelWithElement(rh, rh.gs(R.string.sendsmsactiontext), "", text)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index 6775c1b34b..61a9d25952 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -5,7 +5,6 @@ import androidx.annotation.DrawableRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TemporaryTarget @@ -13,7 +12,10 @@ import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction +import info.nightscout.androidaps.extensions.friendlyDescription import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.GlucoseUnit +import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger @@ -27,9 +29,6 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper.safeGetDouble -import info.nightscout.androidaps.extensions.friendlyDescription -import info.nightscout.androidaps.interfaces.GlucoseUnit -import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.json.JSONObject @@ -38,7 +37,6 @@ import javax.inject.Inject class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var repository: AppRepository @Inject lateinit var profileFunction: ProfileFunction @@ -55,7 +53,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { } override fun friendlyName(): Int = R.string.starttemptarget - override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper) + override fun shortDescription(): String = rh.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, rh) @DrawableRes override fun icon(): Int = R.drawable.ic_temptarget_high override fun doAction(callback: Callback) { @@ -65,8 +63,8 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } uel.log(UserEntry.Action.TT, Sources.Automation, title, ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.AUTOMATION), - ValueWithUnit.fromGlucoseUnit(tt().lowTarget, Constants.MGDL), - ValueWithUnit.fromGlucoseUnit(tt().highTarget, Constants.MGDL).takeIf { tt().lowTarget != tt().highTarget }, + ValueWithUnit.fromGlucoseUnit(tt().lowTarget, value.units.asText), + ValueWithUnit.fromGlucoseUnit(tt().highTarget, value.units.asText).takeIf { tt().lowTarget != tt().highTarget }, ValueWithUnit.Minute(TimeUnit.MILLISECONDS.toMinutes(tt().duration).toInt())) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() }, { @@ -78,8 +76,8 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { override fun generateDialog(root: LinearLayout) { val unitResId = if (value.units == GlucoseUnit.MGDL) R.string.mgdl else R.string.mmol LayoutBuilder() - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.careportal_temporarytarget) + "\n[" + resourceHelper.gs(unitResId) + "]", "", value)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.duration_min_label), "", duration)) + .add(LabelWithElement(rh, rh.gs(R.string.careportal_temporarytarget) + "\n[" + rh.gs(unitResId) + "]", "", value)) + .add(LabelWithElement(rh, rh.gs(R.string.duration_min_label), "", duration)) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt index 9d4443d466..50a19b144e 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt @@ -11,14 +11,12 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import javax.inject.Inject class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { - @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger @@ -26,17 +24,17 @@ class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { private val disposable = CompositeDisposable() override fun friendlyName(): Int = R.string.stoptemptarget - override fun shortDescription(): String = resourceHelper.gs(R.string.stoptemptarget) + override fun shortDescription(): String = rh.gs(R.string.stoptemptarget) override fun icon(): Int = R.drawable.ic_stop_24dp override fun doAction(callback: Callback) { disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now())) .subscribe({ result -> - uel.log(UserEntry.Action.CANCEL_TT, Sources.Automation, title) - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) - }) + uel.log(UserEntry.Action.CANCEL_TT, Sources.Automation, title) + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } + }, { + aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) + }) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt index 538d78afca..c20789e4d0 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt @@ -13,7 +13,7 @@ import javax.inject.Inject class ChooseOperationDialog : DialogFragmentWithDate() { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper private var checkedIndex = -1 @@ -61,7 +61,7 @@ class ChooseOperationDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - for (t in TriggerConnector.Type.labels(resourceHelper)) { + for (t in TriggerConnector.Type.labels(rh)) { val radioButton = RadioButton(context) radioButton.text = t binding.chooseOperationRadioGroup.addView(radioButton) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt index dd872a88c5..c7f7149757 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt @@ -10,7 +10,7 @@ import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.resources.ResourceHelper -class Comparator(private val resourceHelper: ResourceHelper) : Element() { +class Comparator(private val rh: ResourceHelper) : Element() { enum class Compare { IS_LESSER, @@ -44,17 +44,17 @@ class Comparator(private val resourceHelper: ResourceHelper) : Element() { companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() for (c in values()) { - list.add(resourceHelper.gs(c.stringRes)) + list.add(rh.gs(c.stringRes)) } return list } } } - constructor(resourceHelper: ResourceHelper, value: Compare) : this(resourceHelper) { + constructor(rh: ResourceHelper, value: Compare) : this(rh) { this.value = value } @@ -63,11 +63,11 @@ class Comparator(private val resourceHelper: ResourceHelper) : Element() { override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(1), 0, resourceHelper.dpToPx(1)) + setMargins(0, rh.dpToPx(1), 0, rh.dpToPx(1)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt index 60d49c49eb..6b18559767 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt @@ -10,7 +10,7 @@ import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.resources.ResourceHelper -class ComparatorConnect(private val resourceHelper: ResourceHelper) : Element() { +class ComparatorConnect(private val rh: ResourceHelper) : Element() { enum class Compare { ON_CONNECT, ON_DISCONNECT; @@ -23,15 +23,15 @@ class ComparatorConnect(private val resourceHelper: ResourceHelper) : Element() companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() - for (c in values()) list.add(resourceHelper.gs(c.stringRes)) + for (c in values()) list.add(rh.gs(c.stringRes)) return list } } } - constructor(resourceHelper: ResourceHelper, value: Compare) : this(resourceHelper) { + constructor(rh: ResourceHelper, value: Compare) : this(rh) { this.value = value } @@ -40,12 +40,12 @@ class ComparatorConnect(private val resourceHelper: ResourceHelper) : Element() override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt index 0812d7c798..c9b1b421de 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt @@ -10,7 +10,7 @@ import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.resources.ResourceHelper -class ComparatorExists(private val resourceHelper: ResourceHelper, var value: Compare = Compare.EXISTS) : Element() { +class ComparatorExists(private val rh: ResourceHelper, var value: Compare = Compare.EXISTS) : Element() { enum class Compare { EXISTS, NOT_EXISTS; @@ -23,9 +23,9 @@ class ComparatorExists(private val resourceHelper: ResourceHelper, var value: Co companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() - for (c in values()) list.add(resourceHelper.gs(c.stringRes)) + for (c in values()) list.add(rh.gs(c.stringRes)) return list } } @@ -34,11 +34,11 @@ class ComparatorExists(private val resourceHelper: ResourceHelper, var value: Co override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Compare.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt index 5ac9798ae2..ab82beffe0 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.utils.resources.ResourceHelper -class InputCarePortalMenu(private val resourceHelper: ResourceHelper) : Element() { +class InputCarePortalMenu(private val rh: ResourceHelper) : Element() { enum class EventType(val therapyEventType: TherapyEvent.Type) { NOTE(TherapyEvent.Type.NOTE), @@ -45,17 +45,17 @@ class InputCarePortalMenu(private val resourceHelper: ResourceHelper) : Element( companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() for (e in values()) { - list.add(resourceHelper.gs(e.stringRes)) + list.add(rh.gs(e.stringRes)) } return list } } } - constructor(resourceHelper: ResourceHelper, value: EventType) : this(resourceHelper) { + constructor(rh: ResourceHelper, value: EventType) : this(rh) { this.value = value } @@ -64,11 +64,11 @@ class InputCarePortalMenu(private val resourceHelper: ResourceHelper) : Element( override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, EventType.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, EventType.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt index 2ded79d1d9..fb1f779f0f 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt @@ -12,10 +12,10 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* -class InputDateTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() { +class InputDateTime(private val rh: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() { override fun addToLayout(root: LinearLayout) { - val px = resourceHelper.dpToPx(10) + val px = rh.dpToPx(10) root.addView( LinearLayout(root.context).apply { @@ -23,7 +23,7 @@ class InputDateTime(private val resourceHelper: ResourceHelper, private val date layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) addView( TextView(root.context).apply { - text = resourceHelper.gs(R.string.atspecifiedtime, "") + text = rh.gs(R.string.atspecifiedtime, "") setTypeface(typeface, Typeface.BOLD) setPadding(px, px, px, px) }) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt index e6b4484f44..946c0576e1 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat -class InputDelta(private val resourceHelper: ResourceHelper) : Element() { +class InputDelta(private val rh: ResourceHelper) : Element() { enum class DeltaType { DELTA, SHORT_AVERAGE, LONG_AVERAGE; @@ -26,10 +26,10 @@ class InputDelta(private val resourceHelper: ResourceHelper) : Element() { companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() for (d in values()) { - list.add(resourceHelper.gs(d.stringRes)) + list.add(rh.gs(d.stringRes)) } return list } @@ -43,7 +43,7 @@ class InputDelta(private val resourceHelper: ResourceHelper) : Element() { private var decimalFormat: DecimalFormat? = null var deltaType: DeltaType = DeltaType.DELTA - constructor(resourceHelper: ResourceHelper, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat, deltaType: DeltaType) : this(resourceHelper) { + constructor(rh: ResourceHelper, value: Double, minValue: Double, maxValue: Double, step: Double, decimalFormat: DecimalFormat, deltaType: DeltaType) : this(rh) { this.value = value this.minValue = minValue this.maxValue = maxValue @@ -52,7 +52,7 @@ class InputDelta(private val resourceHelper: ResourceHelper) : Element() { this.deltaType = deltaType } - constructor(resourceHelper: ResourceHelper, inputDelta: InputDelta) : this(resourceHelper) { + constructor(rh: ResourceHelper, inputDelta: InputDelta) : this(rh) { value = inputDelta.value minValue = inputDelta.minValue maxValue = inputDelta.maxValue @@ -64,11 +64,11 @@ class InputDelta(private val resourceHelper: ResourceHelper) : Element() { override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, DeltaType.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, DeltaType.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt index 7ec5dbc62e..4929bb3278 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt @@ -10,17 +10,17 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* -class InputDropdownMenu(private val resourceHelper: ResourceHelper) : Element() { +class InputDropdownMenu(private val rh: ResourceHelper) : Element() { private var itemList: ArrayList = ArrayList() var value: String = "" - constructor(resourceHelper: ResourceHelper, name: String) : this(resourceHelper) { + constructor(rh: ResourceHelper, name: String) : this(rh) { value = name } @Suppress("unused") - constructor(resourceHelper: ResourceHelper, another: InputDropdownMenu) : this(resourceHelper) { + constructor(rh: ResourceHelper, another: InputDropdownMenu) : this(rh) { value = another.value } @@ -31,7 +31,7 @@ class InputDropdownMenu(private val resourceHelper: ResourceHelper) : Element() setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).also { - it.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + it.setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt index 234d2016e3..0a4200aae9 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt @@ -10,7 +10,7 @@ import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.resources.ResourceHelper -class InputLocationMode(private val resourceHelper: ResourceHelper) : Element() { +class InputLocationMode(private val rh: ResourceHelper) : Element() { enum class Mode { INSIDE, OUTSIDE, GOING_IN, GOING_OUT; @@ -32,10 +32,10 @@ class InputLocationMode(private val resourceHelper: ResourceHelper) : Element() companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() for (c in values()) { - list.add(resourceHelper.gs(c.stringRes)) + list.add(rh.gs(c.stringRes)) } return list } @@ -44,18 +44,18 @@ class InputLocationMode(private val resourceHelper: ResourceHelper) : Element() var value: Mode = Mode.INSIDE - constructor(resourceHelper: ResourceHelper, value: InputLocationMode.Mode) : this(resourceHelper) { + constructor(rh: ResourceHelper, value: InputLocationMode.Mode) : this(rh) { this.value = value } override fun addToLayout(root: LinearLayout) { root.addView( Spinner(root.context).apply { - adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Mode.labels(resourceHelper)).apply { + adapter = ArrayAdapter(root.context, R.layout.spinner_centered, Mode.labels(rh)).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } val spinnerParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } layoutParams = spinnerParams onItemSelectedListener = object : AdapterView.OnItemSelectedListener { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt index 6af8d3ab9a..d28a78408f 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.utils.resources.ResourceHelper -class InputProfileName(private val resourceHelper: ResourceHelper, private val activePlugin: ActivePlugin, val name: String = "") : Element() { +class InputProfileName(private val rh: ResourceHelper, private val activePlugin: ActivePlugin, val name: String = "") : Element() { var value: String = name @@ -24,7 +24,7 @@ class InputProfileName(private val resourceHelper: ResourceHelper, private val a setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply { - setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) + setMargins(0, rh.dpToPx(4), 0, rh.dpToPx(4)) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt index bdb9e66bd0..fcee35b411 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* -class InputTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() { +class InputTime(private val rh: ResourceHelper, private val dateUtil: DateUtil) : Element() { var value: Int = getMinSinceMidnight(dateUtil.now()) @@ -25,13 +25,13 @@ class InputTime(private val resourceHelper: ResourceHelper, private val dateUtil layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) addView( TextView(root.context).apply { - text = resourceHelper.gs(R.string.atspecifiedtime, "") + text = rh.gs(R.string.atspecifiedtime, "") setTypeface(typeface, Typeface.BOLD) }) addView( TextView(root.context).apply { text = dateUtil.timeString(toMills(value)) - val px = resourceHelper.dpToPx(10) + val px = rh.dpToPx(10) setPadding(px, px, px, px) setOnClickListener { root.context?.let { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt index e011d7ee54..343f617a27 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt @@ -14,17 +14,17 @@ import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* -class InputTimeRange(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() { +class InputTimeRange(private val rh: ResourceHelper, private val dateUtil: DateUtil) : Element() { var start: Int = getMinSinceMidnight(dateUtil.now()) var end: Int = getMinSinceMidnight(dateUtil.now()) override fun addToLayout(root: LinearLayout) { - val px = resourceHelper.dpToPx(10) + val px = rh.dpToPx(10) root.addView( TextView(root.context).apply { - text = resourceHelper.gs(R.string.between) + text = rh.gs(R.string.between) setTypeface(typeface, Typeface.BOLD) gravity = Gravity.CENTER_HORIZONTAL }) @@ -56,7 +56,7 @@ class InputTimeRange(private val resourceHelper: ResourceHelper, private val dat }) addView(TextView(root.context).apply { @Suppress("SetTextI18n") - text = resourceHelper.gs(R.string.and) + " " + dateUtil.timeString(toMills(end)) + text = rh.gs(R.string.and) + " " + dateUtil.timeString(toMills(end)) setPadding(px, px, px, px) setOnClickListener { root.context?.let { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt index d69e3504d5..648ee6a397 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt @@ -7,7 +7,7 @@ import android.widget.TextView import info.nightscout.androidaps.utils.resources.ResourceHelper class LabelWithElement( - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, var textPre: String = "", var textPost: String = "", var element: Element? = null, @@ -15,7 +15,7 @@ class LabelWithElement( override fun addToLayout(root: LinearLayout) { // container layout // text view pre element - val px = resourceHelper.dpToPx(1) + val px = rh.dpToPx(1) root.addView( TextView(root.context).apply { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt index 6510457264..57ef1c09c7 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt @@ -7,28 +7,28 @@ import android.widget.TextView import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.utils.resources.ResourceHelper -class StaticLabel(private val resourceHelper: ResourceHelper) : Element() { +class StaticLabel(private val rh: ResourceHelper) : Element() { var label = "" var trigger: Trigger? = null - constructor(resourceHelper: ResourceHelper, label: String, trigger: Trigger) : this(resourceHelper) { + constructor(rh: ResourceHelper, label: String, trigger: Trigger) : this(rh) { this.label = label this.trigger = trigger } - constructor(resourceHelper: ResourceHelper, resourceId: Int, trigger: Trigger) : this(resourceHelper) { - label = resourceHelper.gs(resourceId) + constructor(rh: ResourceHelper, resourceId: Int, trigger: Trigger) : this(rh) { + label = rh.gs(resourceId) this.trigger = trigger } override fun addToLayout(root: LinearLayout) { - val px = resourceHelper.dpToPx(10) + val px = rh.dpToPx(10) root.addView( LinearLayout(root.context).apply { orientation = LinearLayout.HORIZONTAL layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) - setBackgroundColor(resourceHelper.gc(android.R.color.black)) + setBackgroundColor(rh.gc(android.R.color.black)) addView( TextView(root.context).apply { text = label diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index fd9e7295c4..e9c1160edf 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -32,7 +32,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var sp: SP @Inject lateinit var locationDataContainer: LastLocationDataContainer @@ -132,7 +132,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { gravity = Gravity.CENTER } setImageResource(R.drawable.ic_add) - contentDescription = resourceHelper.gs(R.string.add_short) + contentDescription = rh.gs(R.string.add_short) setOnClickListener { scanForActivity(context)?.supportFragmentManager?.let { val dialog = ChooseTriggerDialog() @@ -154,7 +154,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { gravity = Gravity.CENTER } setImageResource(R.drawable.ic_remove) - contentDescription = resourceHelper.gs(R.string.delete_short) + contentDescription = rh.gs(R.string.delete_short) setOnClickListener { rxBus.send(EventTriggerRemove(trigger)) } @@ -168,7 +168,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { } layoutParams = params setImageResource(R.drawable.ic_clone) - contentDescription = resourceHelper.gs(R.string.copy_short) + contentDescription = rh.gs(R.string.copy_short) setOnClickListener { rxBus.send(EventTriggerClone(trigger)) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt index 45fc094d6a..cad06f303d 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt @@ -22,11 +22,11 @@ class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) { private val decimalFormat = DecimalFormat("1") var autosens: InputDouble = InputDouble(100.0, minValue.toDouble(), maxValue.toDouble(), step, decimalFormat) - var comparator: Comparator = Comparator(resourceHelper) + var comparator: Comparator = Comparator(rh) private constructor(injector: HasAndroidInjector, triggerAutosensValue: TriggerAutosensValue) : this(injector) { autosens = InputDouble(triggerAutosensValue.autosens) - comparator = Comparator(resourceHelper, triggerAutosensValue.comparator.value) + comparator = Comparator(rh, triggerAutosensValue.comparator.value) } override fun shouldRun(): Boolean { @@ -61,7 +61,7 @@ class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.autosenslabel override fun friendlyDescription(): String = - resourceHelper.gs(R.string.autosenscompared, resourceHelper.gs(comparator.value.stringRes), autosens.value) + rh.gs(R.string.autosenscompared, rh.gs(comparator.value.stringRes), autosens.value) override fun icon(): Optional = Optional.of(R.drawable.ic_as) @@ -69,9 +69,9 @@ class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.autosenslabel, this)) + .add(StaticLabel(rh, R.string.autosenslabel, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.autosenslabel) + ": ", "", autosens)) + .add(LabelWithElement(rh, rh.gs(R.string.autosenslabel) + ": ", "", autosens)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDevice.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDevice.kt index 292a29cda6..36d4297ef2 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDevice.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBTDevice.kt @@ -22,11 +22,11 @@ class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) { @Inject lateinit var context: Context @Inject lateinit var automationPlugin: AutomationPlugin - var btDevice = InputDropdownMenu(resourceHelper, "") - var comparator: ComparatorConnect = ComparatorConnect(resourceHelper) + var btDevice = InputDropdownMenu(rh, "") + var comparator: ComparatorConnect = ComparatorConnect(rh) private constructor(injector: HasAndroidInjector, triggerBTDevice: TriggerBTDevice) : this(injector) { - comparator = ComparatorConnect(resourceHelper, triggerBTDevice.comparator.value) + comparator = ComparatorConnect(rh, triggerBTDevice.comparator.value) btDevice.value = triggerBTDevice.btDevice.value } @@ -54,7 +54,7 @@ class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.btdevice override fun friendlyDescription(): String = - resourceHelper.gs(R.string.btdevicecompared, btDevice.value, resourceHelper.gs(comparator.value.stringRes)) + rh.gs(R.string.btdevicecompared, btDevice.value, rh.gs(comparator.value.stringRes)) override fun icon(): Optional = Optional.of(R.drawable.ic_bluetooth_white_48dp) @@ -64,7 +64,7 @@ class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) { val pairedDevices = devicesPaired() btDevice.setList(pairedDevices) LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.btdevice, this)) + .add(StaticLabel(rh, R.string.btdevice, this)) .add(btDevice) .add(comparator) .build(root) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt index b28654035d..85564f6360 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt @@ -19,16 +19,16 @@ import org.json.JSONObject class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { var bg = InputBg(profileFunction) - var comparator = Comparator(resourceHelper) + var comparator = Comparator(rh) constructor(injector: HasAndroidInjector, value: Double, units: GlucoseUnit, compare: Comparator.Compare) : this(injector) { bg = InputBg(profileFunction, value, units) - comparator = Comparator(resourceHelper, compare) + comparator = Comparator(rh, compare) } constructor(injector: HasAndroidInjector, triggerBg: TriggerBg) : this(injector) { bg = InputBg(profileFunction, triggerBg.bg.value, triggerBg.bg.units) - comparator = Comparator(resourceHelper, triggerBg.comparator.value) + comparator = Comparator(rh, triggerBg.comparator.value) } fun setUnits(units: GlucoseUnit): TriggerBg { @@ -82,9 +82,9 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String { return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) - resourceHelper.gs(R.string.glucoseisnotavailable) + rh.gs(R.string.glucoseisnotavailable) else - resourceHelper.gs(if (bg.units == GlucoseUnit.MGDL) R.string.glucosecomparedmgdl else R.string.glucosecomparedmmol, resourceHelper.gs(comparator.value.stringRes), bg.value, bg.units) + rh.gs(if (bg.units == GlucoseUnit.MGDL) R.string.glucosecomparedmgdl else R.string.glucosecomparedmmol, rh.gs(comparator.value.stringRes), bg.value, bg.units) } override fun icon(): Optional = Optional.of(R.drawable.ic_cp_bgcheck) @@ -93,9 +93,9 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.glucose, this)) + .add(StaticLabel(rh, R.string.glucose, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.glucose_u, bg.units), "", bg)) + .add(LabelWithElement(rh, rh.gs(R.string.glucose_u, bg.units), "", bg)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt index 74f3b77648..9d8c979448 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt @@ -19,11 +19,11 @@ import org.json.JSONObject class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { var minutesAgo: InputDuration = InputDuration(30, InputDuration.TimeUnit.MINUTES) - var comparator: Comparator = Comparator(resourceHelper) + var comparator: Comparator = Comparator(rh) private constructor(injector: HasAndroidInjector, triggerBolusAgo: TriggerBolusAgo) : this(injector) { minutesAgo = InputDuration(triggerBolusAgo.minutesAgo.value, InputDuration.TimeUnit.MINUTES) - comparator = Comparator(resourceHelper, triggerBolusAgo.comparator.value) + comparator = Comparator(rh, triggerBolusAgo.comparator.value) } fun setValue(value: Int): TriggerBolusAgo { @@ -73,7 +73,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.lastboluslabel override fun friendlyDescription(): String = - resourceHelper.gs(R.string.lastboluscompared, resourceHelper.gs(comparator.value.stringRes), minutesAgo.getMinutes()) + rh.gs(R.string.lastboluscompared, rh.gs(comparator.value.stringRes), minutesAgo.getMinutes()) override fun icon(): Optional = Optional.of(R.drawable.ic_bolus) @@ -81,9 +81,9 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.lastboluslabel, this)) + .add(StaticLabel(rh, R.string.lastboluslabel, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.lastboluslabel) + ": ", resourceHelper.gs(R.string.unit_minutes), minutesAgo)) + .add(LabelWithElement(rh, rh.gs(R.string.lastboluslabel) + ": ", rh.gs(R.string.unit_minutes), minutesAgo)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt index dda052bcaf..c582f8103d 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt @@ -20,11 +20,11 @@ class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { private val minValue = 0 private val maxValue = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48) var cob: InputDouble = InputDouble(0.0, minValue.toDouble(), maxValue.toDouble(), 1.0, DecimalFormat("1")) - var comparator: Comparator = Comparator(resourceHelper) + var comparator: Comparator = Comparator(rh) private constructor(injector: HasAndroidInjector, triggerCOB: TriggerCOB) : this(injector) { cob = InputDouble(triggerCOB.cob) - comparator = Comparator(resourceHelper, triggerCOB.comparator.value) + comparator = Comparator(rh, triggerCOB.comparator.value) } fun setValue(value: Double): TriggerCOB { @@ -71,7 +71,7 @@ class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.triggercoblabel override fun friendlyDescription(): String = - resourceHelper.gs(R.string.cobcompared, resourceHelper.gs(comparator.value.stringRes), cob.value) + rh.gs(R.string.cobcompared, rh.gs(comparator.value.stringRes), cob.value) override fun icon(): Optional = Optional.of(R.drawable.ic_cp_bolus_carbs) @@ -79,9 +79,9 @@ class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.triggercoblabel, this)) + .add(StaticLabel(rh, R.string.triggercoblabel, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.triggercoblabel) + ": ", "", cob)) + .add(LabelWithElement(rh, rh.gs(R.string.triggercoblabel) + ": ", "", cob)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt index 8a4c667d85..9e6bc5d3eb 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt @@ -43,10 +43,10 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { companion object { - fun labels(resourceHelper: ResourceHelper): List { + fun labels(rh: ResourceHelper): List { val list: MutableList = ArrayList() for (t in values()) { - list.add(resourceHelper.gs(t.stringRes)) + list.add(rh.gs(t.stringRes)) } return list } @@ -109,7 +109,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { val result = StringBuilder() for ((counter, t) in list.withIndex()) { if (counter > 0) - result.append("\n").append(resourceHelper.gs(friendlyName())).append("\n") + result.append("\n").append(rh.gs(friendlyName())).append("\n") result.append(t.friendlyDescription()) } return result.toString() @@ -124,7 +124,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { it.orientation = LinearLayout.HORIZONTAL it.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } - val padding = resourceHelper.dpToPx(3) + val padding = rh.dpToPx(3) mainLayout.setPadding(padding, padding, padding, padding) mainLayout.setBackgroundResource(R.drawable.border_automation_unit) @@ -146,7 +146,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { val listLayout = LinearLayout(root.context).also { it.orientation = LinearLayout.VERTICAL it.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { params -> - params.setMargins(resourceHelper.dpToPx(1), 0, resourceHelper.dpToPx(1), resourceHelper.dpToPx(2)) + params.setMargins(rh.dpToPx(1), 0, rh.dpToPx(1), rh.dpToPx(2)) } } for (t in list) { @@ -154,7 +154,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { listLayout.addView( TextView(root.context).also { it.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) - it.setPadding(0, resourceHelper.dpToPx(0.3f), 0, 0) + it.setPadding(0, rh.dpToPx(0.3f), 0, 0) }) } rightSideLayout.addView(listLayout) @@ -167,12 +167,12 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { private fun createVerticalView(context: Context): VerticalTextView = VerticalTextView(context).apply { - text = resourceHelper.gs(connectorType.stringRes) + text = rh.gs(connectorType.stringRes) gravity = gravity or Gravity.CENTER_VERTICAL setTypeface(typeface, Typeface.BOLD) - setBackgroundColor(resourceHelper.gc(R.color.black_overlay)) + setBackgroundColor(rh.gc(R.color.black_overlay)) layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT).also { ll -> - ll.setMargins(resourceHelper.dpToPx(3), resourceHelper.dpToPx(3), resourceHelper.dpToPx(3), resourceHelper.dpToPx(3)) + ll.setMargins(rh.dpToPx(3), rh.dpToPx(3), rh.dpToPx(3), rh.dpToPx(3)) } setOnClickListener { scanForActivity(context)?.supportFragmentManager?.let { @@ -181,7 +181,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { override fun run() { result?.let { result -> setType(Type.values()[result]) - text = resourceHelper.gs(connectorType.stringRes) + text = rh.gs(connectorType.stringRes) } } }) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt index 4b93bd6076..fc44c27227 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt @@ -21,8 +21,8 @@ import java.text.DecimalFormat class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { var units: GlucoseUnit = GlucoseUnit.MGDL - var delta: InputDelta = InputDelta(resourceHelper) - var comparator: Comparator = Comparator(resourceHelper) + var delta: InputDelta = InputDelta(rh) + var comparator: Comparator = Comparator(rh) companion object { @@ -32,8 +32,8 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { init { units = profileFunction.getUnits() - delta = if (units == GlucoseUnit.MMOL) InputDelta(resourceHelper, 0.0, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), DeltaType.DELTA) - else InputDelta(resourceHelper, 0.0, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), DeltaType.DELTA) + delta = if (units == GlucoseUnit.MMOL) InputDelta(rh, 0.0, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), DeltaType.DELTA) + else InputDelta(rh, 0.0, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), DeltaType.DELTA) } constructor(injector: HasAndroidInjector, inputDelta: InputDelta, units: GlucoseUnit, comparator: Comparator.Compare) : this(injector) { @@ -44,8 +44,8 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { private constructor(injector: HasAndroidInjector, triggerDelta: TriggerDelta) : this(injector) { units = triggerDelta.units - delta = InputDelta(resourceHelper, triggerDelta.delta) - comparator = Comparator(resourceHelper, triggerDelta.comparator.value) + delta = InputDelta(rh, triggerDelta.delta) + comparator = Comparator(rh, triggerDelta.comparator.value) } fun units(units: GlucoseUnit): TriggerDelta { @@ -99,8 +99,8 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { val type = DeltaType.valueOf(JsonHelper.safeGetString(d, "deltaType", "")) val value = JsonHelper.safeGetDouble(d, "value") delta = - if (units == GlucoseUnit.MMOL) InputDelta(resourceHelper, value, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), type) - else InputDelta(resourceHelper, value, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), type) + if (units == GlucoseUnit.MMOL) InputDelta(rh, value, (-MMOL_MAX), MMOL_MAX, 0.1, DecimalFormat("0.1"), type) + else InputDelta(rh, value, (-MGDL_MAX), MGDL_MAX, 1.0, DecimalFormat("1"), type) comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this } @@ -108,7 +108,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.deltalabel override fun friendlyDescription(): String = - resourceHelper.gs(R.string.deltacompared, resourceHelper.gs(comparator.value.stringRes), delta.value, resourceHelper.gs(delta.deltaType.stringRes)) + rh.gs(R.string.deltacompared, rh.gs(comparator.value.stringRes), delta.value, rh.gs(delta.deltaType.stringRes)) override fun icon(): Optional = Optional.of(R.drawable.ic_auto_delta) @@ -116,9 +116,9 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.deltalabel, this)) + .add(StaticLabel(rh, R.string.deltalabel, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.deltalabel_u, units) + ": ", "", delta)) + .add(LabelWithElement(rh, rh.gs(R.string.deltalabel_u, units) + ": ", "", delta)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt index 8707c6c576..cc17bbcf52 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt @@ -15,11 +15,11 @@ import org.json.JSONObject class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { var insulin = InputInsulin() - var comparator: Comparator = Comparator(resourceHelper) + var comparator: Comparator = Comparator(rh) constructor(injector: HasAndroidInjector, triggerIob: TriggerIob) : this(injector) { insulin = InputInsulin(triggerIob.insulin) - comparator = Comparator(resourceHelper, triggerIob.comparator.value) + comparator = Comparator(rh, triggerIob.comparator.value) } fun setValue(value: Double): TriggerIob { @@ -58,7 +58,7 @@ class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.iob override fun friendlyDescription(): String = - resourceHelper.gs(R.string.iobcompared, resourceHelper.gs(comparator.value.stringRes), insulin.value) + rh.gs(R.string.iobcompared, rh.gs(comparator.value.stringRes), insulin.value) override fun icon(): Optional = Optional.of(R.drawable.ic_keyboard_capslock) @@ -66,9 +66,9 @@ class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.iob, this)) + .add(StaticLabel(rh, R.string.iob, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.iob_u), "", insulin)) + .add(LabelWithElement(rh, rh.gs(R.string.iob_u), "", insulin)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt index f9fbbfc27b..94d98ff603 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt @@ -16,7 +16,7 @@ class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { var latitude = InputDouble(0.0, -90.0, +90.0, 0.000001, DecimalFormat("0.000000")) var longitude = InputDouble(0.0, -180.0, +180.0, 0.000001, DecimalFormat("0.000000")) var distance = InputDouble(200.0, 0.0, 100000.0, 10.0, DecimalFormat("0")) - var modeSelected = InputLocationMode(resourceHelper) + var modeSelected = InputLocationMode(rh) var name: InputString = InputString() var lastMode = InputLocationMode.Mode.INSIDE @@ -32,7 +32,7 @@ class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { latitude = InputDouble(triggerLocation.latitude) longitude = InputDouble(triggerLocation.longitude) distance = InputDouble(triggerLocation.distance) - modeSelected = InputLocationMode(resourceHelper, triggerLocation.modeSelected.value) + modeSelected = InputLocationMode(rh, triggerLocation.modeSelected.value) if (modeSelected.value == InputLocationMode.Mode.GOING_OUT) lastMode = InputLocationMode.Mode.OUTSIDE name = triggerLocation.name @@ -79,7 +79,7 @@ class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.location override fun friendlyDescription(): String = - resourceHelper.gs(R.string.locationis, resourceHelper.gs(modeSelected.value.stringRes), " " + name.value) + rh.gs(R.string.locationis, rh.gs(modeSelected.value.stringRes), " " + name.value) override fun icon(): Optional = Optional.of(R.drawable.ic_location_on) @@ -87,13 +87,13 @@ class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.location, this)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.name_short), "", name)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.latitude_short), "", latitude)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.longitude_short), "", longitude)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.distance_short), "", distance)) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.location_mode), "", modeSelected)) - .maybeAdd(InputButton(resourceHelper.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null) + .add(StaticLabel(rh, R.string.location, this)) + .add(LabelWithElement(rh, rh.gs(R.string.name_short), "", name)) + .add(LabelWithElement(rh, rh.gs(R.string.latitude_short), "", latitude)) + .add(LabelWithElement(rh, rh.gs(R.string.longitude_short), "", longitude)) + .add(LabelWithElement(rh, rh.gs(R.string.distance_short), "", distance)) + .add(LabelWithElement(rh, rh.gs(R.string.location_mode), "", modeSelected)) + .maybeAdd(InputButton(rh.gs(R.string.currentlocation), buttonAction), locationDataContainer.lastLocation != null) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt index d03022cc18..bea8e799a1 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt @@ -17,16 +17,16 @@ import org.json.JSONObject class TriggerProfilePercent(injector: HasAndroidInjector) : Trigger(injector) { var pct = InputPercent() - var comparator = Comparator(resourceHelper) + var comparator = Comparator(rh) constructor(injector: HasAndroidInjector, value: Double, compare: Comparator.Compare) : this(injector) { pct = InputPercent(value) - comparator = Comparator(resourceHelper, compare) + comparator = Comparator(rh, compare) } constructor(injector: HasAndroidInjector, triggerProfilePercent: TriggerProfilePercent) : this(injector) { pct = InputPercent(triggerProfilePercent.pct.value) - comparator = Comparator(resourceHelper, triggerProfilePercent.comparator.value) + comparator = Comparator(rh, triggerProfilePercent.comparator.value) } fun setValue(value: Double): TriggerProfilePercent { @@ -80,7 +80,7 @@ class TriggerProfilePercent(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.profilepercentage override fun friendlyDescription(): String = - resourceHelper.gs(R.string.percentagecompared, resourceHelper.gs(comparator.value.stringRes), pct.value.toInt()) + rh.gs(R.string.percentagecompared, rh.gs(comparator.value.stringRes), pct.value.toInt()) override fun icon(): Optional = Optional.of(R.drawable.ic_actions_profileswitch) @@ -88,9 +88,9 @@ class TriggerProfilePercent(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.profilepercentage, this)) + .add(StaticLabel(rh, R.string.profilepercentage, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.percent_u), "", pct)) + .add(LabelWithElement(rh, rh.gs(R.string.percent_u), "", pct)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt index cfcdd788ba..8472a64814 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt @@ -17,17 +17,17 @@ import org.json.JSONObject class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector) { var minutesAgo = InputDuration() - var comparator = Comparator(resourceHelper) + var comparator = Comparator(rh) @Suppress("unused") constructor(injector: HasAndroidInjector, value: Int, unit: InputDuration.TimeUnit, compare: Comparator.Compare) : this(injector) { minutesAgo = InputDuration(value, unit) - comparator = Comparator(resourceHelper, compare) + comparator = Comparator(rh, compare) } constructor(injector: HasAndroidInjector, triggerPumpLastConnection: TriggerPumpLastConnection) : this(injector) { minutesAgo = InputDuration(triggerPumpLastConnection.minutesAgo.value, triggerPumpLastConnection.minutesAgo.unit) - comparator = Comparator(resourceHelper, triggerPumpLastConnection.comparator.value) + comparator = Comparator(rh, triggerPumpLastConnection.comparator.value) } fun setValue(value: Int): TriggerPumpLastConnection { @@ -71,7 +71,7 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector override fun friendlyName(): Int = R.string.automation_trigger_pump_last_connection_label override fun friendlyDescription(): String = - resourceHelper.gs(R.string.automation_trigger_pump_last_connection_compared, resourceHelper.gs(comparator.value.stringRes), minutesAgo.value) + rh.gs(R.string.automation_trigger_pump_last_connection_compared, rh.gs(comparator.value.stringRes), minutesAgo.value) override fun icon(): Optional = Optional.of(R.drawable.ic_remove) @@ -79,9 +79,9 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.automation_trigger_pump_last_connection_label, this)) + .add(StaticLabel(rh, R.string.automation_trigger_pump_last_connection_label, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.automation_trigger_pump_last_connection_description) + ": ", "", minutesAgo)) + .add(LabelWithElement(rh, rh.gs(R.string.automation_trigger_pump_last_connection_description) + ": ", "", minutesAgo)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt index aefd11b83a..cc9df0d5c7 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt @@ -18,7 +18,7 @@ import java.util.* class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { val days = InputWeekDay() - val time = InputTime(resourceHelper, dateUtil) + val time = InputTime(rh, dateUtil) constructor(injector: HasAndroidInjector, triggerRecurringTime: TriggerRecurringTime) : this(injector) { this.time.value = triggerRecurringTime.time.value @@ -72,16 +72,16 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String { val sb = StringBuilder() - sb.append(resourceHelper.gs(R.string.every)) + sb.append(rh.gs(R.string.every)) sb.append(" ") var counter = 0 for (i in days.getSelectedDays()) { if (counter++ > 0) sb.append(",") - sb.append(resourceHelper.gs(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(i)).shortName)) + sb.append(rh.gs(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(i)).shortName)) } sb.append(" ") sb.append(dateUtil.timeString(toMills(time.value))) - return if (counter == 0) resourceHelper.gs(R.string.never) else sb.toString() + return if (counter == 0) rh.gs(R.string.never) else sb.toString() } override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) @@ -94,7 +94,7 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.recurringTime, this)) + .add(StaticLabel(rh, R.string.recurringTime, this)) .add(days) .add(time) .build(root) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt index 216e84871d..1a0b707b83 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt @@ -14,14 +14,14 @@ import org.json.JSONObject class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { - var comparator = ComparatorExists(resourceHelper) + var comparator = ComparatorExists(rh) constructor(injector: HasAndroidInjector, compare: ComparatorExists.Compare) : this(injector) { - comparator = ComparatorExists(resourceHelper, compare) + comparator = ComparatorExists(rh, compare) } constructor(injector: HasAndroidInjector, triggerTempTarget: TriggerTempTarget) : this(injector) { - comparator = ComparatorExists(resourceHelper, triggerTempTarget.comparator.value) + comparator = ComparatorExists(rh, triggerTempTarget.comparator.value) } fun comparator(comparator: ComparatorExists.Compare): TriggerTempTarget { @@ -56,7 +56,7 @@ class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.careportal_temporarytarget override fun friendlyDescription(): String = - resourceHelper.gs(R.string.temptargetcompared, resourceHelper.gs(comparator.value.stringRes)) + rh.gs(R.string.temptargetcompared, rh.gs(comparator.value.stringRes)) override fun icon(): Optional = Optional.of(R.drawable.ic_keyboard_tab) @@ -64,7 +64,7 @@ class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.careportal_temporarytarget, this)) + .add(StaticLabel(rh, R.string.careportal_temporarytarget, this)) .add(comparator) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetValue.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetValue.kt index 96d83c0326..fbd0e560e5 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetValue.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetValue.kt @@ -20,16 +20,16 @@ import org.json.JSONObject class TriggerTempTargetValue(injector: HasAndroidInjector) : Trigger(injector) { var ttValue = InputBg(profileFunction) - var comparator = Comparator(resourceHelper) + var comparator = Comparator(rh) constructor(injector: HasAndroidInjector, value: Double, units: GlucoseUnit, compare: Comparator.Compare) : this(injector) { ttValue = InputBg(profileFunction, value, units) - comparator = Comparator(resourceHelper, compare) + comparator = Comparator(rh, compare) } constructor(injector: HasAndroidInjector, triggerTempTarget: TriggerTempTargetValue) : this(injector) { ttValue = InputBg(profileFunction, triggerTempTarget.ttValue.value, triggerTempTarget.ttValue.units) - comparator = Comparator(resourceHelper, triggerTempTarget.comparator.value) + comparator = Comparator(rh, triggerTempTarget.comparator.value) } fun comparator(comparator: Comparator.Compare): TriggerTempTargetValue { @@ -79,9 +79,9 @@ class TriggerTempTargetValue(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String { return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) - resourceHelper.gs(R.string.notemptarget) + rh.gs(R.string.notemptarget) else - resourceHelper.gs(if (ttValue.units == GlucoseUnit.MGDL) R.string.temptargetcomparedmgdl else R.string.temptargetcomparedmmol, resourceHelper.gs(comparator.value.stringRes), ttValue.value, ttValue.units) + rh.gs(if (ttValue.units == GlucoseUnit.MGDL) R.string.temptargetcomparedmgdl else R.string.temptargetcomparedmmol, rh.gs(comparator.value.stringRes), ttValue.value, ttValue.units) } override fun icon(): Optional = Optional.of(R.drawable.ic_keyboard_tab) @@ -90,9 +90,9 @@ class TriggerTempTargetValue(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.careportal_temporarytargetvalue, this)) + .add(StaticLabel(rh, R.string.careportal_temporarytargetvalue, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.target_u, ttValue.units), "", ttValue)) + .add(LabelWithElement(rh, rh.gs(R.string.target_u, ttValue.units), "", ttValue)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt index f03c35c6fc..1e3bbd7347 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt @@ -14,7 +14,7 @@ import org.json.JSONObject class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { - var time = InputDateTime(resourceHelper, dateUtil) + var time = InputDateTime(rh, dateUtil) constructor(injector: HasAndroidInjector, runAt: Long) : this(injector) { this.time.value = runAt @@ -53,7 +53,7 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.time override fun friendlyDescription(): String = - resourceHelper.gs(R.string.atspecifiedtime, dateUtil.dateAndTimeString(time.value)) + rh.gs(R.string.atspecifiedtime, dateUtil.dateAndTimeString(time.value)) override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) @@ -61,7 +61,7 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.time, this)) + .add(StaticLabel(rh, R.string.time, this)) .add(time) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt index 3a56314706..44ccddd278 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt @@ -17,7 +17,7 @@ import org.json.JSONObject class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { // in minutes since midnight 60 means 1AM - var range = InputTimeRange(resourceHelper, dateUtil) + var range = InputTimeRange(rh, dateUtil) constructor(injector: HasAndroidInjector, start: Int, end: Int) : this(injector) { range.start = start @@ -64,7 +64,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.time_range override fun friendlyDescription(): String = - resourceHelper.gs(R.string.timerange_value, dateUtil.timeString(toMills(range.start)), dateUtil.timeString(toMills(range.end))) + rh.gs(R.string.timerange_value, dateUtil.timeString(toMills(range.start)), dateUtil.timeString(toMills(range.end))) override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) @@ -76,7 +76,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.time_range, this)) + .add(StaticLabel(rh, R.string.time_range, this)) .add(range) .build(root) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt index 8fa919e8c3..28b5768189 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt @@ -20,17 +20,17 @@ class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { @Inject lateinit var receiverStatusStore: ReceiverStatusStore var ssid = InputString() - var comparator = Comparator(resourceHelper) + var comparator = Comparator(rh) @Suppress("unused") constructor(injector: HasAndroidInjector, ssid: String, compare: Comparator.Compare) : this(injector) { this.ssid = InputString(ssid) - comparator = Comparator(resourceHelper, compare) + comparator = Comparator(rh, compare) } constructor(injector: HasAndroidInjector, triggerWifiSsid: TriggerWifiSsid) : this(injector) { this.ssid = InputString(triggerWifiSsid.ssid.value) - comparator = Comparator(resourceHelper, triggerWifiSsid.comparator.value) + comparator = Comparator(rh, triggerWifiSsid.comparator.value) } fun setValue(ssid: String): TriggerWifiSsid { @@ -72,7 +72,7 @@ class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.ns_wifi_ssids override fun friendlyDescription(): String = - resourceHelper.gs(R.string.wifissidcompared, resourceHelper.gs(comparator.value.stringRes), ssid.value) + rh.gs(R.string.wifissidcompared, rh.gs(comparator.value.stringRes), ssid.value) override fun icon(): Optional = Optional.of(R.drawable.ic_network_wifi) @@ -80,9 +80,9 @@ class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { override fun generateDialog(root: LinearLayout) { LayoutBuilder() - .add(StaticLabel(resourceHelper, R.string.ns_wifi_ssids, this)) + .add(StaticLabel(rh, R.string.ns_wifi_ssids, this)) .add(comparator) - .add(LabelWithElement(resourceHelper, resourceHelper.gs(R.string.ns_wifi_ssids) + ": ", "", ssid)) + .add(LabelWithElement(rh, rh.gs(R.string.ns_wifi_ssids) + ": ", "", ssid)) .build(root) } } \ No newline at end of file diff --git a/automation/src/main/res/values-bg-rBG/strings.xml b/automation/src/main/res/values-bg-rBG/strings.xml index 0a5d42ab5f..4229418173 100644 --- a/automation/src/main/res/values-bg-rBG/strings.xml +++ b/automation/src/main/res/values-bg-rBG/strings.xml @@ -38,6 +38,9 @@ КЗ не е достъпна КЗ %1$s %2$.0f %3$s КЗ %1$s %2$.1f %3$s + Времената цел не съществува + Временна цел %1$s %2$.0f %3$s + Временна цел %1$s %2$.1f %3$s Профил процент %1$s %2$d IOB %1$s %2$.1f И @@ -86,6 +89,7 @@ Ширина: Дължина: КЗ [%1$s]: + Цел [%1$s]: Последен болус Последен болус преди %1$s %2$s минути Активни въглехидрати @@ -101,9 +105,11 @@ РЕД Избиране на действие Иберете условие + Избери тип на операция Активиращи условия: ИЗТРИИ Предварителни условия: Събитие Подреди + Потребителско действие diff --git a/automation/src/main/res/values-ca-rES/strings.xml b/automation/src/main/res/values-ca-rES/strings.xml index 2c3eb7c126..e1bcb612e6 100644 --- a/automation/src/main/res/values-ca-rES/strings.xml +++ b/automation/src/main/res/values-ca-rES/strings.xml @@ -1,16 +1,61 @@ + Auto + Automatització Tasques d\'automatització definides per l\'usuari Introduïu un nom de tasca. Especifiqueu almenys un activador. Especifiqueu almenys una acció. + Alarma: %1$s + Alarma: + Msstg: + Ja activat + Ja desactivat Ja aturat No aturat Aturar el llaç durant %1$d min Avís: %1$s + Canviar perfil a + Canviar perfil a %1$s + Darrera connexió a la bomba + Darrera connexió a la bomba [minuts transcorreguts] + Darrera connexió a la bomba fa %1$s %2$s min + Ja definit + Percentatge de perfil + Iniciar perfil %1$d%% + Percentatge [%]: + Enviar SMS: %1$s + Enviar SMS amb text + Iniciar objectiu temporal + Aturar objectiu temporal + és menor que + és igual o menor que + és igual a + és igual o més gran que + és més gran que + no està disponible + Glucèmia no disponible + Glucèmia %1$s %2$.0f %3$s + Glucèmia %1$s %2$.1f %3$s + L’Objectiu Temporal no existeix + Objectiu Temporal %1$s %2$.0f %3$s + Objectiu Temporal %1$s %2$.1f %3$s + O + Exclusiu o + A les %1$s + Utilitzar ubicació de xarxa + Utilitzar ubicació GPS + Utilitzar ubicació passiva + Servei d\'ubicació + En connectar + En desconnectar Delta mitjana curta Delta mitjana llarga Delta + Quan + Quan sigueu dins la zona + Quan sigueu fora de la zona + Quan entreu a l\'àrea anomenada Dg Ds Dv diff --git a/automation/src/main/res/values-fr-rFR/strings.xml b/automation/src/main/res/values-fr-rFR/strings.xml index a42641de69..c580c81d44 100644 --- a/automation/src/main/res/values-fr-rFR/strings.xml +++ b/automation/src/main/res/values-fr-rFR/strings.xml @@ -105,9 +105,11 @@ ÉDITER Choisir un type d\'action Choisir un type de déclencheur + Choisissez un type d\'opération Déclencheurs : SUPPRIMER Conditions préalables : Evénement auto. Réordonner + Actions utilisateur diff --git a/automation/src/main/res/values-hu-rHU/strings.xml b/automation/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/automation/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/automation/src/main/res/values-it-rIT/strings.xml b/automation/src/main/res/values-it-rIT/strings.xml index fb8001f975..2ff0e7466f 100644 --- a/automation/src/main/res/values-it-rIT/strings.xml +++ b/automation/src/main/res/values-it-rIT/strings.xml @@ -105,9 +105,11 @@ MODIFICA Scegli un tipo di azione Scegli un tipo di trigger + Scegli un tipo di operazione Trigger: RIMUOVI Presupposti: Evento di automazione Riordina + Azione utente diff --git a/automation/src/main/res/values-iw-rIL/strings.xml b/automation/src/main/res/values-iw-rIL/strings.xml index 46a2efd8ef..5ba51cb7fa 100644 --- a/automation/src/main/res/values-iw-rIL/strings.xml +++ b/automation/src/main/res/values-iw-rIL/strings.xml @@ -105,9 +105,11 @@ עריכה בחרו סוג פעולה בחירת סוג הטריגר + נא לבחור סוג פעולה טריגרים: הסר תנאים מוקדמים: אירוע אוטומציה סדר מחדש + פעולות משתמש diff --git a/automation/src/main/res/values-no-rNO/strings.xml b/automation/src/main/res/values-no-rNO/strings.xml index 1df8018334..9ddd8db943 100644 --- a/automation/src/main/res/values-no-rNO/strings.xml +++ b/automation/src/main/res/values-no-rNO/strings.xml @@ -105,9 +105,11 @@ REDIGER Velg en handling Velg en trigger type + Velg en handling Triggere: FJERN Forutsetninger: Automasjons hendelse Endre rekkefølge + Bruker handling diff --git a/automation/src/main/res/values-ro-rRO/strings.xml b/automation/src/main/res/values-ro-rRO/strings.xml index 9a8f99b0df..f2886728d1 100644 --- a/automation/src/main/res/values-ro-rRO/strings.xml +++ b/automation/src/main/res/values-ro-rRO/strings.xml @@ -105,9 +105,11 @@ EDITARE Selectați tipul de acțiune Selectați un tip de factor declanșator + Alege tipul de operațiune Declanșatori: ȘTERGE Condiții pre-existente: Eveniment automatizare Reordonează + Acțiunea utilizatorului diff --git a/automation/src/main/res/values-ru-rRU/strings.xml b/automation/src/main/res/values-ru-rRU/strings.xml index 9557684a9a..96a71d6cd0 100644 --- a/automation/src/main/res/values-ru-rRU/strings.xml +++ b/automation/src/main/res/values-ru-rRU/strings.xml @@ -105,9 +105,11 @@ РЕДАКТ Выберите тип действия Выберите тип триггера + Выберите тип действия Триггеры: УДАЛИТЬ Предусловия: Автоматизированное событие Повторный заказ + Действия пользователя diff --git a/automation/src/main/res/values-sk-rSK/strings.xml b/automation/src/main/res/values-sk-rSK/strings.xml index b06dc622ac..4e39609a62 100644 --- a/automation/src/main/res/values-sk-rSK/strings.xml +++ b/automation/src/main/res/values-sk-rSK/strings.xml @@ -105,9 +105,11 @@ EDIT Vyberte akciu Vyberte typ podmienky + Vyberte typ operácie Podmienky: VYMAZAŤ Predpoklady: Udalosť automatiky Zmena poradia + Akcia užívateľa diff --git a/automation/src/main/res/values-sv-rSE/strings.xml b/automation/src/main/res/values-sv-rSE/strings.xml index 58b952a2ab..98c412a7db 100644 --- a/automation/src/main/res/values-sv-rSE/strings.xml +++ b/automation/src/main/res/values-sv-rSE/strings.xml @@ -105,9 +105,11 @@ ÄNDRA Välj en åtgärd Vänligen välj typ av utlösare + Välj en åtgärdstyp Utlösare: TA BORT Förutsättningar: Automationshändelse Ändra ordning + Användaråtgärd diff --git a/automation/src/main/res/values-tr-rTR/strings.xml b/automation/src/main/res/values-tr-rTR/strings.xml index 452c77aa68..4375cca0f0 100644 --- a/automation/src/main/res/values-tr-rTR/strings.xml +++ b/automation/src/main/res/values-tr-rTR/strings.xml @@ -1,13 +1,70 @@ - Hali hazır iptal edilmiş - %1$d dak döngüyü duraklat + Otomatik + Otomasyon + Kullanıcı tanımlı otomasyon görevleri + Lütfen bir görev adı girin. + Lütfen en az bir tetikleyici belirtin. + Lütfen en az bir işlem belirtin. + Alarm: %1$s + Alarm: + Msj: + Zaten etkin + Zaten devre dışı + Zaten askıya alındı + Askıya alınmadı + %1$d dk. döngüyü duraklat + Bildirim: %1$s + Profili değiştir + Profili %1$s olarak değiştir + Pompayla son bağlantı + Pompayla son bağlantı [dakika önce] + Pompayla son bağlantı %1$s %2$s dakika önce + Zaten ayarlanmış + Profil yüzdesi + Profil %1$d%% başladı + Yüzde [%]: + SMS gönder: %1$s + Tüm numaralara SMS gönder + Metin ile SMS gönder + Geçici hedefi başlat + Geçici hedefi durdur + küçükse + eşit veya küçükse + eşitse + eşit veya büyükse + büyükse + mevcut değil Glikoz verileri mevcut değil + Glukoz %1$s %2$.0f %3$s + Glukoz %1$s %2$.1f %3$s + Geçici Hedef mevcut değil + Geçici Hedef %1$s %2$.0f %3$s + Geçici Hedef %1$s %2$.1f %3$s + Profil yüzdesi %1$s %2$d + Aktif insülin %1$s %2$.1f Ve Veya + Özel veya + %1$s\'de + Ağ konumunu kullan + GPS konumunu kullan + Pasif konumu kullan + Konum servisi + Bağlandığında + Bağlantı kesildiğinde Kısa ortalama delta Uzun ortalama delta Delta + %1$s %2$s + Ne zaman + Bölgenin içindeyken + Alanın dışında olduğunuzda + Adlı alana girdiğinizde + Adlı alandan ayrıldığınızda + Zaman aralığı + %1$s ile %2$s arasında + Arasında Pzr Cts Cum @@ -15,5 +72,44 @@ Çrş Salı Pzt + SİL EKLE + KOPYALA + Geçici hedef %1$s + %1$s %2$s cihazına Bluetooth bağlantısı + Bluetooth cihazına bağlantı + WiFi SSID %1$s %2$s + Otoduyarlılık %1$s %2$s %% + Otoduyarlılık % + %3$s %1$s %2$s + KŞ farkı + KŞ farkı [%1$s] + Mevcut konum + Konum + Enlem: + Boylam: + Glukoz [%1$s]: + Hedef [%1$s]: + Son bolus önce + Son bolus zamanı %1$s %2$s dakika önce + COB + AK (COB) %1$s %2$.0f + IOB [U]: + Mesafe [m]: + Yinelenen zaman + Her + Asla + Koşul: + Aksiyon: + Görev adı + DÜZENLE + Eylem tipini seçin + Tetikleyici tipini seçin + İşlem tipini seçin + Tetikleyiciler: + KALDIR + Ön koşullar: + Otomasyon durumu + Yeniden sırala + Kullanıcı Hareketleri diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt index 8f6673c375..30b8fe078e 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt @@ -20,7 +20,7 @@ import org.mockito.Mock class AutomationEventTest : TestBase() { @Mock lateinit var loopPlugin: Loop - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var configBuilder: ConfigBuilder var injector: HasAndroidInjector = HasAndroidInjector { @@ -33,7 +33,7 @@ class AutomationEventTest : TestBase() { } if (it is ActionLoopEnable) { it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.configBuilder = configBuilder it.rxBus = RxBus(aapsSchedulers, aapsLogger) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt index 79a9b09d7f..37e7e01ad7 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt @@ -24,7 +24,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper @@ -34,7 +34,7 @@ open class TestBaseWithProfile : TestBase() { val rxBus = RxBus(aapsSchedulers, aapsLogger) - val profileInjector = HasAndroidInjector { + private val profileInjector = HasAndroidInjector { AndroidInjector { } } @@ -45,7 +45,9 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) } @@ -57,4 +59,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt index cb63dea9ec..892bf09e12 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt @@ -19,10 +19,10 @@ import org.json.JSONObject @Suppress("MemberVisibilityCanBePrivate") class TestPumpPlugin(pluginDescription: PluginDescription, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, injector: HasAndroidInjector ) : PluginBase( - pluginDescription, aapsLogger, resourceHelper, injector + pluginDescription, aapsLogger, rh, injector ), Pump { var connected = false diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt index 4b3b12bc18..d49a9fcc83 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt @@ -21,7 +21,7 @@ import org.mockito.Mockito.`when` class ActionAlarmTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var context: Context @Mock lateinit var timerUtil: TimerUtil @@ -31,23 +31,23 @@ class ActionAlarmTest : TestBase() { var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is ActionAlarm) { - it.resourceHelper = resourceHelper + it.rh = rh it.rxBus = rxBus it.context = context it.timerUtil = timerUtil it.dateUtil = dateUtil } if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } @Before fun setup() { - `when`(resourceHelper.gs(R.string.ok)).thenReturn("OK") - `when`(resourceHelper.gs(R.string.alarm)).thenReturn("Alarm") - `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.alarm_message), ArgumentMatchers.anyString())).thenReturn("Alarm: %s") + `when`(rh.gs(R.string.ok)).thenReturn("OK") + `when`(rh.gs(R.string.alarm)).thenReturn("Alarm") + `when`(rh.gs(ArgumentMatchers.eq(R.string.alarm_message), ArgumentMatchers.anyString())).thenReturn("Alarm: %s") sut = ActionAlarm(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEventTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEventTest.kt index 2507c1cb85..8badae72d2 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEventTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionCarePortalEventTest.kt @@ -23,7 +23,7 @@ class ActionCarePortalEventTest : ActionsTestBase() { fun setup() { `when`(sp.getString(ArgumentMatchers.anyString(), ArgumentMatchers.anyString())).thenReturn("AndroidAPS") `when`( - resourceHelper.gs( + rh.gs( ArgumentMatchers.eq(R.string.careportal_note_message), ArgumentMatchers.anyString() ) @@ -34,7 +34,7 @@ class ActionCarePortalEventTest : ActionsTestBase() { .thenReturn(Single.just(InsertIfNewByTimestampTherapyEventTransaction.TransactionResult().apply { })) sut = ActionCarePortalEvent(injector) - sut.cpEvent = InputCarePortalMenu(resourceHelper) + sut.cpEvent = InputCarePortalMenu(rh) sut.cpEvent.value = InputCarePortalMenu.EventType.NOTE sut.note = InputString("Asd") sut.duration = InputDuration(5, InputDuration.TimeUnit.MINUTES) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt index c50f16ea5a..17858ebea5 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.kt @@ -18,8 +18,8 @@ class ActionLoopDisableTest : ActionsTestBase() { fun setup() { testPumpPlugin.pumpDescription.isTempBasalCapable = true - `when`(resourceHelper.gs(R.string.disableloop)).thenReturn("Disable loop") - `when`(resourceHelper.gs(R.string.alreadydisabled)).thenReturn("Disable loop") + `when`(rh.gs(R.string.disableloop)).thenReturn("Disable loop") + `when`(rh.gs(R.string.alreadydisabled)).thenReturn("Disable loop") sut = ActionLoopDisable(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.kt index e7bc6e5320..0ab4e677f2 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.kt @@ -17,8 +17,8 @@ class ActionLoopEnableTest : ActionsTestBase() { fun setup() { testPumpPlugin.pumpDescription.isTempBasalCapable = true - `when`(resourceHelper.gs(R.string.enableloop)).thenReturn("Enable loop") - `when`(resourceHelper.gs(R.string.alreadyenabled)).thenReturn("Already enabled") + `when`(rh.gs(R.string.enableloop)).thenReturn("Enable loop") + `when`(rh.gs(R.string.alreadyenabled)).thenReturn("Already enabled") sut = ActionLoopEnable(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.kt index e630a0df01..72401cc0a7 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.kt @@ -18,8 +18,8 @@ class ActionLoopResumeTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(R.string.resumeloop)).thenReturn("Resume loop") - `when`(resourceHelper.gs(R.string.notsuspended)).thenReturn("Not suspended") + `when`(rh.gs(R.string.resumeloop)).thenReturn("Resume loop") + `when`(rh.gs(R.string.notsuspended)).thenReturn("Not suspended") sut = ActionLoopResume(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.kt index 66140b09d0..2c5bddf948 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.kt @@ -17,9 +17,9 @@ class ActionLoopSuspendTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(R.string.suspendloop)).thenReturn("Suspend loop") - `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.suspendloopforXmin), ArgumentMatchers.anyInt())).thenReturn("Suspend loop for %d min") - `when`(resourceHelper.gs(R.string.alreadysuspended)).thenReturn("Already suspended") + `when`(rh.gs(R.string.suspendloop)).thenReturn("Suspend loop") + `when`(rh.gs(ArgumentMatchers.eq(R.string.suspendloopforXmin), ArgumentMatchers.anyInt())).thenReturn("Suspend loop for %d min") + `when`(rh.gs(R.string.alreadysuspended)).thenReturn("Already suspended") sut = ActionLoopSuspend(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt index 23097a5de0..21c0812627 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt @@ -23,7 +23,7 @@ import org.mockito.Mockito.`when` class ActionNotificationTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var rxBus: RxBus @Mock lateinit var repository: AppRepository @@ -31,22 +31,22 @@ class ActionNotificationTest : TestBase() { var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is ActionNotification) { - it.resourceHelper = resourceHelper + it.rh = rh it.rxBus = rxBus it.repository = repository } if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } @Before fun setup() { - `when`(resourceHelper.gs(R.string.ok)).thenReturn("OK") - `when`(resourceHelper.gs(R.string.notification)).thenReturn("Notification") + `when`(rh.gs(R.string.ok)).thenReturn("OK") + `when`(rh.gs(R.string.notification)).thenReturn("Notification") `when`( - resourceHelper.gs( + rh.gs( ArgumentMatchers.eq(R.string.notification_message), ArgumentMatchers.anyString() ) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.kt index 60a109bd62..7a37cac6e0 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.queue.Callback import org.junit.Assert import org.junit.Before import org.junit.Test +import org.mockito.ArgumentMatchers import org.mockito.Mockito import org.mockito.Mockito.`when` @@ -17,8 +18,8 @@ class ActionProfileSwitchPercentTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(R.string.startprofileforever)).thenReturn("Start profile %d%%") - `when`(resourceHelper.gs(R.string.startprofile)).thenReturn("Start profile %d%% for %d min") + `when`(rh.gs(R.string.startprofileforever)).thenReturn("Start profile %d%%") + `when`(rh.gs(R.string.startprofile)).thenReturn("Start profile %d%% for %d min") sut = ActionProfileSwitchPercent(injector) } @@ -38,6 +39,7 @@ class ActionProfileSwitchPercentTest : ActionsTestBase() { } @Test fun doActionTest() { + `when`(profileFunction.createProfileSwitch(Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(true) sut.pct = InputPercent(110.0) sut.duration = InputDuration(30, InputDuration.TimeUnit.MINUTES) sut.doAction(object : Callback() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt index c15d1030b0..51d36bf4f3 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.kt @@ -20,12 +20,12 @@ class ActionProfileSwitchTest : ActionsTestBase() { private val stringJson = "{\"data\":{\"profileToSwitchTo\":\"Test\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionProfileSwitch\"}" @Before fun setUp() { - `when`(resourceHelper.gs(R.string.profilename)).thenReturn("Change profile to") - `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s") - `when`(resourceHelper.gs(R.string.alreadyset)).thenReturn("Already set") - `when`(resourceHelper.gs(R.string.notexists)).thenReturn("not exists") - `when`(resourceHelper.gs(R.string.error_field_must_not_be_empty)).thenReturn("The field must not be empty") - `when`(resourceHelper.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") + `when`(rh.gs(R.string.profilename)).thenReturn("Change profile to") + `when`(rh.gs(ArgumentMatchers.eq(R.string.changengetoprofilename), ArgumentMatchers.anyString())).thenReturn("Change profile to %s") + `when`(rh.gs(R.string.alreadyset)).thenReturn("Already set") + `when`(rh.gs(R.string.notexists)).thenReturn("not exists") + `when`(rh.gs(R.string.error_field_must_not_be_empty)).thenReturn("The field must not be empty") + `when`(rh.gs(R.string.noprofile)).thenReturn("No profile loaded from NS yet") sut = ActionProfileSwitch(injector) } @@ -41,7 +41,7 @@ class ActionProfileSwitchTest : ActionsTestBase() { @Test fun doAction() { //Empty input `when`(profileFunction.getProfileName()).thenReturn("Test") - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, "") + sut.inputProfileName = InputProfileName(rh, activePlugin, "") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) @@ -50,7 +50,7 @@ class ActionProfileSwitchTest : ActionsTestBase() { //Not initialized profileStore `when`(profileFunction.getProfile()).thenReturn(null) - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, "someProfile") + sut.inputProfileName = InputProfileName(rh, activePlugin, "someProfile") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) @@ -60,7 +60,7 @@ class ActionProfileSwitchTest : ActionsTestBase() { //profile already set `when`(profileFunction.getProfile()).thenReturn(validProfile) `when`(profileFunction.getProfileName()).thenReturn("Test") - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, "Test") + sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) @@ -70,7 +70,7 @@ class ActionProfileSwitchTest : ActionsTestBase() { // profile doesn't exists `when`(profileFunction.getProfileName()).thenReturn("Active") - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, "Test") + sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") sut.doAction(object : Callback() { override fun run() { Assert.assertFalse(result.success) @@ -80,7 +80,8 @@ class ActionProfileSwitchTest : ActionsTestBase() { // do profile switch `when`(profileFunction.getProfileName()).thenReturn("Test") - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, TESTPROFILENAME) + `when`(profileFunction.createProfileSwitch(anyObject(), anyString(), anyInt(), anyInt(), anyInt(), anyLong())).thenReturn(true) + sut.inputProfileName = InputProfileName(rh, activePlugin, TESTPROFILENAME) sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) @@ -95,7 +96,7 @@ class ActionProfileSwitchTest : ActionsTestBase() { } @Test fun toJSONTest() { - sut.inputProfileName = InputProfileName(resourceHelper, activePlugin, "Test") + sut.inputProfileName = InputProfileName(rh, activePlugin, "Test") Assert.assertEquals(stringJson, sut.toJSON()) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.kt index cd2d36f941..7c7e675826 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.kt @@ -17,8 +17,8 @@ class ActionSendSMSTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(eq(R.string.sendsmsactionlabel), anyString())).thenReturn("Send SMS: %s") - `when`(resourceHelper.gs(R.string.sendsmsactiondescription)).thenReturn("Send SMS to all numbers") + `when`(rh.gs(eq(R.string.sendsmsactionlabel), anyString())).thenReturn("Send SMS: %s") + `when`(rh.gs(R.string.sendsmsactiondescription)).thenReturn("Send SMS to all numbers") sut = ActionSendSMS(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt index bca2b68ef4..c01b372c09 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt @@ -21,7 +21,7 @@ class ActionStartTempTargetTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(R.string.starttemptarget)).thenReturn("Start temp target") + `when`(rh.gs(R.string.starttemptarget)).thenReturn("Start temp target") sut = ActionStartTempTarget(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt index e3310ed65e..08e1effa01 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTargetTest.kt @@ -18,7 +18,7 @@ class ActionStopTempTargetTest : ActionsTestBase() { @Before fun setup() { - `when`(resourceHelper.gs(R.string.stoptemptarget)).thenReturn("Stop temp target") + `when`(rh.gs(R.string.stoptemptarget)).thenReturn("Stop temp target") sut = ActionStopTempTarget(injector) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt index 06237a3b89..70f9462ce7 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt @@ -21,11 +21,11 @@ open class ActionsTestBase : TestBaseWithProfile() { open class TestLoopPlugin( aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, + rh: ResourceHelper, injector: HasAndroidInjector, pluginDescription: PluginDescription ) : PluginBase( - pluginDescription, aapsLogger, resourceHelper, injector + pluginDescription, aapsLogger, rh, injector ), Loop { private var suspended = false @@ -44,7 +44,7 @@ open class ActionsTestBase : TestBaseWithProfile() { } @Mock lateinit var sp: SP - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var configBuilder: ConfigBuilder @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var profilePlugin: ProfileSource @@ -59,14 +59,14 @@ open class ActionsTestBase : TestBaseWithProfile() { AndroidInjector { if (it is ActionStopTempTarget) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.dateUtil = dateUtil it.repository = repository it.uel = uel } if (it is ActionStartTempTarget) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.activePlugin = activePlugin it.repository = repository it.profileFunction = profileFunction @@ -75,12 +75,12 @@ open class ActionsTestBase : TestBaseWithProfile() { } if (it is ActionSendSMS) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.smsCommunicatorPlugin = smsCommunicatorPlugin } if (it is ActionProfileSwitch) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.activePlugin = activePlugin it.profileFunction = profileFunction it.uel = uel @@ -88,26 +88,26 @@ open class ActionsTestBase : TestBaseWithProfile() { } if (it is ActionProfileSwitchPercent) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.profileFunction = profileFunction it.uel = uel } if (it is ActionNotification) { it.aapsLogger = aapsLogger - it.resourceHelper = resourceHelper + it.rh = rh it.rxBus = rxBus } if (it is ActionLoopSuspend) { it.aapsLogger = aapsLogger it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.rxBus = rxBus it.uel = uel } if (it is ActionLoopResume) { it.aapsLogger = aapsLogger it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.configBuilder = configBuilder it.rxBus = rxBus it.repository = repository @@ -117,7 +117,7 @@ open class ActionsTestBase : TestBaseWithProfile() { if (it is ActionLoopEnable) { it.aapsLogger = aapsLogger it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.configBuilder = configBuilder it.rxBus = rxBus it.uel = uel @@ -125,14 +125,14 @@ open class ActionsTestBase : TestBaseWithProfile() { if (it is ActionLoopDisable) { it.aapsLogger = aapsLogger it.loopPlugin = loopPlugin - it.resourceHelper = resourceHelper + it.rh = rh it.configBuilder = configBuilder it.commandQueue = commandQueue it.rxBus = rxBus it.uel = uel } if (it is ActionCarePortalEvent) { - it.resourceHelper = resourceHelper + it.rh = rh it.repository = repository it.sp = sp it.dateUtil = dateUtil @@ -140,10 +140,10 @@ open class ActionsTestBase : TestBaseWithProfile() { it.uel = uel } if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } if (it is Trigger) { - it.resourceHelper = resourceHelper + it.rh = rh it.profileFunction = profileFunction } } @@ -151,13 +151,13 @@ open class ActionsTestBase : TestBaseWithProfile() { @Before fun mock() { - testPumpPlugin = TestPumpPlugin(pluginDescription, aapsLogger, resourceHelper, injector) + testPumpPlugin = TestPumpPlugin(pluginDescription, aapsLogger, rh, injector) `when`(activePlugin.activePump).thenReturn(testPumpPlugin) `when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) `when`(activePlugin.activeProfileSource).thenReturn(profilePlugin) `when`(profilePlugin.profile).thenReturn(getValidProfileStore()) - `when`(resourceHelper.gs(R.string.ok)).thenReturn("OK") - `when`(resourceHelper.gs(R.string.error)).thenReturn("Error") + `when`(rh.gs(R.string.ok)).thenReturn("OK") + `when`(rh.gs(R.string.error)).thenReturn("Error") } } \ No newline at end of file diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnectTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnectTest.kt index 0842c232d8..045b3f30a7 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnectTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnectTest.kt @@ -7,11 +7,11 @@ import org.junit.Test class ComparatorConnectTest : TriggerTestBase() { @Test fun labelsTest() { - Assert.assertEquals(2, ComparatorConnect.Compare.labels(resourceHelper).size) + Assert.assertEquals(2, ComparatorConnect.Compare.labels(rh).size) } @Test fun setValueTest() { - val c = ComparatorConnect(resourceHelper) + val c = ComparatorConnect(rh) c.value = ComparatorConnect.Compare.ON_DISCONNECT Assert.assertEquals(ComparatorConnect.Compare.ON_DISCONNECT, c.value) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExistsTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExistsTest.kt index 1011db6565..8d5e8a487e 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExistsTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExistsTest.kt @@ -7,11 +7,11 @@ import org.junit.Test class ComparatorExistsTest : TriggerTestBase() { @Test fun labelsTest() { - Assert.assertEquals(2, ComparatorExists.Compare.labels(resourceHelper).size) + Assert.assertEquals(2, ComparatorExists.Compare.labels(rh).size) } @Test fun setValueTest() { - val c = ComparatorExists(resourceHelper) + val c = ComparatorExists(rh) c.value = ComparatorExists.Compare.NOT_EXISTS Assert.assertEquals(ComparatorExists.Compare.NOT_EXISTS, c.value) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorTest.kt index 71b8fc4233..7a6532916e 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorTest.kt @@ -24,12 +24,12 @@ class ComparatorTest : TriggerTestBase() { @Test fun labelsTest() { - Assert.assertEquals(6, Comparator.Compare.labels(resourceHelper).size) + Assert.assertEquals(6, Comparator.Compare.labels(rh).size) } @Test fun setValueTest() { - val c: Comparator = Comparator(resourceHelper).setValue(Comparator.Compare.IS_EQUAL_OR_GREATER) + val c: Comparator = Comparator(rh).setValue(Comparator.Compare.IS_EQUAL_OR_GREATER) Assert.assertEquals(Comparator.Compare.IS_EQUAL_OR_GREATER, c.value) } } \ No newline at end of file diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalEventTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalEventTest.kt index 3d23d84d96..54c50a5825 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalEventTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalEventTest.kt @@ -8,12 +8,12 @@ class InputCarePortalEventTest : TriggerTestBase() { @Test fun labelsTest() { - Assert.assertEquals(4, InputCarePortalMenu.EventType.labels(resourceHelper).size) + Assert.assertEquals(4, InputCarePortalMenu.EventType.labels(rh).size) } @Test fun setValueTest() { - val cp = InputCarePortalMenu(resourceHelper, InputCarePortalMenu.EventType.EXERCISE) + val cp = InputCarePortalMenu(rh, InputCarePortalMenu.EventType.EXERCISE) Assert.assertEquals(InputCarePortalMenu.EventType.EXERCISE, cp.value) } } \ No newline at end of file diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileNameTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileNameTest.kt index 26f0b69976..176672c9e1 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileNameTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileNameTest.kt @@ -7,7 +7,7 @@ import org.junit.Test class InputProfileNameTest : TriggerTestBase() { @Test fun setValue() { - val inputProfileName = InputProfileName(resourceHelper, activePlugin, "Test") + val inputProfileName = InputProfileName(rh, activePlugin, "Test") Assert.assertEquals("Test", inputProfileName.value) inputProfileName.value = "Test2" Assert.assertEquals("Test2", inputProfileName.value) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElementTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElementTest.kt index 5ccdb971ed..32eb7379a2 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElementTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElementTest.kt @@ -8,7 +8,7 @@ class LabelWithElementTest : TriggerTestBase() { @Test fun constructorTest() { - val l = LabelWithElement(resourceHelper, "A", "B", InputInsulin()) + val l = LabelWithElement(rh, "A", "B", InputInsulin()) Assert.assertEquals("A", l.textPre) Assert.assertEquals("B", l.textPost) Assert.assertEquals(InputInsulin::class.java, l.element!!.javaClass) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabelTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabelTest.kt index 0f5a9edda5..1277a84251 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabelTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabelTest.kt @@ -10,10 +10,10 @@ import org.mockito.Mockito.`when` class StaticLabelTest : TriggerTestBase() { @Test fun constructor() { - var sl = StaticLabel(resourceHelper, "any", TriggerDummy(injector)) + var sl = StaticLabel(rh, "any", TriggerDummy(injector)) Assert.assertEquals("any", sl.label) - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - sl = StaticLabel(resourceHelper, R.string.pumplimit, TriggerDummy(injector)) + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + sl = StaticLabel(rh, R.string.pumplimit, TriggerDummy(injector)) Assert.assertEquals("pump limit", sl.label) } } \ No newline at end of file diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt index aacbe7fad4..b8af1dbee0 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt @@ -36,7 +36,7 @@ open class TriggerTestBase : TestBaseWithProfile() { @Before fun prepareMock1() { receiverStatusStore = ReceiverStatusStore(context, rxBus) - testPumpPlugin = TestPumpPlugin(pluginDescription, aapsLogger, resourceHelper, injector) + testPumpPlugin = TestPumpPlugin(pluginDescription, aapsLogger, rh, injector) `when`(activePlugin.activePump).thenReturn(testPumpPlugin) `when`(iobCobCalculator.ads).thenReturn(autosensDataStore) } @@ -46,7 +46,7 @@ open class TriggerTestBase : TestBaseWithProfile() { if (it is Trigger) { it.aapsLogger = aapsLogger it.rxBus = RxBus(aapsSchedulers, aapsLogger) - it.resourceHelper = resourceHelper + it.rh = rh it.profileFunction = profileFunction it.sp = sp it.locationDataContainer = locationDataContainer diff --git a/build.gradle b/build.gradle index 97b1ff47f7..4a59385c49 100644 --- a/build.gradle +++ b/build.gradle @@ -30,7 +30,7 @@ buildscript { dexmakerVersion = "1.2" retrofit2Version = '2.9.0' okhttp3Version = '4.9.0' - byteBuddyVersion = '1.11.21' + byteBuddyVersion = '1.12.0' androidx_junit = '1.1.2' androidx_rules = '1.4.0-alpha04' @@ -43,7 +43,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:7.0.3' classpath 'com.google.gms:google-services:4.3.10' - classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.1' + classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index ce3b03e142..9e10c4701f 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -17,7 +17,7 @@ import javax.inject.Inject; import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.combo.R; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdateGUI; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; @@ -33,8 +33,8 @@ import io.reactivex.disposables.CompositeDisposable; public class ComboFragment extends DaggerFragment { @Inject ComboPlugin comboPlugin; - @Inject CommandQueueProvider commandQueue; - @Inject ResourceHelper resourceHelper; + @Inject CommandQueue commandQueue; + @Inject ResourceHelper rh; @Inject RxBus rxBus; @Inject SP sp; @Inject DateUtil dateUtil; @@ -149,7 +149,7 @@ public class ComboFragment extends DaggerFragment { } else { activityView.setTextColor(Color.RED); activityView.setTextSize(14); - activityView.setText(resourceHelper.gs(R.string.pump_unreachable)); + activityView.setText(rh.gs(R.string.pump_unreachable)); } if (comboPlugin.isInitialized()) { @@ -169,13 +169,13 @@ public class ComboFragment extends DaggerFragment { // reservoir int reservoirLevel = comboPlugin.getPump().reservoirLevel; if (reservoirLevel != -1) { - reservoirView.setText(reservoirLevel + " " + resourceHelper.gs(R.string.insulin_unit_shortname)); + reservoirView.setText(reservoirLevel + " " + rh.gs(R.string.insulin_unit_shortname)); } else if (ps.insulinState == PumpState.LOW) { - reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_low)); + reservoirView.setText(rh.gs(R.string.combo_reservoir_low)); } else if (ps.insulinState == PumpState.EMPTY) { - reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_empty)); + reservoirView.setText(rh.gs(R.string.combo_reservoir_empty)); } else { - reservoirView.setText(resourceHelper.gs(R.string.combo_reservoir_normal)); + reservoirView.setText(rh.gs(R.string.combo_reservoir_normal)); } if (ps.insulinState == PumpState.UNKNOWN) { @@ -193,13 +193,13 @@ public class ComboFragment extends DaggerFragment { } // last connection - String minAgo = dateUtil.minAgo(resourceHelper, comboPlugin.getPump().lastSuccessfulCmdTime); + String minAgo = dateUtil.minAgo(rh, comboPlugin.getPump().lastSuccessfulCmdTime); long min = (System.currentTimeMillis() - comboPlugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; if (comboPlugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { lastConnectionView.setText(R.string.combo_pump_connected_now); lastConnectionView.setTextColor(Color.WHITE); } else if (comboPlugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { - lastConnectionView.setText(resourceHelper.gs(R.string.combo_no_pump_connection, min)); + lastConnectionView.setText(rh.gs(R.string.combo_no_pump_connection, min)); lastConnectionView.setTextColor(Color.RED); } else { lastConnectionView.setText(minAgo); @@ -211,22 +211,22 @@ public class ComboFragment extends DaggerFragment { if (bolus != null) { long agoMsc = System.currentTimeMillis() - bolus.timestamp; double bolusMinAgo = agoMsc / 60d / 1000d; - String unit = resourceHelper.gs(R.string.insulin_unit_shortname); + String unit = rh.gs(R.string.insulin_unit_shortname); String ago; if ((agoMsc < 60 * 1000)) { - ago = resourceHelper.gs(R.string.combo_pump_connected_now); + ago = rh.gs(R.string.combo_pump_connected_now); } else if (bolusMinAgo < 60) { - ago = dateUtil.minAgo(resourceHelper, bolus.timestamp); + ago = dateUtil.minAgo(rh, bolus.timestamp); } else { - ago = dateUtil.hourAgo(bolus.timestamp, resourceHelper); + ago = dateUtil.hourAgo(bolus.timestamp, rh); } - lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); + lastBolusView.setText(rh.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); } else { lastBolusView.setText(""); } // base basal rate - baseBasalRate.setText(resourceHelper.gs(R.string.pump_basebasalrate, comboPlugin.getBaseBasalRate())); + baseBasalRate.setText(rh.gs(R.string.pump_basebasalrate, comboPlugin.getBaseBasalRate())); // TBR String tbrStr = ""; @@ -234,7 +234,7 @@ public class ComboFragment extends DaggerFragment { long minSinceRead = (System.currentTimeMillis() - comboPlugin.getPump().state.timestamp) / 1000 / 60; long remaining = ps.tbrRemainingDuration - minSinceRead; if (remaining >= 0) { - tbrStr = resourceHelper.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); + tbrStr = rh.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); } } tempBasalText.setText(tbrStr); diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index a24792979a..ae14fc7c38 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -27,7 +27,7 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.extensions.PumpStateExtensionKt; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraints; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -94,7 +94,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { private final ProfileFunction profileFunction; private final SP sp; private RxBus rxBus; - private final CommandQueueProvider commandQueue; + private final CommandQueue commandQueue; private final Context context; private final PumpSync pumpSync; private final DateUtil dateUtil; @@ -147,10 +147,10 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { HasAndroidInjector injector, AAPSLogger aapsLogger, RxBus rxBus, - ResourceHelper resourceHelper, + ResourceHelper rh, ProfileFunction profileFunction, SP sp, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, Context context, PumpSync pumpSync, DateUtil dateUtil @@ -162,7 +162,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { .pluginName(R.string.combopump) .shortName(R.string.combopump_shortname) .description(R.string.description_pump_combo), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ); this.rxBus = rxBus; this.profileFunction = profileFunction; @@ -193,15 +193,15 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { ? "E" + ps.activeAlert.errorCode + ": " + ps.activeAlert.message : "W" + ps.activeAlert.warningCode + ": " + ps.activeAlert.message; } else if (ps.suspended && (ps.batteryState == PumpState.EMPTY || ps.insulinState == PumpState.EMPTY)) { - return getResourceHelper().gs(R.string.combo_pump_state_suspended_due_to_error); + return getRh().gs(R.string.combo_pump_state_suspended_due_to_error); } else if (ps.suspended) { - return getResourceHelper().gs(R.string.combo_pump_state_suspended_by_user); + return getRh().gs(R.string.combo_pump_state_suspended_by_user); } else if (!pump.initialized) { - return getResourceHelper().gs(R.string.combo_pump_state_initializing); + return getRh().gs(R.string.combo_pump_state_initializing); } else if (!validBasalRateProfileSelectedOnPump) { - return getResourceHelper().gs(R.string.loopdisabled); + return getRh().gs(R.string.loopdisabled); } - return getResourceHelper().gs(R.string.combo_pump_state_running); + return getRh().gs(R.string.combo_pump_state_running); } @Override @@ -263,7 +263,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { // note that this should not happen anymore since the queue is present, which // issues a READSTATE when starting to issue commands which initializes the pump getAapsLogger().error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); + Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getRh().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.pumpNotInitializedProfileNotSet); } @@ -281,10 +281,10 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.combo_force_disabled_notification); } - CommandResult setResult = runCommand(getResourceHelper().gs(R.string.combo_activity_setting_basal_profile), 2, + CommandResult setResult = runCommand(getRh().gs(R.string.combo_activity_setting_basal_profile), 2, () -> ruffyScripter.setBasalProfile(requestedBasalProfile)); if (!setResult.success) { - Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, getRh().gs(R.string.failedupdatebasalprofile), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.failedupdatebasalprofile); } @@ -295,7 +295,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)); //issue success notification - Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60); + Notification notification = new Notification(Notification.PROFILE_SET_OK, getRh().gs(R.string.profile_set_ok), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); return new PumpEnactResult(getInjector()).success(true).enacted(true); } @@ -370,7 +370,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState); if (stateResult.invalidSetup) { rxBus.send(new EventNewNotification( - new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_invalid_setup), Notification.URGENT))); + new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_invalid_setup), Notification.URGENT))); return; } if (!stateResult.success) { @@ -386,7 +386,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - getResourceHelper().gs(R.string.combo_force_disabled_notification), + getRh().gs(R.string.combo_force_disabled_notification), Notification.URGENT); n.setSoundId(R.raw.alarm); rxBus.send(new EventNewNotification(n)); @@ -394,7 +394,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } // read basal profile into cache (KeepAlive will trigger a profile update if needed) - CommandResult readBasalResult = runCommand(getResourceHelper().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); + CommandResult readBasalResult = runCommand(getRh().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); if (!readBasalResult.success) { return; } @@ -410,7 +410,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { long lastBolusTimestamp = recentBoluses.get(0).timestamp; long now = System.currentTimeMillis(); if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_check_date), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_check_date), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } } @@ -475,19 +475,19 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; switch (state) { case PROGRAMMING: - event.setStatus(getResourceHelper().gs(R.string.combo_programming_bolus)); + event.setStatus(getRh().gs(R.string.combo_programming_bolus)); break; case DELIVERING: - event.setStatus(getResourceHelper().gs(R.string.bolusdelivering, delivered)); + event.setStatus(getRh().gs(R.string.bolusdelivering, delivered)); break; case DELIVERED: - event.setStatus(getResourceHelper().gs(R.string.bolusdelivered, delivered)); + event.setStatus(getRh().gs(R.string.bolusdelivered, delivered)); break; case STOPPING: - event.setStatus(getResourceHelper().gs(R.string.bolusstopping)); + event.setStatus(getRh().gs(R.string.bolusstopping)); break; case STOPPED: - event.setStatus(getResourceHelper().gs(R.string.bolusstopped)); + event.setStatus(getRh().gs(R.string.bolusstopped)); break; } event.setPercent(percent); @@ -503,7 +503,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { throw new IllegalArgumentException(detailedBolusInfo.toString()); } try { - pump.activity = getResourceHelper().gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin); + pump.activity = getRh().gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin); rxBus.send(new EventComboPumpUpdateGUI()); // check pump is ready and all pump bolus records are known @@ -608,7 +608,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { // check pump bolus record has a sane timestamp long now = System.currentTimeMillis(); if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_suspious_bolus_time), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_suspious_bolus_time), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } @@ -622,7 +622,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return new PumpEnactResult(getInjector()).success(true).enacted(true); } return new PumpEnactResult(getInjector()).success(false).enacted(true) - .comment(getResourceHelper().gs(R.string.combo_error_partial_bolus_delivered, + .comment(getRh().gs(R.string.combo_error_partial_bolus_delivered, lastPumpBolus.amount, detailedBolusInfo.insulin)); } @@ -650,11 +650,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } private void incrementBolusCount() { - try { - sp.putLong(R.string.combo_boluses_delivered, sp.getLong(R.string.combo_boluses_delivered, 0L) + 1); - } catch (Exception e) { - // ignore - } + sp.incLong(R.string.combo_boluses_delivered); } public Long getTbrsSet() { @@ -681,7 +677,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } catch (Exception e) { getAapsLogger().error("Adding treatment record failed", e); if (detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_error_updating_treatment_record), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } return false; @@ -756,7 +752,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } int finalAdjustedPercent = adjustedPercent; - CommandResult commandResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), + CommandResult commandResult = runCommand(getRh().gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes), 3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes)); if (!commandResult.success) { return new PumpEnactResult(getInjector()).success(false).enacted(false); @@ -807,7 +803,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { getAapsLogger().debug(LTag.PUMP, "cancelTempBasal called"); final PumpSync.PumpState.TemporaryBasal activeTemp = pumpSync.expectedPumpState().getTemporaryBasal(); if (enforceNew) { - CommandResult stateResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); + CommandResult stateResult = runCommand(getRh().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); if (!stateResult.success) { return new PumpEnactResult(getInjector()).success(false).enacted(false); } @@ -815,7 +811,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return new PumpEnactResult(getInjector()).success(true).enacted(false); } getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: hard-cancelling TBR since force requested"); - CommandResult cancelResult = runCommand(getResourceHelper().gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr); + CommandResult cancelResult = runCommand(getRh().gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr); if (!cancelResult.success) { return new PumpEnactResult(getInjector()).success(false).enacted(false); } @@ -871,7 +867,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { try { if (!ruffyScripter.isConnected()) { String originalActivity = pump.activity; - pump.activity = getResourceHelper().gs(R.string.combo_activity_checking_pump_state); + pump.activity = getRh().gs(R.string.combo_activity_checking_pump_state); rxBus.send(new EventComboPumpUpdateGUI()); CommandResult preCheckError = runOnConnectChecks(); pump.activity = originalActivity; @@ -904,7 +900,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { if (validBasalRateProfileSelectedOnPump && commandResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) { setValidBasalRateProfileSelectedOnPump(false); Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - getResourceHelper().gs(R.string.combo_force_disabled_notification), + getRh().gs(R.string.combo_force_disabled_notification), Notification.URGENT); n.setSoundId(R.raw.alarm); rxBus.send(new EventNewNotification(n)); @@ -954,7 +950,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { // so update the var with it, so the check routines below can work on it preCheckResult = alertConfirmationResult; } else if (activeAlert.errorCode != null) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, dateUtil.now(), getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message), Notification.URGENT, 0); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, dateUtil.now(), getRh().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message), Notification.URGENT, 0); rxBus.send(new EventNewNotification(notification)); return preCheckResult.success(false); } @@ -1015,13 +1011,13 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } if (Math.abs(pumpBasalRate - getBaseBasalRate()) > 0.001) { - CommandResult readBasalResult = runCommand(getResourceHelper().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); + CommandResult readBasalResult = runCommand(getRh().gs(R.string.combo_actvity_reading_basal_profile), 2, ruffyScripter::readBasalProfile); if (readBasalResult.success) { pump.basalProfile = readBasalResult.basalProfile; - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL); rxBus.send(new EventNewNotification(notification)); } else { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } } @@ -1036,11 +1032,11 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { // time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field) } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) { getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.URGENT); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_notification_check_time_date), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { getAapsLogger().debug(LTag.PUMP, "Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string.combo_notification_check_time_date), Notification.NORMAL); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string.combo_notification_check_time_date), Notification.NORMAL); rxBus.send(new EventNewNotification(notification)); } } @@ -1057,11 +1053,11 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { notification.setId(Notification.COMBO_PUMP_ALARM); notification.setLevel(Notification.NORMAL); if (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW) { - notification.setText(getResourceHelper().gs(R.string.combo_pump_cartridge_low_warrning)); + notification.setText(getRh().gs(R.string.combo_pump_cartridge_low_warrning)); } else if (activeAlert.warningCode == PumpWarningCodes.BATTERY_LOW) { - notification.setText(getResourceHelper().gs(R.string.combo_pump_battery_low_warrning)); + notification.setText(getRh().gs(R.string.combo_pump_battery_low_warrning)); } else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) { - notification.setText(getResourceHelper().gs(R.string.combo_pump_tbr_cancelled_warrning)); + notification.setText(getRh().gs(R.string.combo_pump_tbr_cancelled_warrning)); } rxBus.send(new EventNewNotification(notification)); } @@ -1083,7 +1079,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { lowSuspendOnlyLoopEnforcedUntil = lastViolation + 6 * 60 * 60 * 1000; if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis() && violationWarningRaisedForBolusAt != lowSuspendOnlyLoopEnforcedUntil) { Notification n = new Notification(Notification.COMBO_PUMP_ALARM, - getResourceHelper().gs(R.string.combo_low_suspend_forced_notification), + getRh().gs(R.string.combo_low_suspend_forced_notification), Notification.URGENT); n.setSoundId(R.raw.alarm); rxBus.send(new EventNewNotification(n)); @@ -1154,7 +1150,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { * Reads the pump's history and updates the DB accordingly. */ private boolean readHistory(@Nullable PumpHistoryRequest request) { - CommandResult historyResult = runCommand(getResourceHelper().gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request)); + CommandResult historyResult = runCommand(getRh().gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(request)); PumpHistory history = historyResult.history; if (!historyResult.success || history == null) { return false; @@ -1213,7 +1209,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { * @return null on success or the failed command result */ private CommandResult checkHistory() { - CommandResult quickInfoResult = runCommand(getResourceHelper().gs(R.string.combo_activity_checking_for_history_changes), 3, + CommandResult quickInfoResult = runCommand(getRh().gs(R.string.combo_activity_checking_for_history_changes), 3, () -> ruffyScripter.readQuickInfo(2)); // no history, nothing to check or complain about @@ -1240,7 +1236,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { // fetch new records long lastKnownPumpRecordTimestamp = recentBoluses.isEmpty() ? 0 : recentBoluses.get(0).timestamp; - CommandResult historyResult = runCommand(getResourceHelper().gs(R.string.combo_activity_reading_pump_history), 3, () -> + CommandResult historyResult = runCommand(getRh().gs(R.string.combo_activity_reading_pump_history), 3, () -> ruffyScripter.readHistory(new PumpHistoryRequest().bolusHistory(lastKnownPumpRecordTimestamp))); if (!historyResult.success) { pumpHistoryChanged = true; @@ -1254,7 +1250,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { HashSet bolusSet = new HashSet<>(historyResult.history.bolusHistory); if (bolusSet.size() != historyResult.history.bolusHistory.size()) { getAapsLogger().debug(LTag.PUMP, "Bolus with same amount within the same minute imported. Only one will make it to the DB."); - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getResourceHelper().gs(R.string. + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, getRh().gs(R.string. combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); } @@ -1409,14 +1405,14 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { @NonNull @Override public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { if (!validBasalRateProfileSelectedOnPump) - value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.novalidbasalrate), this); + value.set(getAapsLogger(), false, getRh().gs(R.string.novalidbasalrate), this); return value; } @NonNull @Override public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis()) - maxIob.setIfSmaller(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingmaxiob), 0d, getResourceHelper().gs(R.string.unsafeusage)), this); + maxIob.setIfSmaller(getAapsLogger(), 0d, String.format(getRh().gs(R.string.limitingmaxiob), 0d, getRh().gs(R.string.unsafeusage)), this); return maxIob; } diff --git a/combo/src/main/res/values-hu-rHU/strings.xml b/combo/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/combo/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/combo/src/main/res/values-iw-rIL/strings.xml b/combo/src/main/res/values-iw-rIL/strings.xml index 8eb2f9e680..5c8c7b0e8b 100644 --- a/combo/src/main/res/values-iw-rIL/strings.xml +++ b/combo/src/main/res/values-iw-rIL/strings.xml @@ -19,7 +19,7 @@ שימוש לא בטוח: המשאבה משתמשת בפרופיל בזאלי שונה מהראשון. הלולאה הושבתה. בחרו את הפרופיל הראשון במשאבה ורעננו. התבקשו בולוסים זהים בשתי הדקות האחרונות. כדי למנוע בולוסים כפולים בטעות ולשמור מפני באגים הדבר אסור. עכשיו - קריאת היסטוריית המשאבה + קורא היסטוריית המשאבה הגדרת פרופיל בזאלי רמת מכל נמוכה סוללת המשאבה חלשה @@ -35,7 +35,7 @@ אספקת הבולוס ואימות ההיסטוריה של המשאבה נכשלו, אנא בדקו את המשאבה. אם ניתן בולוס, הוא יתווסף לטיפולים במהלך החיבור הבא למשאבה. לא נותר מספיק אינסולין במיכל בשביל להשלים את הבולוס הגדרת משאבה לא חוקית, בדקו את הוראות ההפעלה וודאו שתפריט \'מידע מהיר\' נקרא בשם QUICK INFO באמצעות תוכנת התצורה 360. - קריאת פרופיל בזאלי + קורא פרופיל בזאלי היסטוריית המשאבה השתנתה לאחר ביצוע חישוב הבולוס. הבולוס לא הוזרק. אנא חשב מחדש אם יש עדיין צורך בבולוס. הבולוס הוזרק בהצלחה אבל רישומו נכשל. זה יכול לקרות אם שני בולוסים קטנים, באותו הגודל, ניתנים בתוך שתי הדקות האחרונות. בדקו את היסטוריית המשאבה ואת ערכי הטיפול והשתמשו בפורטל הטיפולים להוספת ערכים חסרים. הקפידו לא להוסיף טיפולים זהים באותה דקה. הגדרת ערך מטרה גבוה נדחתה כיוון שהחישוב לא לקח בחשבון שינוי שנעשה לאחרונה בהיסטוריית המשאבה diff --git a/combo/src/main/res/values-tr-rTR/strings.xml b/combo/src/main/res/values-tr-rTR/strings.xml index e16e4246d8..ecda216f5c 100644 --- a/combo/src/main/res/values-tr-rTR/strings.xml +++ b/combo/src/main/res/values-tr-rTR/strings.xml @@ -12,6 +12,7 @@ Çalışıyor TBR (Geçici Bazal Oranı) İptal ediliyor TBR(Geçici Bazal Oranı) ayarı (%1$d%% / %2$d dak) + Bolus (%1$.1f Ü) teslim ediliyor Yenileniyor... İstenen işlem pompası tarafından desteklenmiyor Güvensiz kullanım: yayım veya çoklu dalgalı (kare dalgalı) boluslar aktiftir. Döngü modu 6 saat içinde ekstra insülin vermeyecektir. Döngü modunda sadece normal boluslar desteklenir @@ -43,6 +44,7 @@ Bazal oranı pompada değiştirildi, ancak okuma başarısız oldu Geçmiş değişiklikleri kontrol ediliyor Aynı dakika içinde aynı miktarda birden fazla boluslar eklenildi. Tedavilere sadece bir kayıt eklenebilir. Lütfen pompayı kontrol edin ve Careportal sekmesini kullanarak elle bir bolus kaydı ekleyin. Başka bolus kullanmayan bir zamana sahip bir bolus oluşturduğunuzdan emin olun. + \n\ndocumentation:\nhttps://androidaps.readthedocs.io\n\nfacebook:\nhttps://www.facebook.com/groups/AndroidAPSUsers Son bolus 24 saatten daha eski veya gelecekte. Lütfen pompadaki tarihin doğru ayarlandığını kontrol edin. Teslim edilen bolusun pompadaki zamanı/tarihı yanlış görünüyor, IOB (Insulin On Board) muhtemelen yanlıştır. Lütfen pompa zamanını/tarihini kontrol edin. Bolus sayısı diff --git a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt index 4c30f0e478..efc08c4b1d 100644 --- a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt +++ b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt @@ -20,10 +20,10 @@ import org.mockito.Mockito.`when` class ComboPluginTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var activePlugin: ActivePlugin - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @Mock lateinit var sp: SP @Mock lateinit var context: Context @@ -32,7 +32,7 @@ class ComboPluginTest : TestBase() { val injector = HasAndroidInjector { AndroidInjector { if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } @@ -41,9 +41,9 @@ class ComboPluginTest : TestBase() { @Before fun prepareMocks() { - `when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") - `when`(resourceHelper.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") - comboPlugin = ComboPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), resourceHelper, profileFunction, sp, commandQueue, context, pumpSync, dateUtil) + `when`(rh.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") + `when`(rh.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") + comboPlugin = ComboPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), rh, profileFunction, sp, commandQueue, context, pumpSync, dateUtil) } @Test diff --git a/core/src/main/java/info/nightscout/androidaps/activities/BolusProgressHelperActivity.kt b/core/src/main/java/info/nightscout/androidaps/activities/BolusProgressHelperActivity.kt index fe55cdcdf2..063ebe0d7d 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/BolusProgressHelperActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/BolusProgressHelperActivity.kt @@ -9,6 +9,7 @@ class BolusProgressHelperActivity : DialogAppCompatActivity() { BolusProgressDialog() .setHelperActivity(this) .setInsulin(intent.getDoubleExtra("insulin", 0.0)) + .setTimestamp(intent.getLongExtra("timestamp", 0L)) .show(supportFragmentManager, "BolusProgress") } } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt b/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt index 986ef95719..0a2941fe7b 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt @@ -15,7 +15,7 @@ import javax.inject.Inject open class DaggerAppCompatActivityWithResult : DaggerAppCompatActivity() { - @Inject lateinit var resourceHelper: ResourceHelperImplementation + @Inject lateinit var rh: ResourceHelperImplementation @Inject lateinit var importExportPrefs: ImportExportPrefs val callForPrefFile = registerForActivityResult(PrefsFileContract()) { @@ -35,7 +35,7 @@ open class DaggerAppCompatActivityWithResult : DaggerAppCompatActivity() { when (it.key) { Manifest.permission.WRITE_EXTERNAL_STORAGE -> //show dialog after permission is granted - OKDialog.show(this, "", resourceHelper.gs(R.string.alert_dialog_storage_permission_text)) + OKDialog.show(this, "", rh.gs(R.string.alert_dialog_storage_permission_text)) // ignore the rest } } diff --git a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt index 3a8dea9020..4b0fb71da7 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.extensions.total import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus @@ -50,7 +50,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var repository: AppRepository @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -94,23 +94,23 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { trHead.setBackgroundColor(Color.DKGRAY) trHead.layoutParams = TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) trHead.addView(TextView(this).also { labelDate -> - labelDate.text = resourceHelper.gs(R.string.date) + labelDate.text = rh.gs(R.string.date) labelDate.setTextColor(Color.WHITE) }) trHead.addView(TextView(this).also { labelBasalRate -> - labelBasalRate.text = resourceHelper.gs(R.string.basalrate) + labelBasalRate.text = rh.gs(R.string.basalrate) labelBasalRate.setTextColor(Color.WHITE) }) trHead.addView(TextView(this).also { labelBolus -> - labelBolus.text = resourceHelper.gs(R.string.bolus) + labelBolus.text = rh.gs(R.string.bolus) labelBolus.setTextColor(Color.WHITE) }) trHead.addView(TextView(this).also { labelTdd -> - labelTdd.text = resourceHelper.gs(R.string.tdd) + labelTdd.text = rh.gs(R.string.tdd) labelTdd.setTextColor(Color.WHITE) }) trHead.addView(TextView(this).also { labelRatio -> - labelRatio.text = resourceHelper.gs(R.string.ratio) + labelRatio.text = rh.gs(R.string.ratio) labelRatio.setTextColor(Color.WHITE) }) }, TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) @@ -122,15 +122,15 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { ctrHead.setBackgroundColor(Color.DKGRAY) ctrHead.layoutParams = TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) ctrHead.addView(TextView(this).also { labelCumAmountDays -> - labelCumAmountDays.text = resourceHelper.gs(R.string.amount_days) + labelCumAmountDays.text = rh.gs(R.string.amount_days) labelCumAmountDays.setTextColor(Color.WHITE) }) ctrHead.addView(TextView(this).also { labelCumTdd -> - labelCumTdd.text = resourceHelper.gs(R.string.tdd) + labelCumTdd.text = rh.gs(R.string.tdd) labelCumTdd.setTextColor(Color.WHITE) }) ctrHead.addView(TextView(this).also { labelCumRatio -> - labelCumRatio.text = resourceHelper.gs(R.string.ratio) + labelCumRatio.text = rh.gs(R.string.ratio) labelCumRatio.setTextColor(Color.WHITE) }) }, TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) @@ -142,15 +142,15 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { etrHead.setBackgroundColor(Color.DKGRAY) etrHead.layoutParams = TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) etrHead.addView(TextView(this).also { labelExpWeight -> - labelExpWeight.text = resourceHelper.gs(R.string.weight) + labelExpWeight.text = rh.gs(R.string.weight) labelExpWeight.setTextColor(Color.WHITE) }) etrHead.addView(TextView(this).also { labelExpTdd -> - labelExpTdd.text = resourceHelper.gs(R.string.tdd) + labelExpTdd.text = rh.gs(R.string.tdd) labelExpTdd.setTextColor(Color.WHITE) }) etrHead.addView(TextView(this).also { labelExpRatio -> - labelExpRatio.text = resourceHelper.gs(R.string.ratio) + labelExpRatio.text = rh.gs(R.string.ratio) labelExpRatio.setTextColor(Color.WHITE) }) }, TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) @@ -160,7 +160,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { binding.reload.visibility = View.GONE binding.connectionStatus.visibility = View.VISIBLE binding.message.visibility = View.VISIBLE - binding.message.text = resourceHelper.gs(R.string.warning_Message) + binding.message.text = rh.gs(R.string.warning_Message) commandQueue.loadTDDs(object : Callback() { override fun run() { loadDataFromDB() @@ -195,18 +195,20 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { override fun onResume() { super.onResume() - disposable.add(rxBus - .toObservable(EventPumpStatusChanged::class.java) - .observeOn(aapsSchedulers.main) - .subscribe({ event -> binding.connectionStatus.text = event.getStatus(resourceHelper) }, fabricPrivacy::logException) + disposable.add( + rxBus + .toObservable(EventPumpStatusChanged::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ event -> binding.connectionStatus.text = event.getStatus(rh) }, fabricPrivacy::logException) ) - disposable.add(rxBus - .toObservable(EventDanaRSyncStatus::class.java) - .observeOn(aapsSchedulers.main) - .subscribe({ event -> - aapsLogger.debug("EventDanaRSyncStatus: " + event.message) - binding.connectionStatus.text = event.message - }, fabricPrivacy::logException) + disposable.add( + rxBus + .toObservable(EventDanaRSyncStatus::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ event -> + aapsLogger.debug("EventDanaRSyncStatus: " + event.message) + binding.connectionStatus.text = event.message + }, fabricPrivacy::logException) ) } @@ -292,7 +294,8 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { tr.id = 100 + i tr.layoutParams = TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, - TableLayout.LayoutParams.WRAP_CONTENT) + TableLayout.LayoutParams.WRAP_CONTENT + ) // Here create the TextView dynamically tr.addView(TextView(this@TDDStatsActivity).also { labelDATE -> @@ -302,17 +305,17 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { }) tr.addView(TextView(this@TDDStatsActivity).also { labelBASAL -> labelBASAL.id = 300 + i - labelBASAL.text = resourceHelper.gs(R.string.formatinsulinunits, record.basalAmount) + labelBASAL.text = rh.gs(R.string.formatinsulinunits, record.basalAmount) labelBASAL.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelBOLUS -> labelBOLUS.id = 400 + i - labelBOLUS.text = resourceHelper.gs(R.string.formatinsulinunits, record.bolusAmount) + labelBOLUS.text = rh.gs(R.string.formatinsulinunits, record.bolusAmount) labelBOLUS.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelTDD -> labelTDD.id = 500 + i - labelTDD.text = resourceHelper.gs(R.string.formatinsulinunits, tdd) + labelTDD.text = rh.gs(R.string.formatinsulinunits, tdd) labelTDD.setTextColor(Color.WHITE) }) tr.addView(TextView(this@TDDStatsActivity).also { labelRATIO -> @@ -320,7 +323,8 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { labelRATIO.text = (100 * tdd / magicNumber).roundToInt().toString() + "%" labelRATIO.setTextColor(Color.WHITE) }) - }, TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)) + }, TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT) + ) i++ } i = 0 @@ -349,7 +353,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { ctr.addView(TextView(this@TDDStatsActivity).also { labelCUMTDD -> labelCUMTDD.id = 900 + i - labelCUMTDD.text = resourceHelper.gs(R.string.formatinsulinunits, sum / i) + labelCUMTDD.text = rh.gs(R.string.formatinsulinunits, sum / i) labelCUMTDD.setTextColor(Color.WHITE) }) @@ -363,7 +367,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { } if (isOldData(historyList) && activePlugin.activePump.pumpDescription.needsManualTDDLoad) { binding.message.visibility = View.VISIBLE - binding.message.text = resourceHelper.gs(R.string.olddata_Message) + binding.message.text = rh.gs(R.string.olddata_Message) } else binding.mainTable.setBackgroundColor(Color.TRANSPARENT) if (historyList.isNotEmpty() && df1.format(Date(historyList[0].timestamp)) == df1.format(Date())) { //Today should not be included @@ -401,9 +405,9 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { etr.addView(TextView(this@TDDStatsActivity).also { labelEXPTDD -> labelEXPTDD.id = 1300 + i labelEXPTDD.text = """ - ${resourceHelper.gs(R.string.formatinsulinunits, weighted03)} - ${resourceHelper.gs(R.string.formatinsulinunits, weighted05)} - ${resourceHelper.gs(R.string.formatinsulinunits, weighted07)} + ${rh.gs(R.string.formatinsulinunits, weighted03)} + ${rh.gs(R.string.formatinsulinunits, weighted05)} + ${rh.gs(R.string.formatinsulinunits, weighted07)} """.trimIndent() labelEXPTDD.setTextColor(Color.WHITE) }) @@ -429,7 +433,8 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { private fun isOldData(historyList: List): Boolean { val type = activePlugin.activePump.pumpDescription.pumpType - val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT_VIRTUAL || type == PumpType.DIACONN_G8 + val startsYesterday = + type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT_VIRTUAL || type == PumpType.DIACONN_G8 val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } diff --git a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt index 93286b5a3d..462259b76b 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt @@ -95,7 +95,7 @@ sealed class ProfileSealed( value.timeZone.rawOffset.toLong() ) - override fun isValid(from: String, pump: Pump, config: Config, resourceHelper: ResourceHelper, rxBus: RxBus, hardLimits: HardLimits, sendNotifications: Boolean): Profile.ValidityCheck { + override fun isValid(from: String, pump: Pump, config: Config, rh: ResourceHelper, rxBus: RxBus, hardLimits: HardLimits, sendNotifications: Boolean): Profile.ValidityCheck { val validityCheck = Profile.ValidityCheck() val description = pump.pumpDescription for (basal in basalBlocks) { @@ -107,14 +107,14 @@ sealed class ProfileSealed( if (sendNotifications && config.APS) { val notification = Notification( Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, - resourceHelper.gs(R.string.basalprofilenotaligned, from), + rh.gs(R.string.basalprofilenotaligned, from), Notification.NORMAL ) rxBus.send(EventNewNotification(notification)) } validityCheck.isValid = false validityCheck.reasons.add( - resourceHelper.gs( + rh.gs( R.string.basalprofilenotaligned, from ) @@ -122,73 +122,73 @@ sealed class ProfileSealed( break } } + if (!hardLimits.isInRange(basalAmount, 0.01, hardLimits.maxBasal())) { + validityCheck.isValid = false + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.basal_value), basalAmount)) + break + } // Check for minimal basal value if (basalAmount < description.basalMinimumRate) { basal.amount = description.basalMinimumRate - if (sendNotifications) sendBelowMinimumNotification(from, rxBus, resourceHelper) + if (sendNotifications) sendBelowMinimumNotification(from, rxBus, rh) validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.minimalbasalvaluereplaced, from)) + validityCheck.reasons.add(rh.gs(R.string.minimalbasalvaluereplaced, from)) break } else if (basalAmount > description.basalMaximumRate) { basal.amount = description.basalMaximumRate - if (sendNotifications) sendAboveMaximumNotification(from, rxBus, resourceHelper) + if (sendNotifications) sendAboveMaximumNotification(from, rxBus, rh) validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.maximumbasalvaluereplaced, from)) - break - } - if (!hardLimits.isInRange(basalAmount, 0.01, hardLimits.maxBasal())) { - validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.basal_value), basalAmount)) + validityCheck.reasons.add(rh.gs(R.string.maximumbasalvaluereplaced, from)) break } } if (!hardLimits.isInRange(dia, hardLimits.minDia(), hardLimits.maxDia())) { validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.profile_dia), dia)) + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.profile_dia), dia)) } for (ic in icBlocks) if (!hardLimits.isInRange(ic.amount * 100.0 / percentage, hardLimits.minIC(), hardLimits.maxIC())) { validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.profile_carbs_ratio_value), ic.amount * 100.0 / percentage)) + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.profile_carbs_ratio_value), ic.amount * 100.0 / percentage)) break } for (isf in isfBlocks) if (!hardLimits.isInRange(toMgdl(isf.amount * 100.0 / percentage, units), HardLimits.MIN_ISF, HardLimits.MAX_ISF)) { validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.profile_sensitivity_value), isf.amount * 100.0 / percentage)) + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.profile_sensitivity_value), isf.amount * 100.0 / percentage)) break } for (target in targetBlocks) { if (!hardLimits.isInRange( - Profile.toMgdl(target.lowTarget, units), - HardLimits.VERY_HARD_LIMIT_MIN_BG[0].toDouble(), - HardLimits.VERY_HARD_LIMIT_MIN_BG[1].toDouble() + toMgdl(target.lowTarget, units), + HardLimits.VERY_HARD_LIMIT_MIN_BG[0], + HardLimits.VERY_HARD_LIMIT_MIN_BG[1] ) ) { validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.profile_low_target), target.lowTarget)) + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.profile_low_target), target.lowTarget)) break } if (!hardLimits.isInRange( - Profile.toMgdl(target.highTarget, units), - HardLimits.VERY_HARD_LIMIT_MAX_BG[0].toDouble(), - HardLimits.VERY_HARD_LIMIT_MAX_BG[1].toDouble() + toMgdl(target.highTarget, units), + HardLimits.VERY_HARD_LIMIT_MAX_BG[0], + HardLimits.VERY_HARD_LIMIT_MAX_BG[1] ) ) { validityCheck.isValid = false - validityCheck.reasons.add(resourceHelper.gs(R.string.value_out_of_hard_limits, resourceHelper.gs(R.string.profile_high_target), target.highTarget)) + validityCheck.reasons.add(rh.gs(R.string.value_out_of_hard_limits, rh.gs(R.string.profile_high_target), target.highTarget)) break } } return validityCheck } - protected open fun sendBelowMinimumNotification(from: String, rxBus: RxBus, resourceHelper: ResourceHelper) { - rxBus.send(EventNewNotification(Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.minimalbasalvaluereplaced, from), Notification.NORMAL))) + protected open fun sendBelowMinimumNotification(from: String, rxBus: RxBus, rh: ResourceHelper) { + rxBus.send(EventNewNotification(Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, rh.gs(R.string.minimalbasalvaluereplaced, from), Notification.NORMAL))) } - protected open fun sendAboveMaximumNotification(from: String, rxBus: RxBus, resourceHelper: ResourceHelper) { - rxBus.send(EventNewNotification(Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, resourceHelper.gs(R.string.maximumbasalvaluereplaced, from), Notification.NORMAL))) + protected open fun sendAboveMaximumNotification(from: String, rxBus: RxBus, rh: ResourceHelper) { + rxBus.send(EventNewNotification(Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, rh.gs(R.string.maximumbasalvaluereplaced, from), Notification.NORMAL))) } override val units: GlucoseUnit @@ -212,6 +212,7 @@ sealed class ProfileSealed( if (getTargetLowMgdlTimeFromMidnight(seconds) != profile.getTargetLowMgdlTimeFromMidnight(seconds)) return false if (getTargetHighMgdlTimeFromMidnight(seconds) != profile.getTargetHighMgdlTimeFromMidnight(seconds)) return false if (dia != profile.dia) return false + if ((profile is EPS) && profileName != profile.value.originalProfileName) return false // handle profile name change too } return true } @@ -239,10 +240,10 @@ sealed class ProfileSealed( private fun getTargetHighTimeFromMidnight(timeAsSeconds: Int): Double = targetBlocks.highTargetBlockValueBySeconds(timeAsSeconds, timeshift) override fun getTargetHighMgdlTimeFromMidnight(timeAsSeconds: Int): Double = toMgdl(targetBlocks.highTargetBlockValueBySeconds(timeAsSeconds, timeshift), units) - override fun getIcList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = getValuesList(icBlocks, 100.0 / percentage, DecimalFormat("0.0"), resourceHelper.gs(R.string.profile_carbs_per_unit), dateUtil) - override fun getIsfList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = getValuesList(isfBlocks, 100.0 / percentage, DecimalFormat("0.0"), units.asText + resourceHelper.gs(R.string.profile_per_unit), dateUtil) - override fun getBasalList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = getValuesList(basalBlocks, percentage / 100.0, DecimalFormat("0.00"), resourceHelper.gs(R.string.profile_ins_units_per_hour), dateUtil) - override fun getTargetList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = getTargetValuesList(targetBlocks, DecimalFormat("0.0"), units.asText, dateUtil) + override fun getIcList(rh: ResourceHelper, dateUtil: DateUtil): String = getValuesList(icBlocks, 100.0 / percentage, DecimalFormat("0.0"), rh.gs(R.string.profile_carbs_per_unit), dateUtil) + override fun getIsfList(rh: ResourceHelper, dateUtil: DateUtil): String = getValuesList(isfBlocks, 100.0 / percentage, DecimalFormat("0.0"), units.asText + rh.gs(R.string.profile_per_unit), dateUtil) + override fun getBasalList(rh: ResourceHelper, dateUtil: DateUtil): String = getValuesList(basalBlocks, percentage / 100.0, DecimalFormat("0.00"), rh.gs(R.string.profile_ins_units_per_hour), dateUtil) + override fun getTargetList(rh: ResourceHelper, dateUtil: DateUtil): String = getTargetValuesList(targetBlocks, DecimalFormat("0.0"), units.asText, dateUtil) override fun convertToNonCustomizedProfile(dateUtil: DateUtil): PureProfile = PureProfile( diff --git a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt index 6b8b5ef214..77985485bb 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt @@ -11,7 +11,7 @@ import javax.inject.Inject class PumpEnactResult(injector: HasAndroidInjector) { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper init { injector.androidInjector().inject(this) @@ -36,7 +36,7 @@ class PumpEnactResult(injector: HasAndroidInjector) { fun success(success: Boolean): PumpEnactResult = this.also { this.success = success } fun enacted(enacted: Boolean): PumpEnactResult = this.also { it.enacted = enacted } fun comment(comment: String): PumpEnactResult = this.also { it.comment = comment } - fun comment(comment: Int): PumpEnactResult = this.also { it.comment = resourceHelper.gs(comment) } + fun comment(comment: Int): PumpEnactResult = this.also { it.comment = rh.gs(comment) } fun duration(duration: Int): PumpEnactResult = this.also { it.duration = duration } fun absolute(absolute: Double): PumpEnactResult = this.also { it.absolute = absolute } fun percent(percent: Int): PumpEnactResult = this.also { it.percent = percent } @@ -61,75 +61,75 @@ class PumpEnactResult(injector: HasAndroidInjector) { } override fun toString(): String { - var ret = resourceHelper.gs(R.string.success) + ": " + success + var ret = rh.gs(R.string.success) + ": " + success if (enacted) { when { bolusDelivered > 0 -> { - ret += "\n${resourceHelper.gs(R.string.enacted)}: $enacted" - ret += "\n${resourceHelper.gs(R.string.comment)}: $comment" - ret += "\n${resourceHelper.gs(R.string.configbuilder_insulin)}: $bolusDelivered ${resourceHelper.gs(R.string.insulin_unit_shortname)}" + ret += "\n${rh.gs(R.string.enacted)}: $enacted" + ret += "\n${rh.gs(R.string.comment)}: $comment" + ret += "\n${rh.gs(R.string.configbuilder_insulin)}: $bolusDelivered ${rh.gs(R.string.insulin_unit_shortname)}" } isTempCancel -> { - ret += "\n${resourceHelper.gs(R.string.enacted)}: $enacted" - if (comment.isNotEmpty()) ret += "\n${resourceHelper.gs(R.string.comment)}: $comment" - ret += "\n${resourceHelper.gs(R.string.canceltemp)}" + ret += "\n${rh.gs(R.string.enacted)}: $enacted" + if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment" + ret += "\n${rh.gs(R.string.canceltemp)}" } isPercent -> { - ret += "\n${resourceHelper.gs(R.string.enacted)}: $enacted" - if (comment.isNotEmpty()) ret += "\n${resourceHelper.gs(R.string.comment)}: $comment" - ret += "\n${resourceHelper.gs(R.string.duration)}: $duration min" - ret += "\n${resourceHelper.gs(R.string.percent)}: $percent%" + ret += "\n${rh.gs(R.string.enacted)}: $enacted" + if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment" + ret += "\n${rh.gs(R.string.duration)}: $duration min" + ret += "\n${rh.gs(R.string.percent)}: $percent%" } else -> { - ret += "\n${resourceHelper.gs(R.string.enacted)}: $enacted" - if (comment.isNotEmpty()) ret += "\n${resourceHelper.gs(R.string.comment)}: $comment" - ret += "\n${resourceHelper.gs(R.string.duration)}: $duration min" - ret += "\n${resourceHelper.gs(R.string.absolute)}: $absolute U/h" + ret += "\n${rh.gs(R.string.enacted)}: $enacted" + if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment" + ret += "\n${rh.gs(R.string.duration)}: $duration min" + ret += "\n${rh.gs(R.string.absolute)}: $absolute U/h" } } } else { - ret += "\n${resourceHelper.gs(R.string.comment)}: $comment" + ret += "\n${rh.gs(R.string.comment)}: $comment" } return ret } fun toHtml(): String { - var ret = "" + resourceHelper.gs(R.string.success) + ": " + success + var ret = "" + rh.gs(R.string.success) + ": " + success if (queued) { - ret = resourceHelper.gs(R.string.waitingforpumpresult) + ret = rh.gs(R.string.waitingforpumpresult) } else if (enacted) { when { bolusDelivered > 0 -> { - ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted - if (comment.isNotEmpty()) ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment - ret += "
" + resourceHelper.gs(R.string.smb_shortname) + ": " + bolusDelivered + " " + resourceHelper.gs(R.string.insulin_unit_shortname) + ret += "
" + rh.gs(R.string.enacted) + ": " + enacted + if (comment.isNotEmpty()) ret += "
" + rh.gs(R.string.comment) + ": " + comment + ret += "
" + rh.gs(R.string.smb_shortname) + ": " + bolusDelivered + " " + rh.gs(R.string.insulin_unit_shortname) } isTempCancel -> { - ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted - ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment + - "
" + resourceHelper.gs(R.string.canceltemp) + ret += "
" + rh.gs(R.string.enacted) + ": " + enacted + ret += "
" + rh.gs(R.string.comment) + ": " + comment + + "
" + rh.gs(R.string.canceltemp) } isPercent && percent != -1 -> { - ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted - if (comment.isNotEmpty()) ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment - ret += "
" + resourceHelper.gs(R.string.duration) + ": " + duration + " min" - ret += "
" + resourceHelper.gs(R.string.percent) + ": " + percent + "%" + ret += "
" + rh.gs(R.string.enacted) + ": " + enacted + if (comment.isNotEmpty()) ret += "
" + rh.gs(R.string.comment) + ": " + comment + ret += "
" + rh.gs(R.string.duration) + ": " + duration + " min" + ret += "
" + rh.gs(R.string.percent) + ": " + percent + "%" } absolute != -1.0 -> { - ret += "
" + resourceHelper.gs(R.string.enacted) + ": " + enacted - if (comment.isNotEmpty()) ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment - ret += "
" + resourceHelper.gs(R.string.duration) + ": " + duration + " min" - ret += "
" + resourceHelper.gs(R.string.absolute) + ": " + DecimalFormatter.to2Decimal(absolute) + " U/h" + ret += "
" + rh.gs(R.string.enacted) + ": " + enacted + if (comment.isNotEmpty()) ret += "
" + rh.gs(R.string.comment) + ": " + comment + ret += "
" + rh.gs(R.string.duration) + ": " + duration + " min" + ret += "
" + rh.gs(R.string.absolute) + ": " + DecimalFormatter.to2Decimal(absolute) + " U/h" } } } else { - if (comment.isNotEmpty()) ret += "
" + resourceHelper.gs(R.string.comment) + ": " + comment + if (comment.isNotEmpty()) ret += "
" + rh.gs(R.string.comment) + ": " + comment } return ret } diff --git a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt index 556f473524..b67b8e50ff 100644 --- a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt +++ b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt @@ -27,7 +27,7 @@ open class CoreModule { @Provides @Singleton - fun provideSharedPreferences(context: Context, resourceHelper: ResourceHelper): SP = SPImplementation(PreferenceManager.getDefaultSharedPreferences(context), resourceHelper) + fun provideSharedPreferences(context: Context, rh: ResourceHelper): SP = SPImplementation(PreferenceManager.getDefaultSharedPreferences(context), rh) @Provides @Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt index eb139bd4c7..c73ad818eb 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.core.databinding.DialogBolusprogressBinding import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.events.EventPumpStatusChanged -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger @@ -25,14 +25,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy 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 javax.inject.Inject class BolusProgressDialog : DaggerDialogFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var rh: ResourceHelper + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uel: UserEntryLogger @@ -40,15 +41,22 @@ class BolusProgressDialog : DaggerDialogFragment() { private val disposable = CompositeDisposable() companion object { + var bolusEnded = false var stopPressed = false } private var running = true private var amount = 0.0 + var timestamp: Long = 0L private var state: String? = null private var helpActivity: BolusProgressHelperActivity? = null + fun setTimestamp(timestamp: Long): BolusProgressDialog { + this.timestamp = timestamp + return this + } + fun setInsulin(amount: Double): BolusProgressDialog { this.amount = amount bolusEnded = false @@ -66,8 +74,10 @@ class BolusProgressDialog : DaggerDialogFragment() { // onDestroyView. private val binding get() = _binding!! - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle?): View { + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View { dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) isCancelable = false @@ -80,8 +90,9 @@ class BolusProgressDialog : DaggerDialogFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { savedInstanceState?.let { amount = it.getDouble("amount") + timestamp = it.getLong("timestamp") } - binding.title.text = resourceHelper.gs(R.string.goingtodeliver, amount) + binding.title.text = rh.gs(R.string.goingtodeliver, amount) binding.stop.setOnClickListener { aapsLogger.debug(LTag.UI, "Stop bolus delivery button pressed") stopPressed = true @@ -90,7 +101,7 @@ class BolusProgressDialog : DaggerDialogFragment() { uel.log(Action.CANCEL_BOLUS, Sources.Overview, state) commandQueue.cancelAllBoluses() } - val defaultState = resourceHelper.gs(R.string.waitingforpump) + val defaultState = rh.gs(R.string.waitingforpump) binding.progressbar.max = 100 state = savedInstanceState?.getString("state", defaultState) ?: defaultState binding.status.text = state @@ -111,30 +122,30 @@ class BolusProgressDialog : DaggerDialogFragment() { if (bolusEnded) dismiss() else running = true - disposable.add(rxBus + disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ binding.status.text = it.getStatus(resourceHelper) }, fabricPrivacy::logException) - ) - disposable.add(rxBus + .subscribe({ binding.status.text = it.getStatus(rh) }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventDismissBolusProgressIfRunning::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ if (running) dismiss() }, fabricPrivacy::logException) - ) - disposable.add(rxBus + .subscribe({ + if (it.bolusTimestamp == null || it.bolusTimestamp == timestamp) + if (running) dismiss() + }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventOverviewBolusProgress::class.java) .observeOn(aapsSchedulers.main) .subscribe({ - aapsLogger.debug(LTag.UI, "Status: ${it.status} Percent: ${it.percent}") - binding.status.text = it.status - binding.progressbar.progress = it.percent - if (it.percent == 100) { - binding.stop.visibility = View.INVISIBLE - scheduleDismiss() - } - state = it.status - }, fabricPrivacy::logException) - ) + aapsLogger.debug(LTag.UI, "Status: ${it.status} Percent: ${it.percent}") + binding.status.text = it.status + binding.progressbar.progress = it.percent + if (it.percent == 100) { + binding.stop.visibility = View.INVISIBLE + scheduleDismiss() + } + state = it.status + }, fabricPrivacy::logException) } override fun dismiss() { @@ -161,6 +172,7 @@ class BolusProgressDialog : DaggerDialogFragment() { super.onSaveInstanceState(outState) outState.putString("state", state) outState.putDouble("amount", amount) + outState.putLong("timestamp", timestamp) } override fun onDestroyView() { diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt index d4b564cbb8..39e23a09d4 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt @@ -23,7 +23,7 @@ class NtpProgressDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -51,14 +51,14 @@ class NtpProgressDialog : DaggerDialogFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val defaultMessage = resourceHelper.gs(R.string.timedetection) - dialog?.setTitle(resourceHelper.gs(R.string.objectives)) + val defaultMessage = rh.gs(R.string.timedetection) + dialog?.setTitle(rh.gs(R.string.objectives)) binding.stop.setOnClickListener { dismiss() } binding.status.text = state ?: defaultMessage binding.progressbar.max = 100 binding.progressbar.progress = percent - binding.stop.text = resourceHelper.gs(R.string.close) - binding.title.text = resourceHelper.gs(R.string.please_wait) + binding.stop.text = rh.gs(R.string.close) + binding.title.text = rh.gs(R.string.please_wait) } override fun onResume() { diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index c0263cec07..b51f4fe50c 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -34,7 +34,7 @@ import javax.inject.Inject class ProfileViewerDialog : DaggerDialogFragment() { @Inject lateinit var injector: HasAndroidInjector - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var repository: AppRepository @@ -140,7 +140,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { profile?.let { profile1 -> profile2?.let { profile2 -> binding.units.text = profileFunction.getUnits().asText - binding.dia.text = HtmlHelper.fromHtml(formatColors("", profile1.dia, profile2.dia, DecimalFormat("0.00"), resourceHelper.gs(R.string.shorthour))) + binding.dia.text = HtmlHelper.fromHtml(formatColors("", profile1.dia, profile2.dia, DecimalFormat("0.00"), rh.gs(R.string.shorthour))) val profileNames = profileName!!.split("\n").toTypedArray() binding.activeprofile.text = HtmlHelper.fromHtml(formatColors(profileNames[0], profileNames[1])) binding.date.text = date @@ -152,25 +152,25 @@ class ProfileViewerDialog : DaggerDialogFragment() { } binding.noprofile.visibility = View.GONE - val validity = profile1.isValid("ProfileViewDialog", activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) - binding.invalidprofile.text = resourceHelper.gs(R.string.invalidprofile) + "\n" + validity.reasons.joinToString(separator = "\n") + val validity = profile1.isValid("ProfileViewDialog", activePlugin.activePump, config, rh, rxBus, hardLimits, false) + binding.invalidprofile.text = rh.gs(R.string.invalidprofile) + "\n" + validity.reasons.joinToString(separator = "\n") binding.invalidprofile.visibility = validity.isValid.not().toVisibility() } else profile?.let { binding.units.text = it.units.asText - binding.dia.text = resourceHelper.gs(R.string.format_hours, it.dia) + binding.dia.text = rh.gs(R.string.format_hours, it.dia) binding.activeprofile.text = profileName binding.date.text = date - binding.ic.text = it.getIcList(resourceHelper, dateUtil) - binding.isf.text = it.getIsfList(resourceHelper, dateUtil) - binding.basal.text = it.getBasalList(resourceHelper, dateUtil) - binding.target.text = it.getTargetList(resourceHelper, dateUtil) + binding.ic.text = it.getIcList(rh, dateUtil) + binding.isf.text = it.getIsfList(rh, dateUtil) + binding.basal.text = it.getBasalList(rh, dateUtil) + binding.target.text = it.getTargetList(rh, dateUtil) binding.basalGraph.show(it) binding.noprofile.visibility = View.GONE - val validity = it.isValid("ProfileViewDialog", activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) - binding.invalidprofile.text = resourceHelper.gs(R.string.invalidprofile) + "\n" + validity.reasons.joinToString(separator = "\n") + val validity = it.isValid("ProfileViewDialog", activePlugin.activePump, config, rh, rxBus, hardLimits, false) + binding.invalidprofile.text = rh.gs(R.string.invalidprofile) + "\n" + validity.reasons.joinToString(separator = "\n") binding.invalidprofile.visibility = validity.isValid.not().toVisibility() } } @@ -200,20 +200,20 @@ class ProfileViewerDialog : DaggerDialogFragment() { } private fun formatColors(label: String, text1: String, text2: String, units: String): String { - var s = "$label" + var s = "$label" s += " " - s += "$text1" + s += "$text1" s += " " - s += "$text2" + s += "$text2" s += " " - s += "$units" + s += "$units" return s } private fun formatColors(text1: String, text2: String): String { - var s = "$text1" + var s = "$text1" s += "
" - s += "$text2" + s += "$text2" return s } @@ -225,7 +225,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = profile1.getBasalTimeFromMidnight(hour * 60 * 60) val val2 = profile2.getBasalTimeFromMidnight(hour * 60 * 60) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.00"), " " + resourceHelper.gs(R.string.profile_ins_units_per_hour))) + s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.00"), " " + rh.gs(R.string.profile_ins_units_per_hour))) s.append("
") } prev1 = val1 @@ -236,7 +236,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { profile1.baseBasalSum(), profile2.baseBasalSum(), DecimalFormat("0.00"), - resourceHelper.gs(R.string.insulin_unit_shortname))) + rh.gs(R.string.insulin_unit_shortname))) return HtmlHelper.fromHtml(s.toString()) } @@ -248,7 +248,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = profile1.getIcTimeFromMidnight(hour * 60 * 60) val val2 = profile2.getIcTimeFromMidnight(hour * 60 * 60) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), " " + resourceHelper.gs(R.string.profile_carbs_per_unit))) + s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), " " + rh.gs(R.string.profile_carbs_per_unit))) s.append("
") } prev1 = val1 @@ -266,7 +266,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = Profile.fromMgdlToUnits(profile1.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) val val2 = Profile.fromMgdlToUnits(profile2.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), units.asText + " " + resourceHelper.gs(R.string.profile_per_unit))) + s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), units.asText + " " + rh.gs(R.string.profile_per_unit))) s.append("
") } prev1 = val1 diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt b/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt index 2938a005c4..04afc9e486 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt @@ -11,11 +11,11 @@ class EventPreferenceChange : Event { changedKey = key } - constructor(resourceHelper: ResourceHelper, resourceID: Int) { - changedKey = resourceHelper.gs(resourceID) + constructor(rh: ResourceHelper, resourceID: Int) { + changedKey = rh.gs(resourceID) } - fun isChanged(resourceHelper: ResourceHelper, id: Int): Boolean { - return changedKey == resourceHelper.gs(id) + fun isChanged(rh: ResourceHelper, id: Int): Boolean { + return changedKey == rh.gs(id) } } diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt b/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt index e65a7fe6e5..bb88afde62 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt @@ -45,14 +45,14 @@ class EventPumpStatusChanged : EventStatus { } // status for startup wizard - override fun getStatus(resourceHelper: ResourceHelper): String { + override fun getStatus(rh: ResourceHelper): String { return when (status) { - Status.CONNECTING -> String.format(resourceHelper.gs(R.string.connectingfor), secondsElapsed) - Status.HANDSHAKING -> resourceHelper.gs(R.string.handshaking) - Status.CONNECTED -> resourceHelper.gs(R.string.connected) + Status.CONNECTING -> String.format(rh.gs(R.string.connectingfor), secondsElapsed) + Status.HANDSHAKING -> rh.gs(R.string.handshaking) + Status.CONNECTED -> rh.gs(R.string.connected) Status.PERFORMING -> performingAction - Status.WAITING_FOR_DISCONNECTION -> resourceHelper.gs(R.string.waiting_for_disconnection) - Status.DISCONNECTING -> resourceHelper.gs(R.string.disconnecting) + Status.WAITING_FOR_DISCONNECTION -> rh.gs(R.string.waiting_for_disconnection) + Status.DISCONNECTING -> rh.gs(R.string.disconnecting) Status.DISCONNECTED -> "" } } diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt b/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt index 88c8073e69..bb88f3529a 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt @@ -4,5 +4,5 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper // pass string to startup wizard abstract class EventStatus : Event() { - abstract fun getStatus(resourceHelper: ResourceHelper) : String + abstract fun getStatus(rh: ResourceHelper) : String } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt index d42d4c4b41..339dd0b797 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt @@ -50,10 +50,10 @@ fun ExtendedBolus.toTemporaryBasal(profile: Profile): TemporaryBasal = type = TemporaryBasal.Type.FAKE_EXTENDED ) -fun ExtendedBolus.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil, useAbsolute: Boolean): JSONObject = +fun ExtendedBolus.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil): JSONObject = if (isEmulatingTempBasal) toTemporaryBasal(profile) - .toJson(isAdd, profile, dateUtil, useAbsolute) + .toJson(isAdd, profile, dateUtil) .put("extendedEmulated", toRealJson(isAdd, dateUtil)) else toRealJson(isAdd, dateUtil) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt b/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt index e72d37e334..56c6e6b46b 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt @@ -6,6 +6,6 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper fun String.formatBold(): String = "$this" -fun String.formatColor(resourceHelper: ResourceHelper, @ColorRes colorId: Int): String = - "" + this + "" +fun String.formatColor(rh: ResourceHelper, @ColorRes colorId: Int): String = + "" + this + "" diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt b/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt index 3a42eabe4b..15f400315a 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt @@ -5,43 +5,43 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONObject -fun JSONObject.putInt(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject = - if (sp.contains(key)) put(resourceHelper.gs(key), sp.getInt(key, 0)) else this +fun JSONObject.putInt(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = + if (sp.contains(key)) put(rh.gs(key), sp.getInt(key, 0)) else this -fun JSONObject.putLong(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject = - if (sp.contains(key)) put(resourceHelper.gs(key), sp.getLong(key, 0)) else this +fun JSONObject.putLong(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = + if (sp.contains(key)) put(rh.gs(key), sp.getLong(key, 0)) else this -fun JSONObject.putDouble(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject = - if (sp.contains(key)) put(resourceHelper.gs(key), sp.getDouble(key, 0.0)) else this +fun JSONObject.putDouble(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = + if (sp.contains(key)) put(rh.gs(key), sp.getDouble(key, 0.0)) else this -fun JSONObject.putString(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject = - if (sp.contains(key)) put(resourceHelper.gs(key), sp.getString(key, "")) else this +fun JSONObject.putString(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = + if (sp.contains(key)) put(rh.gs(key), sp.getString(key, "")) else this -fun JSONObject.putBoolean(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject = - if (sp.contains(key)) put(resourceHelper.gs(key), sp.getBoolean(key, false)) else this +fun JSONObject.putBoolean(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject = + if (sp.contains(key)) put(rh.gs(key), sp.getBoolean(key, false)) else this -fun JSONObject.storeInt(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject { - if (has(resourceHelper.gs(key))) sp.putString(key, getInt(resourceHelper.gs(key)).toString()) +fun JSONObject.storeInt(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { + if (has(rh.gs(key))) sp.putString(key, getInt(rh.gs(key)).toString()) return this } -fun JSONObject.storeLong(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject { - if (has(resourceHelper.gs(key))) sp.putString(key, getLong(resourceHelper.gs(key)).toString()) +fun JSONObject.storeLong(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { + if (has(rh.gs(key))) sp.putString(key, getLong(rh.gs(key)).toString()) return this } -fun JSONObject.storeDouble(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject { - if (has(resourceHelper.gs(key))) sp.putString(key, getDouble(resourceHelper.gs(key)).toString()) +fun JSONObject.storeDouble(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { + if (has(rh.gs(key))) sp.putString(key, getDouble(rh.gs(key)).toString()) return this } -fun JSONObject.storeString(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject { - if (has(resourceHelper.gs(key))) sp.putString(key, getString(resourceHelper.gs(key)).toString()) +fun JSONObject.storeString(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { + if (has(rh.gs(key))) sp.putString(key, getString(rh.gs(key)).toString()) return this } -fun JSONObject.storeBoolean(@StringRes key: Int, sp: SP, resourceHelper: ResourceHelper): JSONObject { - if (has(resourceHelper.gs(key))) sp.putString(key, getBoolean(resourceHelper.gs(key)).toString()) +fun JSONObject.storeBoolean(@StringRes key: Int, sp: SP, rh: ResourceHelper): JSONObject { + if (has(rh.gs(key))) sp.putString(key, getBoolean(rh.gs(key)).toString()) return this } diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt index fcb480a87c..876a544300 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/ProfileSwitchExtension.kt @@ -97,8 +97,8 @@ fun profileSwitchFromJson(jsonObject: JSONObject, dateUtil: DateUtil, activePlug */ fun pureProfileFromJson(jsonObject: JSONObject, dateUtil: DateUtil, defaultUnits: String? = null): PureProfile? { try { - JsonHelper.safeGetStringAllowNull(jsonObject, "units", defaultUnits) ?: return null - val units = GlucoseUnit.fromText(JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL)) + val txtUnits = JsonHelper.safeGetStringAllowNull(jsonObject, "units", defaultUnits) ?: return null + val units = GlucoseUnit.fromText(txtUnits) val dia = JsonHelper.safeGetDoubleAllowNull(jsonObject, "dia") ?: return null val timezone = TimeZone.getTimeZone(JsonHelper.safeGetString(jsonObject, "timezone", "UTC")) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt index fca80bd85b..b80ca45c65 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt @@ -62,7 +62,7 @@ fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil): String { } } -fun TemporaryBasal.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil, useAbsolute: Boolean): JSONObject = +fun TemporaryBasal.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil): JSONObject = JSONObject() .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", "openaps://" + "AndroidAPS") @@ -72,9 +72,9 @@ fun TemporaryBasal.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil, .put("durationInMilliseconds", duration) // rounded duration leads to different basal IOB .put("rate", rate) .put("type", type.name) + .put("isAbsolute", isAbsolute) + .put("absolute", convertedToAbsolute(timestamp, profile)) .also { - if (useAbsolute) it.put("absolute", convertedToAbsolute(timestamp, profile)) - else it.put("percent", convertedToPercent(timestamp, profile) - 100) if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) if (interfaceIDs.endId != null) it.put("endId", interfaceIDs.endId) if (interfaceIDs.pumpType != null) it.put("pumpType", interfaceIDs.pumpType!!.name) @@ -82,21 +82,11 @@ fun TemporaryBasal.toJson(isAdd: Boolean, profile: Profile, dateUtil: DateUtil, if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) } -/* - create fake object with nsID and isValid == false - */ -fun temporaryBasalFromNsIdForInvalidating(nsId: String): TemporaryBasal = - temporaryBasalFromJson( - JSONObject() - .put("mills", 1) - .put("absolute", 1.0) - .put("duration", 1.0) - .put("_id", nsId) - .put("isValid", false) - )!! - +@Suppress("IfThenToElvis") fun temporaryBasalFromJson(jsonObject: JSONObject): TemporaryBasal? { val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null + var rate = JsonHelper.safeGetDoubleAllowNull(jsonObject, "rate") + var isAbsolute = JsonHelper.safeGetBooleanAllowNull(jsonObject, "isAbsolute") val percent = JsonHelper.safeGetDoubleAllowNull(jsonObject, "percent") val absolute = JsonHelper.safeGetDoubleAllowNull(jsonObject, "absolute") val duration = JsonHelper.safeGetLongAllowNull(jsonObject, "duration") ?: return null @@ -109,7 +99,16 @@ fun temporaryBasalFromJson(jsonObject: JSONObject): TemporaryBasal? { val pumpType = InterfaceIDs.PumpType.fromString(JsonHelper.safeGetStringAllowNull(jsonObject, "pumpType", null)) val pumpSerial = JsonHelper.safeGetStringAllowNull(jsonObject, "pumpSerial", null) - val rate = if (percent != null) percent + 100 else absolute ?: return null + if (rate == null) { + if (absolute != null) { + rate = absolute + isAbsolute = true + } else if (percent != null) { + rate = percent + 100 + isAbsolute = false + } else return null + } + if (isAbsolute == null) return null if (duration == 0L) return null if (timestamp == 0L) return null @@ -118,7 +117,7 @@ fun temporaryBasalFromJson(jsonObject: JSONObject): TemporaryBasal? { rate = rate, duration = durationInMilliseconds ?: T.mins(duration).msecs(), type = type, - isAbsolute = percent == null, + isAbsolute = isAbsolute, isValid = isValid ).also { it.interfaceIDs.nightscoutId = id diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt index cb4e48454f..37b00f7c07 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt @@ -28,10 +28,10 @@ fun TemporaryTarget.highValueToUnitsToString(units: GlucoseUnit): String = fun TemporaryTarget.target(): Double = (this.lowTarget + this.highTarget) / 2 -fun TemporaryTarget.friendlyDescription(units: GlucoseUnit, resourceHelper: ResourceHelper): String = +fun TemporaryTarget.friendlyDescription(units: GlucoseUnit, rh: ResourceHelper): String = Profile.toTargetRangeString(lowTarget, highTarget, GlucoseUnit.MGDL, units) + units.asText + - "@" + resourceHelper.gs(R.string.format_mins, TimeUnit.MILLISECONDS.toMinutes(duration)) + "(" + reason.text + ")" + "@" + rh.gs(R.string.format_mins, TimeUnit.MILLISECONDS.toMinutes(duration)) + "(" + reason.text + ")" /* create fake object with nsID and isValid == false diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt index 893baf09a2..c18ef9a31f 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt @@ -12,13 +12,13 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import java.util.concurrent.TimeUnit -fun TherapyEvent.age(useShortText: Boolean, resourceHelper: ResourceHelper, dateUtil: DateUtil): String { +fun TherapyEvent.age(useShortText: Boolean, rh: ResourceHelper, dateUtil: DateUtil): String { val diff = dateUtil.computeDiff(timestamp, System.currentTimeMillis()) - var days = " " + resourceHelper.gs(R.string.days) + " " - var hours = " " + resourceHelper.gs(R.string.hours) + " " + var days = " " + rh.gs(R.string.days) + " " + var hours = " " + rh.gs(R.string.hours) + " " if (useShortText) { - days = resourceHelper.gs(R.string.shortday) - hours = resourceHelper.gs(R.string.shorthour) + days = rh.gs(R.string.shortday) + hours = rh.gs(R.string.shorthour) } return diff[TimeUnit.DAYS].toString() + days + diff[TimeUnit.HOURS] + hours } diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt index eab8085a8c..31f228125f 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt @@ -4,7 +4,6 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.TotalDailyDose import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* val TotalDailyDose.total get() = if (totalAmount > 0) totalAmount else basalAmount + bolusAmount @@ -12,10 +11,12 @@ val TotalDailyDose.total val TotalDailyDose.basalPct: Double get() = if (total > 0) basalAmount / total * 100 else 0.0 -fun TotalDailyDose.toText(resourceHelper: ResourceHelper, dateUtil: DateUtil, includeCarbs: Boolean): String = - if (includeCarbs) resourceHelper.gs(R.string.tddwithcarbsformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalPct, carbs) - else resourceHelper.gs(R.string.tddformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalPct) +fun TotalDailyDose.toText(rh: ResourceHelper, dateUtil: DateUtil, includeCarbs: Boolean): String = + if (total.isNaN() || bolusAmount.isNaN() || basalAmount.isNaN() || carbs.isNaN()) "" + else if (includeCarbs) rh.gs(R.string.tddwithcarbsformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalPct, carbs) + else rh.gs(R.string.tddformat, dateUtil.dateStringShort(timestamp), total, bolusAmount, basalAmount, basalPct) -fun TotalDailyDose.toText(resourceHelper: ResourceHelper, days: Int, includeCarbs: Boolean): String = - if (includeCarbs) resourceHelper.gs(R.string.tddwithcarbsformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100, carbs) - else resourceHelper.gs(R.string.tddformat, String.format(Locale.getDefault(), "%d ", days) + resourceHelper.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100) +fun TotalDailyDose.toText(rh: ResourceHelper, days: Int, includeCarbs: Boolean): String = + if (total.isNaN() || bolusAmount.isNaN() || basalAmount.isNaN() || carbs.isNaN()) "" + else if (includeCarbs) rh.gs(R.string.tddwithcarbsformat, days.toString() + rh.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100, carbs) + else rh.gs(R.string.tddformat, days.toString() + rh.gs(R.string.days), total, bolusAmount, basalAmount, basalAmount / total * 100) diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueue.kt similarity index 98% rename from core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt rename to core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueue.kt index 31fb77e6b1..7218b06df2 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueueProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/CommandQueue.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.commands.Command -interface CommandQueueProvider { +interface CommandQueue { fun isRunning(type: Command.CommandType): Boolean fun pickup() diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt index 9e3a9d428a..7c75e0ebc8 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt @@ -64,6 +64,17 @@ interface IobCobCalculator { */ fun getTempBasalIncludingConvertedExtended(timestamp: Long): TemporaryBasal? + /** + * Get running temporary basals for given time range, sliced by calculationStep. + * For each step between given range it calculates equivalent of getTempBasalIncludingConvertedExtended + * + * @param startTime start of calculated period, timestamp + * @param endTime end of calculated period, timestamp + * @param calculationStep calculation step, in millisecond + * @return map where for each step, its timestamp is a key and calculated optional temporary basal is a value + */ + fun getTempBasalIncludingConvertedExtendedForRange(startTime: Long, endTime: Long, calculationStep: Long): Map + /** * Get running extended bolus at time * diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt index 9e47f94639..a5972f31a7 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper abstract class PluginBase( val pluginDescription: PluginDescription, val aapsLogger: AAPSLogger, - val resourceHelper: ResourceHelper, + val rh: ResourceHelper, val injector: HasAndroidInjector ) { @@ -30,20 +30,20 @@ abstract class PluginBase( get() = pluginDescription.pluginIcon2 open val name: String - get() = if (pluginDescription.pluginName == -1) "UNKNOWN" else resourceHelper.gs(pluginDescription.pluginName) + get() = if (pluginDescription.pluginName == -1) "UNKNOWN" else rh.gs(pluginDescription.pluginName) //only if translation exists // use long name as fallback val nameShort: String get() { if (pluginDescription.shortName == -1) return name - val translatedName = resourceHelper.gs(pluginDescription.shortName) + val translatedName = rh.gs(pluginDescription.shortName) return if (translatedName.trim { it <= ' ' }.isNotEmpty()) translatedName else name // use long name as fallback } val description: String? - get() = if (pluginDescription.description == -1) null else resourceHelper.gs(pluginDescription.description) + get() = if (pluginDescription.description == -1) null else rh.gs(pluginDescription.description) fun getType(): PluginType = pluginDescription.mainType diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt index 9947426be4..7c808c3bbc 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt @@ -16,7 +16,7 @@ interface Profile { class ValidityCheck(var isValid: Boolean = true, val reasons: ArrayList = arrayListOf()) - fun isValid(from: String, pump: Pump, config: Config, resourceHelper: ResourceHelper, rxBus: RxBus, hardLimits: HardLimits, sendNotifications: Boolean): ValidityCheck + fun isValid(from: String, pump: Pump, config: Config, rh: ResourceHelper, rxBus: RxBus, hardLimits: HardLimits, sendNotifications: Boolean): ValidityCheck /** * Units used for ISF & target @@ -101,10 +101,10 @@ interface Profile { */ fun getTargetHighMgdlTimeFromMidnight(timeAsSeconds: Int): Double - fun getIcList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String - fun getIsfList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String - fun getBasalList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String - fun getTargetList(resourceHelper: ResourceHelper, dateUtil: DateUtil): String + fun getIcList(rh: ResourceHelper, dateUtil: DateUtil): String + fun getIsfList(rh: ResourceHelper, dateUtil: DateUtil): String + fun getBasalList(rh: ResourceHelper, dateUtil: DateUtil): String + fun getTargetList(rh: ResourceHelper, dateUtil: DateUtil): String fun convertToNonCustomizedProfile(dateUtil: DateUtil): PureProfile fun toPureNsJson(dateUtil: DateUtil): JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileFunction.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileFunction.kt index 03b2f03590..73d20102b4 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileFunction.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileFunction.kt @@ -55,8 +55,9 @@ interface ProfileFunction { * @param percentage 100 = no modification * @param timeShiftInHours 0 = no modification * @param timestamp expected time + * @return null if profile cannot be created from profile store */ - fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch + fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes:Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch? /** * Create a new circadian profile switch request based on provided profile @@ -67,8 +68,9 @@ interface ProfileFunction { * @param percentage 100 = no modification * @param timeShiftInHours 0 = no modification * @param timestamp expected time + * @return true if profile was created from store */ - fun createProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long) + fun createProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): Boolean /** * Create a new circadian profile switch request based on currently selected profile interface and default profile diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt index 03b0d773bf..c3a9e7e8df 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/ProfileStore.kt @@ -22,6 +22,8 @@ class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject, val d private val cachedObjects = ArrayMap() + private fun storeUnits() : String? = JsonHelper.safeGetStringAllowNull(data, "units", null) + private fun getStore(): JSONObject? { try { if (data.has("store")) return data.getJSONObject("store") @@ -31,8 +33,8 @@ class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject, val d return null } - fun getCreatedAt(): Long { - val iso = JsonHelper.safeGetString(data, "created_at") ?: return 0 + fun getStartDate(): Long { + val iso = JsonHelper.safeGetString(data, "startDate") ?: return 0 return try { dateUtil.fromISODateString(iso) } catch (e: Exception) { @@ -61,14 +63,14 @@ class ProfileStore(val injector: HasAndroidInjector, val data: JSONObject, val d fun getSpecificProfile(profileName: String): PureProfile? { var profile: PureProfile? = null - val defaultUnits = JsonHelper.safeGetStringAllowNull(data, "units", null) + val units = JsonHelper.safeGetStringAllowNull(data, "units", storeUnits()) getStore()?.let { store -> if (store.has(profileName)) { profile = cachedObjects[profileName] if (profile == null) { JsonHelper.safeGetJSONObject(store, profileName, null)?.let { profileObject -> - profile = pureProfileFromJson(profileObject, dateUtil, defaultUnits) - cachedObjects[profileName] = profile + profile = pureProfileFromJson(profileObject, dateUtil, units) + profile?.let { cachedObjects[profileName] = profile } } } } diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Pump.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Pump.kt index 969c85163c..c044aee4cb 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/Pump.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/Pump.kt @@ -254,7 +254,7 @@ interface Pump { /** * Executes a custom queued command - * See [CommandQueueProvider.customCommand] for queuing a custom command. + * See [CommandQueue.customCommand] for queuing a custom command. * * @param customCommand the custom command to be executed * @return PumpEnactResult that represents the command execution result diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt index 2def7e2aff..0c324bc0fe 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt @@ -9,9 +9,9 @@ abstract class PumpPluginBase( pluginDescription: PluginDescription, injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, - val commandQueue: CommandQueueProvider -) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector) { + rh: ResourceHelper, + val commandQueue: CommandQueue +) : PluginBase(pluginDescription, aapsLogger, rh, injector) { override fun onStart() { super.onStart() diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt index 6c7633e693..5c5aaed393 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt @@ -39,7 +39,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil var date: Long = 0 @@ -97,56 +97,56 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { } val carbsRequiredText: String - get() = String.format(resourceHelper.gs(R.string.carbsreq), carbsReq, carbsReqWithin) + get() = String.format(rh.gs(R.string.carbsreq), carbsReq, carbsReqWithin) override fun toString(): String { val pump = activePlugin.activePump if (isChangeRequested) { // rate - var ret: String = if (rate == 0.0 && duration == 0) "${resourceHelper.gs(R.string.canceltemp)} " - else if (rate == -1.0) "${resourceHelper.gs(R.string.let_temp_basal_run)}\n" - else if (usePercent) "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + - "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " - else "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + - "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " + var ret: String = if (rate == 0.0 && duration == 0) "${rh.gs(R.string.canceltemp)} " + else if (rate == -1.0) "${rh.gs(R.string.let_temp_basal_run)}\n" + else if (usePercent) "${rh.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + + "${rh.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " + else "${rh.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + + "${rh.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " // smb - if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper)} " + if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh)} " if (isCarbsRequired) { ret += "$carbsRequiredText " } // reason - ret += resourceHelper.gs(R.string.reason) + ": " + reason + ret += rh.gs(R.string.reason) + ": " + reason return ret } return if (isCarbsRequired) { carbsRequiredText - } else resourceHelper.gs(R.string.nochangerequested) + } else rh.gs(R.string.nochangerequested) } fun toSpanned(): Spanned { val pump = activePlugin.activePump if (isChangeRequested) { // rate - var ret: String = if (rate == 0.0 && duration == 0) resourceHelper.gs(R.string.canceltemp) + "
" else if (rate == -1.0) resourceHelper.gs(R.string.let_temp_basal_run) + "
" else if (usePercent) "" + resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent.toDouble()) + "% " + + var ret: String = if (rate == 0.0 && duration == 0) rh.gs(R.string.canceltemp) + "
" else if (rate == -1.0) rh.gs(R.string.let_temp_basal_run) + "
" else if (usePercent) "" + rh.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(percent.toDouble()) + "% " + "(" + DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)
" + - "" + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + resourceHelper.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + + "" + rh.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + rh.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + "(" + DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%)
" + - "" + resourceHelper.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" + "" + rh.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" // smb - if (smb != 0.0) ret += "" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper) + "
" + if (smb != 0.0) ret += "" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh) + "
" if (isCarbsRequired) { ret += "$carbsRequiredText
" } // reason - ret += "" + resourceHelper.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">") + ret += "" + rh.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">") return fromHtml(ret) } return if (isCarbsRequired) { fromHtml(carbsRequiredText) - } else fromHtml(resourceHelper.gs(R.string.nochangerequested)) + } else fromHtml(rh.gs(R.string.nochangerequested)) } open fun newAndClone(injector: HasAndroidInjector): APSResult { diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt index 3b47c4670a..0aa41d107e 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -63,7 +63,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isLoopInvocationAllowed(value) } return value @@ -73,7 +73,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isClosedLoopAllowed(value) } return value @@ -83,7 +83,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isLgsAllowed(value) } return value @@ -93,7 +93,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isAutosensModeEnabled(value) } return value @@ -103,7 +103,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isSMBModeEnabled(value) } return value @@ -113,7 +113,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isUAMEnabled(value) } return value @@ -123,7 +123,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isAdvancedFilteringEnabled(value) } return value @@ -133,7 +133,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isSuperBolusEnabled(value) } return value @@ -143,7 +143,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.applyBasalConstraints(absoluteRate, profile) } return absoluteRate @@ -153,7 +153,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constrain = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constrain.applyBasalPercentConstraints(percentRate, profile) } return percentRate @@ -163,7 +163,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constrain = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constrain.applyBolusConstraints(insulin) } return insulin @@ -173,7 +173,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constrain = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constrain.applyExtendedBolusConstraints(insulin) } return insulin @@ -183,7 +183,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constrain = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constrain.applyCarbsConstraints(carbs) } return carbs @@ -193,7 +193,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constrain = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constrain.applyMaxIOBConstraints(maxIob) } return maxIob @@ -203,7 +203,7 @@ class ConstraintChecker @Inject constructor(private val activePlugin: ActivePlug val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) for (p in constraintsPlugins) { val constraint = p as Constraints - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + if (!p.isEnabled()) continue constraint.isAutomationEnabled(value) } return value diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt index 1cf6adb708..2e5b3871b5 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt @@ -24,8 +24,9 @@ class RunningConfiguration @Inject constructor( private val sp: SP, private val aapsLogger: AAPSLogger, private val config: Config, - private val resourceHelper: ResourceHelper, - private val rxBus: RxBus + private val rh: ResourceHelper, + private val rxBus: RxBus, + private val pumpSync: PumpSync ) { private var counter = 0 @@ -34,11 +35,13 @@ class RunningConfiguration @Inject constructor( // called in AAPS mode only fun configuration(): JSONObject { val json = JSONObject() + val pumpInterface = activePlugin.activePump + + if (!pumpInterface.isInitialized()) return json if (counter++ % every == 0) try { val insulinInterface = activePlugin.activeInsulin val sensitivityInterface = activePlugin.activeSensitivity - val pumpInterface = activePlugin.activePump val overviewInterface = activePlugin.activeOverview val safetyInterface = activePlugin.activeSafety @@ -61,7 +64,7 @@ class RunningConfiguration @Inject constructor( if (configuration.has("version")) { rxBus.send(EventNSClientNewLog("VERSION", "Received AndroidAPS version ${configuration.getString("version")}")) if (config.VERSION_NAME.startsWith(configuration.getString("version")).not()) { - rxBus.send(EventNewNotification(Notification(Notification.NSCLIENT_VERSION_DOES_NOT_MATCH, resourceHelper.gs(R.string.nsclient_version_does_not_match), Notification.NORMAL))) + rxBus.send(EventNewNotification(Notification(Notification.NSCLIENT_VERSION_DOES_NOT_MATCH, rh.gs(R.string.nsclient_version_does_not_match), Notification.NORMAL))) } } if (configuration.has("insulin")) { @@ -94,9 +97,12 @@ class RunningConfiguration @Inject constructor( if (configuration.has("pump")) { val pumpType = JsonHelper.safeGetString(configuration, "pump", PumpType.GENERIC_AAPS.description) - sp.putString(R.string.key_virtualpump_type, pumpType) - activePlugin.activePump.pumpDescription.fillFor(PumpType.getByDescription(pumpType)) - aapsLogger.debug(LTag.CORE, "Changing pump type to $pumpType") + if (sp.getString(R.string.key_virtualpump_type, "fake") != pumpType) { + sp.putString(R.string.key_virtualpump_type, pumpType) + activePlugin.activePump.pumpDescription.fillFor(PumpType.getByDescription(pumpType)) + pumpSync.connectNewPump() + aapsLogger.debug(LTag.CORE, "Changing pump type to $pumpType") + } } if (configuration.has("overviewConfiguration")) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt index da7a41ce28..ce9d6a7ab1 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.io.IOException @@ -22,7 +23,7 @@ import javax.inject.Singleton class VersionCheckerUtils @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val rxBus: RxBus, private val config: Config, private val receiverStatusStore: ReceiverStatusStore, @@ -60,11 +61,11 @@ class VersionCheckerUtils @Inject constructor( compareWithCurrentVersion(version, config.VERSION_NAME) // App expiration - var endDate = sp.getLong(resourceHelper.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) + var endDate = sp.getLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) AllowedVersions().findByVersion(definition, config.VERSION_NAME)?.let { expirationJson -> AllowedVersions().endDateToMilliseconds(expirationJson.getString("endDate"))?.let { ed -> - sp.putLong(resourceHelper.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, ed) - endDate = ed + endDate = ed + T.days(1).msecs() + sp.putLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, endDate) } } if (endDate != 0L) onExpiredVersionDetected(config.VERSION_NAME, dateUtil.dateString(endDate)) @@ -127,7 +128,7 @@ class VersionCheckerUtils @Inject constructor( aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion") val notification = Notification( Notification.NEW_VERSION_DETECTED, - resourceHelper.gs(R.string.versionavailable, newVersion.toString()), + rh.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW ) rxBus.send(EventNewNotification(notification)) @@ -141,7 +142,7 @@ class VersionCheckerUtils @Inject constructor( aapsLogger.debug(LTag.CORE, "Version $currentVersion expired.") val notification = Notification( Notification.VERSION_EXPIRE, - resourceHelper.gs(R.string.version_expire, currentVersion, endDate), + rh.gs(R.string.version_expire, currentVersion, endDate), Notification.LOW ) rxBus.send(EventNewNotification(notification)) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt index f46c12abc3..e7234602b0 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -22,7 +22,7 @@ import kotlin.math.abs @OpenForTesting @Singleton class PrefFileListProvider @Inject constructor( - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val config: Config, private val encryptedPrefsFormat: EncryptedPrefsFormat, private val storage: Storage, @@ -86,7 +86,7 @@ class PrefFileListProvider @Inject constructor( } fun legacyFile(): File { - return File(path, resourceHelper.gs(R.string.app_name) + "Preferences") + return File(path, rh.gs(R.string.app_name) + "Preferences") } fun ensureExportDirExists(): File { @@ -131,14 +131,14 @@ class PrefFileListProvider @Inject constructor( val flavourOfPrefs = flavour.value if (flavour.value != config.FLAVOR) { flavour.status = PrefsStatus.WARN - flavour.info = resourceHelper.gs(R.string.metadata_warning_different_flavour, flavourOfPrefs, config.FLAVOR) + flavour.info = rh.gs(R.string.metadata_warning_different_flavour, flavourOfPrefs, config.FLAVOR) } } meta[PrefsMetadataKey.DEVICE_MODEL]?.let { model -> if (model.value != config.currentDeviceModelString) { model.status = PrefsStatus.WARN - model.info = resourceHelper.gs(R.string.metadata_warning_different_device) + model.info = rh.gs(R.string.metadata_warning_different_device) } } @@ -151,11 +151,11 @@ class PrefFileListProvider @Inject constructor( if (daysOld > IMPORT_AGE_NOT_YET_OLD_DAYS) { createdAt.status = PrefsStatus.WARN - createdAt.info = resourceHelper.gs(R.string.metadata_warning_old_export, daysOld.toString()) + createdAt.info = rh.gs(R.string.metadata_warning_old_export, daysOld.toString()) } } catch (e: Exception) { createdAt.status = PrefsStatus.WARN - createdAt.info = resourceHelper.gs(R.string.metadata_warning_date_format) + createdAt.info = rh.gs(R.string.metadata_warning_date_format) } } @@ -165,12 +165,12 @@ class PrefFileListProvider @Inject constructor( if ((currentAppVer.size >= 2) && (metadataVer.size >= 2) && (abs(currentAppVer[1] - metadataVer[1]) > 1)) { version.status = PrefsStatus.WARN - version.info = resourceHelper.gs(R.string.metadata_warning_different_version) + version.info = rh.gs(R.string.metadata_warning_different_version) } if ((currentAppVer.isNotEmpty()) && (metadataVer.isNotEmpty()) && (currentAppVer[0] != metadataVer[0])) { version.status = PrefsStatus.WARN - version.info = resourceHelper.gs(R.string.metadata_urgent_different_version) + version.info = rh.gs(R.string.metadata_urgent_different_version) } } @@ -184,13 +184,13 @@ class PrefFileListProvider @Inject constructor( val hours = Hours.hoursBetween(itTime, refTime).hours return if (hours == 0) { - resourceHelper.gs(R.string.exported_less_than_hour_ago) + rh.gs(R.string.exported_less_than_hour_ago) } else if ((hours < 24) && (hours > 0)) { - resourceHelper.gs(R.string.exported_ago, resourceHelper.gq(R.plurals.hours, hours, hours)) + rh.gs(R.string.exported_ago, rh.gq(R.plurals.hours, hours, hours)) } else if ((days < IMPORT_AGE_NOT_YET_OLD_DAYS) && (days > 0)) { - resourceHelper.gs(R.string.exported_ago, resourceHelper.gq(R.plurals.days, days, days)) + rh.gs(R.string.exported_ago, rh.gq(R.plurals.days, days, days)) } else { - resourceHelper.gs(R.string.exported_at, utcTime.substring(0, 10)) + rh.gs(R.string.exported_at, utcTime.substring(0, 10)) } } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt index 8cb3aeac6e..ead45005be 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt @@ -25,7 +25,7 @@ import javax.inject.Inject class PrefImportListActivity : DaggerAppCompatActivity() { - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var prefFileListProvider: PrefFileListProvider private lateinit var binding: MaintenanceImportListActivityBinding @@ -37,7 +37,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() { val view = binding.root setContentView(view) - title = resourceHelper.gs(R.string.preferences_import_list_title) + title = rh.gs(R.string.preferences_import_list_title) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayShowTitleEnabled(true) @@ -80,7 +80,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() { filelistName.text = prefFile.file.name filelistName.tag = prefFile - filelistDir.text = resourceHelper.gs(R.string.in_directory, prefFile.file.parentFile?.absolutePath) + filelistDir.text = rh.gs(R.string.in_directory, prefFile.file.parentFile?.absolutePath) metalineName.visibility = View.VISIBLE metaDateTimeIcon.visibility = View.VISIBLE @@ -89,7 +89,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() { prefFile.metadata[PrefsMetadataKey.AAPS_FLAVOUR]?.let { metaVariantFormat.text = it.value val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning - metaVariantFormat.setTextColor(resourceHelper.gc(color)) + metaVariantFormat.setTextColor(rh.gc(color)) } prefFile.metadata[PrefsMetadataKey.CREATED_AT]?.let { @@ -99,7 +99,7 @@ class PrefImportListActivity : DaggerAppCompatActivity() { prefFile.metadata[PrefsMetadataKey.AAPS_VERSION]?.let { metaAppVersion.text = it.value val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning - metaAppVersion.setTextColor(resourceHelper.gc(color)) + metaAppVersion.setTextColor(rh.gc(color)) } prefFile.metadata[PrefsMetadataKey.DEVICE_NAME]?.let { diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt index 6afeb854b5..bb82a9f251 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt @@ -17,7 +17,7 @@ import javax.inject.Singleton @Singleton class EncryptedPrefsFormat @Inject constructor( - private var resourceHelper: ResourceHelper, + private var rh: ResourceHelper, private var cryptoUtil: CryptoUtil, private var storage: Storage ) : PrefsFormat { @@ -124,16 +124,16 @@ class EncryptedPrefsFormat @Inject constructor( var secure: PrefsStatus = PrefsStatus.OK var decryptedOk = false var contentJsonObj: JSONObject? = null - var insecurityReason = resourceHelper.gs(R.string.prefdecrypt_settings_tampered) + var insecurityReason = rh.gs(R.string.prefdecrypt_settings_tampered) if (security.has("file_hash")) { if (calculatedFileHash != security.getString("file_hash")) { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_modified)) + issues.add(rh.gs(R.string.prefdecrypt_issue_modified)) } } else { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_missing_file_hash)) + issues.add(rh.gs(R.string.prefdecrypt_issue_missing_file_hash)) } if (encrypted) { @@ -152,27 +152,27 @@ class EncryptedPrefsFormat @Inject constructor( decryptedOk = true } else { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_modified)) + issues.add(rh.gs(R.string.prefdecrypt_issue_modified)) } } catch (e: JSONException) { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_parsing)) + issues.add(rh.gs(R.string.prefdecrypt_issue_parsing)) } } else { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_wrong_pass)) - insecurityReason = resourceHelper.gs(R.string.prefdecrypt_wrong_password) + issues.add(rh.gs(R.string.prefdecrypt_issue_wrong_pass)) + insecurityReason = rh.gs(R.string.prefdecrypt_wrong_password) } } else { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_wrong_format)) + issues.add(rh.gs(R.string.prefdecrypt_issue_wrong_format)) } } else { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_wrong_algorithm)) + issues.add(rh.gs(R.string.prefdecrypt_issue_wrong_algorithm)) } } else { @@ -183,7 +183,7 @@ class EncryptedPrefsFormat @Inject constructor( if (!(security.has("algorithm") && security.get("algorithm") == "none")) { secure = PrefsStatus.ERROR - issues.add(resourceHelper.gs(R.string.prefdecrypt_issue_wrong_algorithm)) + issues.add(rh.gs(R.string.prefdecrypt_issue_wrong_algorithm)) } contentJsonObj = container.getJSONObject("content") @@ -198,9 +198,9 @@ class EncryptedPrefsFormat @Inject constructor( val issuesStr: String? = if (issues.size > 0) issues.joinToString("\n") else null val encryptionDescStr = if (encrypted) { - if (secure == PrefsStatus.OK) resourceHelper.gs(R.string.prefdecrypt_settings_secure) else insecurityReason + if (secure == PrefsStatus.OK) rh.gs(R.string.prefdecrypt_settings_secure) else insecurityReason } else { - if (secure != PrefsStatus.ERROR) resourceHelper.gs(R.string.prefdecrypt_settings_unencrypted) else resourceHelper.gs(R.string.prefdecrypt_settings_tampered) + if (secure != PrefsStatus.ERROR) rh.gs(R.string.prefdecrypt_settings_unencrypted) else rh.gs(R.string.prefdecrypt_settings_tampered) } metadata[PrefsMetadataKey.ENCRYPTION] = PrefMetadata(encryptionDescStr, secure, issuesStr) @@ -230,7 +230,7 @@ class EncryptedPrefsFormat @Inject constructor( if (container.has(PrefsMetadataKey.FILE_FORMAT.key) && container.has("security") && container.has("content") && container.has("metadata")) { val fileFormat = container.getString(PrefsMetadataKey.FILE_FORMAT.key) if ((fileFormat != FORMAT_KEY_ENC) && (fileFormat != FORMAT_KEY_NOENC)) { - metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.metadata_format_other), PrefsStatus.ERROR) + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(rh.gs(R.string.metadata_format_other), PrefsStatus.ERROR) } else { val meta = container.getJSONObject("metadata") metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(fileFormat, PrefsStatus.OK) @@ -242,7 +242,7 @@ class EncryptedPrefsFormat @Inject constructor( } } } else { - metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR) + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(rh.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR) } return metadata diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt index 53ab699d9c..dfde13b932 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.general.overview.events import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.events.Event -class EventDismissBolusProgressIfRunning(val result: PumpEnactResult?) : Event() \ No newline at end of file +class EventDismissBolusProgressIfRunning(val result: PumpEnactResult?, val bolusTimestamp: Long?) : Event() \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.kt index b7325e964e..c7b55e93ae 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/Notification.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.overview.notifications +import android.content.Context import androidx.annotation.RawRes import info.nightscout.androidaps.utils.T @@ -14,6 +15,8 @@ open class Notification { var action: Runnable? = null var buttonText = 0 + var contextForAction: Context? = null + constructor() constructor(id: Int, date: Long, text: String, level: Int, validTo: Long) { this.id = id @@ -55,6 +58,7 @@ open class Notification { const val LOW = 2 const val INFO = 3 const val ANNOUNCEMENT = 4 + const val PROFILE_SET_FAILED = 0 const val PROFILE_SET_OK = 1 const val EASY_MODE_ENABLED = 2 @@ -122,6 +126,7 @@ open class Notification { const val WRONG_PUMP_DATA = 72 const val NSCLIENT_VERSION_DOES_NOT_MATCH = 73 const val VERSION_EXPIRE = 74 + const val INVALID_PROFILE_NOT_ACCEPTED = 75 const val USER_MESSAGE = 1000 diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensDataStore.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensDataStore.kt index 30dc01477f..52d9511095 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensDataStore.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/AutosensDataStore.kt @@ -19,7 +19,7 @@ import kotlin.math.roundToLong class AutosensDataStore { private val dataLock = Any() - private var lastUsed5minCalculation: Boolean? = null // true if used 5min bucketed data + var lastUsed5minCalculation: Boolean? = null // true if used 5min bucketed data // we need to make sure that bucketed_data will always have the same timestamp for correct use of cached values // once referenceTime != null all bucketed data should be (x * 5min) from referenceTime diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt index 5feb71b104..7f83f953d6 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt @@ -19,9 +19,9 @@ class CobInfo(val timestamp: Long, val displayCob: Double?, val futureCarbs: Dou return cobStringResult } - fun displayText(resourceHelper: ResourceHelper, dateUtil: DateUtil, isDev: Boolean): String? = + fun displayText(rh: ResourceHelper, dateUtil: DateUtil, isDev: Boolean): String? = if (displayCob != null) { - var cobText = resourceHelper.gs(R.string.format_carbs, displayCob.toInt()) + var cobText = rh.gs(R.string.format_carbs, displayCob.toInt()) if (futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(futureCarbs) + ")" // This is only temporary for debugging if (isDev) cobText += "\n" + dateUtil.timeString(timestamp) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java index bad39f9289..2745a06f49 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.java @@ -29,7 +29,7 @@ public class AutosensData implements DataPointWithLabelInterface { @Inject AAPSLogger aapsLogger; @Inject SP sp; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject ProfileFunction profileFunction; @Inject DateUtil dateUtil; @@ -51,9 +51,9 @@ public class AutosensData implements DataPointWithLabelInterface { time = t.getTimestamp(); carbs = t.getAmount(); remaining = t.getAmount(); - if (isAAPSOrWeighted) { + Profile profile = profileFunction.getProfile(t.getTimestamp()); + if (isAAPSOrWeighted && profile != null) { double maxAbsorptionHours = sp.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); - Profile profile = profileFunction.getProfile(t.getTimestamp()); double sens = profile.getIsfMgdl(t.getTimestamp()); double ic = profile.getIc(t.getTimestamp()); min5minCarbImpact = t.getAmount() / (maxAbsorptionHours * 60 / 5) * sens / ic; @@ -197,7 +197,7 @@ public class AutosensData implements DataPointWithLabelInterface { @Override public int getColor() { - return resourceHelper.gc(R.color.cob); + return rh.gc(R.color.cob); } } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index 1a92af8ae6..7cf4d09b88 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -29,7 +29,7 @@ class PumpSyncImplementation @Inject constructor( private val dateUtil: DateUtil, private val sp: SP, private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val profileFunction: ProfileFunction, private val repository: AppRepository, private val uel: UserEntryLogger @@ -51,7 +51,7 @@ class PumpSyncImplementation @Inject constructor( * @param serialNumber serial number of of pump * @return true if data is allowed */ - private fun confirmActivePump(timestamp: Long, type: PumpType, serialNumber: String): Boolean { + private fun confirmActivePump(timestamp: Long, type: PumpType, serialNumber: String, showNotification: Boolean = true): Boolean { val storedType = sp.getString(R.string.key_active_pump_type, "") val storedSerial = sp.getString(R.string.key_active_pump_serial_number, "") val storedTimestamp = sp.getLong(R.string.key_active_pump_change_timestamp, 0L) @@ -70,8 +70,8 @@ class PumpSyncImplementation @Inject constructor( return true } - if ((type.description != storedType || serialNumber != storedSerial) && timestamp >= storedTimestamp) - rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_DATA, resourceHelper.gs(R.string.wrong_pump_data), Notification.URGENT))) + if (showNotification && (type.description != storedType || serialNumber != storedSerial) && timestamp >= storedTimestamp) + rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_DATA, rh.gs(R.string.wrong_pump_data), Notification.URGENT))) aapsLogger.error(LTag.PUMP, "Ignoring pump history record Allowed: ${dateUtil.dateAndTimeAndSecondsString(storedTimestamp)} $storedType $storedSerial Received: $timestamp ${dateUtil.dateAndTimeAndSecondsString(timestamp)} ${type.description} $serialNumber") return false } @@ -397,7 +397,8 @@ class PumpSyncImplementation @Inject constructor( } override fun createOrUpdateTotalDailyDose(timestamp: Long, bolusAmount: Double, basalAmount: Double, totalAmount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean { - if (!confirmActivePump(timestamp, pumpType, pumpSerial)) return false + // there are probably old data in pump -> do not show notification, just ignore + if (!confirmActivePump(timestamp, pumpType, pumpSerial, showNotification = false)) return false val tdd = TotalDailyDose( timestamp = timestamp, bolusAmount = bolusAmount, diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt index 6af48de667..02bcec2e0b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt @@ -18,7 +18,7 @@ import javax.inject.Singleton @Singleton class BlePreCheck @Inject constructor( - val resourceHelper: ResourceHelper + val rh: ResourceHelper ) { companion object { @@ -27,7 +27,7 @@ class BlePreCheck @Inject constructor( fun prerequisitesCheck(activity: AppCompatActivity): Boolean { if (!activity.packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { - OKDialog.show(activity, resourceHelper.gs(R.string.message), resourceHelper.gs(R.string.ble_not_supported)) + OKDialog.show(activity, rh.gs(R.string.message), rh.gs(R.string.ble_not_supported)) return false } else { // Use this check to determine whether BLE is supported on the device. Then @@ -41,7 +41,7 @@ class BlePreCheck @Inject constructor( // Ensures Bluetooth is available on the device and it is enabled. If not, // displays a dialog requesting user permission to enable Bluetooth. if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled) { - OKDialog.show(activity, resourceHelper.gs(R.string.message), resourceHelper.gs(R.string.ble_not_enabled)) + OKDialog.show(activity, rh.gs(R.string.message), rh.gs(R.string.ble_not_enabled)) return false } else { // Will request that GPS be enabled for devices running Marshmallow or newer. @@ -80,7 +80,7 @@ class BlePreCheck @Inject constructor( } // Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533 - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.location_not_found_title), resourceHelper.gs(R.string.location_not_found_message), Runnable { + OKDialog.showConfirmation(activity, rh.gs(R.string.location_not_found_title), rh.gs(R.string.location_not_found_message), Runnable { activity.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) }) } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index daadd2dc78..8783644cde 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -297,9 +297,9 @@ enum class PumpType { source = Sources.MDI), //Diaconn Pump - DIACONN_G8(description = "DiaconnG8", + DIACONN_G8(description = "Diaconn G8", manufacturer = ManufacturerType.G2e, - model = "Diaconn G8", + model = "DiaconnG8", bolusSize = 0.01, specialBolusSize = null, extendedBolusSettings = DoseSettings(0.05, 10, 5 * 60, 0.05), @@ -403,11 +403,11 @@ enum class PumpType { this.source = source } - fun getFullDescription(i18nTemplate: String, hasExtendedBasals: Boolean, resourceHelper: ResourceHelper): String { + fun getFullDescription(i18nTemplate: String, hasExtendedBasals: Boolean, rh: ResourceHelper): String { val unit = if (pumpTempBasalType == PumpTempBasalType.Percent) "%" else "" val eb = extendedBolusSettings ?: return "INVALID" val tbr = tbrSettings ?: return "INVALID" - val extendedNote = if (hasExtendedBasals) resourceHelper.gs(R.string.def_extended_note) else "" + val extendedNote = if (hasExtendedBasals) rh.gs(R.string.def_extended_note) else "" return String.format(i18nTemplate, getStep("" + bolusSize, specialBolusSize), eb.step, eb.durationStep, eb.maxDuration / 60, diff --git a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt index 0692ac68e3..14596e50fe 100644 --- a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt +++ b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt @@ -17,7 +17,7 @@ abstract class Command( ) { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var repository: AppRepository enum class CommandType { @@ -49,7 +49,7 @@ abstract class Command( fun cancel() { val result = PumpEnactResult(injector) result.success = false - result.comment = resourceHelper.gs(R.string.connectiontimedout) + result.comment = rh.gs(R.string.connectiontimedout) aapsLogger.debug(LTag.PUMPQUEUE, "Result cancel") callback?.result(result)?.run() } diff --git a/core/src/main/java/info/nightscout/androidaps/queue/commands/CustomCommand.kt b/core/src/main/java/info/nightscout/androidaps/queue/commands/CustomCommand.kt index d0c5c26d51..e2fdd9fdb9 100644 --- a/core/src/main/java/info/nightscout/androidaps/queue/commands/CustomCommand.kt +++ b/core/src/main/java/info/nightscout/androidaps/queue/commands/CustomCommand.kt @@ -4,7 +4,7 @@ import java.io.Serializable /** * Implement this interface for every custom pump command that you want to be able to queue - * See [info.nightscout.androidaps.interfaces.CommandQueueProvider.customCommand] for queuing a custom command. + * See [info.nightscout.androidaps.interfaces.CommandQueue.customCommand] for queuing a custom command. */ interface CustomCommand : Serializable { diff --git a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt index 7af82b750d..35bc4ca815 100644 --- a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt +++ b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt @@ -23,7 +23,7 @@ import kotlin.math.pow class AlarmSoundService : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var notificationHolder: NotificationHolder @Inject lateinit var sp: SP @@ -74,7 +74,7 @@ class AlarmSoundService : DaggerService() { if (intent?.hasExtra(ErrorHelperActivity.SOUND_ID) == true) resourceId = intent.getIntExtra(ErrorHelperActivity.SOUND_ID, R.raw.error) player = MediaPlayer() try { - val afd = resourceHelper.openRawResourceFd(resourceId) ?: return START_STICKY + val afd = rh.openRawResourceFd(resourceId) ?: return START_STICKY player?.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length) afd.close() player?.isLooping = true diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt index 6f0a2f6655..d2d9feef7b 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -138,10 +138,10 @@ class DateUtil @Inject constructor(private val context: Context) { return if (mills == 0L) "" else dateString(mills) + " " + timeStringWithSeconds(mills) } - fun minAgo(resourceHelper: ResourceHelper, time: Long?): String { + fun minAgo(rh: ResourceHelper, time: Long?): String { if (time == null) return "" val mins = ((now() - time) / 1000 / 60).toInt() - return resourceHelper.gs(R.string.minago, mins) + return rh.gs(R.string.minago, mins) } fun minAgoShort(time: Long?): String { @@ -150,9 +150,9 @@ class DateUtil @Inject constructor(private val context: Context) { return (if (mins > 0) "+" else "") + mins } - fun hourAgo(time: Long, resourceHelper: ResourceHelper): String { + fun hourAgo(time: Long, rh: ResourceHelper): String { val hours = (now() - time) / 1000.0 / 60 / 60 - return resourceHelper.gs(R.string.hoursago, hours) + return rh.gs(R.string.hoursago, hours) } fun timeStringFromSeconds(seconds: Int): String { @@ -163,19 +163,19 @@ class DateUtil @Inject constructor(private val context: Context) { return t } - fun timeFrameString(timeInMillis: Long, resourceHelper: ResourceHelper): String { + fun timeFrameString(timeInMillis: Long, rh: ResourceHelper): String { var remainingTimeMinutes = timeInMillis / (1000 * 60) val remainingTimeHours = remainingTimeMinutes / 60 remainingTimeMinutes %= 60 - return "(" + (if (remainingTimeHours > 0) remainingTimeHours.toString() + resourceHelper.gs(R.string.shorthour) + " " else "") + remainingTimeMinutes + "')" + return "(" + (if (remainingTimeHours > 0) remainingTimeHours.toString() + rh.gs(R.string.shorthour) + " " else "") + remainingTimeMinutes + "')" } - fun sinceString(timestamp: Long, resourceHelper: ResourceHelper): String { - return timeFrameString(System.currentTimeMillis() - timestamp, resourceHelper) + fun sinceString(timestamp: Long, rh: ResourceHelper): String { + return timeFrameString(System.currentTimeMillis() - timestamp, rh) } - fun untilString(timestamp: Long, resourceHelper: ResourceHelper): String { - return timeFrameString(timestamp - System.currentTimeMillis(), resourceHelper) + fun untilString(timestamp: Long, rh: ResourceHelper): String { + return timeFrameString(timestamp - System.currentTimeMillis(), rh) } fun now(): Long { @@ -221,15 +221,15 @@ class DateUtil @Inject constructor(private val context: Context) { return result } - fun age(milliseconds: Long, useShortText: Boolean, resourceHelper: ResourceHelper): String { + fun age(milliseconds: Long, useShortText: Boolean, rh: ResourceHelper): String { val diff = computeDiff(0L, milliseconds) - var days = " " + resourceHelper.gs(R.string.days) + " " - var hours = " " + resourceHelper.gs(R.string.hours) + " " - var minutes = " " + resourceHelper.gs(R.string.unit_minutes) + " " + var days = " " + rh.gs(R.string.days) + " " + var hours = " " + rh.gs(R.string.hours) + " " + var minutes = " " + rh.gs(R.string.unit_minutes) + " " if (useShortText) { - days = resourceHelper.gs(R.string.shortday) - hours = resourceHelper.gs(R.string.shorthour) - minutes = resourceHelper.gs(R.string.shortminute) + days = rh.gs(R.string.shortday) + hours = rh.gs(R.string.shorthour) + minutes = rh.gs(R.string.shortminute) } var result = "" if (diff[TimeUnit.DAYS]!! > 0) result += diff[TimeUnit.DAYS].toString() + days @@ -238,27 +238,27 @@ class DateUtil @Inject constructor(private val context: Context) { return result } - fun niceTimeScalar(time: Long, resourceHelper: ResourceHelper): String { + fun niceTimeScalar(time: Long, rh: ResourceHelper): String { var t = time - var unit = resourceHelper.gs(R.string.unit_second) + var unit = rh.gs(R.string.unit_second) t /= 1000 - if (t != 1L) unit = resourceHelper.gs(R.string.unit_seconds) + if (t != 1L) unit = rh.gs(R.string.unit_seconds) if (t > 59) { - unit = resourceHelper.gs(R.string.unit_minute) + unit = rh.gs(R.string.unit_minute) t /= 60 - if (t != 1L) unit = resourceHelper.gs(R.string.unit_minutes) + if (t != 1L) unit = rh.gs(R.string.unit_minutes) if (t > 59) { - unit = resourceHelper.gs(R.string.unit_hour) + unit = rh.gs(R.string.unit_hour) t /= 60 - if (t != 1L) unit = resourceHelper.gs(R.string.unit_hours) + if (t != 1L) unit = rh.gs(R.string.unit_hours) if (t > 24) { - unit = resourceHelper.gs(R.string.unit_day) + unit = rh.gs(R.string.unit_day) t /= 24 - if (t != 1L) unit = resourceHelper.gs(R.string.unit_days) + if (t != 1L) unit = rh.gs(R.string.unit_days) if (t > 28) { - unit = resourceHelper.gs(R.string.unit_week) + unit = rh.gs(R.string.unit_week) t /= 7 - if (t != 1L) unit = resourceHelper.gs(R.string.unit_weeks) + if (t != 1L) unit = rh.gs(R.string.unit_weeks) } } } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt b/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt index 280e8a348e..7c2a96f46b 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt @@ -21,6 +21,6 @@ object DecimalFormatter { fun to3Decimal(value: Double): String = format3dec.format(value) fun to3Decimal(value: Double, unit: String): String = format3dec.format(value) + unit fun toPumpSupportedBolus(value: Double, pump: Pump): String = if (pump.pumpDescription.bolusStep <= 0.051) to2Decimal(value) else to1Decimal(value) - fun toPumpSupportedBolus(value: Double, pump: Pump, resourceHelper: ResourceHelper): String = if (pump.pumpDescription.bolusStep <= 0.051) resourceHelper.gs(R.string.formatinsulinunits, value) else resourceHelper.gs(R.string.formatinsulinunits1, value) + fun toPumpSupportedBolus(value: Double, pump: Pump, rh: ResourceHelper): String = if (pump.pumpDescription.bolusStep <= 0.051) rh.gs(R.string.formatinsulinunits, value) else rh.gs(R.string.formatinsulinunits1, value) fun pumpSupportedBolusFormat(pump: Pump): DecimalFormat = if (pump.pumpDescription.bolusStep <= 0.051) DecimalFormat("0.00") else DecimalFormat("0.0") } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index aecb0ff2b4..6a892a9ecb 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -22,7 +22,7 @@ class HardLimits @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, private val sp: SP, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val context: Context, private val repository: AppRepository ) { @@ -40,9 +40,9 @@ class HardLimits @Inject constructor( // Very Hard Limits Ranges // First value is the Lowest and second value is the Highest a Limit can define - val VERY_HARD_LIMIT_MIN_BG = intArrayOf(80, 180) - val VERY_HARD_LIMIT_MAX_BG = intArrayOf(90, 270) - val VERY_HARD_LIMIT_TARGET_BG = intArrayOf(80, 200) + val VERY_HARD_LIMIT_MIN_BG = doubleArrayOf(80.0, 180.0) + val VERY_HARD_LIMIT_MAX_BG = doubleArrayOf(90.0, 200.0) + val VERY_HARD_LIMIT_TARGET_BG = doubleArrayOf(80.0, 200.0) // Very Hard Limits Ranges for Temp Targets val VERY_HARD_LIMIT_TEMP_MIN_BG = intArrayOf(72, 180) @@ -65,11 +65,11 @@ class HardLimits @Inject constructor( } private fun loadAge(): Int = when (sp.getString(R.string.key_age, "")) { - resourceHelper.gs(R.string.key_child) -> CHILD - resourceHelper.gs(R.string.key_teenage) -> TEENAGE - resourceHelper.gs(R.string.key_adult) -> ADULT - resourceHelper.gs(R.string.key_resistantadult) -> RESISTANT_ADULT - resourceHelper.gs(R.string.key_pregnant) -> PREGNANT + rh.gs(R.string.key_child) -> CHILD + rh.gs(R.string.key_teenage) -> TEENAGE + rh.gs(R.string.key_adult) -> ADULT + rh.gs(R.string.key_resistantadult) -> RESISTANT_ADULT + rh.gs(R.string.key_pregnant) -> PREGNANT else -> ADULT } @@ -94,9 +94,9 @@ class HardLimits @Inject constructor( if (newValue < lowLimit || newValue > highLimit) { newValue = max(newValue, lowLimit) newValue = min(newValue, highLimit) - var msg = String.format(resourceHelper.gs(R.string.valueoutofrange), resourceHelper.gs(valueName)) + var msg = String.format(rh.gs(R.string.valueoutofrange), rh.gs(valueName)) msg += ".\n" - msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newValue) + msg += String.format(rh.gs(R.string.valuelimitedto), value, newValue) aapsLogger.error(msg) disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(msg)).subscribe() ToastUtils.showToastInUiThread(context, rxBus, msg, R.raw.error) diff --git a/core/src/main/java/info/nightscout/androidaps/utils/JsonHelper.kt b/core/src/main/java/info/nightscout/androidaps/utils/JsonHelper.kt index d592a180b7..5f411115fb 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/JsonHelper.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/JsonHelper.kt @@ -150,4 +150,15 @@ object JsonHelper { } return result } + + fun safeGetBooleanAllowNull(json: JSONObject?, fieldName: String, defaultValue: Boolean? = null): Boolean? { + var result = defaultValue + if (json != null && json.has(fieldName)) { + try { + result = json.getBoolean(fieldName) + } catch (ignored: JSONException) { + } + } + return result + } } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt index d1977090ac..34ce548ce8 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt @@ -11,7 +11,7 @@ import javax.inject.Singleton @Singleton class TimerUtil @Inject constructor( private val context: Context, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val dateUtil: DateUtil ) { @@ -21,7 +21,7 @@ class TimerUtil @Inject constructor( flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK putExtra(AlarmClock.EXTRA_LENGTH, length) putExtra(AlarmClock.EXTRA_SKIP_UI, true) - putExtra(AlarmClock.EXTRA_MESSAGE, text ?: resourceHelper.gs(R.string.app_name)) + putExtra(AlarmClock.EXTRA_MESSAGE, text ?: rh.gs(R.string.app_name)) context.startActivity(this) } } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java b/core/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java index 5718b80fd3..994998ef90 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java +++ b/core/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java @@ -22,6 +22,8 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific public class ToastUtils { + private static Toast lastToast = null; + public static class Long { public static void warnToast(final Context ctx, final String string) { @@ -76,10 +78,11 @@ public class ToastUtils { ImageView toastIcon = toastRoot.findViewById(android.R.id.icon); toastIcon.setImageResource(iconId); - Toast toast = new Toast(ctx); - toast.setDuration(isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG); - toast.setView(toastRoot); - toast.show(); + if (lastToast != null) lastToast.cancel(); + lastToast = new Toast(ctx); + lastToast.setDuration(isShort ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG); + lastToast.setView(toastRoot); + lastToast.show(); }); } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt b/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt index f24e0f5edc..39593aa8d0 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt @@ -13,143 +13,143 @@ import javax.inject.Singleton @Singleton class Translator @Inject internal constructor( - private val resourceHelper: ResourceHelper + private val rh: ResourceHelper ) { fun translate(action: Action): String = when (action) { - Action.BOLUS -> resourceHelper.gs(R.string.uel_bolus) - Action.BOLUS_CALCULATOR_RESULT -> resourceHelper.gs(R.string.uel_bolus_calculator) - Action.BOLUS_CALCULATOR_RESULT_REMOVED -> resourceHelper.gs(R.string.uel_bolus_calculator) - Action.SMB -> resourceHelper.gs(R.string.smb_shortname) - Action.BOLUS_ADVISOR -> resourceHelper.gs(R.string.uel_bolus_advisor) - Action.EXTENDED_BOLUS -> resourceHelper.gs(R.string.uel_extended_bolus) - Action.SUPERBOLUS_TBR -> resourceHelper.gs(R.string.uel_superbolus_tbr) - Action.CARBS -> resourceHelper.gs(R.string.uel_carbs) - Action.EXTENDED_CARBS -> resourceHelper.gs(R.string.uel_extended_carbs) - Action.TEMP_BASAL -> resourceHelper.gs(R.string.uel_temp_basal) - Action.TT -> resourceHelper.gs(R.string.uel_tt) - Action.NEW_PROFILE -> resourceHelper.gs(R.string.uel_new_profile) - Action.CLONE_PROFILE -> resourceHelper.gs(R.string.uel_clone_profile) - Action.STORE_PROFILE -> resourceHelper.gs(R.string.uel_store_profile) - Action.PROFILE_SWITCH -> resourceHelper.gs(R.string.uel_profile_switch) - Action.PROFILE_SWITCH_CLONED -> resourceHelper.gs(R.string.uel_profile_switch_cloned) - Action.CLOSED_LOOP_MODE -> resourceHelper.gs(R.string.uel_closed_loop_mode) - Action.LGS_LOOP_MODE -> resourceHelper.gs(R.string.uel_lgs_loop_mode) - Action.OPEN_LOOP_MODE -> resourceHelper.gs(R.string.uel_open_loop_mode) - Action.LOOP_DISABLED -> resourceHelper.gs(R.string.uel_loop_disabled) - Action.LOOP_ENABLED -> resourceHelper.gs(R.string.uel_loop_enabled) - Action.RECONNECT -> resourceHelper.gs(R.string.uel_reconnect) - Action.DISCONNECT -> resourceHelper.gs(R.string.uel_disconnect) - Action.RESUME -> resourceHelper.gs(R.string.uel_resume) - Action.SUSPEND -> resourceHelper.gs(R.string.uel_suspend) - Action.HW_PUMP_ALLOWED -> resourceHelper.gs(R.string.uel_hw_pump_allowed) - Action.CLEAR_PAIRING_KEYS -> resourceHelper.gs(R.string.uel_clear_pairing_keys) - Action.ACCEPTS_TEMP_BASAL -> resourceHelper.gs(R.string.uel_accepts_temp_basal) - Action.CANCEL_TEMP_BASAL -> resourceHelper.gs(R.string.uel_cancel_temp_basal) - Action.CANCEL_BOLUS -> resourceHelper.gs(R.string.uel_cancel_bolus) - Action.CANCEL_EXTENDED_BOLUS -> resourceHelper.gs(R.string.uel_cancel_extended_bolus) - Action.CANCEL_TT -> resourceHelper.gs(R.string.uel_cancel_tt) - Action.CAREPORTAL -> resourceHelper.gs(R.string.uel_careportal) - Action.SITE_CHANGE -> resourceHelper.gs(R.string.uel_site_change) - Action.RESERVOIR_CHANGE -> resourceHelper.gs(R.string.uel_reservoir_change) - Action.CALIBRATION -> resourceHelper.gs(R.string.uel_calibration) - Action.PRIME_BOLUS -> resourceHelper.gs(R.string.uel_prime_bolus) - Action.TREATMENT -> resourceHelper.gs(R.string.uel_treatment) - Action.CAREPORTAL_NS_REFRESH -> resourceHelper.gs(R.string.uel_careportal_ns_refresh) - Action.PROFILE_SWITCH_NS_REFRESH -> resourceHelper.gs(R.string.uel_profile_switch_ns_refresh) - Action.TREATMENTS_NS_REFRESH -> resourceHelper.gs(R.string.uel_treatments_ns_refresh) - Action.TT_NS_REFRESH -> resourceHelper.gs(R.string.uel_tt_ns_refresh) - Action.AUTOMATION_REMOVED -> resourceHelper.gs(R.string.uel_automation_removed) - Action.BG_REMOVED -> resourceHelper.gs(R.string.uel_bg_removed) - Action.CAREPORTAL_REMOVED -> resourceHelper.gs(R.string.uel_careportal_removed) - Action.BOLUS_REMOVED -> resourceHelper.gs(R.string.uel_bolus_removed) - Action.CARBS_REMOVED -> resourceHelper.gs(R.string.uel_carbs_removed) - Action.TEMP_BASAL_REMOVED -> resourceHelper.gs(R.string.uel_temp_basal_removed) - Action.EXTENDED_BOLUS_REMOVED -> resourceHelper.gs(R.string.uel_extended_bolus_removed) - Action.FOOD -> resourceHelper.gs(R.string.uel_food) - Action.FOOD_REMOVED -> resourceHelper.gs(R.string.uel_food_removed) - Action.PROFILE_REMOVED -> resourceHelper.gs(R.string.uel_profile_removed) - Action.PROFILE_SWITCH_REMOVED -> resourceHelper.gs(R.string.uel_profile_switch_removed) - Action.RESTART_EVENTS_REMOVED -> resourceHelper.gs(R.string.uel_restart_events_removed) - Action.TREATMENT_REMOVED -> resourceHelper.gs(R.string.uel_treatment_removed) - Action.TT_REMOVED -> resourceHelper.gs(R.string.uel_tt_removed) - Action.NS_PAUSED -> resourceHelper.gs(R.string.uel_ns_paused) - Action.NS_RESUME -> resourceHelper.gs(R.string.uel_ns_resume) - Action.NS_QUEUE_CLEARED -> resourceHelper.gs(R.string.uel_ns_queue_cleared) - Action.NS_SETTINGS_COPIED -> resourceHelper.gs(R.string.uel_ns_settings_copied) - Action.ERROR_DIALOG_OK -> resourceHelper.gs(R.string.uel_error_dialog_ok) - Action.ERROR_DIALOG_MUTE -> resourceHelper.gs(R.string.uel_error_dialog_mute) - Action.ERROR_DIALOG_MUTE_5MIN -> resourceHelper.gs(R.string.uel_error_dialog_mute_5min) - Action.OBJECTIVE_STARTED -> resourceHelper.gs(R.string.uel_objective_started) - Action.OBJECTIVE_UNSTARTED -> resourceHelper.gs(R.string.uel_objective_unstarted) - Action.OBJECTIVES_SKIPPED -> resourceHelper.gs(R.string.uel_objectives_skipped) - Action.STAT_RESET -> resourceHelper.gs(R.string.uel_stat_reset) - Action.DELETE_LOGS -> resourceHelper.gs(R.string.uel_delete_logs) - Action.DELETE_FUTURE_TREATMENTS -> resourceHelper.gs(R.string.uel_delete_future_treatments) - Action.EXPORT_SETTINGS -> resourceHelper.gs(R.string.uel_export_settings) - Action.IMPORT_SETTINGS -> resourceHelper.gs(R.string.uel_import_settings) - Action.RESET_DATABASES -> resourceHelper.gs(R.string.uel_reset_databases) - Action.EXPORT_DATABASES -> resourceHelper.gs(R.string.uel_export_databases) - Action.IMPORT_DATABASES -> resourceHelper.gs(R.string.uel_import_databases) - Action.OTP_EXPORT -> resourceHelper.gs(R.string.uel_otp_export) - Action.OTP_RESET -> resourceHelper.gs(R.string.uel_otp_reset) - Action.EXPORT_CSV -> resourceHelper.gs(R.string.uel_export_csv) - Action.STOP_SMS -> resourceHelper.gs(R.string.uel_stop_sms) - Action.START_AAPS -> resourceHelper.gs(R.string.uel_start_aaps) - Action.EXIT_AAPS -> resourceHelper.gs(R.string.uel_exit_aaps) - Action.PLUGIN_ENABLED -> resourceHelper.gs(R.string.uel_plugin_enabled) - Action.PLUGIN_DISABLED -> resourceHelper.gs(R.string.uel_plugin_disabled) - Action.LOOP_CHANGE -> resourceHelper.gs(R.string.uel_loop_change) - Action.LOOP_REMOVED -> resourceHelper.gs(R.string.uel_loop_removed) - Action.UNKNOWN -> resourceHelper.gs(R.string.unknown) + Action.BOLUS -> rh.gs(R.string.uel_bolus) + Action.BOLUS_CALCULATOR_RESULT -> rh.gs(R.string.uel_bolus_calculator) + Action.BOLUS_CALCULATOR_RESULT_REMOVED -> rh.gs(R.string.uel_bolus_calculator) + Action.SMB -> rh.gs(R.string.smb_shortname) + Action.BOLUS_ADVISOR -> rh.gs(R.string.uel_bolus_advisor) + Action.EXTENDED_BOLUS -> rh.gs(R.string.uel_extended_bolus) + Action.SUPERBOLUS_TBR -> rh.gs(R.string.uel_superbolus_tbr) + Action.CARBS -> rh.gs(R.string.uel_carbs) + Action.EXTENDED_CARBS -> rh.gs(R.string.uel_extended_carbs) + Action.TEMP_BASAL -> rh.gs(R.string.uel_temp_basal) + Action.TT -> rh.gs(R.string.uel_tt) + Action.NEW_PROFILE -> rh.gs(R.string.uel_new_profile) + Action.CLONE_PROFILE -> rh.gs(R.string.uel_clone_profile) + Action.STORE_PROFILE -> rh.gs(R.string.uel_store_profile) + Action.PROFILE_SWITCH -> rh.gs(R.string.uel_profile_switch) + Action.PROFILE_SWITCH_CLONED -> rh.gs(R.string.uel_profile_switch_cloned) + Action.CLOSED_LOOP_MODE -> rh.gs(R.string.uel_closed_loop_mode) + Action.LGS_LOOP_MODE -> rh.gs(R.string.uel_lgs_loop_mode) + Action.OPEN_LOOP_MODE -> rh.gs(R.string.uel_open_loop_mode) + Action.LOOP_DISABLED -> rh.gs(R.string.uel_loop_disabled) + Action.LOOP_ENABLED -> rh.gs(R.string.uel_loop_enabled) + Action.RECONNECT -> rh.gs(R.string.uel_reconnect) + Action.DISCONNECT -> rh.gs(R.string.uel_disconnect) + Action.RESUME -> rh.gs(R.string.uel_resume) + Action.SUSPEND -> rh.gs(R.string.uel_suspend) + Action.HW_PUMP_ALLOWED -> rh.gs(R.string.uel_hw_pump_allowed) + Action.CLEAR_PAIRING_KEYS -> rh.gs(R.string.uel_clear_pairing_keys) + Action.ACCEPTS_TEMP_BASAL -> rh.gs(R.string.uel_accepts_temp_basal) + Action.CANCEL_TEMP_BASAL -> rh.gs(R.string.uel_cancel_temp_basal) + Action.CANCEL_BOLUS -> rh.gs(R.string.uel_cancel_bolus) + Action.CANCEL_EXTENDED_BOLUS -> rh.gs(R.string.uel_cancel_extended_bolus) + Action.CANCEL_TT -> rh.gs(R.string.uel_cancel_tt) + Action.CAREPORTAL -> rh.gs(R.string.uel_careportal) + Action.SITE_CHANGE -> rh.gs(R.string.uel_site_change) + Action.RESERVOIR_CHANGE -> rh.gs(R.string.uel_reservoir_change) + Action.CALIBRATION -> rh.gs(R.string.uel_calibration) + Action.PRIME_BOLUS -> rh.gs(R.string.uel_prime_bolus) + Action.TREATMENT -> rh.gs(R.string.uel_treatment) + Action.CAREPORTAL_NS_REFRESH -> rh.gs(R.string.uel_careportal_ns_refresh) + Action.PROFILE_SWITCH_NS_REFRESH -> rh.gs(R.string.uel_profile_switch_ns_refresh) + Action.TREATMENTS_NS_REFRESH -> rh.gs(R.string.uel_treatments_ns_refresh) + Action.TT_NS_REFRESH -> rh.gs(R.string.uel_tt_ns_refresh) + Action.AUTOMATION_REMOVED -> rh.gs(R.string.uel_automation_removed) + Action.BG_REMOVED -> rh.gs(R.string.uel_bg_removed) + Action.CAREPORTAL_REMOVED -> rh.gs(R.string.uel_careportal_removed) + Action.BOLUS_REMOVED -> rh.gs(R.string.uel_bolus_removed) + Action.CARBS_REMOVED -> rh.gs(R.string.uel_carbs_removed) + Action.TEMP_BASAL_REMOVED -> rh.gs(R.string.uel_temp_basal_removed) + Action.EXTENDED_BOLUS_REMOVED -> rh.gs(R.string.uel_extended_bolus_removed) + Action.FOOD -> rh.gs(R.string.uel_food) + Action.FOOD_REMOVED -> rh.gs(R.string.uel_food_removed) + Action.PROFILE_REMOVED -> rh.gs(R.string.uel_profile_removed) + Action.PROFILE_SWITCH_REMOVED -> rh.gs(R.string.uel_profile_switch_removed) + Action.RESTART_EVENTS_REMOVED -> rh.gs(R.string.uel_restart_events_removed) + Action.TREATMENT_REMOVED -> rh.gs(R.string.uel_treatment_removed) + Action.TT_REMOVED -> rh.gs(R.string.uel_tt_removed) + Action.NS_PAUSED -> rh.gs(R.string.uel_ns_paused) + Action.NS_RESUME -> rh.gs(R.string.uel_ns_resume) + Action.NS_QUEUE_CLEARED -> rh.gs(R.string.uel_ns_queue_cleared) + Action.NS_SETTINGS_COPIED -> rh.gs(R.string.uel_ns_settings_copied) + Action.ERROR_DIALOG_OK -> rh.gs(R.string.uel_error_dialog_ok) + Action.ERROR_DIALOG_MUTE -> rh.gs(R.string.uel_error_dialog_mute) + Action.ERROR_DIALOG_MUTE_5MIN -> rh.gs(R.string.uel_error_dialog_mute_5min) + Action.OBJECTIVE_STARTED -> rh.gs(R.string.uel_objective_started) + Action.OBJECTIVE_UNSTARTED -> rh.gs(R.string.uel_objective_unstarted) + Action.OBJECTIVES_SKIPPED -> rh.gs(R.string.uel_objectives_skipped) + Action.STAT_RESET -> rh.gs(R.string.uel_stat_reset) + Action.DELETE_LOGS -> rh.gs(R.string.uel_delete_logs) + Action.DELETE_FUTURE_TREATMENTS -> rh.gs(R.string.uel_delete_future_treatments) + Action.EXPORT_SETTINGS -> rh.gs(R.string.uel_export_settings) + Action.IMPORT_SETTINGS -> rh.gs(R.string.uel_import_settings) + Action.RESET_DATABASES -> rh.gs(R.string.uel_reset_databases) + Action.EXPORT_DATABASES -> rh.gs(R.string.uel_export_databases) + Action.IMPORT_DATABASES -> rh.gs(R.string.uel_import_databases) + Action.OTP_EXPORT -> rh.gs(R.string.uel_otp_export) + Action.OTP_RESET -> rh.gs(R.string.uel_otp_reset) + Action.EXPORT_CSV -> rh.gs(R.string.uel_export_csv) + Action.STOP_SMS -> rh.gs(R.string.uel_stop_sms) + Action.START_AAPS -> rh.gs(R.string.uel_start_aaps) + Action.EXIT_AAPS -> rh.gs(R.string.uel_exit_aaps) + Action.PLUGIN_ENABLED -> rh.gs(R.string.uel_plugin_enabled) + Action.PLUGIN_DISABLED -> rh.gs(R.string.uel_plugin_disabled) + Action.LOOP_CHANGE -> rh.gs(R.string.uel_loop_change) + Action.LOOP_REMOVED -> rh.gs(R.string.uel_loop_removed) + Action.UNKNOWN -> rh.gs(R.string.unknown) } fun translate(units: ValueWithUnit?): String = when (units) { - is ValueWithUnit.Gram -> resourceHelper.gs(R.string.shortgram) - is ValueWithUnit.Hour -> resourceHelper.gs(R.string.shorthour) - is ValueWithUnit.Insulin -> resourceHelper.gs(R.string.insulin_unit_shortname) - is ValueWithUnit.Mgdl -> resourceHelper.gs(R.string.mgdl) - is ValueWithUnit.Minute -> resourceHelper.gs(R.string.shortminute) - is ValueWithUnit.Mmoll -> resourceHelper.gs(R.string.mmol) - is ValueWithUnit.Percent -> resourceHelper.gs(R.string.shortpercent) - is ValueWithUnit.UnitPerHour -> resourceHelper.gs(R.string.profile_ins_units_per_hour) + is ValueWithUnit.Gram -> rh.gs(R.string.shortgram) + is ValueWithUnit.Hour -> rh.gs(R.string.shorthour) + is ValueWithUnit.Insulin -> rh.gs(R.string.insulin_unit_shortname) + is ValueWithUnit.Mgdl -> rh.gs(R.string.mgdl) + is ValueWithUnit.Minute -> rh.gs(R.string.shortminute) + is ValueWithUnit.Mmoll -> rh.gs(R.string.mmol) + is ValueWithUnit.Percent -> rh.gs(R.string.shortpercent) + is ValueWithUnit.UnitPerHour -> rh.gs(R.string.profile_ins_units_per_hour) else -> "" } fun translate(meterType: TherapyEvent.MeterType?): String = when (meterType) { - TherapyEvent.MeterType.FINGER -> resourceHelper.gs(R.string.glucosetype_finger) - TherapyEvent.MeterType.SENSOR -> resourceHelper.gs(R.string.glucosetype_sensor) - TherapyEvent.MeterType.MANUAL -> resourceHelper.gs(R.string.manual) + TherapyEvent.MeterType.FINGER -> rh.gs(R.string.glucosetype_finger) + TherapyEvent.MeterType.SENSOR -> rh.gs(R.string.glucosetype_sensor) + TherapyEvent.MeterType.MANUAL -> rh.gs(R.string.manual) - else -> resourceHelper.gs(R.string.unknown) + else -> rh.gs(R.string.unknown) } fun translate(type: TherapyEvent.Type?): String = when (type) { - TherapyEvent.Type.FINGER_STICK_BG_VALUE -> resourceHelper.gs(R.string.careportal_bgcheck) - TherapyEvent.Type.SNACK_BOLUS -> resourceHelper.gs(R.string.careportal_snackbolus) - TherapyEvent.Type.MEAL_BOLUS -> resourceHelper.gs(R.string.careportal_mealbolus) - TherapyEvent.Type.CORRECTION_BOLUS -> resourceHelper.gs(R.string.careportal_correctionbolus) - TherapyEvent.Type.CARBS_CORRECTION -> resourceHelper.gs(R.string.careportal_carbscorrection) - TherapyEvent.Type.BOLUS_WIZARD -> resourceHelper.gs(R.string.boluswizard) - TherapyEvent.Type.COMBO_BOLUS -> resourceHelper.gs(R.string.careportal_combobolus) - TherapyEvent.Type.ANNOUNCEMENT -> resourceHelper.gs(R.string.careportal_announcement) - TherapyEvent.Type.NOTE -> resourceHelper.gs(R.string.careportal_note) - TherapyEvent.Type.QUESTION -> resourceHelper.gs(R.string.careportal_question) - TherapyEvent.Type.EXERCISE -> resourceHelper.gs(R.string.careportal_exercise) - TherapyEvent.Type.CANNULA_CHANGE -> resourceHelper.gs(R.string.careportal_pumpsitechange) - TherapyEvent.Type.PUMP_BATTERY_CHANGE -> resourceHelper.gs(R.string.careportal_pumpbatterychange) - TherapyEvent.Type.SENSOR_STARTED -> resourceHelper.gs(R.string.careportal_cgmsensorstart) - TherapyEvent.Type.SENSOR_STOPPED -> resourceHelper.gs(R.string.careportal_cgm_sensor_stop) - TherapyEvent.Type.SENSOR_CHANGE -> resourceHelper.gs(R.string.careportal_cgmsensorinsert) - TherapyEvent.Type.INSULIN_CHANGE -> resourceHelper.gs(R.string.careportal_insulincartridgechange) - TherapyEvent.Type.DAD_ALERT -> resourceHelper.gs(R.string.careportal_dad_alert) - TherapyEvent.Type.TEMPORARY_BASAL_START -> resourceHelper.gs(R.string.careportal_tempbasalstart) - TherapyEvent.Type.TEMPORARY_BASAL_END -> resourceHelper.gs(R.string.careportal_tempbasalend) - TherapyEvent.Type.PROFILE_SWITCH -> resourceHelper.gs(R.string.careportal_profileswitch) - TherapyEvent.Type.TEMPORARY_TARGET -> resourceHelper.gs(R.string.careportal_temporarytarget) - TherapyEvent.Type.TEMPORARY_TARGET_CANCEL -> resourceHelper.gs(R.string.careportal_temporarytargetcancel) - TherapyEvent.Type.APS_OFFLINE -> resourceHelper.gs(R.string.careportal_openapsoffline) - TherapyEvent.Type.NS_MBG -> resourceHelper.gs(R.string.careportal_mbg) + TherapyEvent.Type.FINGER_STICK_BG_VALUE -> rh.gs(R.string.careportal_bgcheck) + TherapyEvent.Type.SNACK_BOLUS -> rh.gs(R.string.careportal_snackbolus) + TherapyEvent.Type.MEAL_BOLUS -> rh.gs(R.string.careportal_mealbolus) + TherapyEvent.Type.CORRECTION_BOLUS -> rh.gs(R.string.careportal_correctionbolus) + TherapyEvent.Type.CARBS_CORRECTION -> rh.gs(R.string.careportal_carbscorrection) + TherapyEvent.Type.BOLUS_WIZARD -> rh.gs(R.string.boluswizard) + TherapyEvent.Type.COMBO_BOLUS -> rh.gs(R.string.careportal_combobolus) + TherapyEvent.Type.ANNOUNCEMENT -> rh.gs(R.string.careportal_announcement) + TherapyEvent.Type.NOTE -> rh.gs(R.string.careportal_note) + TherapyEvent.Type.QUESTION -> rh.gs(R.string.careportal_question) + TherapyEvent.Type.EXERCISE -> rh.gs(R.string.careportal_exercise) + TherapyEvent.Type.CANNULA_CHANGE -> rh.gs(R.string.careportal_pumpsitechange) + TherapyEvent.Type.PUMP_BATTERY_CHANGE -> rh.gs(R.string.careportal_pumpbatterychange) + TherapyEvent.Type.SENSOR_STARTED -> rh.gs(R.string.careportal_cgmsensorstart) + TherapyEvent.Type.SENSOR_STOPPED -> rh.gs(R.string.careportal_cgm_sensor_stop) + TherapyEvent.Type.SENSOR_CHANGE -> rh.gs(R.string.careportal_cgmsensorinsert) + TherapyEvent.Type.INSULIN_CHANGE -> rh.gs(R.string.careportal_insulincartridgechange) + TherapyEvent.Type.DAD_ALERT -> rh.gs(R.string.careportal_dad_alert) + TherapyEvent.Type.TEMPORARY_BASAL_START -> rh.gs(R.string.careportal_tempbasalstart) + TherapyEvent.Type.TEMPORARY_BASAL_END -> rh.gs(R.string.careportal_tempbasalend) + TherapyEvent.Type.PROFILE_SWITCH -> rh.gs(R.string.careportal_profileswitch) + TherapyEvent.Type.TEMPORARY_TARGET -> rh.gs(R.string.careportal_temporarytarget) + TherapyEvent.Type.TEMPORARY_TARGET_CANCEL -> rh.gs(R.string.careportal_temporarytargetcancel) + TherapyEvent.Type.APS_OFFLINE -> rh.gs(R.string.careportal_openapsoffline) + TherapyEvent.Type.NS_MBG -> rh.gs(R.string.careportal_mbg) /* TherapyEvent.Type.TEMPORARY_BASAL -> TODO() TherapyEvent.Type.TUBE_CHANGE -> TODO() @@ -170,29 +170,29 @@ class Translator @Inject internal constructor( TherapyEvent.Type.FEELING_HIGH -> TODO() TherapyEvent.Type.LEAKING_INFUSION_SET -> TODO() */ - TherapyEvent.Type.NONE -> resourceHelper.gs(R.string.unknown) + TherapyEvent.Type.NONE -> rh.gs(R.string.unknown) - else -> resourceHelper.gs(R.string.unknown) + else -> rh.gs(R.string.unknown) } fun translate(reason: TemporaryTarget.Reason?): String = when (reason) { - TemporaryTarget.Reason.CUSTOM -> resourceHelper.gs(R.string.custom) - TemporaryTarget.Reason.HYPOGLYCEMIA -> resourceHelper.gs(R.string.hypo) - TemporaryTarget.Reason.EATING_SOON -> resourceHelper.gs(R.string.eatingsoon) - TemporaryTarget.Reason.ACTIVITY -> resourceHelper.gs(R.string.activity) - TemporaryTarget.Reason.AUTOMATION -> resourceHelper.gs(R.string.automation) - TemporaryTarget.Reason.WEAR -> resourceHelper.gs(R.string.wear) + TemporaryTarget.Reason.CUSTOM -> rh.gs(R.string.custom) + TemporaryTarget.Reason.HYPOGLYCEMIA -> rh.gs(R.string.hypo) + TemporaryTarget.Reason.EATING_SOON -> rh.gs(R.string.eatingsoon) + TemporaryTarget.Reason.ACTIVITY -> rh.gs(R.string.activity) + TemporaryTarget.Reason.AUTOMATION -> rh.gs(R.string.automation) + TemporaryTarget.Reason.WEAR -> rh.gs(R.string.wear) - else -> resourceHelper.gs(R.string.unknown) + else -> rh.gs(R.string.unknown) } fun translate(reason: OfflineEvent.Reason?): String = when (reason) { - OfflineEvent.Reason.SUSPEND -> resourceHelper.gs(R.string.uel_suspend) - OfflineEvent.Reason.DISABLE_LOOP -> resourceHelper.gs(R.string.disableloop) - OfflineEvent.Reason.DISCONNECT_PUMP -> resourceHelper.gs(R.string.uel_disconnect) - OfflineEvent.Reason.OTHER -> resourceHelper.gs(R.string.uel_other) + OfflineEvent.Reason.SUSPEND -> rh.gs(R.string.uel_suspend) + OfflineEvent.Reason.DISABLE_LOOP -> rh.gs(R.string.disableloop) + OfflineEvent.Reason.DISCONNECT_PUMP -> rh.gs(R.string.uel_disconnect) + OfflineEvent.Reason.OTHER -> rh.gs(R.string.uel_other) - else -> resourceHelper.gs(R.string.unknown) + else -> rh.gs(R.string.unknown) } fun translate(source: Sources): String = when (source) { @@ -283,13 +283,13 @@ class Translator @Inject internal constructor( Sources.Stats -> TODO() Sources.Aaps -> TODO() */ - Sources.Automation -> resourceHelper.gs(R.string.automation) - Sources.Loop -> resourceHelper.gs(R.string.loop) - Sources.NSClient -> resourceHelper.gs(R.string.ns) - Sources.Pump -> resourceHelper.gs(R.string.pump) - Sources.SMS -> resourceHelper.gs(R.string.smb_shortname) - Sources.Wear -> resourceHelper.gs(R.string.wear) - Sources.Unknown -> resourceHelper.gs(R.string.unknown) + Sources.Automation -> rh.gs(R.string.automation) + Sources.Loop -> rh.gs(R.string.loop) + Sources.NSClient -> rh.gs(R.string.ns) + Sources.Pump -> rh.gs(R.string.pump) + Sources.SMS -> rh.gs(R.string.smb_shortname) + Sources.Wear -> rh.gs(R.string.wear) + Sources.Unknown -> rh.gs(R.string.unknown) else -> source.name } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt b/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt index e61b6bd327..0114d51601 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt @@ -10,7 +10,7 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class WarnColors @Inject constructor(val resourceHelper: ResourceHelper) { +class WarnColors @Inject constructor(val rh: ResourceHelper) { private val normalColor = Color.WHITE private val warnColor = Color.YELLOW @@ -32,8 +32,8 @@ class WarnColors @Inject constructor(val resourceHelper: ResourceHelper) { fun setColorByAge(view: TextView?, therapyEvent: TherapyEvent, warnThreshold: Double, urgentThreshold: Double) = view?.setTextColor(when { - therapyEvent.isOlderThan(urgentThreshold) -> resourceHelper.gc(R.color.low) - therapyEvent.isOlderThan(warnThreshold) -> resourceHelper.gc(R.color.high) + therapyEvent.isOlderThan(urgentThreshold) -> rh.gc(R.color.low) + therapyEvent.isOlderThan(warnThreshold) -> rh.gc(R.color.high) else -> Color.WHITE }) } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt index 44a3119382..cd698c96e0 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -26,6 +26,7 @@ interface SP { fun getInt(key: String, defaultValue: Int): Int fun getLong(@StringRes resourceID: Int, defaultValue: Long): Long fun getLong(key: String, defaultValue: Long): Long + fun incLong(@StringRes resourceID: Int) fun putBoolean(key: String, value: Boolean) fun putBoolean(@StringRes resourceID: Int, value: Boolean) fun putDouble(key: String, value: Double) diff --git a/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt b/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt index 52f5c61f26..6592ece693 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt @@ -12,7 +12,7 @@ import javax.inject.Singleton @Singleton class SPImplementation @Inject constructor( private val sharedPreferences: SharedPreferences, - private val resourceHelper: ResourceHelper) : SP { + private val rh: ResourceHelper) : SP { override fun getAll(): Map = sharedPreferences.all @@ -20,19 +20,19 @@ class SPImplementation @Inject constructor( override fun contains(key: String): Boolean = sharedPreferences.contains(key) - override fun contains(resourceId: Int): Boolean = sharedPreferences.contains(resourceHelper.gs(resourceId)) + override fun contains(resourceId: Int): Boolean = sharedPreferences.contains(rh.gs(resourceId)) override fun remove(resourceID: Int) = - sharedPreferences.edit().remove(resourceHelper.gs(resourceID)).apply() + sharedPreferences.edit().remove(rh.gs(resourceID)).apply() override fun remove(key: String) = sharedPreferences.edit().remove(key).apply() override fun getString(resourceID: Int, defaultValue: String): String = - sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue) ?: defaultValue + sharedPreferences.getString(rh.gs(resourceID), defaultValue) ?: defaultValue override fun getStringOrNull(resourceID: Int, defaultValue: String?): String? = - sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue) ?: defaultValue + sharedPreferences.getString(rh.gs(resourceID), defaultValue) ?: defaultValue override fun getStringOrNull(key: String, defaultValue: String?): String? = sharedPreferences.getString(key, defaultValue) @@ -42,7 +42,7 @@ class SPImplementation @Inject constructor( override fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean { return try { - sharedPreferences.getBoolean(resourceHelper.gs(resourceID), defaultValue) + sharedPreferences.getBoolean(rh.gs(resourceID), defaultValue) } catch (e: Exception) { defaultValue } @@ -57,16 +57,16 @@ class SPImplementation @Inject constructor( } override fun getDouble(resourceID: Int, defaultValue: Double): Double = - SafeParse.stringToDouble(sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue.toString())) + SafeParse.stringToDouble(sharedPreferences.getString(rh.gs(resourceID), defaultValue.toString())) override fun getDouble(key: String, defaultValue: Double): Double = SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) override fun getInt(resourceID: Int, defaultValue: Int): Int { return try { - sharedPreferences.getInt(resourceHelper.gs(resourceID), defaultValue) + sharedPreferences.getInt(rh.gs(resourceID), defaultValue) } catch (e: Exception) { - SafeParse.stringToInt(sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue.toString())) + SafeParse.stringToInt(sharedPreferences.getString(rh.gs(resourceID), defaultValue.toString())) } } @@ -80,9 +80,13 @@ class SPImplementation @Inject constructor( override fun getLong(resourceID: Int, defaultValue: Long): Long { return try { - sharedPreferences.getLong(resourceHelper.gs(resourceID), defaultValue) + sharedPreferences.getLong(rh.gs(resourceID), defaultValue) } catch (e: Exception) { - SafeParse.stringToLong(sharedPreferences.getString(resourceHelper.gs(resourceID), defaultValue.toString())) + try { + SafeParse.stringToLong(sharedPreferences.getString(rh.gs(resourceID), defaultValue.toString())) + } catch (e: Exception) { + defaultValue + } } } @@ -98,37 +102,42 @@ class SPImplementation @Inject constructor( } } + override fun incLong(resourceID: Int) { + val value = getLong(resourceID, 0) + 1L + sharedPreferences.edit().putLong(rh.gs(resourceID), value).apply() + } + override fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() override fun putBoolean(resourceID: Int, value: Boolean) = - sharedPreferences.edit().putBoolean(resourceHelper.gs(resourceID), value).apply() + sharedPreferences.edit().putBoolean(rh.gs(resourceID), value).apply() override fun putDouble(key: String, value: Double) = sharedPreferences.edit().putString(key, value.toString()).apply() override fun putDouble(resourceID: Int, value: Double) { - sharedPreferences.edit().putString(resourceHelper.gs(resourceID), value.toString()).apply() + sharedPreferences.edit().putString(rh.gs(resourceID), value.toString()).apply() } override fun putLong(key: String, value: Long) = sharedPreferences.edit().putLong(key, value).apply() override fun putLong(resourceID: Int, value: Long) = - sharedPreferences.edit().putLong(resourceHelper.gs(resourceID), value).apply() + sharedPreferences.edit().putLong(rh.gs(resourceID), value).apply() override fun putInt(key: String, value: Int) = sharedPreferences.edit().putInt(key, value).apply() override fun putInt(resourceID: Int, value: Int) = - sharedPreferences.edit().putInt(resourceHelper.gs(resourceID), value).apply() + sharedPreferences.edit().putInt(rh.gs(resourceID), value).apply() override fun incInt(resourceID: Int) { val value = getInt(resourceID, 0) + 1 - sharedPreferences.edit().putInt(resourceHelper.gs(resourceID), value).apply() + sharedPreferences.edit().putInt(rh.gs(resourceID), value).apply() } override fun putString(resourceID: Int, value: String) = - sharedPreferences.edit().putString(resourceHelper.gs(resourceID), value).apply() + sharedPreferences.edit().putString(rh.gs(resourceID), value).apply() override fun putString(key: String, value: String) = sharedPreferences.edit().putString(key, value).apply() diff --git a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt index f2627a3d55..2472ef84b8 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt @@ -23,7 +23,7 @@ import javax.inject.Inject class UserEntryPresentationHelper @Inject constructor( private val translator: Translator, private val profileFunction: ProfileFunction, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val dateUtil: DateUtil ) { @@ -109,7 +109,7 @@ class UserEntryPresentationHelper @Inject constructor( else -> HtmlHelper.fromHtml(coloredAction(action)) } - private fun coloredAction(action: Action): String = "${translator.translate(action)}" + private fun coloredAction(action: Action): String = "${translator.translate(action)}" fun listToPresentationString(list: List) = list.joinToString(separator = " ", transform = this::toPresentationString) @@ -131,12 +131,12 @@ class UserEntryPresentationHelper @Inject constructor( is ValueWithUnit.Mgdl -> { if (profileFunction.getUnits() == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) - else DecimalFormatter.to1Decimal(valueWithUnit.value / Constants.MMOLL_TO_MGDL) + translator.translate(valueWithUnit) + else DecimalFormatter.to1Decimal(valueWithUnit.value * Constants.MGDL_TO_MMOLL) + translator.translate(valueWithUnit) } is ValueWithUnit.Mmoll -> { - if (profileFunction.getUnits() == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) - else DecimalFormatter.to1Decimal(valueWithUnit.value * Constants.MMOLL_TO_MGDL) + translator.translate(valueWithUnit) + if (profileFunction.getUnits() == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) + else DecimalFormatter.to0Decimal(valueWithUnit.value * Constants.MMOLL_TO_MGDL) + translator.translate(valueWithUnit) } ValueWithUnit.UNKNOWN -> "" @@ -147,7 +147,7 @@ class UserEntryPresentationHelper @Inject constructor( return getCsvHeader() + userEntries.joinToString("\n") { entry -> getCsvEntry(entry) } } - private fun getCsvHeader() = resourceHelper.gs(R.string.ue_csv_header, + private fun getCsvHeader() = rh.gs(R.string.ue_csv_header, csvString(R.string.ue_timestamp), csvString(R.string.date), csvString(R.string.ue_utc_offset), @@ -220,7 +220,7 @@ class UserEntryPresentationHelper @Inject constructor( } private fun csvString(action: Action): String = "\"" + translator.translate(action).replace("\"", "\"\"").replace("\n", " / ") + "\"" - private fun csvString(id: Int): String = if (id != 0) "\"" + resourceHelper.gs(id).replace("\"", "\"\"").replace("\n", " / ") + "\"" else "" + private fun csvString(id: Int): String = if (id != 0) "\"" + rh.gs(id).replace("\"", "\"\"").replace("\n", " / ") + "\"" else "" private fun csvString(s: String): String = if (s != "") "\"" + s.replace("\"", "\"\"").replace("\n", " / ") + "\"" else "" private fun String.addWithSeparator(add: Any) = diff --git a/core/src/main/res/layout/activity_tdd_stats.xml b/core/src/main/res/layout/activity_tdd_stats.xml index f7967bfebf..772859ccd2 100644 --- a/core/src/main/res/layout/activity_tdd_stats.xml +++ b/core/src/main/res/layout/activity_tdd_stats.xml @@ -167,7 +167,7 @@ Свързана
Не е сврзана Разкачане + Изчакване за разкачане Стартиран AndroidAPS %1$.1fЕ %1$.2fЕ @@ -63,6 +64,7 @@ мг/дл ммол/л гр. + % Допълнителни настройки Bluetooth BT ограничения @@ -103,6 +105,7 @@ Бележки Изтрий Добави нов + Данните идват от различна помпа. Сменете драйвера на помпата и за да възстановите състоянието на помпата. Ограничаване на макс. базална стойност до %1$.2f Е/ч поради %2$s лимит на помпата @@ -118,6 +121,7 @@ Разбрах Bluetooth Low Energy не се поддържа. + Нискоенергиен Bluetooth не се потдържа или устройството не е сдвоено. Bluetooth не е включен. Локацията не е включена За да работи откриването на нови устройсва чрез Bluetooth, трябва да включите локацията. AAPS не проследява вашето местоположение и ще можете да я изключите след успешното свързване. @@ -168,7 +172,9 @@ %1$s: ∑: %2$.2fЕ Бол: %3$.2fЕ Баз: %4$.2fЕ(%5$.0f%%)]]> %1$s: ∑: %2$.2fЕ Бол: %3$.2fЕ Баз: %4$.2fЕ(%5$.0f%%) Въгл: %6$.0fгр]]> + %1$s: %2$s in %3$d days
]]>
+ Careportal Проверка на КЗ Калибрация или ръчна КЗ Известие @@ -285,10 +291,15 @@ С Н + Разкачане СПРИ БОЛУС Източник Действие + + %1$d дeн + %1$d дни + %1$d час %1$d часа diff --git a/core/src/main/res/values-es-rES/strings.xml b/core/src/main/res/values-es-rES/strings.xml index 66a5a1cacb..11ab72c05c 100644 --- a/core/src/main/res/values-es-rES/strings.xml +++ b/core/src/main/res/values-es-rES/strings.xml @@ -209,7 +209,7 @@ Sensor Manualmente desconocido - Comer pronto + Comiendo Pronto Hipo Actividad Reloj @@ -304,6 +304,7 @@ D BOLO + CALCULADOR DE BOLO RECOMENDADOR BOLO BOLO EXTENDIDO SUPERBOLO TBR diff --git a/core/src/main/res/values-hu-rHU/strings.xml b/core/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..0a9e749b51 --- /dev/null +++ b/core/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/core/src/main/res/values-hu-rHU/validator.xml b/core/src/main/res/values-hu-rHU/validator.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/core/src/main/res/values-hu-rHU/validator.xml @@ -0,0 +1,2 @@ + + diff --git a/core/src/main/res/values-it-rIT/strings.xml b/core/src/main/res/values-it-rIT/strings.xml index 7d993762ae..1daa37f44e 100644 --- a/core/src/main/res/values-it-rIT/strings.xml +++ b/core/src/main/res/values-it-rIT/strings.xml @@ -385,7 +385,7 @@ PLUGIN DISABILITATO SCONOSCIUTO Stringa - Fonte + Origine Offset UTC Azione Data e ora diff --git a/core/src/main/res/values-iw-rIL/strings.xml b/core/src/main/res/values-iw-rIL/strings.xml index 576adaac67..1f48ff2e51 100644 --- a/core/src/main/res/values-iw-rIL/strings.xml +++ b/core/src/main/res/values-iw-rIL/strings.xml @@ -54,7 +54,7 @@ התחברות אחרונה בולוס אחרון יחידות יומיות - בזאלי בסיסי + מינון בזאלי בסיסי בזאלי זמני בולוס ממושך מכל @@ -245,7 +245,7 @@ יחס # ימים משקל - שימוש בבולוס למילוי / פריימינג עשוי לגרום לחוסר דיוק! + שימוש בבולוס למילוי \\ תיחול עשוי לגרום לחוסר דיוק! הנתונים ישנים. לרענון לחצו \"טען מחדש\" סה\"כ בזאלי בסיסי סה\"כ בזאלי בסיסי * 2 diff --git a/core/src/main/res/values-no-rNO/strings.xml b/core/src/main/res/values-no-rNO/strings.xml index fd1b371d10..368df9e88d 100644 --- a/core/src/main/res/values-no-rNO/strings.xml +++ b/core/src/main/res/values-no-rNO/strings.xml @@ -304,6 +304,7 @@ S BOLUS + BOLUS KALKULATOR BOLUS ASSISTENT FORLENGET BOLUS SUPERBOLUS TBR diff --git a/core/src/main/res/values-sv-rSE/strings.xml b/core/src/main/res/values-sv-rSE/strings.xml index a2039bced1..e0099aba4a 100644 --- a/core/src/main/res/values-sv-rSE/strings.xml +++ b/core/src/main/res/values-sv-rSE/strings.xml @@ -304,6 +304,7 @@ S BOLUS + BOLUS KALKYLATOR BOLUS KALKYLATOR FÖRLÄNGD BOLUS SUPERBOLUS TEMPBASAL diff --git a/core/src/main/res/values-tr-rTR/strings.xml b/core/src/main/res/values-tr-rTR/strings.xml index 7a4d5e1725..63294cf575 100644 --- a/core/src/main/res/values-tr-rTR/strings.xml +++ b/core/src/main/res/values-tr-rTR/strings.xml @@ -2,50 +2,424 @@ + Yenile + Hata + Ayarlanmadı + Bazal profiliniz güncellenemedi + Pompadaki Bazal profil güncellendi + Geçersiz bilgi girişi + Geçici Bazal teslimat hatası + %1$.2f Ü gönderilecek + Pompa bekleniyor + %1$d bağlanıyor + %1$.2f Ü gönderiliyor + El Sıkışma + Bağlanıyor + Bağlanıldı + Bağlantı kesildi + Bağlantı kesiliyor + Bağlantının kesilmesi bekleniyor + AndroidAPS başladı + %1$.1f Ü + %1$.2f Ü + %1$+.2f Ü + %1$d g + %1$.0f / %2$d Ü %1$.2f U/h + %1$.2f sa + %1$d dakika + Pompa meşgul + Pompa bağlantı hatası + İzin verilen sınıra ulaştınız + Görevler + Kapat + Lütfen bekleyin… + Sessiz + Yeniden yükle + DURDUR BASILI + Dur + Karbonhidrat + Geçersiz profil!!! + PROFİL AYARLANMADI + Tarih + Ünite + İES + IC Karbonhidrat İnsülin Oranı + İDF + Bazal + Hedef + Başlatılıyor ... + Seri numarası + Pil + Son bağlantı + Son bolus + Günlük ünite + Temel bazal oranı + Geçici Bazal + Yayma Bolus + Rezervuar + Pompa geçmişi + Profili görüntüle + Etkinlik Türü + mg/dl + mmol/l + gr + % + Gelişmiş Ayarlar + Bluetooth + BT Watchdog + Pompa ile herhangi bir bağlantı sorunu yaşanıyorsa, Akıllı telefonunuzda Bluetooth bağlantısını kapatıp açın. Bu bluetooth bağlantı sorununu giderecektir. + Eşleştirme Evet Hayır - DÖNGÜ KISITLAMALARDAN İPTAL EDİLDİ + DÖNGÜ KISITLAMALARDAN DEVREDIŞI BIRAKILDI + %1$.2f Ü bolus başarıyla gönderildi + Tamam Pompadan okunan geçerli bir bazal oranı yok %2$s\'den dolayı max IOB\'yi (Aktif İnsülin) %1$.1f U ile sınırlandırılıyor güvenli olmayan kullanım Pompa ulaşılamıyor + Yayma Bolus Pompa zamanı güncellendi + Çıkış + Kaydı kaldır + Döngü devre dışı + Alarm Döngü devre dışı bırak Döngü etkinleştir - Döngüyü başlat + Döngüyü devam ettir Döngüyü duraklat - Henüz NightSout\'tan profil yüklenmedi + Süre [min] + Bildirim + Henüz NS\'tan profil yüklenmedi + var + yok Glikoz + IOB + COB + İsim: Zaman WiFi SSID + Yükleniyor… + Etkinlik saati + Notlar + Kaldır + Yeni ekle + Veriler farklı pompadan geliyor. Pompa durumunu sıfırlamak için pompa sürücüsünü değiştirin. + %2$s nedeniyle max bazal oranı %1$.2f Ü/s ile sınırlı + pompa sınırı + %2$s\'den dolayı max yüzde oranı %1$d%% ile sınırlandırılıyor + pozitif bir değer olmalıdır + %2$s\'den dolayı bolus %1$.1f Ü ile sınırlandırılıyor + Pompa başlatılamadı, profil oluşturulmamış! + Onaylama + İleti + Tamam + İptal + REDDET + Düşük Enerji Bluetooth desteklenmez. + Düşük Enerji Bluetooth desteklenmiyor veya cihaz eşleştirilmedi. + Bluetooth etkin değil. + Konum Etkin Değil + Bluetooth cihaz bulmanın daha yeni cihazlarda çalışması için konum etkinleştirilmelidir. AAPS konumunuzu izlemez ve eşleştirme başarılı olduktan sonra devre dışı bırakılabilir. + %1$d dak önce + %1$.1f sa önce + sa + günler + saatler + saniye + dakika + saat + gün + hafta + saniye + dakika + saatler + günler + hafta + dk + gün + Hatalı parola + Şifreler eşleşmiyor + Bazal değerler saatlerle uyumlu değil: %1$s + Bazal değeri minimum desteklenen değerle değiştirilir: %1$s + Bazal değeri maksimum desteklenen değerle değiştirilir: %1$s + + Ü/s + g/Ü + Profil seçilmedi + %2$d dakika için %1$d%% profilini başlat + * Sanal pompada yalnızca belirli değerler, aralıklar değil ayrıntı olarak bazal/bolus desteklenmez. + Geçici bazali iptal et + Geçici bazala izin ver + Oranı + Süre + Sebep + Değişiklik yapılmadı + Geçersiz profil: %1$s + %1$d dak + %1$s: ∑: %2$.2f Ü Bol: %3$.2f Ü Baz: %4$.2f Ü(%5$.0f%%)]]> + %1$s: ∑: %2$.2f Ü Bol: %3$.2f Ü Baz: %4$.2f Ü(%5$.0f%%) Karbhr: %6$.0f g]]> + %1$s: %2$s içinde %3$d gün
]]>
+ Bakım Portalı + KŞ Kontrol + Manuel KŞ veya Kalibrasyon + Duyuru + Not + Soru + Egzersiz + Duyuru : %1$s + Not : %1$s + Soru : %1$s + Alıştırma : %1$s + Pompa Kanül Değişimi + CGM Sensör Yerleştir + CGM sensörü Başlat + CGM Sensör Durdurma + D.A.D Alarmı + İnsülin Kartuş Değişimi + Profil değiştir + Aperatif Bolusu + Öğün Bolusu + Düzeltme Bolusu + Kombo Bolus + Geçici Bazal Başlat + Geçici Bazal Bitimi + Karbonhidrat düzeltme + OpenAPS Çevrimdışı + Pompa Pil Değişimi + Geçici hedef + Geçici hedef değeri + Geçici hedef iptali + Bolus sihirbazı + Parmak + Sensör + Manuel + bilinmiyor Yakında Öğün Hipo + Aktivite Wear + Otomasyon Özel + Pompa + Döngü + NS + Kayıt + Pompa geçmişi okunuyor + Pompa simgesi + Bağlantı zaman aşımına uğradı + Yürütüldü + Yorum + Başarılı + Yüzde + Mutlak + İnsülin + Ü + Sonuç bekleniyor... + SMB + %2$d Dakika İçinde %1$d g Ek Karbonhidrat Gerekiyor + İstatistikler + Kümülatif GTD (Günlük Toplam Doz) + Üstel Ağırlıklı TDD + Bazal + Bolus + TGD + Oran + # Gün + Ağırlık + Hazırlama / doldurma için boluslar kullanılıyorsa muhtemelen yanlış! + Eski Veri Lütfen \"Yeniden Yükle\"ye Basın + Günlük bazal miktarı + TBB * 2 + Zaman algılama + %1$dsa %2$ddk + 5 dakika sessize al + Dosya formatı + Oluşturuldu + AAPS Versiyonu + Yapı Varyantı + Cihaz hasta adını dışa aktarma + Cihaz modelini dışa aktarma + Dosya şifreleme + Yeni şifrelenmiş format + Yeni hata ayıklama formatı (şifrelenmemiş) + Bilinmeyen dışa aktarma formatı + %1$s önce dışa aktarıldı + %1$s\'de dışa aktarıldı + bir süre önce dışa aktarıldı + dizinde: %1$s + İçe aktarılacak dosyayı seçin + Sizde: %2$s varken, farklı AAPS (%1$s) türeviyle tercihler oluşturuldu.\n\nBazı ayarlar eksik veya geçersiz olabilir - içe aktardıktan sonra lütfen tercihlerinizi kontrol edin ve güncelleyin. + Tercihler farklı bir cihazda oluşturuldu. Daha eski/farklı bir telefondan içe aktarıyorsanız sorun değil, ancak içe aktarılan tercihlerin doğru olduğundan emin olun! + Eski AAPS sürümünün güvenli olmayan eski dosya biçimini kullanıyorsunuz! Geçerli JSON formatında bir dosyanız yoksa son çare olarak kullanın. + İçe aktarılan tercihler zaten %1$s günlük! Belki daha güncel tercihleriniz var ya da yanlış dosyayı mı seçiyorsunuz? Tercihleri düzenli olarak dışa aktarmayı unutmayın! + Geçersiz tarih-saat biçimi! + Uygulamanın farklı alt sürümlerinden tercihler. Yükseltmeden sonra içe aktarıyorsanız sorun değil, ancak tercihlerin hala doğru olup olmadığını içe aktarmadan sonra kontrol edin! + Uygulamanın farklı ana sürümünden tercihler. Ana sürümler önemli ölçüde farklılık gösterir ve uyumsuz tercihlere sahip olabilir! İçe aktardıktan sonra tercihlerin hala doğru olduğundan emin olun! + Ayarlar dosyası kurcalanmış + Ayarlar dosyası güvenli + Güvenli olmayan, şifrelenmemiş ayar biçimi kullanma + JSON biçim hatası, gerekli alan eksik (biçim, içerik, meta veri veya güvenlik) + Şifre çözme hatası, verilen şifre dosyayı çözemiyor + Dosya sağlama eksik, ayarların gerçekliğini doğrulayamıyor! + Dosya dışa aktarıldıktan sonra değiştirildi! + Şifre çözme hatası, tercihler ayrıştırılamadı! + Şifre çözme hatası, sağlanan şifre geçersiz veya ayar dosyası değiştirildi! İçe aktarılan dosya farklı bir Ana parola ile dışa aktarılmış olabilir. + Şifreleme yapılandırması eksik, ayar formatı geçersiz! + Desteklenmeyen veya belirtilmeyen şifreleme algoritması! + İmza doğrulayıcı + Geçersiz bir sürüm çalıştırdığınızı tespit ettik. Döngü devre dışı! Sürüm %1$s mevcut + %1$s sürümünün süresi %2$s tarihinde sona eriyor + Lütfen telefonunu yeniden başlat, yada Android APS sistem ayarları üzerinden yeniden başlat.\nAksi taktirde Android APS hiç bir günlük tutmayacak (takip ve doğrulama, algoritmanın düzenli çalışmasi için önemli)! + P + S + Ç + P + C + C + P + BOLUS + BOLUS HESAPLAYICI + BOLUS DANIŞMANI + YAYMA BOLUS + SURBOLUS TBR + KARBLR + YAYMA KARBONHİDRAT + GEÇİCİ BAZAL + GEÇİCİ HEDEF + YENİ PROFİL + PROFİL KLONLA + PROFİLİ DEPOLA + PROFİLİ DEĞİŞTİR + PROFİLİ KLONLA DEĞİŞTİR + KAPALI DÖNGÜ MODU + LGS DÖNGÜ MODU + AÇIK DÖNGÜ MODU + DÖNGÜ DEVRE DIŞI + DÖNGÜ ETKİN + YENİDEN BAĞLAN + BAĞLANTIYI KES + DEVAM ET + ASKIYA AL + HW POMPASINI KABUL ET + EŞLEŞTİRME ANAHTARLARINI TEMİZLE + GEÇİCİ BAZALI KABUL ET + GEÇİCİ BAZALI İPTAL ET + BOLUSU İPTAL ET + YAYMA BOLUS İPTAL + GEÇİCİ HEDEF İPTAL + BAKIM PORTALI + KANÜL DEĞİŞİMİ + REZERVUAR DEĞİŞİMİ + KALİBRASYON + BAŞLANGIÇ BOLUS + TEDAVİ + BAKIM PORTALI NS YENİLEME + PROFİL DEĞİŞTİRME NS YENİLEME + TEDAVİLER NS YENİLEME + GEÇİCİ HEDEF NS YENİLEME + OTOMASYON KALDIRILDI + KŞ KALDIRILDI + BAKIM PORTALI KALDIRILDI + BOLUS KALDIRILDI + KARBLAR KALDIRILDI + GEÇİCİ BAZAL KALDIRILDI + YAYMA BOLUS KALDIRILDI + YEMEK + YEMEK KALDIRILDI + PROFİL KALDIRILDI + PROFİL DEĞİŞTİRİCİ KALDIRILDI + TEKRAR BAŞLAT ETKİNLİKLERİ KALDIRILDI + TEDAVİ KALDIRILDI + GEÇİCİ HEDEF KALDIRILDI + NS DURAKLATILDI + NS DEVAM ET + NS KUYRUĞU TEMİZLENDİ + NS AYARLARI KOPYALANDI + HATA DİYALOGU TAMAM + HATA DİYALOĞU SESSİZ + HATA DİYALOĞU 5DK SESSİZ + GÖREV BAŞLADI + GÖREV BAŞLAMADI + GÖREV ATLANDI + İSTATİSK SIFIRLAMA + GÜNLÜKLERİ SİL + GELECEK TEDAVİLERİ SİL + AYARLARI DIŞA AKTAR + AYARLARI İÇE AKTAR + VERİTABANLARINI SIFIRLA + VERİTABANINI DIŞA AKTAR + VERİTABANINI İÇE AKTAR + OTP DIŞA AKTAR + OTP SIFIRLAMA + SMS\'İ DURDUR + KULLANICI GİRİŞLERİNİ DIŞA AKTAR + AAPS\'i BAŞLAT + AAPS\'DEN ÇIK + EKLENTİ ETKİN + EKLENTİ DEVRE DIŞI + BİLİNMEYEN + Dizi + Kaynak + UTC Denkleme + Eylem + Zaman damgası + Birim Yok + Kullanıcı Girişlerini Excel\'e Aktar (csv) + DÖNGÜ DEĞİŞTİ + DÖNGÜ KALDIRILDI + DİĞER + Düşük hedef profili + Yüksek hedef profili + Geçici hedef alt değeri + Geçici hedef üst değeri + Geçici hedef değeri + Profil DIA değeri + Profil duyarlılık değeri + Azami profil bazal değeri + Mevcut bazal değer + Profil karbonhidrat oranı değeri + %1$.2f, %2$.2f ile sınırlıdır + »%1$s« sınırların dışında + »%1$s« %2$.2f sınırların dışında + Bazal değer + NSClient sürümü AndroidAPS ile eşleşmiyor. Lütfen güncelle. + + %1$d gün + %1$d gün + + + %1$d saat + %1$d saat + + + %1$d dakika + %1$d dakika +
diff --git a/core/src/main/res/values-tr-rTR/validator.xml b/core/src/main/res/values-tr-rTR/validator.xml index 2ad874719e..b1c2f99948 100644 --- a/core/src/main/res/values-tr-rTR/validator.xml +++ b/core/src/main/res/values-tr-rTR/validator.xml @@ -1,7 +1,24 @@ - Yalnızca sayısal rakam girebilirsiniz. - %1$s - %2$s aralığında yalnızca sayısal rakamlar kullanılabilir. + Yalnızca rakam girebilirsiniz. + %1$s - %2$s aralığında yalnızca rakamlar kullanılabilir. + Bu alan herhangi bir özel karakter içeremez + Yalnızca standart harflere izin verilir Alan boş olmamalı + E-posta adresi geçerli değil + Kredi kartı numarası geçerli değil Telefon numarası geçerli değil + Alan adı geçerli değil + IP Adresi geçerli değil + Web adresi geçerli değil + Geçerli bir ad veya soyadı değil. + Geçerli bir isim değil. + Fromat geçerli değil + 4 haneli sayı olmalı + 6 haneli sayı olmalı + 12 karakter olmalı ve ABCDEF0123456789 kullanılmalıdır + 8 karakter olmalı ve ABCDEF0123456789 kullanılmalıdır + 4 karakter olmalı ve ABCDEF0123456789 kullanılmalıdır + Minimum uzunlukta değil + Pin 3- 6 rakamdan oluşmalı, aynı veya sıralı rakamlar kullanılmamalıdır diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index b653a9bc23..3ac720e134 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -24,7 +24,6 @@ pump_unreachable_threshold missed_bg_readings_threshold gradually_increase_notification_volume - ns_sync_use_absolute virtualpump_type QuickWizard wearcontrol @@ -225,7 +224,6 @@ g/U - No profile selected Start profile %1$d%% for %2$d min diff --git a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 40e85034d8..edc280d55e 100644 --- a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -22,7 +22,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper @@ -42,7 +42,9 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) } @@ -54,4 +56,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt index f002f15d26..5f9a7a3f0e 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt @@ -34,7 +34,7 @@ import java.util.* class ProfileTest : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var context: Context @Mock lateinit var config: Config @Mock lateinit var sp: SP @@ -60,12 +60,12 @@ class ProfileTest : TestBase() { testPumpPlugin = TestPumpPlugin { AndroidInjector { } } dateUtil = DateUtil(context) rxBus = RxBus(TestAapsSchedulers(), aapsLogger) - hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) + hardLimits = HardLimits(aapsLogger, rxBus, sp, rh, context, repository) `when`(activePluginProvider.activePump).thenReturn(testPumpPlugin) - `when`(resourceHelper.gs(R.string.profile_per_unit)).thenReturn("/U") - `when`(resourceHelper.gs(R.string.profile_carbs_per_unit)).thenReturn("g/U") - `when`(resourceHelper.gs(R.string.profile_ins_units_per_hour)).thenReturn("U/h") - `when`(resourceHelper.gs(anyInt(), anyString())).thenReturn("") + `when`(rh.gs(R.string.profile_per_unit)).thenReturn("/U") + `when`(rh.gs(R.string.profile_carbs_per_unit)).thenReturn("g/U") + `when`(rh.gs(R.string.profile_ins_units_per_hour)).thenReturn("U/h") + `when`(rh.gs(anyInt(), anyString())).thenReturn("") } @Test @@ -73,7 +73,7 @@ class ProfileTest : TestBase() { // Test valid profile var p = ProfileSealed.Pure(pureProfileFromJson(JSONObject(okProfile), dateUtil)!!) - Assert.assertEquals(true, p.isValid("Test", testPumpPlugin, config, resourceHelper, rxBus, hardLimits, false).isValid) + Assert.assertEquals(true, p.isValid("Test", testPumpPlugin, config, rh, rxBus, hardLimits, false).isValid) // Assert.assertEquals(true, p.log().contains("NS units: mmol")) // JSONAssert.assertEquals(JSONObject(okProfile), p.toPureNsJson(dateUtil), false) Assert.assertEquals(5.0, p.dia, 0.01) @@ -91,13 +91,13 @@ class ProfileTest : TestBase() { Assert.assertEquals(""" 00:00 6,0 mmol/U 02:00 6,2 mmol/U - """.trimIndent(), p.getIsfList(resourceHelper, dateUtil).replace(".", ",")) + """.trimIndent(), p.getIsfList(rh, dateUtil).replace(".", ",")) Assert.assertEquals(30.0, p.getIc(c.timeInMillis), 0.01) Assert.assertEquals(30.0, p.getIcTimeFromMidnight(2 * 60 * 60), 0.01) - Assert.assertEquals("00:00 30,0 g/U", p.getIcList(resourceHelper, dateUtil).replace(".", ",")) + Assert.assertEquals("00:00 30,0 g/U", p.getIcList(rh, dateUtil).replace(".", ",")) Assert.assertEquals(0.1, p.getBasal(c.timeInMillis), 0.01) Assert.assertEquals(0.1, p.getBasalTimeFromMidnight(2 * 60 * 60), 0.01) - Assert.assertEquals("00:00 0,10 U/h", p.getBasalList(resourceHelper, dateUtil).replace(".", ",")) + Assert.assertEquals("00:00 0,10 U/h", p.getBasalList(rh, dateUtil).replace(".", ",")) Assert.assertEquals(0.1, p.getBasalValues()[0].value, 0.01) Assert.assertEquals(0.1, p.getMaxDailyBasal(), 0.01) Assert.assertEquals(2.4, p.percentageBasalSum(), 0.01) @@ -107,7 +107,7 @@ class ProfileTest : TestBase() { // Assert.assertEquals(4.0, p.getTargetLowTimeFromMidnight(2 * 60 * 60), 0.01) Assert.assertEquals(90.0, p.getTargetHighMgdl(c.timeInMillis), 0.01) // Assert.assertEquals(5.0, p.getTargetHighTimeFromMidnight(2 * 60 * 60), 0.01) - Assert.assertEquals("00:00 5,0 - 5,0 mmol", p.getTargetList(resourceHelper, dateUtil).replace(".", ",")) + Assert.assertEquals("00:00 5,0 - 5,0 mmol", p.getTargetList(rh, dateUtil).replace(".", ",")) Assert.assertEquals(100, p.percentage) Assert.assertEquals(0, p.timeshift) Assert.assertEquals(0.1, Profile.toMgdl(0.1, GlucoseUnit.MGDL), 0.01) @@ -125,7 +125,7 @@ class ProfileTest : TestBase() { //Test basal profile below limit p = ProfileSealed.Pure(pureProfileFromJson(JSONObject(belowLimitValidProfile), dateUtil)!!) - p.isValid("Test", testPumpPlugin, config, resourceHelper, rxBus, hardLimits, false) + p.isValid("Test", testPumpPlugin, config, rh, rxBus, hardLimits, false) // Test profile w/o units Assert.assertNull(pureProfileFromJson(JSONObject(noUnitsValidProfile), dateUtil)) @@ -153,11 +153,11 @@ class ProfileTest : TestBase() { 00:00 6.2 mmol/U 01:00 6.0 mmol/U 03:00 6.2 mmol/U - """.trimIndent(), p.getIsfList(resourceHelper, dateUtil)) + """.trimIndent(), p.getIsfList(rh, dateUtil)) // Test hour alignment testPumpPlugin.pumpDescription.is30minBasalRatesCapable = false p = ProfileSealed.Pure(pureProfileFromJson(JSONObject(notAlignedBasalValidProfile), dateUtil)!!) - p.isValid("Test", testPumpPlugin, config, resourceHelper, rxBus, hardLimits, false) + p.isValid("Test", testPumpPlugin, config, rh, rxBus, hardLimits, false) } } \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/data/PumpEnactResultTest.kt b/core/src/test/java/info/nightscout/androidaps/data/PumpEnactResultTest.kt index 687c9a64e8..0165075af4 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/PumpEnactResultTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/PumpEnactResultTest.kt @@ -16,23 +16,23 @@ class PumpEnactResultTest : TestBaseWithProfile() { val injector = HasAndroidInjector { AndroidInjector { if (it is PumpEnactResult) { - it.resourceHelper = resourceHelper + it.rh = rh } } } @Before fun mock() { - `when`(resourceHelper.gs(R.string.success)).thenReturn("Success") - `when`(resourceHelper.gs(R.string.enacted)).thenReturn("Enacted") - `when`(resourceHelper.gs(R.string.comment)).thenReturn("Comment") - `when`(resourceHelper.gs(R.string.configbuilder_insulin)).thenReturn("Insulin") - `when`(resourceHelper.gs(R.string.smb_shortname)).thenReturn("SMB") - `when`(resourceHelper.gs(R.string.insulin_unit_shortname)).thenReturn("U") - `when`(resourceHelper.gs(R.string.canceltemp)).thenReturn("Cancel temp basal") - `when`(resourceHelper.gs(R.string.duration)).thenReturn("Duration") - `when`(resourceHelper.gs(R.string.percent)).thenReturn("Percent") - `when`(resourceHelper.gs(R.string.absolute)).thenReturn("Absolute") + `when`(rh.gs(R.string.success)).thenReturn("Success") + `when`(rh.gs(R.string.enacted)).thenReturn("Enacted") + `when`(rh.gs(R.string.comment)).thenReturn("Comment") + `when`(rh.gs(R.string.configbuilder_insulin)).thenReturn("Insulin") + `when`(rh.gs(R.string.smb_shortname)).thenReturn("SMB") + `when`(rh.gs(R.string.insulin_unit_shortname)).thenReturn("U") + `when`(rh.gs(R.string.canceltemp)).thenReturn("Cancel temp basal") + `when`(rh.gs(R.string.duration)).thenReturn("Duration") + `when`(rh.gs(R.string.percent)).thenReturn("Percent") + `when`(rh.gs(R.string.absolute)).thenReturn("Absolute") } @Test fun successTest() { diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt index 67d0c695f2..116d750da5 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.kt @@ -40,7 +40,7 @@ class APSResultTest : TestBaseWithProfile() { it.activePlugin = activePluginProvider it.iobCobCalculator = iobCobCalculator it.profileFunction = profileFunction - it.resourceHelper = resourceHelper + it.rh = rh } // BASAL RATE IN TEST PROFILE IS 1U/h @@ -161,7 +161,7 @@ class APSResultTest : TestBaseWithProfile() { it.activePlugin = activePluginProvider it.iobCobCalculator = iobCobCalculator it.profileFunction = profileFunction - it.resourceHelper = resourceHelper + it.rh = rh } apsResult.rate(10.0) val apsResult2 = apsResult.newAndClone(injector) @@ -178,7 +178,7 @@ class APSResultTest : TestBaseWithProfile() { it.activePlugin = activePluginProvider it.iobCobCalculator = iobCobCalculator it.profileFunction = profileFunction - it.resourceHelper = resourceHelper + it.rh = rh } apsResult.rate(20.0).tempBasalRequested(true) Assert.assertEquals(20.0, safeGetDouble(apsResult.json(), "rate"), 0.0) diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt index 6f20a5d43e..4b49a3a9a7 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt @@ -26,7 +26,7 @@ import org.mockito.Mockito.verify private lateinit var versionCheckerUtils: VersionCheckerUtils @Mock lateinit var sp: SP - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var context: Context @Mock lateinit var receiverStatusStore: ReceiverStatusStore @Mock lateinit var config: Config @@ -34,7 +34,7 @@ import org.mockito.Mockito.verify @Mock lateinit var rxBus: RxBus @Before fun setup() { - versionCheckerUtils = VersionCheckerUtils(aapsLogger, sp, resourceHelper, rxBus, config, receiverStatusStore, dateUtil) + versionCheckerUtils = VersionCheckerUtils(aapsLogger, sp, rh, rxBus, config, receiverStatusStore, dateUtil) } @Test @@ -376,7 +376,7 @@ import org.mockito.Mockito.verify `when`(dateUtil.now()).thenReturn(10000000000L) assertEquals(10000000000L, dateUtil.now()) - `when`(resourceHelper.gs(anyInt(), anyString())).thenReturn("") + `when`(rh.gs(anyInt(), anyString())).thenReturn("") } } diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt index 087cfcadc1..3dfe9d6f40 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt @@ -17,7 +17,7 @@ import java.io.File @Suppress("SpellCheckingInspection") class EncryptedPrefsFormatTest : TestBase() { - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP @Mock lateinit var file: MockedFile @@ -35,7 +35,7 @@ class EncryptedPrefsFormatTest : TestBase() { @Before fun mock() { - Mockito.`when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation") + Mockito.`when`(rh.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation") } @Test @@ -53,7 +53,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") assumeAES256isSupported(cryptoUtil) @@ -70,7 +70,7 @@ class EncryptedPrefsFormatTest : TestBase() { @Test fun preferenceSavingTest() { val storage = SingleStringStorage("") - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = Prefs( mapOf( "key1" to "A", @@ -87,7 +87,7 @@ class EncryptedPrefsFormatTest : TestBase() { @Test fun importExportStabilityTest() { val storage = SingleStringStorage("") - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefsIn = Prefs( mapOf( "testpref1" to "--1--", @@ -126,7 +126,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = encryptedFormat.loadPreferences(getMockedFile(), "it-is-NOT-right-secret") Assert.assertEquals(prefs.values.size, 0) @@ -153,7 +153,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") assumeAES256isSupported(cryptoUtil) @@ -180,7 +180,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") Assert.assertEquals(prefs.values.size, 0) @@ -195,7 +195,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") Assert.assertEquals(prefs.values.size, 0) @@ -207,7 +207,7 @@ class EncryptedPrefsFormatTest : TestBase() { val frozenPrefs = "whatever man, i duno care" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) encryptedFormat.loadPreferences(getMockedFile(), "sikret") } @@ -226,7 +226,7 @@ class EncryptedPrefsFormatTest : TestBase() { "}" val storage = SingleStringStorage(frozenPrefs) - val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) + val encryptedFormat = EncryptedPrefsFormat(rh, cryptoUtil, storage) encryptedFormat.loadPreferences(getMockedFile(), "sikret") } diff --git a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt index 2df42bf26c..bdd23eec47 100644 --- a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt @@ -13,7 +13,7 @@ import java.util.* class DateUtilTest : TestBase() { @Mock lateinit var context: Context - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Test fun fromISODateStringTest() { @@ -65,7 +65,7 @@ class DateUtilTest : TestBase() { } */ @Test fun timeFrameStringTest() { - `when`(resourceHelper.gs(R.string.shorthour)).thenReturn("h") - Assert.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), resourceHelper)) + `when`(rh.gs(R.string.shorthour)).thenReturn("h") + Assert.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), rh)) } } \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt index 8895b03bfe..4b1200857a 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Pump import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -50,10 +50,10 @@ class DanaFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var danaPump: DanaPump - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var warnColors: WarnColors @Inject lateinit var dateUtil: DateUtil @@ -80,8 +80,10 @@ class DanaFragment : DaggerFragment() { } } - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle?): View { + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle? + ): View { _binding = DanarFragmentBinding.inflate(inflater, container, false) return binding.root } @@ -112,10 +114,12 @@ class DanaFragment : DaggerFragment() { danaPump.reset() commandQueue.readStatus("Clicked connect to pump", null) } - if (activePlugin.activePump.pumpDescription.pumpType == PumpType.DANA_RS) + if (activePlugin.activePump.pumpDescription.pumpType == PumpType.DANA_RS || + activePlugin.activePump.pumpDescription.pumpType == PumpType.DANA_I + ) binding.btconnection.setOnLongClickListener { activity?.let { - OKDialog.showConfirmation(it, resourceHelper.gs(R.string.resetpairing)) { + OKDialog.showConfirmation(it, rh.gs(R.string.resetpairing)) { uel.log(Action.CLEAR_PAIRING_KEYS, Sources.Dana) (activePlugin.activePump as Dana).clearPairing() } @@ -152,22 +156,22 @@ class DanaFragment : DaggerFragment() { .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ - pumpStatusIcon = when (it.status) { - EventPumpStatusChanged.Status.CONNECTING -> - "{fa-bluetooth-b spin} ${it.secondsElapsed}s" - EventPumpStatusChanged.Status.CONNECTED -> - "{fa-bluetooth}" - EventPumpStatusChanged.Status.DISCONNECTED -> - "{fa-bluetooth-b}" + pumpStatusIcon = when (it.status) { + EventPumpStatusChanged.Status.CONNECTING -> + "{fa-bluetooth-b spin} ${it.secondsElapsed}s" + EventPumpStatusChanged.Status.CONNECTED -> + "{fa-bluetooth}" + EventPumpStatusChanged.Status.DISCONNECTED -> + "{fa-bluetooth-b}" - else -> - "{fa-bluetooth-b}" - } - binding.btconnection.text = pumpStatusIcon - pumpStatus = it.getStatus(resourceHelper) - binding.pumpStatus.text = pumpStatus - binding.pumpStatusLayout.visibility = (pumpStatus != "").toVisibility() - }, fabricPrivacy::logException) + else -> + "{fa-bluetooth-b}" + } + binding.btconnection.text = pumpStatusIcon + pumpStatus = it.getStatus(rh) + binding.pumpStatus.text = pumpStatus + binding.pumpStatusLayout.visibility = (pumpStatus != "").toVisibility() + }, fabricPrivacy::logException) pumpStatus = "" pumpStatusIcon = "{fa-bluetooth-b}" @@ -203,7 +207,7 @@ class DanaFragment : DaggerFragment() { if (pump.lastConnection != 0L) { val agoMilliseconds = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMilliseconds.toDouble() / 60.0 / 1000.0).toInt() - binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")" + binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(R.string.minago, agoMin) + ")" warnColors.setColor(binding.lastconnection, agoMin.toDouble(), 16.0, 31.0) } if (pump.lastBolusTime != 0L) { @@ -211,22 +215,22 @@ class DanaFragment : DaggerFragment() { val agoHours = agoMilliseconds.toDouble() / 60.0 / 60.0 / 1000.0 if (agoHours < 6) // max 6h back - binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, rh) + " " + rh.gs(R.string.formatinsulinunits, pump.lastBolusAmount) else binding.lastbolus.text = "" } - binding.dailyunits.text = resourceHelper.gs(R.string.reservoirvalue, pump.dailyTotalUnits, pump.maxDailyTotalUnits) + binding.dailyunits.text = rh.gs(R.string.reservoirvalue, pump.dailyTotalUnits, pump.maxDailyTotalUnits) warnColors.setColor(binding.dailyunits, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75, pump.maxDailyTotalUnits * 0.9) - binding.basabasalrate.text = "( " + (pump.activeProfile + 1) + " ) " + resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) + binding.basabasalrate.text = "( " + (pump.activeProfile + 1) + " ) " + rh.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) // DanaRPlugin, DanaRKoreanPlugin binding.tempbasal.text = danaPump.temporaryBasalToString() binding.extendedbolus.text = danaPump.extendedBolusToString() - binding.reservoir.text = resourceHelper.gs(R.string.reservoirvalue, pump.reservoirRemainingUnits, 300) + binding.reservoir.text = rh.gs(R.string.reservoirvalue, pump.reservoirRemainingUnits, 300) warnColors.setColorInverse(binding.reservoir, pump.reservoirRemainingUnits, 50.0, 20.0) binding.battery.text = "{fa-battery-" + pump.batteryRemaining / 25 + "}" warnColors.setColorInverse(binding.battery, pump.batteryRemaining.toDouble(), 51.0, 26.0) - binding.firmware.text = resourceHelper.gs(R.string.dana_model, pump.modelFriendlyName(), pump.hwModel, pump.protocol, pump.productCode) + binding.firmware.text = rh.gs(R.string.dana_model, pump.modelFriendlyName(), pump.hwModel, pump.protocol, pump.productCode) binding.basalBolusStep.text = pump.basalStep.toString() + "/" + pump.bolusStep.toString() binding.serialNumber.text = pump.serialNumber val icon = if (danaPump.pumpType() == PumpType.DANA_I) R.drawable.ic_dana_i else R.drawable.ic_dana_rs diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt index 5b531eb2ce..baf4ecba8d 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.dana.databinding.DanarHistoryItemBinding import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger @@ -44,7 +44,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -65,7 +65,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ binding.status.text = it.getStatus(resourceHelper) }, fabricPrivacy::logException) + .subscribe({ binding.status.text = it.getStatus(rh) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventDanaRSyncStatus::class.java) .observeOn(aapsSchedulers.main) @@ -96,19 +96,19 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { // Types val typeList = ArrayList() - typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, resourceHelper.gs(R.string.danar_history_alarm))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, resourceHelper.gs(R.string.danar_history_basalhours))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, resourceHelper.gs(R.string.danar_history_bolus))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_CARBO, resourceHelper.gs(R.string.danar_history_carbohydrates))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, resourceHelper.gs(R.string.danar_history_dailyinsulin))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, resourceHelper.gs(R.string.danar_history_glucose))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, rh.gs(R.string.danar_history_alarm))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, rh.gs(R.string.danar_history_basalhours))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, rh.gs(R.string.danar_history_bolus))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_CARBO, rh.gs(R.string.danar_history_carbohydrates))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, rh.gs(R.string.danar_history_dailyinsulin))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, rh.gs(R.string.danar_history_glucose))) if (!isKorean && !isRS) { - typeList.add(TypeList(RecordTypes.RECORD_TYPE_ERROR, resourceHelper.gs(R.string.danar_history_errors))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_ERROR, rh.gs(R.string.danar_history_errors))) } - if (isRS) typeList.add(TypeList(RecordTypes.RECORD_TYPE_PRIME, resourceHelper.gs(R.string.danar_history_prime))) + if (isRS) typeList.add(TypeList(RecordTypes.RECORD_TYPE_PRIME, rh.gs(R.string.danar_history_prime))) if (!isKorean) { - typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, resourceHelper.gs(R.string.danar_history_refill))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, resourceHelper.gs(R.string.danar_history_syspend))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, rh.gs(R.string.danar_history_refill))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, rh.gs(R.string.danar_history_syspend))) } binding.spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, typeList) @@ -180,9 +180,9 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { } RecordTypes.RECORD_TYPE_DAILY -> { - holder.binding.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBasal) - holder.binding.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus) - holder.binding.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) + holder.binding.dailyBasal.text = rh.gs(R.string.formatinsulinunits, record.dailyBasal) + holder.binding.dailyBolus.text = rh.gs(R.string.formatinsulinunits, record.dailyBolus) + holder.binding.dailyTotal.text = rh.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) holder.binding.time.text = dateUtil.dateString(record.timestamp) holder.binding.time.visibility = View.VISIBLE holder.binding.value.visibility = View.GONE diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt index 9993d991fe..a2d30d1547 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaUserOptionsActivity.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.dana.R import info.nightscout.androidaps.dana.databinding.DanarUserOptionsActivityBinding import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus @@ -33,7 +33,7 @@ class DanaUserOptionsActivity : NoSplashAppCompatActivity() { @Inject lateinit var context: Context @Inject lateinit var danaPump: DanaPump @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() @@ -153,7 +153,7 @@ class DanaUserOptionsActivity : NoSplashAppCompatActivity() { commandQueue.setUserOptions(object : Callback() { override fun run() { if (!result.success) { - ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.pumperror), R.raw.boluserror) + ErrorHelperActivity.runAlarm(context, result.comment, rh.gs(R.string.pumperror), R.raw.boluserror) } } }) diff --git a/dana/src/main/res/values-bg-rBG/strings.xml b/dana/src/main/res/values-bg-rBG/strings.xml index ab72bed896..600425914c 100644 --- a/dana/src/main/res/values-bg-rBG/strings.xml +++ b/dana/src/main/res/values-bg-rBG/strings.xml @@ -5,7 +5,9 @@ Сдвояване - ОК Времето за сдвояване изтече Очаква сдвояване с помпа + Dana-i/RS Dana + Интеграция за помпа DANA Diabecare RS и Dana-i Превишавате макс болус Грешка при команда Скорост грешка @@ -113,4 +115,5 @@ Натиснете OK на помпата\nи въведете двата номера\nДръжте дисплея на помпата включен чрез натискане минус бутон, докато завършите въвеждане на код. 1: (12 цифри) 2: (8 цифри) + Базал/Болус стъпка diff --git a/dana/src/main/res/values-hu-rHU/strings.xml b/dana/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/dana/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/dana/src/main/res/values-iw-rIL/strings.xml b/dana/src/main/res/values-iw-rIL/strings.xml index 1be01b16d1..f73217831e 100644 --- a/dana/src/main/res/values-iw-rIL/strings.xml +++ b/dana/src/main/res/values-iw-rIL/strings.xml @@ -51,7 +51,7 @@ הפסקת בזאלי זמני מגדיר בולוס ממושך מפסיק בולוס ממושך - מעדכן את הקצב הבזאלי + מעדכן את המינון הבזאלי הגדרת בזאלי זמני ממתין לסינכרון השעון (%1$d שנ\') סיסמת משאבה שגויה! diff --git a/dana/src/main/res/values-tr-rTR/strings.xml b/dana/src/main/res/values-tr-rTR/strings.xml index 3ea04e700d..fd649ee97e 100644 --- a/dana/src/main/res/values-tr-rTR/strings.xml +++ b/dana/src/main/res/values-tr-rTR/strings.xml @@ -1,2 +1,119 @@ - + + Eşleştirme + Şu ana kadar hiçbir cihaz bulunamadı + Eşleştirme tamam + Eşleştirme zaman aşımı + Pompada eşleştirme bekleniyor + Dana-i/RS + Dana + DANA Diabecare RS ve Dana-i pompaları için pompa entegrasyonu + Max bolus ihlali + Komut hatası + Hız hatası + İnsülin sınırı ihlali + Soruldu: %1$.2fU Teslim edildi: %2$.2fU Hata kodu: %3$s + Değer düzgün ayarlanmamış + Bazal adımı ayarla 0,01 Ü/s + Eşleştirme bilgileri sıfırlansın mı? + %1$s\nModel: %2$02X\nProtokol: %3$02X\nKod: %4$02X + Etkinlik işleniyor + Pompada yayma bolusları etkinleştir + Gönderildi + Durdu + Desteklenmeyen pompa yazılımı + Pompa hatası + Düşük Pil + Önceden ayarlanmış bazal orandan daha az teslimat + Pompayı durdur + Pompa pili bitmiş + Tıkanıklık + Rezervuar boş + Mili kontrol edin + Bazal maks + Günlük maks + Kan şekeri ölçüm uyarısı + Kalan insülin düzeyi + Kaçırılan bolus + Geçersiz eşleştirme bilgisi. Yeni eşleştirme isteği + Pompa durumu alınıyor + Yayma bolus durumu alınıyor + Bolus durumu alınıyor + Geçici bazal durumu alınıyor + Pompa ayarları alınıyor + Pompa durumu alınıyor + Büyük zaman farkı + Büyük zaman farkı:\n1,5 saatten fazla olduğunda pompada zaman kapalıdır.\nLütfen pompanın üzerindeki zamanı manuel olarak ayarlayın ve geçmişin pompadan okunmasından dolayı beklenmedik davranışlara neden olmadığından emin olun.\nMümkünse, zamanı değiştirmeden önce geçmişini pompadan çıkarın veya son yanlış geçmiş girişinden sonra bir DIA için Kapalı Döngü\'yü iptal edin, ancak o andan itibaren en az bir DIA\'yı devre dışı bırakın. + Lütfen pompanızı telefonunuzla bağlayın! + Günlük İnsülin limitine yaklaşıldı + Bolus teslimatı başlatılıyor + Bolus bitimi için bekleniyor. Kalan %1$d san. + Geçici bazal durduruluyor + Yayma bolus ayarlanıyor + Yayma bolus durduruluyor + Bazal oranların güncellenmesi + Geçici bazal ayarı + Zaman senkronizasyonu bekleniyor (%1$d sn) + Hatalı parola! + Alarmlar + Bazal Saatleri + Boluslar + Karbonhidratlar + Günlük İnsülin + Hatalar + Glikoz + Doldur + Askıya alınan + Doldur + Kullanıcı seçenekleri + Saat formatı + Düğme kaydırma + Tuşa basıldığında bip sesi çıkar + Alarm + Ses + Titreşim + İkisi de + LCD açık kalma süresi [seconds] + Arka ışık süresi [seconds] + Glikoz birimleri + Kapatma [hours] + Düşük rezervuar [Units] + Seçenekleri pompaya kaydet + DANA Diabecare R pompaları için pompa entegrasyonu + DANA Diabecare R yerli Kore pompaları için pompa entegrasyonu + Güncellenmiş ürün yazılımlı DANA Diabecare R pompaları için pompa entegrasyonu + DANA + Bluetooth bağdaştırıcısı bulunamadı + Seçili aygıt bulunamadı + Pompayı Ü/d\'den Ü/s\'te değiştirin + DanaR Kore + DanaR + Pompa sürücüsü düzeltildi + DanaRv2 + Pompada EasyUI modunu devre dışı bırak + Bazal profil ayarı başarısız oldu + Bluetooth durumu + IOB(Aktif insülin) pompa + Firmware + Dana pompa ayarları + 12sa + 24sa + + Kapa + DanaR Bluetooth aygıtı + Pompa şifresi (yalnızca v1) + Pompa Şifresi + Yayma bolusu >200%% için kullan + Bolus hızı + Seçilen Pompa + Rezervuar değişikliği günlüğü + Geçmişte tespit edildiğinde careportal\'a \"İnsülin Değişimi\" olayı ekleyin + Kanül değişikliği günlüğü + Geçmişte tespit edildiğinde careportal\'a \"Kanül Değişikliği\" olayı ekle + PIN1 + PIN2 + Pompada OK\'e basın\nve görüntülenen 2 sayıyı girin\nKodu girmeyi bitirene kadar eksi düğmesine basarak pompa ekranını AÇIK tutun. + 1: (12 basamak) + 2: (8 basamak) + Bazal/bolus adımı + diff --git a/dana/src/main/res/values/strings.xml b/dana/src/main/res/values/strings.xml index da88761671..995ae01883 100644 --- a/dana/src/main/res/values/strings.xml +++ b/dana/src/main/res/values/strings.xml @@ -9,6 +9,7 @@ danars_v3_randompairing_key_ danars_v3_pairing_key_ danars_v3_randomsync_key_ + dana_ble5_pairingkey rs_logcanulachange rs_loginsulinchange rs_last_clear_key_request diff --git a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 40e85034d8..87720e4950 100644 --- a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -22,7 +22,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper @@ -42,11 +42,17 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) } fun getValidProfileStore(): ProfileStore { + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + val json = JSONObject() val store = JSONObject() store.put(TESTPROFILENAME, JSONObject(validProfileJSON)) @@ -54,4 +60,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt index 8016c343dd..e064ec9ce7 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt @@ -41,16 +41,16 @@ class DanaRKoreanPlugin @Inject constructor( aapsSchedulers: AapsSchedulers, rxBus: RxBus, private val context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, constraintChecker: ConstraintChecker, activePlugin: ActivePlugin, sp: SP, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, danaPump: DanaPump, dateUtil: DateUtil, private val fabricPrivacy: FabricPrivacy, pumpSync: PumpSync -) : AbstractDanaRPlugin(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync) { +) : AbstractDanaRPlugin(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync) { init { pluginDescription.description(R.string.description_pump_dana_r_korean) @@ -100,7 +100,7 @@ class DanaRKoreanPlugin @Inject constructor( // Plugin base interface override val name: String - get() = resourceHelper.gs(R.string.danarkoreanpump) + get() = rh.gs(R.string.danarkoreanpump) override val preferencesId: Int get() = R.xml.pref_danarkorean @@ -130,7 +130,7 @@ class DanaRKoreanPlugin @Inject constructor( val result = PumpEnactResult(injector) result.success(connectionOK && abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep) .bolusDelivered(t.insulin) - if (!result.success) result.comment(resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.bolusStartErrorCode)) else result.comment(R.string.ok) + if (!result.success) result.comment(rh.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.bolusStartErrorCode)) else result.comment(R.string.ok) aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered) detailedBolusInfo.insulin = t.insulin detailedBolusInfo.timestamp = dateUtil.now() @@ -157,10 +157,22 @@ class DanaRKoreanPlugin @Inject constructor( //This should not be needed while using queue because connection should be done before calling this var result = PumpEnactResult(injector) val absoluteRateAfterConstraint = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() - val doTempOff = baseBasalRate - absoluteRateAfterConstraint == 0.0 && absoluteRateAfterConstraint >= 0.10 + var doTempOff = baseBasalRate - absoluteRateAfterConstraint == 0.0 && absoluteRateAfterConstraint >= 0.10 val doLowTemp = absoluteRateAfterConstraint < baseBasalRate || absoluteRateAfterConstraint < 0.10 val doHighTemp = absoluteRateAfterConstraint > baseBasalRate && !useExtendedBoluses val doExtendedTemp = absoluteRateAfterConstraint > baseBasalRate && useExtendedBoluses + + var percentRate: Int = java.lang.Double.valueOf(absoluteRateAfterConstraint / baseBasalRate * 100).toInt() + // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. + if (absoluteRateAfterConstraint < 0.10) percentRate = 0 + percentRate = if (percentRate < 100) Round.ceilTo(percentRate.toDouble(), 10.0).toInt() else Round.floorTo(percentRate.toDouble(), 10.0).toInt() + if (percentRate > pumpDescription.maxTempPercent) { + percentRate = pumpDescription.maxTempPercent + } + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Calculated percent rate: $percentRate") + + if (percentRate == 100) doTempOff = true + if (doTempOff) { // If extended in progress if (danaPump.isExtendedInProgress && useExtendedBoluses) { @@ -177,15 +189,6 @@ class DanaRKoreanPlugin @Inject constructor( return result } if (doLowTemp || doHighTemp) { - var percentRate: Int = java.lang.Double.valueOf(absoluteRateAfterConstraint / baseBasalRate * 100).toInt() - // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. - if (absoluteRateAfterConstraint < 0.10) percentRate = 0 - percentRate = if (percentRate < 100) Round.ceilTo(percentRate.toDouble(), 10.0).toInt() else Round.floorTo(percentRate.toDouble(), 10.0).toInt() - if (percentRate > pumpDescription.maxTempPercent) { - percentRate = pumpDescription.maxTempPercent - } - aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Calculated percent rate: $percentRate") - // If extended in progress if (danaPump.isExtendedInProgress && useExtendedBoluses) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)") diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBasic_k.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBasic_k.kt index c8a6d7bd88..fab11da0eb 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBasic_k.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBasic_k.kt @@ -32,13 +32,13 @@ class MsgInitConnStatusBasic_k( aapsLogger.debug(LTag.PUMPCOMM, "easyUIMode: $easyUIMode") aapsLogger.debug(LTag.PUMPCOMM, "Pump password: " + danaPump.password) if (danaPump.isEasyModeEnabled) { - val notification = Notification(Notification.EASY_MODE_ENABLED, resourceHelper.gs(R.string.danar_disableeasymode), Notification.URGENT) + val notification = Notification(Notification.EASY_MODE_ENABLED, rh.gs(R.string.danar_disableeasymode), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.EASY_MODE_ENABLED)) } if (!danaPump.isPasswordOK) { - val notification = Notification(Notification.WRONG_PUMP_PASSWORD, resourceHelper.gs(R.string.wrongpumppassword), Notification.URGENT) + val notification = Notification(Notification.WRONG_PUMP_PASSWORD, rh.gs(R.string.wrongpumppassword), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.WRONG_PUMP_PASSWORD)) diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBolus_k.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBolus_k.kt index 290121b7ac..acdda54101 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBolus_k.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusBolus_k.kt @@ -32,7 +32,7 @@ class MsgInitConnStatusBolus_k( aapsLogger.debug(LTag.PUMPCOMM, "Bolus max: " + danaPump.maxBolus) aapsLogger.debug(LTag.PUMPCOMM, "Delivery status: $deliveryStatus") if (!danaPump.isExtendedBolusEnabled) { - val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, resourceHelper.gs(R.string.danar_enableextendedbolus), Notification.URGENT) + val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, rh.gs(R.string.danar_enableextendedbolus), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)) diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt index 26c602a237..a15f694783 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/comm/MsgInitConnStatusTime_k.kt @@ -20,7 +20,7 @@ class MsgInitConnStatusTime_k( override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 < 10) { - val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL) + val notification = Notification(Notification.WRONG_DRIVER, rh.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRKoreanPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to export DanaR") diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java index 1122e449a7..9e22bbd4eb 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java @@ -43,7 +43,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileSwitchChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; @@ -62,12 +62,12 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBus rxBus; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject ConstraintChecker constraintChecker; @Inject DanaPump danaPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; - @Inject CommandQueueProvider commandQueue; + @Inject CommandQueue commandQueue; @Inject MessageHashTableRKorean messageHashTableRKorean; @Inject ActivePlugin activePlugin; @Inject ProfileFunction profileFunction; @@ -126,7 +126,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { try { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus))); //MsgStatus_k statusMsg = new MsgStatus_k(); MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(injector); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(injector); @@ -142,18 +142,18 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { //mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))); long now = System.currentTimeMillis(); danaPump.setLastConnection(now); Profile profile = profileFunction.getProfile(); if (profile != null && Math.abs(danaPump.getCurrentBasal() - profile.getBasal()) >= danaRKoreanPlugin.getPumpDescription().getBasalStep()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal(injector)); if (!danaRKoreanPlugin.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(new EventProfileSwitchChanged()); @@ -161,7 +161,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } if (danaPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !danaRKoreanPlugin.isInitialized()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo(injector)); mSerialIOThread.sendMessage(new MsgSettingMeal(injector)); mSerialIOThread.sendMessage(new MsgSettingBasal_k(injector)); @@ -169,7 +169,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingMaxValues(injector)); mSerialIOThread.sendMessage(new MsgSettingGlucose(injector)); mSerialIOThread.sendMessage(new MsgSettingProfileRatios(injector)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); if (danaPump.getPumpTime() == 0) { // initial handshake was not successful @@ -197,9 +197,9 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (danaPump.getDailyTotalUnits() > danaPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); + Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); - pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); + pumpSync.insertAnnouncement(rh.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); lastApproachingDailyLimit = System.currentTimeMillis(); } } @@ -213,11 +213,11 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean tempBasal(int percent, int durationInHours) { if (!isConnected()) return false; if (danaPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); SystemClock.sleep(500); } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(injector, percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -226,7 +226,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean tempBasalStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -235,7 +235,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(injector, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -244,7 +244,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolusStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(injector)); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -316,7 +316,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates))); Double[] basal = danaPump.buildDanaRProfileRecord(profile); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(injector, basal); mSerialIOThread.sendMessage(msgSet); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index 377247ece1..1fe5f944a2 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -21,7 +21,7 @@ import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventAppExit; 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.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; @@ -47,7 +47,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { private final AAPSLogger aapsLogger; private final Context context; - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final ConstraintChecker constraintChecker; private final DetailedBolusInfoStorage detailedBolusInfoStorage; private final TemporaryBasalStorage temporaryBasalStorage; @@ -62,11 +62,11 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { AapsSchedulers aapsSchedulers, RxBus rxBus, Context context, - ResourceHelper resourceHelper, + ResourceHelper rh, ConstraintChecker constraintChecker, ActivePlugin activePlugin, SP sp, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, DanaPump danaPump, DetailedBolusInfoStorage detailedBolusInfoStorage, TemporaryBasalStorage temporaryBasalStorage, @@ -74,10 +74,10 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { FabricPrivacy fabricPrivacy, PumpSync pumpSync ) { - super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync); + super(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync); this.aapsLogger = aapsLogger; this.context = context; - this.resourceHelper = resourceHelper; + this.rh = rh; this.constraintChecker = constraintChecker; this.detailedBolusInfoStorage = detailedBolusInfoStorage; this.temporaryBasalStorage = temporaryBasalStorage; @@ -127,7 +127,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { @NonNull @Override public String getName() { - return resourceHelper.gs(R.string.danarv2pump); + return rh.gs(R.string.danarv2pump); } @Override @@ -194,7 +194,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { .bolusDelivered(t.insulin) .carbsDelivered(detailedBolusInfo.carbs); if (!result.getSuccess()) - result.comment(resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.getBolusStartErrorCode())); + result.comment(rh.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.getBolusStartErrorCode())); else result.comment(R.string.ok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.getBolusDelivered()); @@ -225,10 +225,21 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); - final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; + boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; final boolean doLowTemp = absoluteRate < getBaseBasalRate() || absoluteRate < 0.10d; final boolean doHighTemp = absoluteRate > getBaseBasalRate(); + int percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); + // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. + if (absoluteRate < 0.10d) percentRate = 0; + if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); + else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); + if (percentRate > 500) // Special high temp 500/15min + percentRate = 500; + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Calculated percent rate: " + percentRate); + + if (percentRate == 100) doTempOff = true; + if (doTempOff) { // If temp in progress if (danaPump.isTempBasalInProgress()) { @@ -241,13 +252,6 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } if (doLowTemp || doHighTemp) { - int percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. - if (absoluteRate < 0.10d) percentRate = 0; - if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); - else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); - if (percentRate > 500) // Special high temp 500/15min - percentRate = 500; // Check if some temp is already in progress if (danaPump.isTempBasalInProgress()) { // Correct basal already set ? diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgCheckValue_v2.kt b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgCheckValue_v2.kt index 500cbc8808..08c73eb232 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgCheckValue_v2.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgCheckValue_v2.kt @@ -27,7 +27,7 @@ class MsgCheckValue_v2( danaPump.protocol = intFromBuff(bytes, 1, 1) danaPump.productCode = intFromBuff(bytes, 2, 1) if (danaPump.hwModel != DanaPump.EXPORT_MODEL) { - val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL) + val notification = Notification(Notification.WRONG_DRIVER, rh.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to Korean DanaR") @@ -44,7 +44,7 @@ class MsgCheckValue_v2( return } if (danaPump.protocol != 2) { - val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL) + val notification = Notification(Notification.WRONG_DRIVER, rh.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRKoreanPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to non APS DanaR") diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEventsV2.kt b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEventsV2.kt index dace263b12..6ce6dc13d5 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEventsV2.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEventsV2.kt @@ -271,6 +271,6 @@ class MsgHistoryEventsV2 constructor( } } if (datetime > danaPump.lastEventTimeLoaded) danaPump.lastEventTimeLoaded = datetime - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.processinghistory) + ": " + status)) } } \ No newline at end of file diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java index 262ff0a0a3..392c5859a0 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java @@ -56,7 +56,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileSwitchChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.Pump; import info.nightscout.androidaps.interfaces.PumpSync; @@ -78,12 +78,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Inject HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @Inject RxBus rxBus; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject DanaPump danaPump; @Inject DanaRKoreanPlugin danaRKoreanPlugin; @Inject DanaRv2Plugin danaRv2Plugin; @Inject ActivePlugin activePlugin; - @Inject CommandQueueProvider commandQueue; + @Inject CommandQueue commandQueue; @Inject Context context; @Inject MessageHashTableRv2 messageHashTableRv2; @Inject ProfileFunction profileFunction; @@ -143,7 +143,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { try { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(injector); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(injector); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(injector); @@ -157,12 +157,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); danaPump.setLastConnection(System.currentTimeMillis()); @@ -170,14 +170,14 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { Profile profile = profileFunction.getProfile(); Pump pump = activePlugin.getActivePump(); if (profile != null && Math.abs(danaPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().getBasalStep()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal(injector)); if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(new EventProfileSwitchChanged()); } } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); if (danaPump.getPumpTime() == 0) { // initial handshake was not successful @@ -193,7 +193,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (Math.abs(timeDiff) > 60 * 60 * 1.5) { aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds - large difference"); //If time-diff is very large, warn user until we can synchronize history readings properly - ErrorHelperActivity.Companion.runAlarm(context, resourceHelper.gs(R.string.largetimediff), resourceHelper.gs(R.string.largetimedifftitle), R.raw.error); + ErrorHelperActivity.Companion.runAlarm(context, rh.gs(R.string.largetimediff), rh.gs(R.string.largetimedifftitle), R.raw.error); //deinitialize pump danaPump.reset(); @@ -212,7 +212,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { long now = System.currentTimeMillis(); if (danaPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !pump.isInitialized()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo(injector)); mSerialIOThread.sendMessage(new MsgSettingActiveProfile(injector)); mSerialIOThread.sendMessage(new MsgSettingMeal(injector)); @@ -234,9 +234,9 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (danaPump.getDailyTotalUnits() > danaPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); + Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); - pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); + pumpSync.insertAnnouncement(rh.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); lastApproachingDailyLimit = System.currentTimeMillis(); } } @@ -248,11 +248,11 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean tempBasal(int percent, int durationInHours) { if (!isConnected()) return false; if (danaPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); SystemClock.sleep(500); } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(injector, percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); loadEvents(); @@ -263,11 +263,11 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean highTempBasal(int percent, int durationInMinutes) { if (!isConnected()) return false; if (danaPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); SystemClock.sleep(500); } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(injector, percent, durationInMinutes == 15, durationInMinutes == 30)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); loadEvents(); @@ -283,11 +283,11 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; if (danaPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); SystemClock.sleep(500); } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(injector, percent, durationInMinutes == 15, durationInMinutes == 30)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); loadEvents(); @@ -297,7 +297,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean tempBasalStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); loadEvents(); @@ -307,7 +307,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(injector, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); loadEvents(); @@ -317,7 +317,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolusStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(injector)); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); loadEvents(); @@ -329,7 +329,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; if (BolusProgressDialog.Companion.getStopPressed()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.startingbolus))); danaPump.setBolusingTreatment(t); danaPump.setBolusDone(false); final int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0); @@ -392,7 +392,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { long expectedEnd = bolusStart + bolusDurationInMSec + 2000; while (System.currentTimeMillis() < expectedEnd) { long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.setStatus(String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); + bolusingEvent.setStatus(String.format(rh.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); rxBus.send(bolusingEvent); SystemClock.sleep(1000); } @@ -401,10 +401,10 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Override public void run() { // load last bolus status - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(new MsgStatus(injector)); bolusingEvent.setPercent(100); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.disconnecting))); } }); return !start.failed; @@ -450,7 +450,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates))); Double[] basal = danaPump.buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile(injector, (byte) 0, basal); mSerialIOThread.sendMessage(msgSet); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index 491d734127..2ed03b933c 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -16,7 +16,7 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.extensions.PumpStateExtensionKt; 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.Constraints; import info.nightscout.androidaps.interfaces.Dana; @@ -66,11 +66,11 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected AbstractDanaRPlugin( HasAndroidInjector injector, DanaPump danaPump, - ResourceHelper resourceHelper, + ResourceHelper rh, ConstraintChecker constraintChecker, AAPSLogger aapsLogger, AapsSchedulers aapsSchedulers, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, RxBus rxBus, ActivePlugin activePlugin, SP sp, @@ -85,7 +85,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump .shortName(R.string.danarpump_shortname) .preferencesId(R.xml.pref_danar) .description(R.string.description_pump_dana_r), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ); this.danaPump = danaPump; this.constraintChecker = constraintChecker; @@ -108,7 +108,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump .toObservable(EventPreferenceChange.class) .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { - if (event.isChanged(getResourceHelper(), R.string.key_danar_bt_name)) { + if (event.isChanged(getRh(), R.string.key_danar_bt_name)) { danaPump.reset(); pumpSync.connectNewPump(); getCommandQueue().readStatus("DeviceChanged", null); @@ -145,7 +145,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump } if (!isInitialized()) { getAapsLogger().error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getResourceHelper().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); + Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getRh().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); result.comment(R.string.pumpNotInitializedProfileNotSet); return result; @@ -153,13 +153,13 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); } if (!sExecutionService.updateBasalsInPump(profile)) { - Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, getResourceHelper().gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, getRh().gs(R.string.failedupdatebasalprofile), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); result.comment(R.string.failedupdatebasalprofile); } else { rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); rxBus.send(new EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)); - Notification notification = new Notification(Notification.PROFILE_SET_OK, getResourceHelper().gs(R.string.profile_set_ok), Notification.INFO, 60); + Notification notification = new Notification(Notification.PROFILE_SET_OK, getRh().gs(R.string.profile_set_ok), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); result.success(true).enacted(true).comment("OK"); } @@ -456,21 +456,21 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfSmaller(getAapsLogger(), danaPump.getMaxBasal(), String.format(getResourceHelper().gs(R.string.limitingbasalratio), danaPump.getMaxBasal(), getResourceHelper().gs(R.string.pumplimit)), this); + absoluteRate.setIfSmaller(getAapsLogger(), danaPump.getMaxBasal(), String.format(getRh().gs(R.string.limitingbasalratio), danaPump.getMaxBasal(), getRh().gs(R.string.pumplimit)), this); return absoluteRate; } @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, String.format(getResourceHelper().gs(R.string.limitingpercentrate), 0, getResourceHelper().gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), String.format(getResourceHelper().gs(R.string.limitingpercentrate), getPumpDescription().getMaxTempPercent(), getResourceHelper().gs(R.string.pumplimit)), this); + percentRate.setIfGreater(getAapsLogger(), 0, String.format(getRh().gs(R.string.limitingpercentrate), 0, getRh().gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), String.format(getRh().gs(R.string.limitingpercentrate), getPumpDescription().getMaxTempPercent(), getRh().gs(R.string.pumplimit)), this); return percentRate; } @NonNull @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(getAapsLogger(), danaPump.getMaxBolus(), String.format(getResourceHelper().gs(R.string.limitingbolus), danaPump.getMaxBolus(), getResourceHelper().gs(R.string.pumplimit)), this); + insulin.setIfSmaller(getAapsLogger(), danaPump.getMaxBolus(), String.format(getRh().gs(R.string.limitingbolus), danaPump.getMaxBolus(), getRh().gs(R.string.pumplimit)), this); return insulin; } diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index 32dfb0265a..9752ef36c7 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -19,7 +19,7 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; 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.PluginType; import info.nightscout.androidaps.interfaces.Profile; @@ -44,7 +44,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { private final AAPSLogger aapsLogger; private final Context context; - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final ConstraintChecker constraintChecker; private final FabricPrivacy fabricPrivacy; @@ -55,20 +55,20 @@ public class DanaRPlugin extends AbstractDanaRPlugin { AapsSchedulers aapsSchedulers, RxBus rxBus, Context context, - ResourceHelper resourceHelper, + ResourceHelper rh, ConstraintChecker constraintChecker, ActivePlugin activePlugin, SP sp, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, DanaPump danaPump, DateUtil dateUtil, FabricPrivacy fabricPrivacy, PumpSync pumpSync ) { - super(injector, danaPump, resourceHelper, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync); + super(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync); this.aapsLogger = aapsLogger; this.context = context; - this.resourceHelper = resourceHelper; + this.rh = rh; this.constraintChecker = constraintChecker; this.fabricPrivacy = fabricPrivacy; @@ -128,7 +128,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @NonNull @Override public String getName() { - return resourceHelper.gs(R.string.danarpump); + return rh.gs(R.string.danarpump); } @Override @@ -170,7 +170,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { .bolusDelivered(t.insulin) .carbsDelivered(detailedBolusInfo.carbs); if (!result.getSuccess()) - result.comment(resourceHelper.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.getBolusStartErrorCode())); + result.comment(rh.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.getBolusStartErrorCode())); else result.comment(R.string.ok); aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.getBolusDelivered()); @@ -209,11 +209,23 @@ public class DanaRPlugin extends AbstractDanaRPlugin { absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); - final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; + boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; final boolean doLowTemp = absoluteRate < getBaseBasalRate() || absoluteRate < 0.10d; final boolean doHighTemp = absoluteRate > getBaseBasalRate() && !useExtendedBoluses; final boolean doExtendedTemp = absoluteRate > getBaseBasalRate() && useExtendedBoluses; + int percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); + // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. + if (absoluteRate < 0.10d) percentRate = 0; + if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); + else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); + if (percentRate > getPumpDescription().getMaxTempPercent()) { + percentRate = getPumpDescription().getMaxTempPercent(); + } + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Calculated percent rate: " + percentRate); + + if (percentRate == 100) doTempOff = true; + if (doTempOff) { // If extended in progress if (danaPump.isExtendedInProgress() && useExtendedBoluses) { @@ -231,16 +243,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin { } if (doLowTemp || doHighTemp) { - int percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. - if (absoluteRate < 0.10d) percentRate = 0; - if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); - else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); - if (percentRate > getPumpDescription().getMaxTempPercent()) { - percentRate = getPumpDescription().getMaxTempPercent(); - } - aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Calculated percent rate: " + percentRate); - // If extended in progress if (danaPump.isExtendedInProgress() && useExtendedBoluses) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)"); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java index 8443f71a22..d75663f088 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java @@ -19,7 +19,7 @@ import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.danaRv2.DanaRv2Plugin; import info.nightscout.androidaps.danar.DanaRPlugin; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.ConfigBuilder; import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; @@ -46,10 +46,10 @@ public class MessageBase { @Inject public DanaRKoreanPlugin danaRKoreanPlugin; @Inject public DanaRv2Plugin danaRv2Plugin; @Inject public RxBus rxBus; - @Inject public ResourceHelper resourceHelper; + @Inject public ResourceHelper rh; @Inject public ActivePlugin activePlugin; @Inject public ConfigBuilder configBuilder; - @Inject public CommandQueueProvider commandQueue; + @Inject public CommandQueue commandQueue; @Inject public DetailedBolusInfoStorage detailedBolusInfoStorage; @Inject public TemporaryBasalStorage temporaryBasalStorage; @Inject public ConstraintChecker constraintChecker; diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusProgress.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusProgress.kt index 2cceeb10f1..b59d96575f 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusProgress.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusProgress.kt @@ -20,7 +20,7 @@ class MsgBolusProgress( danaPump.bolusProgressLastTimeStamp = System.currentTimeMillis() danaPump.bolusingTreatment?.insulin = deliveredInsulin val bolusingEvent = EventOverviewBolusProgress - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, deliveredInsulin) + bolusingEvent.status = rh.gs(R.string.bolusdelivering, deliveredInsulin) bolusingEvent.t = danaPump.bolusingTreatment bolusingEvent.percent = min((deliveredInsulin / danaPump.bolusAmountToBeDelivered * 100).toInt(), 100) aapsLogger.debug(LTag.PUMPCOMM, "Delivered insulin so far: $deliveredInsulin") diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStop.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStop.kt index a531d1cc03..15c0bbec89 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStop.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStop.kt @@ -20,10 +20,10 @@ class MsgBolusStop( danaPump.bolusStopped = true if (!danaPump.bolusStopForced) { danaPump.bolusingTreatment?.insulin = danaPump.bolusAmountToBeDelivered - bolusingEvent.status = resourceHelper.gs(R.string.overview_bolusprogress_delivered) + bolusingEvent.status = rh.gs(R.string.overview_bolusprogress_delivered) bolusingEvent.percent = 100 } else { - bolusingEvent.status = resourceHelper.gs(R.string.overview_bolusprogress_stoped) + bolusingEvent.status = rh.gs(R.string.overview_bolusprogress_stoped) } rxBus.send(bolusingEvent) } diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgError.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgError.kt index af635686a0..9429ff6dc9 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgError.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgError.kt @@ -18,11 +18,11 @@ class MsgError( val errorCode = intFromBuff(bytes, 0, 1) var errorString = "" when (errorCode) { - 1, 2, 3 -> errorString = resourceHelper.gs(R.string.pumperror) + " " + errorCode - 4 -> errorString = resourceHelper.gs(R.string.pumpshutdown) - 5 -> errorString = resourceHelper.gs(R.string.occlusion) - 7 -> errorString = resourceHelper.gs(R.string.lowbattery) - 8 -> errorString = resourceHelper.gs(R.string.batterydischarged) + 1, 2, 3 -> errorString = rh.gs(R.string.pumperror) + " " + errorCode + 4 -> errorString = rh.gs(R.string.pumpshutdown) + 5 -> errorString = rh.gs(R.string.occlusion) + 7 -> errorString = rh.gs(R.string.lowbattery) + 8 -> errorString = rh.gs(R.string.batterydischarged) } if (errorCode < 8) { // bolus delivering stopped val bolusingEvent = EventOverviewBolusProgress diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusBolus.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusBolus.kt index f866533d08..30ede70314 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusBolus.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusBolus.kt @@ -31,7 +31,7 @@ class MsgInitConnStatusBolus( aapsLogger.debug(LTag.PUMPCOMM, "Bolus increment: " + danaPump.bolusStep) aapsLogger.debug(LTag.PUMPCOMM, "Bolus max: " + danaPump.maxBolus) if (!danaPump.isExtendedBolusEnabled) { - val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, resourceHelper.gs(R.string.danar_enableextendedbolus), Notification.URGENT) + val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, rh.gs(R.string.danar_enableextendedbolus), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)) diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusOption.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusOption.kt index 3fa4ef120c..62cd8368af 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusOption.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusOption.kt @@ -34,7 +34,7 @@ class MsgInitConnStatusOption( failed = true } if (!danaPump.isPasswordOK) { - val notification = Notification(Notification.WRONG_PUMP_PASSWORD, resourceHelper.gs(R.string.wrongpumppassword), Notification.URGENT) + val notification = Notification(Notification.WRONG_PUMP_PASSWORD, rh.gs(R.string.wrongpumppassword), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.WRONG_PUMP_PASSWORD)) diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusTime.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusTime.kt index 8afdbfa611..6d1f38ac8f 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusTime.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgInitConnStatusTime.kt @@ -19,7 +19,7 @@ class MsgInitConnStatusTime( override fun handleMessage(bytes: ByteArray) { if (bytes.size - 10 > 7) { - val notification = Notification(Notification.WRONG_DRIVER, resourceHelper.gs(R.string.pumpdrivercorrected), Notification.NORMAL) + val notification = Notification(Notification.WRONG_DRIVER, rh.gs(R.string.pumpdrivercorrected), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) danaRPlugin.disconnect("Wrong Model") aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected. Switching to Korean DanaR") diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt index b72acacffe..ea0b72134f 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetBasalProfile.kt @@ -27,12 +27,12 @@ class MsgSetBasalProfile( if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result FAILED!!!") - val reportFail = Notification(Notification.PROFILE_SET_FAILED, resourceHelper.gs(R.string.profile_set_failed), Notification.URGENT) + val reportFail = Notification(Notification.PROFILE_SET_FAILED, rh.gs(R.string.profile_set_failed), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result") - val reportOK = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) + val reportOK = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(reportOK)) } } diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetSingleBasalProfile.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetSingleBasalProfile.kt index fe183a648e..16baca550c 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetSingleBasalProfile.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetSingleBasalProfile.kt @@ -25,12 +25,12 @@ class MsgSetSingleBasalProfile( if (result != 1) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result FAILED!!!") - val reportFail = Notification(Notification.PROFILE_SET_FAILED, resourceHelper.gs(R.string.profile_set_failed), Notification.URGENT) + val reportFail = Notification(Notification.PROFILE_SET_FAILED, rh.gs(R.string.profile_set_failed), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set basal profile result: $result") - val reportOK = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) + val reportOK = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(reportOK)) } } diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingMeal.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingMeal.kt index 4b9d391453..10da26bab5 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingMeal.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSettingMeal.kt @@ -31,17 +31,17 @@ class MsgSettingMeal( aapsLogger.debug(LTag.PUMPCOMM, "Block time: $blockTime") aapsLogger.debug(LTag.PUMPCOMM, "Is Config U/d: " + danaPump.isConfigUD) // DanaRKorean is not possible to set to 0.01 but it works when controlled from AAPS - if (danaRKoreanPlugin.isEnabled(PluginType.PUMP)) { + if (danaRKoreanPlugin.isEnabled()) { danaPump.basalStep = 0.01 } if (danaPump.basalStep != 0.01) { - val notification = Notification(Notification.WRONG_BASAL_STEP, resourceHelper.gs(R.string.danar_setbasalstep001), Notification.URGENT) + val notification = Notification(Notification.WRONG_BASAL_STEP, rh.gs(R.string.danar_setbasalstep001), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.WRONG_BASAL_STEP)) } if (danaPump.isConfigUD) { - val notification = Notification(Notification.UD_MODE_ENABLED, resourceHelper.gs(R.string.danar_switchtouhmode), Notification.URGENT) + val notification = Notification(Notification.UD_MODE_ENABLED, rh.gs(R.string.danar_switchtouhmode), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.UD_MODE_ENABLED)) diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java index 43fc51a43b..49d5e030e4 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java @@ -64,7 +64,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { @Inject RxBus rxBus; @Inject SP sp; @Inject Context context; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject DanaPump danaPump; @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; @@ -207,10 +207,10 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { } } } else { - ToastUtils.showToastInUiThread(context.getApplicationContext(), resourceHelper.gs(R.string.nobtadapter)); + ToastUtils.showToastInUiThread(context.getApplicationContext(), rh.gs(R.string.nobtadapter)); } if (mBTDevice == null) { - ToastUtils.showToastInUiThread(context.getApplicationContext(), resourceHelper.gs(R.string.devicenotfound)); + ToastUtils.showToastInUiThread(context.getApplicationContext(), rh.gs(R.string.devicenotfound)); } } @@ -281,7 +281,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 3000) break; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); SystemClock.sleep(Math.min(timeToWholeMinute, 100)); } } @@ -295,7 +295,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { if (pumpState.getTemporaryBasal().getRate() != danaPump.getTempBasalPercent() || Math.abs(pumpState.getTemporaryBasal().getTimestamp() - danaPump.getTempBasalStart()) > 10000 ) { // Close current temp basal - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Different temporary basal found running AAPS: " + (pumpState.getTemporaryBasal() + " DanaPump " + danaPump.temporaryBasalToString())); pumpSync.syncTemporaryBasalWithPumpId( @@ -315,7 +315,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { activePlugin.getActivePump().model(), activePlugin.getActivePump().serialNumber() ); - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Temporary basal should not be running. Sending stop to AAPS"); } @@ -330,7 +330,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { activePlugin.getActivePump().model(), activePlugin.getActivePump().serialNumber() ); - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Temporary basal should be running: DanaPump " + danaPump.temporaryBasalToString()); } @@ -341,7 +341,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { if (pumpState.getExtendedBolus().getRate() != danaPump.getExtendedBolusAbsoluteRate() || Math.abs(pumpState.getExtendedBolus().getTimestamp() - danaPump.getExtendedBolusStart()) > 10000 ) { // Close current extended - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Different extended bolus found running AAPS: " + (pumpState.getExtendedBolus() + " DanaPump " + danaPump.extendedBolusToString())); pumpSync.syncExtendedBolusWithPumpId( @@ -361,13 +361,13 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { activePlugin.getActivePump().model(), activePlugin.getActivePump().serialNumber() ); - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Extended bolus should not be running. Sending stop to AAPS"); } } else { if (danaPump.isExtendedInProgress()) { // Create new - Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, resourceHelper.gs(R.string.unsupported_action_in_pump), Notification.URGENT); + Notification notification = new Notification(Notification.UNSUPPORTED_ACTION_IN_PUMP, rh.gs(R.string.unsupported_action_in_pump), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); aapsLogger.error(LTag.PUMP, "Extended bolus should not be running: DanaPump " + danaPump.extendedBolusToString()); pumpSync.syncExtendedBolusWithPumpId( diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java index 857dbf5b00..e88e137eee 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java @@ -49,7 +49,7 @@ import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileSwitchChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; @@ -67,11 +67,11 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DanaRExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBus rxBus; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject DanaPump danaPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; - @Inject CommandQueueProvider commandQueue; + @Inject CommandQueue commandQueue; @Inject MessageHashTableR messageHashTableR; @Inject ProfileFunction profileFunction; @Inject PumpSync pumpSync; @@ -130,7 +130,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { try { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(injector); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(injector); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(injector); @@ -146,18 +146,18 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))); long now = System.currentTimeMillis(); danaPump.setLastConnection(now); Profile profile = profileFunction.getProfile(); if (profile != null && Math.abs(danaPump.getCurrentBasal() - profile.getBasal()) >= danaRPlugin.getPumpDescription().getBasalStep()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal(injector)); if (!danaRPlugin.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(new EventProfileSwitchChanged()); @@ -165,7 +165,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } if (danaPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !danaRPlugin.isInitialized()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo(injector)); mSerialIOThread.sendMessage(new MsgSettingActiveProfile(injector)); mSerialIOThread.sendMessage(new MsgSettingMeal(injector)); @@ -177,7 +177,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingProfileRatios(injector)); mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll(injector)); mSerialIOThread.sendMessage(new MsgSettingUserOptions(injector)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); if (danaPump.getPumpTime() == 0) { // initial handshake was not successful @@ -203,9 +203,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (danaPump.getDailyTotalUnits() > danaPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMP, "Approaching daily limit: " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits()); if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); + Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT); rxBus.send(new EventNewNotification(reportFail)); - pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); + pumpSync.insertAnnouncement(rh.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber()); lastApproachingDailyLimit = System.currentTimeMillis(); } } @@ -219,11 +219,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean tempBasal(int percent, int durationInHours) { if (!isConnected()) return false; if (danaPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); SystemClock.sleep(500); } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(injector, percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -232,7 +232,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean tempBasalStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(injector)); mSerialIOThread.sendMessage(new MsgStatusTempBasal(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -241,7 +241,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(injector, insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -250,7 +250,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean extendedBolusStop() { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(injector)); mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); @@ -328,7 +328,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { while (System.currentTimeMillis() < expectedEnd) { long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.setStatus(String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); + bolusingEvent.setStatus(String.format(rh.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); rxBus.send(bolusingEvent); SystemClock.sleep(1000); } @@ -381,7 +381,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))); + rxBus.send(new EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates))); Double[] basal = danaPump.buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile(injector, (byte) 0, basal); mSerialIOThread.sendMessage(msgSet); diff --git a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 40e85034d8..edc280d55e 100644 --- a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -22,7 +22,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper @@ -42,7 +42,9 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) } @@ -54,4 +56,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt index 395716449f..99960a997e 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.R -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpSync @@ -25,7 +25,7 @@ class DanaRPluginTest : TestBaseWithProfile() { @Mock lateinit var context: Context @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var sp: SP - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync lateinit var danaPump: DanaPump @@ -39,11 +39,11 @@ class DanaRPluginTest : TestBaseWithProfile() { @Before fun prepareMocks() { `when`(sp.getString(R.string.key_danars_address, "")).thenReturn("") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") + `when`(rh.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) - danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) + danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) } @Test @Throws(Exception::class) diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt index bc18d00573..90e9ca9040 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.ConfigBuilder import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.PumpSync @@ -37,9 +37,9 @@ open class DanaRTestBase : TestBase() { @Mock lateinit var danaRPlugin: DanaRPlugin @Mock lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Mock lateinit var danaRv2Plugin: DanaRv2Plugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var configBuilder: ConfigBuilder - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var pumpSync: PumpSync @@ -54,7 +54,7 @@ open class DanaRTestBase : TestBase() { `when`(activePlugin.activePump).thenReturn(testPumpPlugin) doNothing().`when`(danaRKoreanPlugin).setPluginEnabled(anyObject(), anyBoolean()) doNothing().`when`(danaRPlugin).setPluginEnabled(anyObject(), anyBoolean()) - `when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("") + `when`(rh.gs(ArgumentMatchers.anyInt())).thenReturn("") } val injector = HasAndroidInjector { @@ -67,7 +67,7 @@ open class DanaRTestBase : TestBase() { it.danaRKoreanPlugin = danaRKoreanPlugin it.danaRv2Plugin = danaRv2Plugin it.rxBus = RxBus(aapsSchedulers, aapsLogger) - it.resourceHelper = resourceHelper + it.rh = rh it.activePlugin = activePlugin it.configBuilder = configBuilder it.detailedBolusInfoStorage = detailedBolusInfoStorage diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt index 02c197f625..71d5020152 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.kt @@ -11,7 +11,7 @@ import org.mockito.Mockito.`when` class MsgBolusProgressTest : DanaRTestBase() { @Test fun runTest() { - `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.bolusdelivering), ArgumentMatchers.anyDouble())).thenReturn("Delivering %1\$.2fU") + `when`(rh.gs(ArgumentMatchers.eq(R.string.bolusdelivering), ArgumentMatchers.anyDouble())).thenReturn("Delivering %1\$.2fU") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) danaPump.bolusAmountToBeDelivered = 3.0 val packet = MsgBolusProgress(injector) diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt index 76390f7404..fa8bdfeb8d 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.kt @@ -10,7 +10,7 @@ import org.mockito.Mockito.`when` class MsgBolusStopTest : DanaRTestBase() { @Test fun runTest() { - `when`(resourceHelper.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered") + `when`(rh.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val packet = MsgBolusStop(injector) diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt index b118854394..f0860cbf9b 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danar.R -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpSync @@ -25,7 +25,7 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { @Mock lateinit var context: Context @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var sp: SP - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync lateinit var danaPump: DanaPump @@ -39,11 +39,11 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { @Before fun prepareMocks() { `when`(sp.getString(R.string.key_danars_address, "")).thenReturn("") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") + `when`(rh.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) - danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) + danaRPlugin = DanaRKoreanPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePluginProvider, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) } @Test @Throws(Exception::class) diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt index 674b82943d..c97919e5ec 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.R -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpSync @@ -26,7 +26,7 @@ class DanaRv2PluginTest : TestBaseWithProfile() { @Mock lateinit var context: Context @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var sp: SP - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @Mock lateinit var pumpSync: PumpSync @@ -42,11 +42,11 @@ class DanaRv2PluginTest : TestBaseWithProfile() { @Before fun prepareMocks() { `when`(sp.getString(R.string.key_danars_address, "")).thenReturn("") - `when`(resourceHelper.gs(R.string.pumplimit)).thenReturn("pump limit") - `when`(resourceHelper.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") - `when`(resourceHelper.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") + `when`(rh.gs(R.string.pumplimit)).thenReturn("pump limit") + `when`(rh.gs(R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") + `when`(rh.gs(R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) - danaRv2Plugin = DanaRv2Plugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePluginProvider, sp, commandQueue, danaPump,detailedBolusInfoStorage, temporaryBasalStorage, dateUtil, fabricPrivacy, pumpSync) + danaRv2Plugin = DanaRv2Plugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePluginProvider, sp, commandQueue, danaPump,detailedBolusInfoStorage, temporaryBasalStorage, dateUtil, fabricPrivacy, pumpSync) } @Test diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt index 4e3eb5914a..b74ea7d976 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -53,11 +53,11 @@ class DanaRSPlugin @Inject constructor( private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val constraintChecker: ConstraintChecker, private val profileFunction: ProfileFunction, private val sp: SP, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, private val danaPump: DanaPump, private val pumpSync: PumpSync, private val detailedBolusInfoStorage: DetailedBolusInfoStorage, @@ -74,22 +74,23 @@ class DanaRSPlugin @Inject constructor( .shortName(R.string.danarspump_shortname) .preferencesId(R.xml.pref_danars) .description(R.string.description_pump_dana_rs), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ), Pump, Dana, Constraints { private val disposable = CompositeDisposable() private var danaRSService: DanaRSService? = null private var mDeviceAddress = "" var mDeviceName = "" - override val pumpDescription = PumpDescription(PumpType.DANA_RS) + override val pumpDescription + get() = PumpDescription(danaPump.pumpType()) override fun updatePreferenceSummary(pref: Preference) { super.updatePreferenceSummary(pref) - if (pref.key == resourceHelper.gs(R.string.key_danars_name)) { + if (pref.key == rh.gs(R.string.key_danars_name)) { val value = sp.getStringOrNull(R.string.key_danars_name, null) pref.summary = value - ?: resourceHelper.gs(R.string.not_set_short) + ?: rh.gs(R.string.not_set_short) } } @@ -145,7 +146,7 @@ class DanaRSPlugin @Inject constructor( aapsLogger.debug(LTag.PUMP, "RS connect from: $reason") if (danaRSService != null && mDeviceAddress != "" && mDeviceName != "") { val success = danaRSService?.connect(reason, mDeviceAddress) ?: false - if (!success) ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.ble_not_supported_or_not_paired)) + if (!success) ToastUtils.showToastInUiThread(context, rh.gs(R.string.ble_not_supported_or_not_paired)) } } @@ -183,18 +184,18 @@ class DanaRSPlugin @Inject constructor( // Constraints interface override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - absoluteRate.setIfSmaller(aapsLogger, danaPump.maxBasal, resourceHelper.gs(R.string.limitingbasalratio, danaPump.maxBasal, resourceHelper.gs(R.string.pumplimit)), this) + absoluteRate.setIfSmaller(aapsLogger, danaPump.maxBasal, rh.gs(R.string.limitingbasalratio, danaPump.maxBasal, rh.gs(R.string.pumplimit)), this) return absoluteRate } override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - percentRate.setIfGreater(aapsLogger, 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) - percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this) + percentRate.setIfGreater(aapsLogger, 0, rh.gs(R.string.limitingpercentrate, 0, rh.gs(R.string.itmustbepositivevalue)), this) + percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, rh.gs(R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(R.string.pumplimit)), this) return percentRate } override fun applyBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfSmaller(aapsLogger, danaPump.maxBolus, resourceHelper.gs(R.string.limitingbolus, danaPump.maxBolus, resourceHelper.gs(R.string.pumplimit)), this) + insulin.setIfSmaller(aapsLogger, danaPump.maxBolus, rh.gs(R.string.limitingbolus, danaPump.maxBolus, rh.gs(R.string.pumplimit)), this) return insulin } @@ -216,22 +217,22 @@ class DanaRSPlugin @Inject constructor( val result = PumpEnactResult(injector) if (!isInitialized()) { aapsLogger.error("setNewBasalProfile not initialized") - val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT) + val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, rh.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet) + result.comment = rh.gs(R.string.pumpNotInitializedProfileNotSet) return result } else { rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) } return if (danaRSService?.updateBasalsInPump(profile) != true) { - val notification = Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT) + val notification = Notification(Notification.FAILED_UPDATE_PROFILE, rh.gs(R.string.failedupdatebasalprofile), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile) + result.comment = rh.gs(R.string.failedupdatebasalprofile) result } else { rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) rxBus.send(EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)) - val notification = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) + val notification = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) result.success = true result.enacted = true @@ -296,13 +297,13 @@ class DanaRSPlugin @Inject constructor( if (!result.success) { var error = "" + danaPump.bolusStartErrorCode when (danaPump.bolusStartErrorCode) { - 0x10 -> error = resourceHelper.gs(R.string.maxbolusviolation) - 0x20 -> error = resourceHelper.gs(R.string.commanderror) - 0x40 -> error = resourceHelper.gs(R.string.speederror) - 0x80 -> error = resourceHelper.gs(R.string.insulinlimitviolation) + 0x10 -> error = rh.gs(R.string.maxbolusviolation) + 0x20 -> error = rh.gs(R.string.commanderror) + 0x40 -> error = rh.gs(R.string.speederror) + 0x80 -> error = rh.gs(R.string.insulinlimitviolation) } - result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error) - } else result.comment = resourceHelper.gs(R.string.ok) + result.comment = String.format(rh.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error) + } else result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered) result } else { @@ -310,7 +311,7 @@ class DanaRSPlugin @Inject constructor( result.success = false result.bolusDelivered = 0.0 result.carbsDelivered = 0.0 - result.comment = resourceHelper.gs(R.string.invalidinput) + result.comment = rh.gs(R.string.invalidinput) aapsLogger.error("deliverTreatment: Invalid input") result } @@ -325,9 +326,23 @@ class DanaRSPlugin @Inject constructor( override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { var result = PumpEnactResult(injector) val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() - val doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0 + var doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0 val doLowTemp = absoluteAfterConstrain < baseBasalRate val doHighTemp = absoluteAfterConstrain > baseBasalRate + + var percentRate = 0 + // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. + if (absoluteAfterConstrain >= 0.10) { + percentRate = java.lang.Double.valueOf(absoluteAfterConstrain / baseBasalRate * 100).toInt() + } else { + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Requested basal < 0.10u/h. Setting 0u/h (doLowTemp || doHighTemp)") + } + percentRate = if (percentRate < 100) Round.ceilTo(percentRate.toDouble(), 10.0).toInt() else Round.floorTo(percentRate.toDouble(), 10.0).toInt() + if (percentRate > 500) // Special high temp 500/15min + percentRate = 500 + + if (percentRate == 100) doTempOff = true + if (doTempOff) { // If temp in progress if (danaPump.isTempBasalInProgress) { @@ -343,16 +358,6 @@ class DanaRSPlugin @Inject constructor( return result } if (doLowTemp || doHighTemp) { - var percentRate = 0 - // Any basal less than 0.10u/h will be dumped once per hour, not every 4 minutes. So if it's less than .10u/h, set a zero temp. - if (absoluteAfterConstrain >= 0.10) { - percentRate = java.lang.Double.valueOf(absoluteAfterConstrain / baseBasalRate * 100).toInt() - } else { - aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Requested basal < 0.10u/h. Setting 0u/h (doLowTemp || doHighTemp)") - } - percentRate = if (percentRate < 100) Round.ceilTo(percentRate.toDouble(), 10.0).toInt() else Round.floorTo(percentRate.toDouble(), 10.0).toInt() - if (percentRate > 500) // Special high temp 500/15min - percentRate = 500 // Check if some temp is already in progress if (danaPump.isTempBasalInProgress) { aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: currently running") @@ -401,7 +406,7 @@ class DanaRSPlugin @Inject constructor( result.isTempCancel = false result.enacted = false result.success = false - result.comment = resourceHelper.gs(R.string.invalidinput) + result.comment = rh.gs(R.string.invalidinput) aapsLogger.error("setTempBasalPercent: Invalid input") return result } @@ -410,7 +415,7 @@ class DanaRSPlugin @Inject constructor( result.enacted = false result.success = true result.isTempCancel = false - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.duration = danaPump.tempBasalRemainingMin result.percent = danaPump.tempBasalPercent result.isPercent = true @@ -428,7 +433,7 @@ class DanaRSPlugin @Inject constructor( if (connectionOK && danaPump.isTempBasalInProgress && danaPump.tempBasalPercent == percentAfterConstraint) { result.enacted = true result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.isTempCancel = false result.duration = danaPump.tempBasalRemainingMin result.percent = danaPump.tempBasalPercent @@ -438,7 +443,7 @@ class DanaRSPlugin @Inject constructor( } result.enacted = false result.success = false - result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror) + result.comment = rh.gs(R.string.tempbasaldeliveryerror) aapsLogger.error("setTempBasalPercent: Failed to set temp basal. connectionOK: $connectionOK isTempBasalInProgress: ${danaPump.isTempBasalInProgress} tempBasalPercent: ${danaPump.tempBasalPercent}") return result } @@ -449,7 +454,7 @@ class DanaRSPlugin @Inject constructor( if (connectionOK && danaPump.isTempBasalInProgress && danaPump.tempBasalPercent == percent) { result.enacted = true result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.isTempCancel = false result.duration = danaPump.tempBasalRemainingMin result.percent = danaPump.tempBasalPercent @@ -459,7 +464,7 @@ class DanaRSPlugin @Inject constructor( } result.enacted = false result.success = false - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly) + result.comment = rh.gs(R.string.danar_valuenotsetproperly) aapsLogger.error("setHighTempBasalPercent: Failed to set temp basal") return result } @@ -474,7 +479,7 @@ class DanaRSPlugin @Inject constructor( if (danaPump.isExtendedInProgress && abs(danaPump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) { result.enacted = false result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.duration = danaPump.extendedBolusRemainingMinutes result.absolute = danaPump.extendedBolusAbsoluteRate result.isPercent = false @@ -487,7 +492,7 @@ class DanaRSPlugin @Inject constructor( if (connectionOK && danaPump.isExtendedInProgress && abs(danaPump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) { result.enacted = true result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.isTempCancel = false result.duration = danaPump.extendedBolusRemainingMinutes result.absolute = danaPump.extendedBolusAbsoluteRate @@ -498,7 +503,7 @@ class DanaRSPlugin @Inject constructor( } result.enacted = false result.success = false - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly) + result.comment = rh.gs(R.string.danar_valuenotsetproperly) aapsLogger.error("setExtendedBolus: Failed to extended bolus") return result } @@ -515,7 +520,7 @@ class DanaRSPlugin @Inject constructor( result.success = true result.enacted = false result.isTempCancel = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "cancelRealTempBasal: OK") } return result @@ -530,7 +535,7 @@ class DanaRSPlugin @Inject constructor( } else { result.success = true result.enacted = false - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus: OK") } return result @@ -616,9 +621,10 @@ class DanaRSPlugin @Inject constructor( override fun loadTDDs(): PumpEnactResult = loadHistory(RecordTypes.RECORD_TYPE_DAILY) override fun canHandleDST(): Boolean = false override fun clearPairing() { - sp.remove(resourceHelper.gs(R.string.key_danars_pairingkey) + mDeviceName) - sp.remove(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + mDeviceName) - sp.remove(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + mDeviceName) - sp.remove(resourceHelper.gs(R.string.key_danars_v3_randomsynckey) + mDeviceName) + sp.remove(rh.gs(R.string.key_danars_pairingkey) + mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_randompairingkey) + mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_pairingkey) + mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_randomsynckey) + mDeviceName) + sp.remove(rh.gs(R.string.key_dana_ble5_pairingkey) + mDeviceName) } } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt b/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt index 115bc91523..7c6b791a8d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/activities/EnterPinActivity.kt @@ -39,12 +39,12 @@ class EnterPinActivity : NoSplashAppCompatActivity() { setContentView(binding.root) val p1 = DefaultEditTextValidator(binding.rsV3Pin1, this) - .setTestErrorString(resourceHelper.gs(R.string.error_mustbe12hexadidits), this) - .setCustomRegexp(resourceHelper.gs(R.string.twelvehexanumber), this) + .setTestErrorString(rh.gs(R.string.error_mustbe12hexadidits), this) + .setCustomRegexp(rh.gs(R.string.twelvehexanumber), this) .setTestType(EditTextValidator.TEST_REGEXP, this) val p2 = DefaultEditTextValidator(binding.rsV3Pin2, this) - .setTestErrorString(resourceHelper.gs(R.string.error_mustbe8hexadidits), this) - .setCustomRegexp(resourceHelper.gs(R.string.eighthexanumber), this) + .setTestErrorString(rh.gs(R.string.error_mustbe8hexadidits), this) + .setCustomRegexp(rh.gs(R.string.eighthexanumber), this) .setTestType(EditTextValidator.TEST_REGEXP, this) binding.okcancel.ok.setOnClickListener { @@ -56,7 +56,7 @@ class EnterPinActivity : NoSplashAppCompatActivity() { if (result) { bleComm.finishV3Pairing() finish() - } else OKDialog.show(this, resourceHelper.gs(R.string.error), resourceHelper.gs(R.string.invalidinput)) + } else OKDialog.show(this, rh.gs(R.string.error), rh.gs(R.string.invalidinput)) } } binding.okcancel.cancel.setOnClickListener { finish() } @@ -86,12 +86,12 @@ class EnterPinActivity : NoSplashAppCompatActivity() { for (i in pairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor pairingKey[i] - sp.putString(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(pairingKey, Base64.DEFAULT)) + sp.putString(rh.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(pairingKey, Base64.DEFAULT)) for (i in randomPairingKey.indices) pairingKeyCheckSum = pairingKeyCheckSum xor randomPairingKey[i] - sp.putString(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(randomPairingKey, Base64.DEFAULT)) + sp.putString(rh.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, Base64.encodeToString(randomPairingKey, Base64.DEFAULT)) return checksum[0] == pairingKeyCheckSum } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt index b7def3a050..c048d10ebe 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt @@ -24,7 +24,7 @@ open class DanaRSPacketAPSHistoryEvents( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Inject lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -361,7 +361,7 @@ open class DanaRSPacketAPSHistoryEvents( } } if (datetime > danaPump.lastEventTimeLoaded) danaPump.lastEventTimeLoaded = datetime - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.processinghistory) + ": " + status)) } override val friendlyName: String = "APS_HISTORY_EVENTS" diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt index 287554d871..588f021cc6 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt @@ -18,7 +18,7 @@ class DanaRSPacketBasalGetBasalRate( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -48,7 +48,7 @@ class DanaRSPacketBasalGetBasalRate( aapsLogger.debug(LTag.PUMPCOMM, "Basal " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![danaPump.activeProfile][index]) if (danaPump.basalStep != 0.01) { failed = true - val notification = Notification(Notification.WRONG_BASAL_STEP, resourceHelper.gs(R.string.danar_setbasalstep001), Notification.URGENT) + val notification = Notification(Notification.WRONG_BASAL_STEP, rh.gs(R.string.danar_setbasalstep001), Notification.URGENT) rxBus.send(EventNewNotification(notification)) } else { rxBus.send(EventDismissNotification(Notification.WRONG_BASAL_STEP)) diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt index ecf7f60618..5fe7421049 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt @@ -17,7 +17,7 @@ class DanaRSPacketBolusGetBolusOption( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -84,7 +84,7 @@ class DanaRSPacketBolusGetBolusOption( dataSize = 1 val missedBolus04EndMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)) if (!danaPump.isExtendedBolusEnabled) { - val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, resourceHelper.gs(R.string.danar_enableextendedbolus), Notification.URGENT) + val notification = Notification(Notification.EXTENDED_BOLUS_DISABLED, rh.gs(R.string.danar_enableextendedbolus), Notification.URGENT) rxBus.send(EventNewNotification(notification)) failed = true } else { diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt index 6b138a0687..8cd865d013 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt @@ -15,7 +15,7 @@ open class DanaRSPacketBolusSetStepBolusStop( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -37,10 +37,10 @@ open class DanaRSPacketBolusSetStepBolusStop( if (!danaPump.bolusStopForced) { // delivery ended without user intervention danaPump.bolusingTreatment?.insulin = danaPump.bolusAmountToBeDelivered - bolusingEvent.status = resourceHelper.gs(R.string.overview_bolusprogress_delivered) + bolusingEvent.status = rh.gs(R.string.overview_bolusprogress_delivered) bolusingEvent.percent = 100 } else { - bolusingEvent.status = resourceHelper.gs(R.string.overview_bolusprogress_stoped) + bolusingEvent.status = rh.gs(R.string.overview_bolusprogress_stoped) } rxBus.send(bolusingEvent) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt index 7b4bfbc920..7761d2bddb 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt @@ -16,7 +16,7 @@ class DanaRSPacketGeneralGetPumpCheck( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -43,7 +43,7 @@ class DanaRSPacketGeneralGetPumpCheck( aapsLogger.debug(LTag.PUMPCOMM, "Protocol: " + String.format("%02X ", danaPump.protocol)) aapsLogger.debug(LTag.PUMPCOMM, "Product Code: " + String.format("%02X ", danaPump.productCode)) if (danaPump.productCode < 2) { - rxBus.send(EventNewNotification(Notification(Notification.UNSUPPORTED_FIRMWARE, resourceHelper.gs(R.string.unsupportedfirmware), Notification.URGENT))) + rxBus.send(EventNewNotification(Notification(Notification.UNSUPPORTED_FIRMWARE, rh.gs(R.string.unsupportedfirmware), Notification.URGENT))) } } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt index 64eee73f34..40e630c545 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt @@ -9,7 +9,6 @@ import info.nightscout.androidaps.events.EventDanaRSyncStatus import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.T import org.joda.time.DateTime import java.util.* @@ -77,7 +76,7 @@ abstract class DanaRSPacketHistory( dataIndex += dataSize dataSize = 2 totalCount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - aapsLogger.debug(LTag.PUMPCOMM, "History end. Code: " + error + " Success: " + (error == 0x00) + " Toatal count: " + totalCount) + aapsLogger.debug(LTag.PUMPCOMM, "History end. Code: " + error + " Success: " + (error == 0x00) + " Total count: " + totalCount) } else { val recordCode = byteArrayToInt(getBytes(data, DATA_START, 1)) val historyYear = byteArrayToInt(getBytes(data, DATA_START + 1, 1)) @@ -233,7 +232,7 @@ abstract class DanaRSPacketHistory( basalAmount = danaRHistoryRecord.dailyBasal, totalAmount = 0.0, pumpId = null, - pumpType = PumpType.DANA_RS, + pumpType = danaPump.pumpType(), danaPump.serialNumber ) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt index 7d619dd0fd..d3b643bb99 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt @@ -17,7 +17,7 @@ class DanaRSPacketNotifyAlarm( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var pumpSync: PumpSync @Inject lateinit var danaPump: DanaPump @@ -32,31 +32,31 @@ class DanaRSPacketNotifyAlarm( var errorString = "" when (alarmCode) { 0x01 -> // Battery 0% Alarm - errorString = resourceHelper.gs(R.string.batterydischarged) + errorString = rh.gs(R.string.batterydischarged) 0x02 -> // Pump Error - errorString = resourceHelper.gs(R.string.pumperror) + " " + alarmCode + errorString = rh.gs(R.string.pumperror) + " " + alarmCode 0x03 -> // Occlusion - errorString = resourceHelper.gs(R.string.occlusion) + errorString = rh.gs(R.string.occlusion) 0x04 -> // LOW BATTERY - errorString = resourceHelper.gs(R.string.pumpshutdown) + errorString = rh.gs(R.string.pumpshutdown) 0x05 -> // Shutdown - errorString = resourceHelper.gs(R.string.lowbattery) + errorString = rh.gs(R.string.lowbattery) 0x06 -> // Basal Compare - errorString = resourceHelper.gs(R.string.basalcompare) + errorString = rh.gs(R.string.basalcompare) 0x07, 0xFF -> // Blood sugar measurement alert - errorString = resourceHelper.gs(R.string.bloodsugarmeasurementalert) + errorString = rh.gs(R.string.bloodsugarmeasurementalert) 0x08, 0xFE -> // Remaining insulin level - errorString = resourceHelper.gs(R.string.remaininsulinalert) + errorString = rh.gs(R.string.remaininsulinalert) 0x09 -> // Empty Reservoir - errorString = resourceHelper.gs(R.string.emptyreservoir) + errorString = rh.gs(R.string.emptyreservoir) 0x0A -> // Check shaft - errorString = resourceHelper.gs(R.string.checkshaft) + errorString = rh.gs(R.string.checkshaft) 0x0B -> // Basal MAX - errorString = resourceHelper.gs(R.string.basalmax) + errorString = rh.gs(R.string.basalmax) 0x0C -> // Daily MAX - errorString = resourceHelper.gs(R.string.dailymax) + errorString = rh.gs(R.string.dailymax) 0xFD -> // Blood sugar check miss alarm - errorString = resourceHelper.gs(R.string.missedbolus) + errorString = rh.gs(R.string.missedbolus) } // No error no need to upload anything if (errorString == "") { diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt index 31be03c243..1a69a999a4 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt @@ -16,7 +16,7 @@ class DanaRSPacketNotifyDeliveryComplete( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -29,7 +29,7 @@ class DanaRSPacketNotifyDeliveryComplete( val deliveredInsulin = byteArrayToInt(getBytes(data, DATA_START, 2)) / 100.0 danaPump.bolusingTreatment?.insulin = deliveredInsulin val bolusingEvent = EventOverviewBolusProgress - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, deliveredInsulin) + bolusingEvent.status = rh.gs(R.string.bolusdelivering, deliveredInsulin) bolusingEvent.t = danaPump.bolusingTreatment bolusingEvent.percent = min((deliveredInsulin / danaPump.bolusAmountToBeDelivered * 100).toInt(), 100) danaPump.bolusDone = true diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt index 1651d5db49..63adc7d654 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt @@ -16,7 +16,7 @@ class DanaRSPacketNotifyDeliveryRateDisplay( ) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var danaPump: DanaPump init { @@ -29,7 +29,7 @@ class DanaRSPacketNotifyDeliveryRateDisplay( danaPump.bolusProgressLastTimeStamp = System.currentTimeMillis() danaPump.bolusingTreatment?.insulin = deliveredInsulin val bolusingEvent = EventOverviewBolusProgress - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, deliveredInsulin) + bolusingEvent.status = rh.gs(R.string.bolusdelivering, deliveredInsulin) bolusingEvent.t = danaPump.bolusingTreatment bolusingEvent.percent = min((deliveredInsulin / danaPump.bolusAmountToBeDelivered * 100).toInt(), 100) failed = bolusingEvent.percent < 100 diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java index e2fe892184..0a87dfa8ea 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java +++ b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java @@ -29,7 +29,7 @@ import io.reactivex.disposables.CompositeDisposable; public class PairingProgressDialog extends DaggerDialogFragment { @Inject AapsSchedulers aapsSchedulers; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject RxBus rxBus; @Inject FabricPrivacy fabricPrivacy; @@ -146,7 +146,7 @@ public class PairingProgressDialog extends DaggerDialogFragment { if (binding != null) { binding.danarsPairingprogressProgressbar.setMax(100); binding.danarsPairingprogressProgressbar.setProgress(0); - binding.danarsPairingprogressStatus.setText(resourceHelper.gs(R.string.danars_waitingforpairing)); + binding.danarsPairingprogressStatus.setText(rh.gs(R.string.danars_waitingforpairing)); binding.ok.setVisibility(View.GONE); binding.ok.setOnClickListener(v -> dismiss()); } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index 055caea55a..26b1627fd1 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -41,7 +41,7 @@ import javax.inject.Singleton class BLEComm @Inject internal constructor( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val context: Context, private val rxBus: RxBus, private val sp: SP, @@ -149,15 +149,7 @@ class BLEComm @Inject internal constructor( if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) { ToastUtils.showToastInUiThread(context, R.string.invalidpairing) danaRSPlugin.changePump() - sp.getStringOrNull(R.string.key_danars_address, null)?.let { address -> - bluetoothAdapter?.getRemoteDevice(address)?.let { device -> - try { - device::class.java.getMethod("removeBond").invoke(device) - } catch (e: Exception) { - aapsLogger.error("Removing bond has been failed. ${e.message}") - } - } - } + removeBond() } else if (lastClearRequest == 0L) { aapsLogger.error("Clearing pairing keys postponed") sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now()) @@ -169,9 +161,9 @@ class BLEComm @Inject internal constructor( val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0) if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) { aapsLogger.error("Clearing pairing keys !!!") - sp.remove(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName) - sp.remove(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName) - sp.remove(resourceHelper.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName) + sp.remove(rh.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName) ToastUtils.showToastInUiThread(context, R.string.invalidpairing) danaRSPlugin.changePump() } else if (lastClearRequest == 0L) { @@ -196,6 +188,18 @@ class BLEComm @Inject internal constructor( SystemClock.sleep(2000) } + private fun removeBond() { + sp.getStringOrNull(R.string.key_danars_address, null)?.let { address -> + bluetoothAdapter?.getRemoteDevice(address)?.let { device -> + try { + device::class.java.getMethod("removeBond").invoke(device) + } catch (e: Exception) { + aapsLogger.error("Removing bond has been failed. ${e.message}") + } + } + } + } + @Synchronized fun close() { /* if (!encryptedDataRead && !encryptedCommandSent) { @@ -506,7 +510,7 @@ class BLEComm @Inject internal constructor( private fun sendConnect() { val deviceName = connectDeviceName if (deviceName == null || deviceName == "") { - val n = Notification(Notification.DEVICE_NOT_PAIRED, resourceHelper.gs(R.string.pairfirst), Notification.URGENT) + val n = Notification(Notification.DEVICE_NOT_PAIRED, rh.gs(R.string.pairfirst), Notification.URGENT) rxBus.send(EventNewNotification(n)) return } @@ -523,7 +527,7 @@ class BLEComm @Inject internal constructor( encryption = EncryptionType.ENCRYPTION_DEFAULT danaPump.ignoreUserPassword = false // Grab pairing key from preferences if exists - val pairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, "") + val pairingKey = sp.getString(rh.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, "") aapsLogger.debug(LTag.PUMPBTCOMM, "Using stored pairing key: $pairingKey") if (pairingKey.isNotEmpty()) { sendPasskeyCheck(pairingKey) @@ -539,7 +543,7 @@ class BLEComm @Inject internal constructor( danaPump.hwModel = decryptedBuffer[5].toInt() danaPump.protocol = decryptedBuffer[7].toInt() // grab randomSyncKey - sp.putString(resourceHelper.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName, String.format("%02x", decryptedBuffer[decryptedBuffer.size - 1])) + sp.putString(rh.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName, String.format("%02x", decryptedBuffer[decryptedBuffer.size - 1])) if (danaPump.hwModel == 0x05) { aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) @@ -558,9 +562,17 @@ class BLEComm @Inject internal constructor( danaPump.hwModel = decryptedBuffer[5].toInt() danaPump.protocol = decryptedBuffer[7].toInt() val pairingKey = DanaRSPacket.asciiStringFromBuff(decryptedBuffer, 8, 6) // used while bonding + if (decryptedBuffer[8] != 0.toByte()) + sp.putString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, pairingKey) + + val storedPairingKey = sp.getString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, "") + if (storedPairingKey.isNullOrBlank()) { + removeBond() + disconnect("Non existing pairing key") + } if (danaPump.hwModel == 0x09) { - bleEncryption.setBle5Key(pairingKey.encodeToByteArray()) + bleEncryption.setBle5Key(storedPairingKey.encodeToByteArray()) aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK BLE5 (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) // Dana-i BLE5 Pump sendBLE5PairingInformation() @@ -569,22 +581,22 @@ class BLEComm @Inject internal constructor( } else if (decryptedBuffer.size == 6 && decryptedBuffer[2] == 'P'.code.toByte() && decryptedBuffer[3] == 'U'.code.toByte() && decryptedBuffer[4] == 'M'.code.toByte() && decryptedBuffer[5] == 'P'.code.toByte()) { aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() - rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.pumperror))) - pumpSync.insertAnnouncement(resourceHelper.gs(R.string.pumperror), null, danaPump.pumpType(), danaPump.serialNumber) - val n = Notification(Notification.PUMP_ERROR, resourceHelper.gs(R.string.pumperror), Notification.URGENT) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, rh.gs(R.string.pumperror))) + pumpSync.insertAnnouncement(rh.gs(R.string.pumperror), null, danaPump.pumpType(), danaPump.serialNumber) + val n = Notification(Notification.PUMP_ERROR, rh.gs(R.string.pumperror), Notification.URGENT) rxBus.send(EventNewNotification(n)) // response BUSY: error status } else if (decryptedBuffer.size == 6 && decryptedBuffer[2] == 'B'.code.toByte() && decryptedBuffer[3] == 'U'.code.toByte() && decryptedBuffer[4] == 'S'.code.toByte() && decryptedBuffer[5] == 'Y'.code.toByte()) { aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() - rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.pumpbusy))) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, rh.gs(R.string.pumpbusy))) } else { // ERROR in response, wrong serial number aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() - rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.connectionerror))) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, rh.gs(R.string.connectionerror))) danaRSPlugin.clearPairing() - val n = Notification(Notification.WRONG_SERIAL_NUMBER, resourceHelper.gs(R.string.password_cleared), Notification.URGENT) + val n = Notification(Notification.WRONG_SERIAL_NUMBER, rh.gs(R.string.password_cleared), Notification.URGENT) rxBus.send(EventNewNotification(n)) } } @@ -609,13 +621,13 @@ class BLEComm @Inject internal constructor( // 2nd packet v3 // 0x00 Start encryption, 0x01 Request pairing private fun sendV3PairingInformation() { - val randomPairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") - val pairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") + val randomPairingKey = sp.getString(rh.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") + val pairingKey = sp.getString(rh.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { val tPairingKey = Base64.decode(pairingKey, Base64.DEFAULT) val tRandomPairingKey = Base64.decode(randomPairingKey, Base64.DEFAULT) var tRandomSyncKey: Byte = 0 - val randomSyncKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName, "") + val randomSyncKey = sp.getString(rh.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName, "") if (randomSyncKey.isNotEmpty()) { tRandomSyncKey = randomSyncKey.toInt(16).toByte() } @@ -651,8 +663,8 @@ class BLEComm @Inject internal constructor( } else if (encryption == EncryptionType.ENCRYPTION_RSv3) { // decryptedBuffer[2] : 0x00 OK 0x01 Error, No pairing if (decryptedBuffer[2] == 0x00.toByte()) { - val randomPairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") - val pairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") + val randomPairingKey = sp.getString(rh.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") + val pairingKey = sp.getString(rh.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { // expecting successful connect isConnected = true @@ -675,7 +687,7 @@ class BLEComm @Inject internal constructor( aapsLogger.debug(LTag.PUMPBTCOMM, "Pump user password: " + danaPump.rsPassword) if (!danaPump.isRSPasswordOK) { aapsLogger.error(LTag.PUMPBTCOMM, "Wrong pump password") - rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_PASSWORD, resourceHelper.gs(R.string.wrongpumppassword), Notification.URGENT))) + rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_PASSWORD, rh.gs(R.string.wrongpumppassword), Notification.URGENT))) disconnect("WrongPassword") SystemClock.sleep(T.mins(1).msecs()) } else { @@ -707,8 +719,8 @@ class BLEComm @Inject internal constructor( // 3rd packet v3 : only after entering PIN codes fun finishV3Pairing() { - val randomPairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") - val pairingKey = sp.getString(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") + val randomPairingKey = sp.getString(rh.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName, "") + val pairingKey = sp.getString(rh.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName, "") if (randomPairingKey.isNotEmpty() && pairingKey.isNotEmpty()) { val tPairingKey = Base64.decode(pairingKey, Base64.DEFAULT) val tRandomPairingKey = Base64.decode(randomPairingKey, Base64.DEFAULT) @@ -734,7 +746,7 @@ class BLEComm @Inject internal constructor( sendTimeInfo() val pairingKey = byteArrayOf(decryptedBuffer[2], decryptedBuffer[3]) // store pairing key to preferences - sp.putString(resourceHelper.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, DanaRSPacket.bytesToHex(pairingKey)) + sp.putString(rh.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, DanaRSPacket.bytesToHex(pairingKey)) aapsLogger.debug(LTag.PUMPBTCOMM, "Got pairing key: " + DanaRSPacket.bytesToHex(pairingKey)) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index 0092645752..08f8c0d54c 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.PumpSync @@ -59,9 +59,9 @@ class DanaRSService : DaggerService() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var context: Context @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var danaPump: DanaPump @@ -116,8 +116,9 @@ class DanaRSService : DaggerService() { fun readPumpStatus() { try { val pump = activePlugin.activePump - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))) sendMessage(DanaRSPacketEtcKeepConnection(injector)) // test encryption for v3 & BLE + if (!bleComm.isConnected) return sendMessage(DanaRSPacketGeneralGetShippingInformation(injector)) // serial no sendMessage(DanaRSPacketGeneralGetPumpCheck(injector)) // firmware sendMessage(DanaRSPacketBasalGetProfileNumber(injector)) @@ -127,19 +128,19 @@ class DanaRSService : DaggerService() { if (danaPump.profile24) sendMessage(DanaRSPacketBolusGet24CIRCFArray(injector)) else sendMessage(DanaRSPacketBolusGetCIRCFArray(injector)) sendMessage(DanaRSPacketOptionGetUserOption(injector)) // Getting user options - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus))) sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector)) - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))) sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus, bolusStep, maxBolus danaPump.lastConnection = System.currentTimeMillis() val profile = profileFunction.getProfile() if (profile != null && abs(danaPump.currentBasal - profile.getBasal()) >= pump.pumpDescription.basalStep) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))) if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(EventProfileSwitchChanged()) } } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumptime))) if (danaPump.usingUTC) sendMessage(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector)) else sendMessage(DanaRSPacketOptionGetPumpTime(injector)) var timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L @@ -161,7 +162,7 @@ class DanaRSService : DaggerService() { if (abs(timeDiff) > 60 * 60 * 1.5) { aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds - large difference") //If time-diff is very large, warn user until we can synchronize history readings properly - ErrorHelperActivity.runAlarm(context, resourceHelper.gs(R.string.largetimediff), resourceHelper.gs(R.string.largetimedifftitle), R.raw.error) + ErrorHelperActivity.runAlarm(context, rh.gs(R.string.largetimediff), rh.gs(R.string.largetimedifftitle), R.raw.error) //de-initialize pump danaPump.reset() @@ -190,7 +191,7 @@ class DanaRSService : DaggerService() { aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") } } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.reading_pump_history))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.reading_pump_history))) loadEvents() // RS doesn't provide exact timestamp = rely on history val eb = pumpSync.expectedPumpState().extendedBolus @@ -202,10 +203,10 @@ class DanaRSService : DaggerService() { if (danaPump.dailyTotalUnits > danaPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits) if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT) + val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) pumpSync.insertAnnouncement( - resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U", + rh.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U", null, danaPump.pumpType(), danaPump.serialNumber @@ -240,7 +241,7 @@ class DanaRSService : DaggerService() { } danaPump.lastHistoryFetched = if (danaPump.lastEventTimeLoaded != 0L) danaPump.lastEventTimeLoaded - T.mins(1).msecs() else 0 aapsLogger.debug(LTag.PUMPCOMM, "Events loaded") - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus))) sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector)) danaPump.lastConnection = System.currentTimeMillis() return PumpEnactResult(injector).success(msg.success()) @@ -255,7 +256,7 @@ class DanaRSService : DaggerService() { fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean { if (!isConnected) return false if (BolusProgressDialog.stopPressed) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus))) val preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0) danaPump.bolusDone = false danaPump.bolusingTreatment = t @@ -303,7 +304,7 @@ class DanaRSService : DaggerService() { val expectedEnd = bolusStart + bolusDurationInMSec + 2000 while (System.currentTimeMillis() < expectedEnd) { val waitTime = expectedEnd - System.currentTimeMillis() - bolusingEvent.status = String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000) + bolusingEvent.status = String.format(rh.gs(R.string.waitingforestimatedbolusend), waitTime / 1000) rxBus.send(bolusingEvent) SystemClock.sleep(1000) } @@ -311,10 +312,10 @@ class DanaRSService : DaggerService() { commandQueue.loadEvents(object : Callback() { override fun run() { // reread bolus status - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))) sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus bolusingEvent.percent = 100 - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.disconnecting))) } }) return !start.failed @@ -338,11 +339,11 @@ class DanaRSService : DaggerService() { fun tempBasal(percent: Int, durationInHours: Int): Boolean { if (!isConnected) return false if (danaPump.isTempBasalInProgress) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))) val msgTBR = DanaRSPacketBasalSetTemporaryBasal(injector, percent, durationInHours) sendMessage(msgTBR) SystemClock.sleep(200) @@ -355,11 +356,11 @@ class DanaRSService : DaggerService() { fun highTempBasal(percent: Int): Boolean { if (danaPump.isTempBasalInProgress) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))) val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent) sendMessage(msgTBR) loadEvents() @@ -375,11 +376,11 @@ class DanaRSService : DaggerService() { return false } if (danaPump.isTempBasalInProgress) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))) val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent) sendMessage(msgTBR) loadEvents() @@ -392,7 +393,7 @@ class DanaRSService : DaggerService() { fun tempBasalStop(): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) val msgCancel = DanaRSPacketBasalSetCancelTemporaryBasal(injector) sendMessage(msgCancel) loadEvents() @@ -404,7 +405,7 @@ class DanaRSService : DaggerService() { fun extendedBolus(insulin: Double, durationInHalfHours: Int): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus))) val msgExtended = DanaRSPacketBolusSetExtendedBolus(injector, insulin, durationInHalfHours) sendMessage(msgExtended) SystemClock.sleep(200) @@ -417,7 +418,7 @@ class DanaRSService : DaggerService() { fun extendedBolusStop(): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus))) val msgStop = DanaRSPacketBolusSetExtendedBolusCancel(injector) sendMessage(msgStop) loadEvents() @@ -429,7 +430,7 @@ class DanaRSService : DaggerService() { fun updateBasalsInPump(profile: Profile): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates))) val basal = danaPump.buildDanaRProfileRecord(profile) val msgSet = DanaRSPacketBasalSetProfileBasalRate(injector, 0, basal) sendMessage(msgSet) @@ -492,7 +493,7 @@ class DanaRSService : DaggerService() { val time = dateUtil.now() val timeToWholeMinute = 60000 - time % 60000 if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt()))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt()))) SystemClock.sleep(min(timeToWholeMinute, 100)) } } diff --git a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 40e85034d8..edc280d55e 100644 --- a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -22,7 +22,7 @@ import org.mockito.Mock open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper @@ -42,7 +42,9 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { - validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + validProfileJSON = "{\"dia\":\"5\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) } @@ -54,4 +56,4 @@ open class TestBaseWithProfile : TestBase() { json.put("store", store) return ProfileStore(profileInjector, json, dateUtil) } -} \ No newline at end of file +} diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSPluginTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSPluginTest.kt index 45fcde6f93..550484e1e7 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSPluginTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.danars import android.content.Context import dagger.android.AndroidInjector import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PumpSync @@ -22,7 +22,7 @@ class DanaRSPluginTest : DanaRSTestBase() { @Mock lateinit var context: Context @Mock lateinit var constraintChecker: ConstraintChecker - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @Mock lateinit var pumpSync: PumpSync @@ -56,9 +56,9 @@ class DanaRSPluginTest : DanaRSTestBase() { @Before fun prepareMocks() { Mockito.`when`(sp.getString(R.string.key_danars_address, "")).thenReturn("") - Mockito.`when`(resourceHelper.gs(eq(R.string.limitingbasalratio), anyObject(), anyObject())).thenReturn("limitingbasalratio") - Mockito.`when`(resourceHelper.gs(eq(R.string.limitingpercentrate), anyObject(), anyObject())).thenReturn("limitingpercentrate") + Mockito.`when`(rh.gs(eq(R.string.limitingbasalratio), anyObject(), anyObject())).thenReturn("limitingbasalratio") + Mockito.`when`(rh.gs(eq(R.string.limitingpercentrate), anyObject(), anyObject())).thenReturn("limitingpercentrate") - danaRSPlugin = DanaRSPlugin({ AndroidInjector { } }, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin({ AndroidInjector { } }, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt index b7a6c6a25d..9091aaacd6 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt @@ -21,7 +21,7 @@ open class DanaRSTestBase : TestBaseWithProfile() { @Before fun prepare() { - Mockito.`when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("AnyString") + Mockito.`when`(rh.gs(ArgumentMatchers.anyInt())).thenReturn("AnyString") } fun createArray(length: Int, fillWith: Byte): ByteArray { diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt index 034df8113e..1728dd08ef 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt @@ -21,14 +21,14 @@ class DanaRSPacketNotifyDeliveryCompleteTest : DanaRSTestBase() { if (it is DanaRSPacketNotifyDeliveryComplete) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } } @Test fun runTest() { - `when`(resourceHelper.gs(anyInt(), anyDouble())).thenReturn("SomeString") + `when`(rh.gs(anyInt(), anyDouble())).thenReturn("SomeString") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val packet = DanaRSPacketNotifyDeliveryComplete(packetInjector) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt index de5f2d7588..4c0b6c4dd0 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt @@ -29,7 +29,7 @@ class DanaRsPacketApsHistoryEventsTest : DanaRSTestBase() { } if (it is DanaRSPacketAPSHistoryEvents) { it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.pumpSync = pumpSync it.danaPump = danaPump it.detailedBolusInfoStorage = detailedBolusInfoStorage diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt index f7865fce36..5d59c274bc 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketBasalGetBasalRateTest : DanaRSTestBase() { if (it is DanaRSPacketBasalGetBasalRate) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt index 76dec68c50..04a8a69a10 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketBolusGetBolusOptionTest : DanaRSTestBase() { if (it is DanaRSPacketBolusGetBolusOption) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt index c1a9ea46b5..ab385d84f3 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt @@ -5,7 +5,7 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.danars.DanaRSTestBase -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker @@ -20,7 +20,7 @@ import org.mockito.Mockito class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { @Mock lateinit var constraintChecker: ConstraintChecker - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var context: Context @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -54,7 +54,7 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin({ AndroidInjector { } }, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin({ AndroidInjector { } }, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt index 9ef433e555..8a980fb52e 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt @@ -20,14 +20,14 @@ class DanaRsPacketBolusSetStepBolusStopTest : DanaRSTestBase() { if (it is DanaRSPacketBolusSetStepBolusStop) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } } @Test fun runTest() { - `when`(resourceHelper.gs(Mockito.anyInt())).thenReturn("SomeString") + `when`(rh.gs(Mockito.anyInt())).thenReturn("SomeString") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) val testPacket = DanaRSPacketBolusSetStepBolusStop(packetInjector) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt index a3ba829cb9..df3b05c394 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketGeneralGetPumpCheckTest : DanaRSTestBase() { if (it is DanaRSPacketGeneralGetPumpCheck) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt index 371cbb6811..fabe947464 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt @@ -17,7 +17,7 @@ class DanaRsPacketNotifyAlarmTest : DanaRSTestBase() { if (it is DanaRSPacketNotifyAlarm) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.pumpSync = pumpSync it.danaPump = danaPump } diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index 2bb10b963c..de504cf613 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -6,7 +6,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.danars.DanaRSTestBase import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress @@ -23,7 +23,7 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var constraintChecker: ConstraintChecker - @Mock lateinit var commandQueue: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var context: Context @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -36,14 +36,14 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { if (it is DanaRSPacketNotifyDeliveryRateDisplay) { it.aapsLogger = aapsLogger it.rxBus = rxBus - it.resourceHelper = resourceHelper + it.rh = rh it.danaPump = danaPump } } } @Test fun runTest() { - `when`(resourceHelper.gs(ArgumentMatchers.anyInt(), anyObject())).thenReturn("SomeString") + `when`(rh.gs(ArgumentMatchers.anyInt(), anyObject())).thenReturn("SomeString") // val packet = DanaRS_Packet_Notify_Delivery_Rate_Display(1.0, Treatment(treatmentInjector)) val packet = DanaRSPacketNotifyDeliveryRateDisplay(packetInjector) // test params @@ -60,7 +60,7 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { @Before fun mock() { - danaRSPlugin = DanaRSPlugin(packetInjector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) + danaRSPlugin = DanaRSPlugin(packetInjector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) } } \ No newline at end of file diff --git a/database/build.gradle b/database/build.gradle index af81fc73ac..6f6eddd1b2 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -25,7 +25,7 @@ dependencies { implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version" implementation("io.reactivex.rxjava2:rxkotlin:$rxkotlin_version") - implementation "com.google.code.gson:gson:2.8.8" + implementation "com.google.code.gson:gson:2.8.9" api "androidx.room:room-runtime:$room_version" kapt "androidx.room:room-compiler:$room_version" diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt index f32c0aac0f..caff9784bb 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt @@ -685,6 +685,10 @@ import kotlin.math.roundToInt .subscribeOn(Schedulers.io()) .toWrappedSingle() + fun getTemporaryBasalsDataActiveBetweenTimeAndTime(from: Long, to: Long): Single> = + database.temporaryBasalDao.getTemporaryBasalActiveBetweenTimeAndTime(from, to) + .subscribeOn(Schedulers.io()) + fun getTemporaryBasalsDataFromTime(timestamp: Long, ascending: Boolean): Single> = database.temporaryBasalDao.getTemporaryBasalDataFromTime(timestamp) .map { if (!ascending) it.reversed() else it } diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt index 94f717a420..b4aac3ba54 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/TemporaryBasalDao.kt @@ -47,6 +47,9 @@ internal interface TemporaryBasalDao : TraceableDao { @Query("SELECT * FROM $TABLE_TEMPORARY_BASALS WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1") fun getTemporaryBasalActiveAt(timestamp: Long): Maybe + @Query("SELECT * FROM $TABLE_TEMPORARY_BASALS WHERE timestamp <= :to AND (timestamp + duration) > :from AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC") + fun getTemporaryBasalActiveBetweenTimeAndTime(from: Long, to: Long): Single> + @Query("SELECT * FROM $TABLE_TEMPORARY_BASALS WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC") fun getTemporaryBasalDataFromTime(timestamp: Long): Single> diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt index a0981c1b56..889f365ec4 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/UserEntry.kt @@ -64,23 +64,23 @@ data class UserEntry( CALIBRATION (ColorGroup.Careportal), PRIME_BOLUS (ColorGroup.Pump), TREATMENT (ColorGroup.InsulinTreatment), - CAREPORTAL_NS_REFRESH (ColorGroup.Aaps), - PROFILE_SWITCH_NS_REFRESH (ColorGroup.Aaps), - TREATMENTS_NS_REFRESH (ColorGroup.Aaps), - TT_NS_REFRESH (ColorGroup.Aaps), + CAREPORTAL_NS_REFRESH (ColorGroup.Careportal), + PROFILE_SWITCH_NS_REFRESH (ColorGroup.Profile), + TREATMENTS_NS_REFRESH (ColorGroup.InsulinTreatment), + TT_NS_REFRESH (ColorGroup.TT), AUTOMATION_REMOVED (ColorGroup.Aaps), BG_REMOVED (ColorGroup.Aaps), - CAREPORTAL_REMOVED (ColorGroup.Aaps), - EXTENDED_BOLUS_REMOVED (ColorGroup.Aaps), + CAREPORTAL_REMOVED (ColorGroup.Careportal), + EXTENDED_BOLUS_REMOVED (ColorGroup.InsulinTreatment), FOOD_REMOVED (ColorGroup.CarbTreatment), PROFILE_REMOVED (ColorGroup.Profile), - PROFILE_SWITCH_REMOVED (ColorGroup.Aaps), + PROFILE_SWITCH_REMOVED (ColorGroup.Profile), RESTART_EVENTS_REMOVED (ColorGroup.Aaps), - TREATMENT_REMOVED (ColorGroup.Aaps), - BOLUS_REMOVED (ColorGroup.Aaps), - CARBS_REMOVED (ColorGroup.Aaps), - TEMP_BASAL_REMOVED (ColorGroup.Aaps), - TT_REMOVED (ColorGroup.Aaps), + TREATMENT_REMOVED (ColorGroup.InsulinTreatment), + BOLUS_REMOVED (ColorGroup.InsulinTreatment), + CARBS_REMOVED (ColorGroup.CarbTreatment), + TEMP_BASAL_REMOVED (ColorGroup.BasalTreatment), + TT_REMOVED (ColorGroup.TT), NS_PAUSED (ColorGroup.Aaps), NS_RESUME (ColorGroup.Aaps), NS_QUEUE_CLEARED (ColorGroup.Aaps), diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt index b92ae817c1..84ba98e25b 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Pump import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -41,10 +41,10 @@ class DiaconnG8Fragment : DaggerFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var diaconnG8Pump: DiaconnG8Pump - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP @Inject lateinit var warnColors: WarnColors @Inject lateinit var dateUtil: DateUtil @@ -126,8 +126,8 @@ class DiaconnG8Fragment : DaggerFragment() { binding.btconnection.text = "{fa-bluetooth-b}" else -> {} } - if (it.getStatus(resourceHelper) != "") { - binding.diaconnG8Pumpstatus.text = it.getStatus(resourceHelper) + if (it.getStatus(rh) != "") { + binding.diaconnG8Pumpstatus.text = it.getStatus(rh) binding.diaconnG8Pumpstatuslayout.visibility = View.VISIBLE } else { binding.diaconnG8Pumpstatuslayout.visibility = View.GONE @@ -158,7 +158,7 @@ class DiaconnG8Fragment : DaggerFragment() { if (pump.lastConnection != 0L) { val agoMsec = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt() - binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")" + binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(R.string.minago, agoMin) + ")" warnColors.setColor(binding.lastconnection, agoMin.toDouble(), 16.0, 31.0) } if (pump.lastBolusTime != 0L) { @@ -166,24 +166,24 @@ class DiaconnG8Fragment : DaggerFragment() { val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 if (agoHours < 6) // max 6h back - binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, rh) + " " + rh.gs(R.string.formatinsulinunits, pump.lastBolusAmount) else binding.lastbolus.text = "" } val todayInsulinAmount = (pump.todayBaseAmount + pump.todaySnackAmount + pump.todayMealAmount) val todayInsulinLimitAmount = (pump.maxBasal.toInt() * 24) + pump.maxBolusePerDay.toInt() - binding.dailyunits.text = resourceHelper.gs(R.string.reservoirvalue, todayInsulinAmount, todayInsulinLimitAmount) + binding.dailyunits.text = rh.gs(R.string.reservoirvalue, todayInsulinAmount, todayInsulinLimitAmount) warnColors.setColor(binding.dailyunits, todayInsulinAmount, todayInsulinLimitAmount * 0.75, todayInsulinLimitAmount * 0.9) - binding.basabasalrate.text = pump.baseInjAmount.toString() +" / "+ resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) + binding.basabasalrate.text = pump.baseInjAmount.toString() +" / "+ rh.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) binding.tempbasal.text = diaconnG8Pump.temporaryBasalToString() binding.extendedbolus.text = diaconnG8Pump.extendedBolusToString() - binding.reservoir.text = resourceHelper.gs(R.string.reservoirvalue, pump.systemRemainInsulin, 307) + binding.reservoir.text = rh.gs(R.string.reservoirvalue, pump.systemRemainInsulin, 307) warnColors.setColorInverse(binding.reservoir, pump.systemRemainInsulin , 50.0, 20.0) binding.battery.text = "{fa-battery-" + pump.systemRemainBattery / 25 + "}" + " ("+ pump.systemRemainBattery + " %)" warnColors.setColorInverse(binding.battery, pump.systemRemainBattery.toDouble(), 51.0, 26.0) - binding.firmware.text = resourceHelper.gs(R.string.diaconn_g8_pump) + "\nVersion: " + pump.majorVersion.toString() + "." + pump.minorVersion.toString() + "\nCountry: "+pump.country.toString() + "\nProductType: "+ pump.productType.toString() + "\nManufacture: " + pump.makeYear + "." + pump.makeMonth + "." + pump.makeDay + binding.firmware.text = rh.gs(R.string.diaconn_g8_pump) + "\nVersion: " + pump.majorVersion.toString() + "." + pump.minorVersion.toString() + "\nCountry: "+pump.country.toString() + "\nProductType: "+ pump.productType.toString() + "\nManufacture: " + pump.makeYear + "." + pump.makeMonth + "." + pump.makeDay binding.basalstep.text = pump.basalStep.toString() binding.bolusstep.text = pump.bolusStep.toString() binding.serialNumber.text = pump.serialNo.toString() diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt index 26c2dc7c86..9b3fa81a9f 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt @@ -50,11 +50,11 @@ class DiaconnG8Plugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBus, private val context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, private val constraintChecker: ConstraintChecker, private val profileFunction: ProfileFunction, private val sp: SP, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, private val diaconnG8Pump: DiaconnG8Pump, private val pumpSync: PumpSync, private val detailedBolusInfoStorage: DetailedBolusInfoStorage, @@ -69,7 +69,7 @@ class DiaconnG8Plugin @Inject constructor( .shortName(R.string.diaconn_g8_pump_shortname) .preferencesId(R.xml.pref_diaconn) .description(R.string.description_pump_diaconn_g8), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ), Pump, Diaconn, Constraints { private val disposable = CompositeDisposable() @@ -130,7 +130,7 @@ class DiaconnG8Plugin @Inject constructor( aapsLogger.debug(LTag.PUMP, "Diaconn G8 connect from: $reason") if(diaconnG8Service != null && mDeviceAddress != "" && mDeviceName != "") { val success = diaconnG8Service?.connect(reason, mDeviceAddress) ?: false - if(!success) ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.ble_not_supported)) + if(!success) ToastUtils.showToastInUiThread(context, rh.gs(R.string.ble_not_supported)) } } @@ -166,18 +166,18 @@ class DiaconnG8Plugin @Inject constructor( // Constraints interface override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - absoluteRate.setIfSmaller(aapsLogger, diaconnG8Pump.maxBasal, resourceHelper.gs(R.string.limitingbasalratio, diaconnG8Pump.maxBasal, resourceHelper.gs(R.string.pumplimit)), this) + absoluteRate.setIfSmaller(aapsLogger, diaconnG8Pump.maxBasal, rh.gs(R.string.limitingbasalratio, diaconnG8Pump.maxBasal, rh.gs(R.string.pumplimit)), this) return absoluteRate } override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - percentRate.setIfGreater(aapsLogger, 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) - percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this) + percentRate.setIfGreater(aapsLogger, 0, rh.gs(R.string.limitingpercentrate, 0, rh.gs(R.string.itmustbepositivevalue)), this) + percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, rh.gs(R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(R.string.pumplimit)), this) return percentRate } override fun applyBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfSmaller(aapsLogger, diaconnG8Pump.maxBolus, resourceHelper.gs(R.string.limitingbolus, diaconnG8Pump.maxBolus, resourceHelper.gs(R.string.pumplimit)), this) + insulin.setIfSmaller(aapsLogger, diaconnG8Pump.maxBolus, rh.gs(R.string.limitingbolus, diaconnG8Pump.maxBolus, rh.gs(R.string.pumplimit)), this) return insulin } @@ -198,22 +198,22 @@ class DiaconnG8Plugin @Inject constructor( override fun setNewBasalProfile(profile: Profile): PumpEnactResult { val result = PumpEnactResult(injector) if (!isInitialized()) { - val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT) + val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, rh.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet) + result.comment = rh.gs(R.string.pumpNotInitializedProfileNotSet) return result } else { rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) } return if (diaconnG8Service?.updateBasalsInPump(profile) != true) { - val notification = Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT) + val notification = Notification(Notification.FAILED_UPDATE_PROFILE, rh.gs(R.string.failedupdatebasalprofile), Notification.URGENT) rxBus.send(EventNewNotification(notification)) - result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile) + result.comment = rh.gs(R.string.failedupdatebasalprofile) result } else { rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) rxBus.send(EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)) - val notification = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) + val notification = Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) result.success = true result.enacted = true @@ -269,7 +269,7 @@ class DiaconnG8Plugin @Inject constructor( if(result.success) result.enacted = true if (!result.success) { setErrorMsg(diaconnG8Pump.resultErrorCode, result) - } else result.comment = resourceHelper.gs(R.string.ok) + } else result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered) result } else { @@ -277,7 +277,7 @@ class DiaconnG8Plugin @Inject constructor( result.success = false result.bolusDelivered = 0.0 result.carbsDelivered = 0.0 - result.comment = resourceHelper.gs(R.string.invalidinput) + result.comment = rh.gs(R.string.invalidinput) aapsLogger.error("deliverTreatment: Invalid input") result } @@ -343,7 +343,7 @@ class DiaconnG8Plugin @Inject constructor( if (connectionOK && diaconnG8Pump.isTempBasalInProgress && diaconnG8Pump.tempBasalAbsoluteRate == absoluteAfterConstrain) { result.enacted = true result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.isTempCancel = false result.duration = diaconnG8Pump.tempBasalRemainingMin result.absolute = diaconnG8Pump.tempBasalAbsoluteRate @@ -355,7 +355,7 @@ class DiaconnG8Plugin @Inject constructor( result.enacted = false result.success = false - result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror) + result.comment = rh.gs(R.string.tempbasaldeliveryerror) aapsLogger.error("setTempBasalAbsolute: Failed to set temp basal") return result } @@ -383,7 +383,7 @@ class DiaconnG8Plugin @Inject constructor( if (diaconnG8Pump.isExtendedInProgress && abs(diaconnG8Pump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) { result.enacted = false result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.duration = diaconnG8Pump.extendedBolusRemainingMinutes result.absolute = diaconnG8Pump.extendedBolusAbsoluteRate result.isPercent = false @@ -397,7 +397,7 @@ class DiaconnG8Plugin @Inject constructor( if (connectionOK) { result.enacted = true result.success = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) result.isTempCancel = false result.duration = diaconnG8Pump.extendedBolusRemainingMinutes result.absolute = diaconnG8Pump.extendedBolusAbsoluteRate @@ -427,7 +427,7 @@ class DiaconnG8Plugin @Inject constructor( result.success = true result.enacted = false result.isTempCancel = true - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "cancelRealTempBasal: OK") } return result @@ -447,7 +447,7 @@ class DiaconnG8Plugin @Inject constructor( } else { result.success = true result.enacted = false - result.comment = resourceHelper.gs(R.string.ok) + result.comment = rh.gs(R.string.ok) aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus: OK") } return result @@ -552,32 +552,32 @@ class DiaconnG8Plugin @Inject constructor( @Synchronized fun setErrorMsg(errorCode: Int, result: PumpEnactResult) { when (errorCode) { - 1 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_1) - 2 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_2) - 3 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_3) - 4 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_4) - 6 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_6) - 7 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_7) - 8 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_8) - 9 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_9) - 10 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_10) - 11 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_11) - 12 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_12) - 13 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_13) - 14 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_14) - 15 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_15) - 32 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_32) - 33 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_33) - 34 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_34) - 35 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_35) - 36 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_36) + 1 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_1) + 2 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_2) + 3 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_3) + 4 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_4) + 6 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_6) + 7 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_7) + 8 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_8) + 9 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_9) + 10 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_10) + 11 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_11) + 12 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_12) + 13 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_13) + 14 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_14) + 15 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_15) + 32 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_32) + 33 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_33) + 34 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_34) + 35 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_35) + 36 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_36) else -> result.comment = "not defined Error code: $errorCode" } } override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { - val bolusSpeedPreference: Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_diaconn_g8_bolusspeed)) + val bolusSpeedPreference: Preference? = preferenceFragment.findPreference(rh.gs(R.string.key_diaconn_g8_bolusspeed)) bolusSpeedPreference?.setOnPreferenceChangeListener { _, newValue -> val intBolusSpeed = newValue.toString().toInt() diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt index e11f5db161..6be6b27031 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecordDao import info.nightscout.androidaps.diaconn.databinding.DiaconnG8HistoryActivityBinding import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus @@ -41,7 +41,7 @@ class DiaconnG8HistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var diaconnHistoryRecordDao: DiaconnHistoryRecordDao @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -63,7 +63,7 @@ class DiaconnG8HistoryActivity : NoSplashAppCompatActivity() { disposable += rxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ binding.status.text = it.getStatus(resourceHelper) }) { fabricPrivacy.logException(it) } + .subscribe({ binding.status.text = it.getStatus(rh) }) { fabricPrivacy.logException(it) } swapAdapter(showingType) } @@ -84,13 +84,13 @@ class DiaconnG8HistoryActivity : NoSplashAppCompatActivity() { // Types val typeList = ArrayList() - typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, resourceHelper.gs(R.string.diaconn_g8_history_alarm))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, resourceHelper.gs(R.string.diaconn_g8_history_basalhours))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, resourceHelper.gs(R.string.diaconn_g8_history_bolus))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_TB, resourceHelper.gs(R.string.diaconn_g8_history_tempbasal))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, resourceHelper.gs(R.string.diaconn_g8_history_dailyinsulin))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, resourceHelper.gs(R.string.diaconn_g8_history_refill))) - typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, resourceHelper.gs(R.string.diaconn_g8_history_suspend))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, rh.gs(R.string.diaconn_g8_history_alarm))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, rh.gs(R.string.diaconn_g8_history_basalhours))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, rh.gs(R.string.diaconn_g8_history_bolus))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_TB, rh.gs(R.string.diaconn_g8_history_tempbasal))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, rh.gs(R.string.diaconn_g8_history_dailyinsulin))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, rh.gs(R.string.diaconn_g8_history_refill))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, rh.gs(R.string.diaconn_g8_history_suspend))) binding.spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, typeList) binding.reload.setOnClickListener { @@ -163,9 +163,9 @@ class DiaconnG8HistoryActivity : NoSplashAppCompatActivity() { } RecordTypes.RECORD_TYPE_DAILY -> { - holder.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBasal) - holder.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus) - holder.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) + holder.dailyBasal.text = rh.gs(R.string.formatinsulinunits, record.dailyBasal) + holder.dailyBolus.text = rh.gs(R.string.formatinsulinunits, record.dailyBolus) + holder.dailyTotal.text = rh.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) holder.time.text = dateUtil.dateString(record.timestamp) holder.time.visibility = View.VISIBLE holder.value.visibility = View.GONE diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt index b8c6867a6c..1676859acd 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.diaconn.R import info.nightscout.androidaps.diaconn.databinding.DiaconnG8UserOptionsActivityBinding import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus @@ -35,7 +35,7 @@ class DiaconnG8UserOptionsActivity : NoSplashAppCompatActivity() { @Inject lateinit var context: Context @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var sp: SP private val disposable = CompositeDisposable() @@ -158,7 +158,7 @@ class DiaconnG8UserOptionsActivity : NoSplashAppCompatActivity() { val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", resourceHelper.gs(R.string.pumperror)) + i.putExtra("title", rh.gs(R.string.pumperror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) } @@ -169,9 +169,9 @@ class DiaconnG8UserOptionsActivity : NoSplashAppCompatActivity() { private fun fillSoundCategory() { val categories = ArrayList() - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_sound)) - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_vibrate)) - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_silent)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_sound)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_vibrate)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_silent)) context.let { context -> val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) binding.beepAndAlarm.adapter = adapterCategories @@ -180,9 +180,9 @@ class DiaconnG8UserOptionsActivity : NoSplashAppCompatActivity() { private fun fillSoundSubCategory() { val categories = ArrayList() - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_low)) - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_middle)) - categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_high)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_intensity_low)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_intensity_middle)) + categories.add(rh.gs(R.string.diaconn_g8_pumpalarm_intensity_high)) context.let { context -> val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) binding.alarmIntesity.adapter = adapterCategories diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt index 5b56b512df..c2c8400048 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt @@ -22,7 +22,7 @@ class BigAPSMainInfoInquireResponsePacket( @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper private var pumpDesc = PumpDescription(PumpType.DIACONN_G8) init { @@ -77,7 +77,7 @@ class BigAPSMainInfoInquireResponsePacket( diaconnG8Pump.minorVersion = getByteToInt(bufferData) // save current pump firmware version - sp.putString(resourceHelper.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) // 5. pump log status diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // last saved log no @@ -216,7 +216,7 @@ class BigAPSMainInfoInquireResponsePacket( diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][23] = diaconnG8Pump.baseAmount24 //incarnation no 처리 - diaconnG8Pump.isPumpVersionGe2_63 = PumplogUtil.isPumpVersionGe(sp.getString(resourceHelper.gs(R.string.pumpversion), ""),2, 63) + diaconnG8Pump.isPumpVersionGe2_63 = PumplogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""),2, 63) aapsLogger.debug(LTag.PUMPCOMM, "result > " + diaconnG8Pump.result) aapsLogger.debug(LTag.PUMPCOMM, "systemRemainInsulin > " + diaconnG8Pump.systemRemainInsulin) diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt index 7e6e62fd0b..f9f5267f29 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt @@ -32,7 +32,7 @@ class BigLogInquireResponsePacket( ) : DiaconnG8Packet(injector) { @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @@ -89,8 +89,8 @@ class BigLogInquireResponsePacket( diaconnG8Pump.apsWrappingCount = wrapingCount diaconnG8Pump.apslastLogNum = logNum - sp.putInt(resourceHelper.gs(R.string.apslastLogNum), logNum) - sp.putInt(resourceHelper.gs(R.string.apsWrappingCount), wrapingCount) + sp.putInt(rh.gs(R.string.apslastLogNum), logNum) + sp.putInt(rh.gs(R.string.apsWrappingCount), wrapingCount) // process Log to DB val logDataToHexString = toNarrowHex(logdata) @@ -118,7 +118,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() diaconnG8HistoryRecord.bolusType = "M" // meal bolus - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logmealsuccess) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logmealsuccess) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "MEALBOLUSSUCCESS" + dateUtil.timeString(logDateTime) } @@ -142,7 +142,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.value = if ((logItem.injectAmount / 100.0) < 0) 0.0 else (logItem.injectAmount / 100.0) diaconnG8HistoryRecord.duration = logItem.getInjectTime() diaconnG8HistoryRecord.bolusType = "M" // Meal bolus - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logmealfail) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logmealfail) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "MEALBOLUSFAIL " + dateUtil.timeString(logDateTime) } @@ -167,7 +167,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() diaconnG8HistoryRecord.bolusType = "B" // bolus - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsuccess) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logsuccess) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "BOLUSSUCCESS" + dateUtil.timeString(logDateTime) } @@ -217,7 +217,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.setAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsquarestart) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logsquarestart) diaconnG8HistoryRecord.bolusType = "E" // Extended diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "EXTENDEDBOLUSSTART " + dateUtil.timeString(logDateTime) @@ -231,7 +231,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.duration = logItem.getInjectTime() - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsquaresuccess) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logsquaresuccess) diaconnG8HistoryRecord.bolusType = "E" // Extended diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "EXTENDEDBOLUSEND " + dateUtil.timeString(logDateTime) @@ -278,7 +278,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.setSquareAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() * 10 // (1~30) 1:10min 30:300min - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualsquarestart) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logdualsquarestart) diaconnG8HistoryRecord.bolusType = "D" // Extended diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) @@ -309,7 +309,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() diaconnG8HistoryRecord.bolusType = "D" // bolus - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualnormalsuccess) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logdualnormalsuccess) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "DUALBOLUS" + dateUtil.timeString(logDateTime) } @@ -325,7 +325,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.value = logItem.injectSquareAmount / 100.0 diaconnG8HistoryRecord.duration = logItem.getInjectTime() diaconnG8HistoryRecord.bolusType = "D" - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualsquaresuccess) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logdualsquaresuccess) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "DUALBOLUS SQUARESUCCESS " + dateUtil.timeString(logDateTime) } @@ -372,7 +372,7 @@ class BigLogInquireResponsePacket( val logDateTime = logStartDate.time diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_SUSPEND diaconnG8HistoryRecord.timestamp = logDateTime - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_lgosuspend, logItem.getBasalPattern()) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_lgosuspend, logItem.getBasalPattern()) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "SUSPEND " + dateUtil.timeString(logDateTime) } @@ -384,7 +384,7 @@ class BigLogInquireResponsePacket( val logDateTime = logStartDate.time diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_SUSPEND diaconnG8HistoryRecord.timestamp = logDateTime - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_lgorelease, logItem.getBasalPattern()) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_lgorelease, logItem.getBasalPattern()) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "SUSPENDRELEASE " + dateUtil.timeString(logDateTime) } @@ -407,7 +407,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_loginjectorprime, logItem.primeAmount / 100.0) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_loginjectorprime, logItem.primeAmount / 100.0) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "INSULINCHANGE " + dateUtil.timeString(logDateTime) } @@ -421,7 +421,7 @@ class BigLogInquireResponsePacket( val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( timestamp = logDateTime, type = DetailedBolusInfo.EventType.NOTE, - note = resourceHelper.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0), + note = rh.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0), pumpId = logDateTime, pumpType = PumpType.DIACONN_G8, pumpSerial = diaconnG8Pump.serialNo.toString() @@ -433,7 +433,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "TUBECHANGE " + dateUtil.timeString(logDateTime) } @@ -552,7 +552,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logneedleprime, logItem.primeAmount / 100.0) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logneedleprime, logItem.primeAmount / 100.0) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "NEEDLECHANGE " + dateUtil.timeString(logDateTime) } @@ -589,7 +589,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.duration = logItem.tbTime * 15 diaconnG8HistoryRecord.value = absoluteRate - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logtempstart) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logtempstart) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "TEMPSTART " + dateUtil.timeString(logDateTime) } @@ -632,7 +632,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM diaconnG8HistoryRecord.timestamp = logDateTime - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logbatteryshorage) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logbatteryshorage) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "BATTERYALARM " + dateUtil.timeString(logDateTime) } @@ -647,7 +647,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.amount / 100.0 - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logalarmblock, getReasonName(pumplogKind, logItem.reason)) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_logalarmblock, getReasonName(pumplogKind, logItem.reason)) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "BLOCKALARM " + dateUtil.timeString(logDateTime) } @@ -662,7 +662,7 @@ class BigLogInquireResponsePacket( diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM diaconnG8HistoryRecord.timestamp = logDateTime diaconnG8HistoryRecord.value = logItem.remain.toDouble() - diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_loginsulinshorage) + diaconnG8HistoryRecord.stringValue = rh.gs(R.string.diaconn_g8_loginsulinshorage) diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) status = "SHORTAGEALARM " + dateUtil.timeString(logDateTime) } @@ -694,12 +694,12 @@ class BigLogInquireResponsePacket( } else -> { - status = resourceHelper.gs(R.string.diaconn_g8_logsyncinprogress) + status = rh.gs(R.string.diaconn_g8_logsyncinprogress) rxBus.send(EventPumpStatusChanged(status)) continue } } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.processinghistory) + ": " + status)) } } @@ -726,40 +726,40 @@ class BigLogInquireResponsePacket( private fun failLog(reason: Byte): String { return when (reason) { //1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown - 0.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoncomplete) - 1.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoninjectonblock) - 2.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonbatteryshortage) - 3.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoninsulinshortage) - 4.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonuserstop) - 5.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonsystemreset) - 6.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonother) - 7.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonemergencystop) + 0.toByte() -> rh.gs(R.string.diaconn_g8_reasoncomplete) + 1.toByte() -> rh.gs(R.string.diaconn_g8_reasoninjectonblock) + 2.toByte() -> rh.gs(R.string.diaconn_g8_reasonbatteryshortage) + 3.toByte() -> rh.gs(R.string.diaconn_g8_reasoninsulinshortage) + 4.toByte() -> rh.gs(R.string.diaconn_g8_reasonuserstop) + 5.toByte() -> rh.gs(R.string.diaconn_g8_reasonsystemreset) + 6.toByte() -> rh.gs(R.string.diaconn_g8_reasonother) + 7.toByte() -> rh.gs(R.string.diaconn_g8_reasonemergencystop) else -> "No Reason" } } private fun resetLog(reason: Byte): String { return when (reason.toInt()) { - 1 -> resourceHelper.gs(R.string.diaconn_g8_resetfactoryreset) - 2 -> resourceHelper.gs(R.string.diaconn_g8_resetemergencyoff) - 3 -> resourceHelper.gs(R.string.diaconn_g8_resetbatteryreplacement) - 4 -> resourceHelper.gs(R.string.diaconn_g8_resetaftercalibration) - 5 -> resourceHelper.gs(R.string.diaconn_g8_resetpreshipment) - 9 -> resourceHelper.gs(R.string.diaconn_g8_resetunexpected) + 1 -> rh.gs(R.string.diaconn_g8_resetfactoryreset) + 2 -> rh.gs(R.string.diaconn_g8_resetemergencyoff) + 3 -> rh.gs(R.string.diaconn_g8_resetbatteryreplacement) + 4 -> rh.gs(R.string.diaconn_g8_resetaftercalibration) + 5 -> rh.gs(R.string.diaconn_g8_resetpreshipment) + 9 -> rh.gs(R.string.diaconn_g8_resetunexpected) else -> "" } } private fun blockLog(reason: Byte): String { return when (reason.toInt()) { - 1 -> resourceHelper.gs(R.string.diacon_g8_blockbasal) - 2 -> resourceHelper.gs(R.string.diacon_g8_blockmealbolus) - 3 -> resourceHelper.gs(R.string.diacon_g8_blocknormalbolus) - 4 -> resourceHelper.gs(R.string.diacon_g8_blocksquarebolus) - 5 -> resourceHelper.gs(R.string.diacon_g8_blockdualbolus) - 6 -> resourceHelper.gs(R.string.diacon_g8_blockreplacetube) - 7 -> resourceHelper.gs(R.string.diacon_g8_blockreplaceneedle) - 8 -> resourceHelper.gs(R.string.diacon_g8_blockreplacesyringe) + 1 -> rh.gs(R.string.diacon_g8_blockbasal) + 2 -> rh.gs(R.string.diacon_g8_blockmealbolus) + 3 -> rh.gs(R.string.diacon_g8_blocknormalbolus) + 4 -> rh.gs(R.string.diacon_g8_blocksquarebolus) + 5 -> rh.gs(R.string.diacon_g8_blockdualbolus) + 6 -> rh.gs(R.string.diacon_g8_blockreplacetube) + 7 -> rh.gs(R.string.diacon_g8_blockreplaceneedle) + 8 -> rh.gs(R.string.diacon_g8_blockreplacesyringe) else -> "" } } diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt index 42aca3f51e..662d8b846f 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt @@ -22,7 +22,7 @@ class BigMainInfoInquireResponsePacket( @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper private var pumpDesc = PumpDescription(PumpType.DIACONN_G8) init { @@ -76,7 +76,7 @@ class BigMainInfoInquireResponsePacket( diaconnG8Pump.majorVersion = getByteToInt(bufferData) diaconnG8Pump.minorVersion = getByteToInt(bufferData) - sp.putString(resourceHelper.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + sp.putString(rh.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) // 5. pump log status diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // last saved log no @@ -213,7 +213,7 @@ class BigMainInfoInquireResponsePacket( diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][23] = diaconnG8Pump.baseAmount24 //incarnation no 처리 - diaconnG8Pump.isPumpVersionGe2_63 = PumplogUtil.isPumpVersionGe(sp.getString(resourceHelper.gs(R.string.pumpversion), ""),2, 63) + diaconnG8Pump.isPumpVersionGe2_63 = PumplogUtil.isPumpVersionGe(sp.getString(rh.gs(R.string.pumpversion), ""),2, 63) aapsLogger.debug(LTag.PUMPCOMM, "result > " + diaconnG8Pump.result) aapsLogger.debug(LTag.PUMPCOMM, "systemRemainInsulin > " + diaconnG8Pump.systemRemainInsulin) diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt index 55aedbcf05..6e7863e8f4 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt @@ -16,7 +16,7 @@ open class IncarnationInquireResponsePacket( @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper var result = 0 init { diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt index 167025592e..17b768090b 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt @@ -14,7 +14,7 @@ class InjectionExtendedBolusResultReportPacket(injector: HasAndroidInjector) : D @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper init { msgType = 0xe5.toByte() diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt index 0ac9a86d21..13de89d399 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt @@ -14,7 +14,7 @@ class InjectionSnackResultReportPacket(injector: HasAndroidInjector) : DiaconnG8 @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @Inject lateinit var rxBus: RxBus - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper init { msgType = 0xe4.toByte() diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt index c49367ddef..6209a89fb3 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt @@ -25,7 +25,7 @@ import javax.inject.Singleton class BLECommonService @Inject internal constructor( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val context: Context, private val rxBus: RxBus, private val diaconnG8ResponseMessageHashTable: DiaconnG8ResponseMessageHashTable, @@ -300,8 +300,8 @@ class BLECommonService @Inject internal constructor( diaconnG8Pump.bolusBlocked = true val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) - i.putExtra("status", resourceHelper.gs(R.string.injectionblocked)) - i.putExtra("title", resourceHelper.gs(R.string.injectionblocked)) + i.putExtra("status", rh.gs(R.string.injectionblocked)) + i.putExtra("title", rh.gs(R.string.injectionblocked)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) return @@ -311,8 +311,8 @@ class BLECommonService @Inject internal constructor( message.handleMessage(data) val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) - i.putExtra("status", resourceHelper.gs(R.string.needbatteryreplace)) - i.putExtra("title", resourceHelper.gs(R.string.batterywarning)) + i.putExtra("status", rh.gs(R.string.needbatteryreplace)) + i.putExtra("title", rh.gs(R.string.batterywarning)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) return @@ -323,8 +323,8 @@ class BLECommonService @Inject internal constructor( message.handleMessage(data) val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) - i.putExtra("status", resourceHelper.gs(R.string.needinsullinreplace)) - i.putExtra("title", resourceHelper.gs(R.string.insulinlackwarning)) + i.putExtra("status", rh.gs(R.string.needinsullinreplace)) + i.putExtra("title", rh.gs(R.string.insulinlackwarning)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) return diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt index 2fd7ce20cc..e3ca30c8ea 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.PumpSync @@ -58,9 +58,9 @@ class DiaconnG8Service : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var context: Context @Inject lateinit var diaconnG8Plugin : DiaconnG8Plugin @Inject lateinit var diaconnG8Pump: DiaconnG8Pump @@ -133,9 +133,9 @@ class DiaconnG8Service : DaggerService() { fun readPumpStatus() { try { val pump = activePlugin.activePump - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))) - val pumpFirmwareVersion = sp.getString(resourceHelper.gs(R.string.pumpversion),"") + val pumpFirmwareVersion = sp.getString(rh.gs(R.string.pumpversion),"") if(!StringUtils.emptyString(pumpFirmwareVersion) && PumplogUtil.isPumpVersionGe(pumpFirmwareVersion, 3, 0)) { sendMessage(BigAPSMainInfoInquirePacket(injector)) // APS Pump Main Info @@ -152,7 +152,7 @@ class DiaconnG8Service : DaggerService() { val profile = profileFunction.getProfile() if (profile != null && abs(diaconnG8Pump.baseAmount - profile.getBasal()) >= pump.pumpDescription.basalStep) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpsettings))) if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(EventProfileSwitchChanged()) @@ -160,7 +160,7 @@ class DiaconnG8Service : DaggerService() { } // 시간 설정 - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumptime))) var timeDiff = (diaconnG8Pump.getPumpTime() - System.currentTimeMillis()) / 1000L if (diaconnG8Pump.getPumpTime() == 0L) { // initial handshake was not successful @@ -180,7 +180,7 @@ class DiaconnG8Service : DaggerService() { if (abs(timeDiff) > 60 * 60 * 1.5) { aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds - large difference") //If time-diff is very large, warn user until we can synchronize history readings properly - ErrorHelperActivity.runAlarm(context, resourceHelper.gs(R.string.largetimediff), resourceHelper.gs(R.string.largetimedifftitle), R.raw.error) + ErrorHelperActivity.runAlarm(context, rh.gs(R.string.largetimediff), rh.gs(R.string.largetimedifftitle), R.raw.error) //de-initialize pump @@ -213,9 +213,9 @@ class DiaconnG8Service : DaggerService() { if (diaconnG8Pump.dailyTotalUnits > diaconnG8Pump.maxDailyTotalUnits * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + diaconnG8Pump.dailyTotalUnits + "/" + diaconnG8Pump.maxDailyTotalUnits) if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT) + val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, rh.gs(R.string.approachingdailylimit), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) - pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + diaconnG8Pump.dailyTotalUnits + "/" + diaconnG8Pump.maxDailyTotalUnits + "U", null, PumpType.DIACONN_G8, diaconnG8Pump.serialNo.toString()) + pumpSync.insertAnnouncement(rh.gs(R.string.approachingdailylimit) + ": " + diaconnG8Pump.dailyTotalUnits + "/" + diaconnG8Pump.maxDailyTotalUnits + "U", null, PumpType.DIACONN_G8, diaconnG8Pump.serialNo.toString()) lastApproachingDailyLimit = System.currentTimeMillis() } } @@ -243,11 +243,11 @@ class DiaconnG8Service : DaggerService() { // pump log status val pumpLastNum = diaconnG8Pump.pumpLastLogNum val pumpWrappingCount = diaconnG8Pump.pumpWrappingCount - val apsIncarnationNum = sp.getInt(resourceHelper.gs(R.string.apsIncarnationNo), 65536) + val apsIncarnationNum = sp.getInt(rh.gs(R.string.apsIncarnationNo), 65536) // aps last log num - val pumpSerialNo = sp.getInt(resourceHelper.gs(R.string.pumpserialno), 0) - val apsWrappingCount = sp.getInt(resourceHelper.gs(R.string.apsWrappingCount), 0) - val apsLastLogNum = sp.getInt(resourceHelper.gs(R.string.apslastLogNum), 0) + val pumpSerialNo = sp.getInt(rh.gs(R.string.pumpserialno), 0) + val apsWrappingCount = sp.getInt(rh.gs(R.string.apsWrappingCount), 0) + val apsLastLogNum = sp.getInt(rh.gs(R.string.apslastLogNum), 0) // if first install app if(apsWrappingCount == 0 && apsLastLogNum == 0 ) { @@ -257,13 +257,13 @@ class DiaconnG8Service : DaggerService() { // if pump reset if(apsIncarnationNum != diaconnG8Pump.pumpIncarnationNum) { pumpLogDefaultSetting() - sp.putInt(resourceHelper.gs(R.string.apsIncarnationNo), diaconnG8Pump.pumpIncarnationNum) + sp.putInt(rh.gs(R.string.apsIncarnationNo), diaconnG8Pump.pumpIncarnationNum) } // if another pump if(pumpSerialNo != diaconnG8Pump.serialNo) { pumpLogDefaultSetting() - sp.putInt(resourceHelper.gs(R.string.pumpserialno), diaconnG8Pump.serialNo) + sp.putInt(rh.gs(R.string.pumpserialno), diaconnG8Pump.serialNo) } val apsLastNum = apsWrappingCount * 10000 + apsLastLogNum @@ -339,7 +339,7 @@ class DiaconnG8Service : DaggerService() { fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean { if (!isConnected) return false if (BolusProgressDialog.stopPressed) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.startingbolus))) // bolus speed setting val apsPrefBolusSpeed = sp.getInt("g8_bolusspeed", 5) @@ -397,7 +397,7 @@ class DiaconnG8Service : DaggerService() { val totalwaitTime = (expectedEnd - System.currentTimeMillis()) /1000 while (!diaconnG8Pump.bolusDone) { val waitTime = (expectedEnd - System.currentTimeMillis()) / 1000 - bolusingEvent.status = String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), if(waitTime < 0) 0 else waitTime) + bolusingEvent.status = String.format(rh.gs(R.string.waitingforestimatedbolusend), if(waitTime < 0) 0 else waitTime) var progressPecent = 0 if(totalwaitTime > waitTime) { progressPecent = ((totalwaitTime - waitTime) * 100 / totalwaitTime).toInt() @@ -411,11 +411,11 @@ class DiaconnG8Service : DaggerService() { commandQueue.loadEvents(object : Callback() { override fun run() { // reread bolus status - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingbolusstatus))) sendMessage(InjectionSnackInquirePacket(injector), 1000) // last bolus // 볼러스 결과 보고패킷에서 처리함. bolusingEvent.percent = 100 - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.disconnecting))) } }) return !start.failed @@ -443,7 +443,7 @@ class DiaconnG8Service : DaggerService() { sendMessage(TempBasalInquirePacket(injector)) if (diaconnG8Pump.tbStatus ==1 ) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) // tempbasal stop sendMessage(msgPacket) @@ -451,7 +451,7 @@ class DiaconnG8Service : DaggerService() { if(!processConfirm(msgPacket.msgType)) return false diaconnG8Pump.tempBasalStart= dateUtil.now() } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))) val tbInjectRate = ((absoluteRate*100) + 1000).toInt() val msgTBR = TempBasalSettingPacket(injector, 1, ((durationInHours * 60) / 15).toInt(), tbInjectRate) sendMessage(msgTBR) @@ -475,7 +475,7 @@ class DiaconnG8Service : DaggerService() { // temp state check sendMessage(TempBasalInquirePacket(injector)) if (diaconnG8Pump.tbStatus ==1 ) { - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) // tempbasal stop sendMessage(msgPacket) @@ -483,7 +483,7 @@ class DiaconnG8Service : DaggerService() { if(!processConfirm(msgPacket.msgType)) return false SystemClock.sleep(500) } - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingtempbasal))) val tbInjectRate = absoluteRate * 100 + 1000 val msgTBR = TempBasalSettingPacket(injector, 1, 2, tbInjectRate.toInt()) sendMessage(msgTBR) @@ -499,7 +499,7 @@ class DiaconnG8Service : DaggerService() { fun tempBasalStop(): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingtempbasal))) // temp state check sendMessage(TempBasalInquirePacket(injector)) if(diaconnG8Pump.tbStatus == 1) { @@ -525,7 +525,7 @@ class DiaconnG8Service : DaggerService() { fun extendedBolus(insulin: Double, durationInMinutes: Int): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.settingextendedbolus))) aapsLogger.error(LTag.PUMPCOMM, "insulin: $insulin durationInMinutes: $durationInMinutes") val msgExtended = InjectionExtendedBolusSettingPacket(injector, (insulin * 100).toInt(), durationInMinutes, dateUtil.now()) @@ -542,7 +542,7 @@ class DiaconnG8Service : DaggerService() { fun extendedBolusStop(): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.stoppingextendedbolus))) val msgType = if(diaconnG8Pump.dualStatus == 1) 0x09.toByte() else 0x08.toByte() val msgStop = InjectionCancelSettingPacket(injector, msgType) sendMessage(msgStop) @@ -557,7 +557,7 @@ class DiaconnG8Service : DaggerService() { fun updateBasalsInPump(profile: Profile): Boolean { if (!isConnected) return false - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))) + rxBus.send(EventPumpStatusChanged(rh.gs(R.string.updatingbasalrates))) val basalList = diaconnG8Pump.buildDiaconnG8ProfileRecord(profile) val requestReqPacket1 = BasalSettingPacket( @@ -596,8 +596,8 @@ class DiaconnG8Service : DaggerService() { private fun pumpLogDefaultSetting() { val apsWrappingCount = diaconnG8Pump.pumpWrappingCount val apsLastLogNum = if(diaconnG8Pump.pumpLastLogNum - 1 < 0 ) 0 else diaconnG8Pump.pumpLastLogNum - 1 - sp.putInt(resourceHelper.gs(R.string.apslastLogNum), apsLastLogNum) - sp.putInt(resourceHelper.gs(R.string.apsWrappingCount), apsWrappingCount) + sp.putInt(rh.gs(R.string.apslastLogNum), apsLastLogNum) + sp.putInt(rh.gs(R.string.apsWrappingCount), apsWrappingCount) } private fun processConfirm(msgType:Byte) : Boolean { @@ -609,8 +609,8 @@ class DiaconnG8Service : DaggerService() { // Thread { // val i = Intent(context, ErrorHelperActivity::class.java) // i.putExtra("soundid", R.raw.boluserror) - // i.putExtra("status", resourceHelper.gs(R.string.diaconn_g8_errotpreceivedyet)) - // i.putExtra("title", resourceHelper.gs(R.string.pumperror)) + // i.putExtra("status", rh.gs(R.string.diaconn_g8_errotpreceivedyet)) + // i.putExtra("title", rh.gs(R.string.pumperror)) // i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // context.startActivity(i) // }.start() diff --git a/diaconn/src/main/res/values-hu-rHU/strings.xml b/diaconn/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/diaconn/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/diaconn/src/main/res/values-tr-rTR/strings.xml b/diaconn/src/main/res/values-tr-rTR/strings.xml index 3ea04e700d..9123a00060 100644 --- a/diaconn/src/main/res/values-tr-rTR/strings.xml +++ b/diaconn/src/main/res/values-tr-rTR/strings.xml @@ -1,2 +1,155 @@ - + + Eşleştirmeyi Sıfırla + Kullanılabilir Cihaz yok + Diaconn Pompa Eşleştirme + Pompa Hatası + Alarmlar + Bazal Saatler + Boluslar + Günlük İnsülin + Hatalar + Doldurma + Yeniden doldurun + Askıya almak + Eşleştirme tamam + Eşleştirme için bekleyin + Versiyon + Geçersiz eşleştirme bilgisi. Yeniden eşleştirme isteniyor + Pompa ayarları alınıyor + Pompa zamanı alınıyor + Büyük zaman farkı:\nPompadaki süre 1,5 saatten fazla kapalı.\nLütfen zamanı pompada manuel olarak ayarlayın ve pompadan geçmişi okumanın beklenmeyen davranışlara neden olmadığından emin olun.\nMümkünse zamanı değiştirmeden önce geçmişi kaldırın veya son yanlış geçmiş girişinden sonra bir DIA için kapalı döngüyü devre dışı bırakın. + Büyük zaman farkı + İnsülin günlük sınırına yaklaşıyor + Bolus gönderimini başlatma + Tahmini bolus sonu bekleniyor + Bolus Durumu Alınıyor + Geçici bazal durdurma + Geçici bazal ayarı + Yayma bolus ayarı + Yayma bolus durdurma + Bazal oranların güncellenmesi + Diaconn G8 Pompaları için Pompa Entegrasyonu + Diaconn G8 + Diaconn G8 + Maksimum bolus ihlali + Komut hatası + Hız hatası + İnsülin limit ihlali + İstenen: %1$.2fU Teslim edilen: %2$.2fU Hata kodu: %3$s + Değer düzgün ayarlanmadı + Diaconn G8 Bluetooth cihazı + Pompa Şifresi + Bolus hızı + Seçilen pompa + >%%200 için yayma bolus kullanın + Yayma bolusu %% olarak görselleştir + Bluetooth Durumu + TDD + Bolus Adımı + Bazal Adımı + Yazılım + KULLANICI SEÇENEKLERİ + Lütfen pompanızı telefonunuzla eşleştirin! + "Etkinlik İşleniyor " + aps_son_log_num + aps_sarım_sayım + Geçici Bazal + Diaconn pompa Ayarları + Ses + ses + titreşim + sessize al + Alarm yoğunluğu + düşük + orta + yüksek + LCD açık kalma süresi [second] + POMPA SEÇENEĞİNİ KAYDET + Dil + Bolus hızı + Çince + Korece + İngilizce + "10 " + 10 + 20 + 30 + düşük + Enjeksiyon Blokesi + Pil Uyarısı + İnsülin Eksikliği Uyarısı + Pil değişimi gerekli + İnsülin değişimi gerekli + pompa_versiyonu + aps_enkarnasyon_no + pompa_seri_no + Rezervuar değişikliği günlüğe kaydet + Geçmişte tespit edildiğinde careportal\'a \"İnsülin Değişimi\" olayı ekleyin + Kanül değişikliğini günlüğe kaydetme + Geçmişte tespit edildiğinde careportal\'a \"Kanül Değişikliği\" olayı ekleyin + Geçmişte tespit edildiğinde careportal\'a \"Pil Değişikliği\" olayı ekleyin + Pil değişimini günlüğe kaydet + Günlük Senkronizasyonu devam ediyor + İnsülin eksikliği + Pil bitiyor + İğne başlama :%1$.2fU + Enjectör başlama :%1$.2fU + Tüp değişimi başlama :%1$.2fU + Fabrika ayarlarına sıfırladıktan sonra sıfırla + Acil Durum Kapatıldıktan Sonra Sıfırla + Pil değişiminden sonra sıfırla + Kalibrasyondan sonra sıfırla + Sevk-öncesi kurulumdan sonra sıfırla + Beklenmeyen sistem sıfırlaması + Tamamlayınız + Enjeksiyon bloğu + Pil bitiyor + İnsülin bitiyor + Kullanıcı durdurma + Sistem yeniden başlatma + Diğer + Acil stop + BAZAL + YEMEK BOLUSU + NORMAL BOLUS + KARE BOLUS + İKİLİ BOLUS + TÜPÜ DEĞİŞTİR + İĞNE DEĞİŞTİR + ŞIRINGA DEĞİŞTİR + Enjeksiyon Bloğu (%s) + bazal salınım (%s) + bazal askıya alma (%s) + İkili Normal Başarılı + İkili Yayma Başladı + İkili Yayma başarılı + Yayma Başladı + Yayma Başarılı + Yemek Başarısız + Başarılı + Yemek başarılı + Paket CRC hatası nedeniyle arama yapılamıyor. + Giriş parametresi hatasına ayarlanamaz. + Protokol spesifikasyon hatasına ayarlanamaz. + Zamanlanmış yeme, enjekte edilemez. + Pompa tarafından iptal edildi + Diğer işlemleri yapmak, uygulama ayarlarını sınırlamak. + Başka bir Bolus enjeksiyonu sırasında enjeksiyon kısıtlanır. + Bazal enjeksiyonun devam ettirilmesini gerektirir + Pompa yanıt vermediği için iptal edildi. + Düşük pil nedeniyle enjeksiyon mümkün değildir. + İnsülin eksikliği, enjekte edilemez. + Limiti bir kez aştığı için enjekte edemezsiniz. + Günlük enjeksiyon limitini aştığı için enjeksiyon yapılamaz. + Bazal kurulum tamamlandıktan sonra bazal enjeksiyon yapılabilir. + Komut teslim edilmedi. Lütfen tekrar deneyin. + Tüp değişim günlüğü + Geçmişte tespit edildiğinde Not\'a \"Tüp Değişikliği\" olayı ekleyin + Geçici Bazal Başlat + LGS çalışırken, enjeksiyon kısıtlanır + LGS durumu AÇIK, AÇ Komutu reddedildi. + LGS durumu KAPALI, KAPAT komutu reddedildi. + Geçici bazal çalışırken Geçici bazal başlatma reddedilir + Geçici bazal çalışmıyorken Geçici bazal durdurma reddedilir + diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java index 8278203eae..76ee9adfd4 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java @@ -39,7 +39,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class InsightAlertService extends DaggerService implements InsightConnectionService.StateCallback { @Inject AAPSLogger aapsLogger; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject AlertUtils alertUtils; private static final int NOTIFICATION_ID = 31345; @@ -309,11 +309,11 @@ public class InsightAlertService extends DaggerService implements InsightConnect case ACTIVE: Intent muteIntent = new Intent(this, InsightAlertService.class).putExtra("command", "mute"); PendingIntent mutePendingIntent = PendingIntent.getService(this, 1, muteIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); - notificationBuilder.addAction(0, resourceHelper.gs(R.string.mute_alert), mutePendingIntent); + notificationBuilder.addAction(0, rh.gs(R.string.mute_alert), mutePendingIntent); case SNOOZED: Intent confirmIntent = new Intent(this, InsightAlertService.class).putExtra("command", "confirm"); PendingIntent confirmPendingIntent = PendingIntent.getService(this, 2, confirmIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); - notificationBuilder.addAction(0, resourceHelper.gs(R.string.confirm), confirmPendingIntent); + notificationBuilder.addAction(0, rh.gs(R.string.confirm), confirmPendingIntent); } Notification notification = notificationBuilder.build(); diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 8aafdff3c2..56653c2216 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -21,7 +21,7 @@ import javax.inject.Inject; import dagger.android.support.DaggerFragment; import info.nightscout.androidaps.insight.R; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; @@ -41,9 +41,9 @@ import io.reactivex.disposables.CompositeDisposable; public class LocalInsightFragment extends DaggerFragment implements View.OnClickListener { @Inject LocalInsightPlugin localInsightPlugin; - @Inject CommandQueueProvider commandQueue; + @Inject CommandQueue commandQueue; @Inject RxBus rxBus; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; @Inject AapsSchedulers aapsSchedulers; @@ -226,9 +226,9 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick string = R.string.recovering; break; } - statusItems.add(getStatusItem(resourceHelper.gs(R.string.insight_status), resourceHelper.gs(string))); + statusItems.add(getStatusItem(rh.gs(R.string.insight_status), rh.gs(string))); if (state == InsightState.RECOVERING) { - statusItems.add(getStatusItem(resourceHelper.gs(R.string.recovery_duration), localInsightPlugin.getConnectionService().getRecoveryDuration() / 1000 + "s")); + statusItems.add(getStatusItem(rh.gs(R.string.recovery_duration), localInsightPlugin.getConnectionService().getRecoveryDuration() / 1000 + "s")); } } @@ -244,11 +244,11 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick double lastConnectionMinAgo = agoMsc / 60d / 1000d; String ago; if (lastConnectionMinAgo < 60) { - ago = dateUtil.minAgo(resourceHelper, lastConnection); + ago = dateUtil.minAgo(rh, lastConnection); } else { - ago = dateUtil.hourAgo(lastConnection, resourceHelper); + ago = dateUtil.hourAgo(lastConnection, rh); } - statusItems.add(getStatusItem(resourceHelper.gs(R.string.last_connected), + statusItems.add(getStatusItem(rh.gs(R.string.last_connected), dateUtil.timeString(lastConnection) + " (" + ago + ")")); } } @@ -275,12 +275,12 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick string = R.string.paused; break; } - statusItems.add(getStatusItem(resourceHelper.gs(R.string.operating_mode), resourceHelper.gs(string))); + statusItems.add(getStatusItem(rh.gs(R.string.operating_mode), rh.gs(string))); } private void getBatteryStatusItem(List statusItems) { if (localInsightPlugin.getBatteryStatus() == null) return; - statusItems.add(getStatusItem(resourceHelper.gs(R.string.battery_label), + statusItems.add(getStatusItem(rh.gs(R.string.battery_label), localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%")); } @@ -290,45 +290,45 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick String status; if (cartridgeStatus.isInserted()) status = DecimalFormatter.INSTANCE.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U"; - else status = resourceHelper.gs(R.string.not_inserted); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.reservoir_label), status)); + else status = rh.gs(R.string.not_inserted); + statusItems.add(getStatusItem(rh.gs(R.string.reservoir_label), status)); } private void getTDDItems(List statusItems) { if (localInsightPlugin.getTotalDailyDose() == null) return; TotalDailyDose tdd = localInsightPlugin.getTotalDailyDose(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_bolus), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolus()))); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_basal), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBasal()))); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.tdd_total), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolusAndBasal()))); + statusItems.add(getStatusItem(rh.gs(R.string.tdd_bolus), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolus()))); + statusItems.add(getStatusItem(rh.gs(R.string.tdd_basal), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBasal()))); + statusItems.add(getStatusItem(rh.gs(R.string.tdd_total), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolusAndBasal()))); } private void getBaseBasalRateItem(List statusItems) { if (localInsightPlugin.getActiveBasalRate() == null) return; ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.basebasalrate_label), + statusItems.add(getStatusItem(rh.gs(R.string.basebasalrate_label), DecimalFormatter.INSTANCE.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); } private void getTBRItem(List statusItems) { if (localInsightPlugin.getActiveTBR() == null) return; ActiveTBR activeTBR = localInsightPlugin.getActiveTBR(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.tempbasal_label), - resourceHelper.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); + statusItems.add(getStatusItem(rh.gs(R.string.tempbasal_label), + rh.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); } private void getLastBolusItem(List statusItems) { if (localInsightPlugin.lastBolusAmount == 0 || localInsightPlugin.lastBolusTimestamp == 0) return; long agoMsc = System.currentTimeMillis() - localInsightPlugin.lastBolusTimestamp; double bolusMinAgo = agoMsc / 60d / 1000d; - String unit = resourceHelper.gs(R.string.insulin_unit_shortname); + String unit = rh.gs(R.string.insulin_unit_shortname); String ago; if (bolusMinAgo < 60) { - ago = dateUtil.minAgo(resourceHelper, localInsightPlugin.lastBolusTimestamp); + ago = dateUtil.minAgo(rh, localInsightPlugin.lastBolusTimestamp); } else { - ago = dateUtil.hourAgo(localInsightPlugin.lastBolusTimestamp, resourceHelper); + ago = dateUtil.hourAgo(localInsightPlugin.lastBolusTimestamp, rh); } - statusItems.add(getStatusItem(resourceHelper.gs(R.string.insight_last_bolus), - resourceHelper.gs(R.string.insight_last_bolus_formater, localInsightPlugin.lastBolusAmount, unit, ago))); + statusItems.add(getStatusItem(rh.gs(R.string.insight_last_bolus), + rh.gs(R.string.insight_last_bolus_formater, localInsightPlugin.lastBolusAmount, unit, ago))); } private void getBolusItems(List statusItems) { @@ -337,15 +337,15 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick String label; switch (activeBolus.getBolusType()) { case MULTIWAVE: - label = resourceHelper.gs(R.string.multiwave_bolus); + label = rh.gs(R.string.multiwave_bolus); break; case EXTENDED: - label = resourceHelper.gs(R.string.extended_bolus); + label = rh.gs(R.string.extended_bolus); break; default: continue; } - statusItems.add(getStatusItem(label, resourceHelper.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()))); + statusItems.add(getStatusItem(label, rh.gs(R.string.eb_formatter, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration()))); } } } \ No newline at end of file diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 85fa1c1f65..83956aaeea 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -41,7 +41,7 @@ import info.nightscout.androidaps.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.insight.database.InsightPumpID; import info.nightscout.androidaps.insight.database.InsightPumpID.EventType; import info.nightscout.androidaps.insight.R; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.Config; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraints; @@ -138,9 +138,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private final AAPSLogger aapsLogger; private final RxBus rxBus; - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final SP sp; - private final CommandQueueProvider commandQueue; + private final CommandQueue commandQueue; private final ProfileFunction profileFunction; private final Context context; private final DateUtil dateUtil; @@ -198,9 +198,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai HasAndroidInjector injector, AAPSLogger aapsLogger, RxBus rxBus, - ResourceHelper resourceHelper, + ResourceHelper rh, SP sp, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, ProfileFunction profileFunction, Context context, Config config, @@ -216,12 +216,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai .description(R.string.description_pump_insight_local) .fragmentClass(LocalInsightFragment.class.getName()) .preferencesId(config.getAPS() ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), - injector, aapsLogger, resourceHelper, commandQueue + injector, aapsLogger, rh, commandQueue ); this.aapsLogger = aapsLogger; this.rxBus = rxBus; - this.resourceHelper = resourceHelper; + this.rh = rh; this.sp = sp; this.commandQueue = commandQueue; this.profileFunction = profileFunction; @@ -280,7 +280,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai private void createNotificationChannel() { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, resourceHelper.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH); + NotificationChannel channel = new NotificationChannel(ALERT_CHANNEL_ID, rh.gs(R.string.insight_alert_notification_channel), NotificationManager.IMPORTANCE_HIGH); channel.setSound(null, null); notificationManager.createNotificationChannel(channel); } @@ -385,7 +385,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai SetDateTimeMessage setDateTimeMessage = new SetDateTimeMessage(); setDateTimeMessage.setPumpTime(pumpTime); connectionService.requestMessage(setDateTimeMessage).await(); - Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, resourceHelper.gs(R.string.pump_time_updated), Notification.INFO, 60); + Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, rh.gs(R.string.pump_time_updated), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); } } @@ -492,7 +492,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai profileBlock.setProfileBlocks(profileBlocks); ParameterBlockUtil.writeConfigurationBlock(connectionService, profileBlock); rxBus.send(new EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)); - Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60); + Notification notification = new Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); result.success(true) .enacted(true) @@ -504,17 +504,17 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai } } catch (AppLayerErrorException e) { aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")"); - Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, rh.gs(R.string.failedupdatebasalprofile), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); result.comment(ExceptionTranslator.getString(context, e)); } catch (InsightException e) { aapsLogger.info(LTag.PUMP, "Exception while setting profile: " + e.getClass().getCanonicalName()); - Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, rh.gs(R.string.failedupdatebasalprofile), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); result.comment(ExceptionTranslator.getString(context, e)); } catch (Exception e) { aapsLogger.error("Exception while setting profile", e); - Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); + Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, rh.gs(R.string.failedupdatebasalprofile), Notification.URGENT); rxBus.send(new EventNewNotification(notification)); result.comment(ExceptionTranslator.getString(context, e)); } @@ -588,7 +588,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; bolusingEvent.setT(t); - bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, 0d, insulin)); + bolusingEvent.setStatus(rh.gs(R.string.insight_delivered, 0d, insulin)); bolusingEvent.setPercent(0); rxBus.send(bolusingEvent); int trials = 0; @@ -627,14 +627,14 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai trials = -1; int percentBefore = bolusingEvent.getPercent(); bolusingEvent.setPercent((int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount()))); - bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount())); + bolusingEvent.setStatus(rh.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount())); if (percentBefore != bolusingEvent.getPercent()) rxBus.send(bolusingEvent); } else { synchronized ($bolusLock) { if (bolusCancelled || trials == -1 || trials++ >= 5) { if (!bolusCancelled) { - bolusingEvent.setStatus(resourceHelper.gs(R.string.insight_delivered, insulin, insulin)); + bolusingEvent.setStatus(rh.gs(R.string.insight_delivered, insulin, insulin)); bolusingEvent.setPercent(100); rxBus.send(bolusingEvent); } @@ -1084,25 +1084,25 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai if (connectionService != null && connectionService.getLastConnected() != 0) { long agoMsec = dateUtil.now() - connectionService.getLastConnected(); int agoMin = (int) (agoMsec / 60d / 1000d); - ret.append(resourceHelper.gs(R.string.short_status_last_connected, agoMin)).append("\n"); + ret.append(rh.gs(R.string.short_status_last_connected, agoMin)).append("\n"); } if (activeTBR != null) { - ret.append(resourceHelper.gs(R.string.short_status_tbr, activeTBR.getPercentage(), + ret.append(rh.gs(R.string.short_status_tbr, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration())).append("\n"); } if (activeBoluses != null) for (ActiveBolus activeBolus : activeBoluses) { if (activeBolus.getBolusType() == BolusType.STANDARD) continue; - ret.append(resourceHelper.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended, + ret.append(rh.gs(activeBolus.getBolusType() == BolusType.MULTIWAVE ? R.string.short_status_multiwave : R.string.short_status_extended, activeBolus.getRemainingAmount(), activeBolus.getInitialAmount(), activeBolus.getRemainingDuration())).append("\n"); } if (!veryShort && totalDailyDose != null) { - ret.append(resourceHelper.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal())).append("\n"); + ret.append(rh.gs(R.string.short_status_tdd, totalDailyDose.getBolusAndBasal())).append("\n"); } if (cartridgeStatus != null) { - ret.append(resourceHelper.gs(R.string.short_status_reservoir, cartridgeStatus.getRemainingAmount())).append("\n"); + ret.append(rh.gs(R.string.short_status_reservoir, cartridgeStatus.getRemainingAmount())).append("\n"); } if (batteryStatus != null) { - ret.append(resourceHelper.gs(R.string.short_status_battery, batteryStatus.getBatteryAmount())).append("\n"); + ret.append(rh.gs(R.string.short_status_battery, batteryStatus.getBatteryAmount())).append("\n"); } return ret.toString(); } @@ -1289,7 +1289,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(), event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset; if (event.getAmount() > 0.0) // Don't record event if amount is null - logNote(timestamp, resourceHelper.gs(R.string.tube_changed)); + logNote(timestamp, rh.gs(R.string.tube_changed)); } private void processSniffingDoneEvent(String serial, SniffingDoneEvent event) { @@ -1319,17 +1319,17 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai pumpID.setEventType(EventType.PumpStarted); pumpStartedEvents.add(pumpID); if (sp.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, resourceHelper.gs(R.string.pump_started)); + logNote(timestamp, rh.gs(R.string.pump_started)); break; case STOPPED: pumpID.setEventType(EventType.PumpStopped); if (sp.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, resourceHelper.gs(R.string.pump_stopped)); + logNote(timestamp, rh.gs(R.string.pump_stopped)); break; case PAUSED: pumpID.setEventType(EventType.PumpPaused); if (sp.getBoolean("insight_log_operating_mode_changes", false)) - logNote(timestamp, resourceHelper.gs(R.string.pump_paused)); + logNote(timestamp, rh.gs(R.string.pump_paused)); break; } insightDbHelper.createOrUpdate(pumpID); @@ -1542,7 +1542,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai break; } if (code != null) - logNote(timestamp, resourceHelper.gs(R.string.insight_alert_formatter, resourceHelper.gs(code), resourceHelper.gs(title))); + logNote(timestamp, rh.gs(R.string.insight_alert_formatter, rh.gs(code), rh.gs(title))); } private long parseDate(int year, int month, int day, int hour, int minute, int second) { @@ -1579,22 +1579,22 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, String.format(resourceHelper.gs(R.string.limitingpercentrate), 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), String.format(resourceHelper.gs(R.string.limitingpercentrate), getPumpDescription().getMaxTempPercent(), resourceHelper.gs(R.string.pumplimit)), this); + percentRate.setIfGreater(getAapsLogger(), 0, String.format(rh.gs(R.string.limitingpercentrate), 0, rh.gs(R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), String.format(rh.gs(R.string.limitingpercentrate), getPumpDescription().getMaxTempPercent(), rh.gs(R.string.pumplimit)), this); return percentRate; } @NonNull @Override public Constraint applyBolusConstraints(@NonNull Constraint insulin) { if (!limitsFetched) return insulin; - insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(resourceHelper.gs(R.string.limitingbolus), maximumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); + insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, String.format(rh.gs(R.string.limitingbolus), maximumBolusAmount, rh.gs(R.string.pumplimit)), this); if (insulin.value() < minimumBolusAmount) { //TODO: Add function to Constraints or use different approach // This only works if the interface of the InsightPlugin is called last. // If not, another constraint could theoretically set the value between 0 and minimumBolusAmount - insulin.set(getAapsLogger(), 0d, String.format(resourceHelper.gs(R.string.limitingbolus), minimumBolusAmount, resourceHelper.gs(R.string.pumplimit)), this); + insulin.set(getAapsLogger(), 0d, String.format(rh.gs(R.string.limitingbolus), minimumBolusAmount, rh.gs(R.string.pumplimit)), this); } return insulin; } @@ -1633,7 +1633,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai @Override public void onTimeoutDuringHandshake() { - Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, resourceHelper.gs(R.string.timeout_during_handshake), Notification.URGENT); + Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, rh.gs(R.string.timeout_during_handshake), Notification.URGENT); new Handler(Looper.getMainLooper()).post(() -> rxBus.send(new EventNewNotification(notification))); } diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt index 11f000ef32..9227816104 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt @@ -10,9 +10,9 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class AlertUtils @Inject constructor(private val resourceHelper: ResourceHelper) { +class AlertUtils @Inject constructor(private val rh: ResourceHelper) { - fun getAlertCode(alertType: AlertType) = resourceHelper.gs(when (alertType) { + fun getAlertCode(alertType: AlertType) = rh.gs(when (alertType) { AlertType.REMINDER_01 -> R.string.alert_r1_code AlertType.REMINDER_02 -> R.string.alert_r2_code AlertType.REMINDER_03 -> R.string.alert_r3_code @@ -41,7 +41,7 @@ class AlertUtils @Inject constructor(private val resourceHelper: ResourceHelper) AlertType.ERROR_13 -> R.string.alert_e13_code }) - fun getAlertTitle(alertType: AlertType) = resourceHelper.gs(when (alertType) { + fun getAlertTitle(alertType: AlertType) = rh.gs(when (alertType) { AlertType.REMINDER_01 -> R.string.alert_r1_title AlertType.REMINDER_02 -> R.string.alert_r2_title AlertType.REMINDER_03 -> R.string.alert_r3_title @@ -79,28 +79,28 @@ class AlertUtils @Inject constructor(private val resourceHelper: ResourceHelper) AlertType.REMINDER_02 -> null AlertType.REMINDER_03 -> null AlertType.REMINDER_04 -> null - AlertType.REMINDER_07 -> resourceHelper.gs(R.string.alert_r7_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) - AlertType.WARNING_31 -> resourceHelper.gs(R.string.alert_w31_description, decimalFormat.format(alert.cartridgeAmount)) - AlertType.WARNING_32 -> resourceHelper.gs(R.string.alert_w32_description) - AlertType.WARNING_33 -> resourceHelper.gs(R.string.alert_w33_description) - AlertType.WARNING_34 -> resourceHelper.gs(R.string.alert_w34_description) - AlertType.WARNING_36 -> resourceHelper.gs(R.string.alert_w36_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) - AlertType.WARNING_38 -> resourceHelper.gs(R.string.alert_w38_description, decimalFormat.format(alert.programmedBolusAmount), decimalFormat.format(alert.deliveredBolusAmount)) + AlertType.REMINDER_07 -> rh.gs(R.string.alert_r7_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) + AlertType.WARNING_31 -> rh.gs(R.string.alert_w31_description, decimalFormat.format(alert.cartridgeAmount)) + AlertType.WARNING_32 -> rh.gs(R.string.alert_w32_description) + AlertType.WARNING_33 -> rh.gs(R.string.alert_w33_description) + AlertType.WARNING_34 -> rh.gs(R.string.alert_w34_description) + AlertType.WARNING_36 -> rh.gs(R.string.alert_w36_description, alert.tbrAmount, DecimalFormat("#0").format(hours.toLong()) + ":" + DecimalFormat("00").format(minutes.toLong())) + AlertType.WARNING_38 -> rh.gs(R.string.alert_w38_description, decimalFormat.format(alert.programmedBolusAmount), decimalFormat.format(alert.deliveredBolusAmount)) AlertType.WARNING_39 -> null - AlertType.MAINTENANCE_20 -> resourceHelper.gs(R.string.alert_m20_description) - AlertType.MAINTENANCE_21 -> resourceHelper.gs(R.string.alert_m21_description) - AlertType.MAINTENANCE_22 -> resourceHelper.gs(R.string.alert_m22_description) - AlertType.MAINTENANCE_23 -> resourceHelper.gs(R.string.alert_m23_description) - AlertType.MAINTENANCE_24 -> resourceHelper.gs(R.string.alert_m24_description) - AlertType.MAINTENANCE_25 -> resourceHelper.gs(R.string.alert_m25_description) - AlertType.MAINTENANCE_26 -> resourceHelper.gs(R.string.alert_m26_description) - AlertType.MAINTENANCE_27 -> resourceHelper.gs(R.string.alert_m27_description) - AlertType.MAINTENANCE_28 -> resourceHelper.gs(R.string.alert_m28_description) - AlertType.MAINTENANCE_29 -> resourceHelper.gs(R.string.alert_m29_description) - AlertType.MAINTENANCE_30 -> resourceHelper.gs(R.string.alert_m30_description) - AlertType.ERROR_6 -> resourceHelper.gs(R.string.alert_e6_description) - AlertType.ERROR_10 -> resourceHelper.gs(R.string.alert_e10_description) - AlertType.ERROR_13 -> resourceHelper.gs(R.string.alert_e13_description) + AlertType.MAINTENANCE_20 -> rh.gs(R.string.alert_m20_description) + AlertType.MAINTENANCE_21 -> rh.gs(R.string.alert_m21_description) + AlertType.MAINTENANCE_22 -> rh.gs(R.string.alert_m22_description) + AlertType.MAINTENANCE_23 -> rh.gs(R.string.alert_m23_description) + AlertType.MAINTENANCE_24 -> rh.gs(R.string.alert_m24_description) + AlertType.MAINTENANCE_25 -> rh.gs(R.string.alert_m25_description) + AlertType.MAINTENANCE_26 -> rh.gs(R.string.alert_m26_description) + AlertType.MAINTENANCE_27 -> rh.gs(R.string.alert_m27_description) + AlertType.MAINTENANCE_28 -> rh.gs(R.string.alert_m28_description) + AlertType.MAINTENANCE_29 -> rh.gs(R.string.alert_m29_description) + AlertType.MAINTENANCE_30 -> rh.gs(R.string.alert_m30_description) + AlertType.ERROR_6 -> rh.gs(R.string.alert_e6_description) + AlertType.ERROR_10 -> rh.gs(R.string.alert_e10_description) + AlertType.ERROR_13 -> rh.gs(R.string.alert_e13_description) } } diff --git a/insight/src/main/res/values-bg-rBG/alert_descriptions.xml b/insight/src/main/res/values-bg-rBG/alert_descriptions.xml index e50451e0ab..244b6cc578 100644 --- a/insight/src/main/res/values-bg-rBG/alert_descriptions.xml +++ b/insight/src/main/res/values-bg-rBG/alert_descriptions.xml @@ -2,7 +2,9 @@ %1$d%%\nПродължителност: %2$s h]]> %1$s U]]> + Сменете на батерията. Задаване на време и дата. + Свържете с Accu-Chek поддръжка. %1$d%%
Продължителност: %2$s ч]]>
%1$s Е
Доставени: %2$s Е]]>
Поставете резервоар. @@ -11,7 +13,9 @@ Проверете статуса на помпата. Сменете сет. Свържете с Accu-Chek поддръжка. + Промяна резервоар. Рестартирайте прехвърляне на данни. + Проверете статуса на помпата. Задайте тип батерия. Задайте тип резевоар. Сменете батерията и резервоарът. diff --git a/insight/src/main/res/values-bg-rBG/alert_titles.xml b/insight/src/main/res/values-bg-rBG/alert_titles.xml index 14ba108de5..26025edc39 100644 --- a/insight/src/main/res/values-bg-rBG/alert_titles.xml +++ b/insight/src/main/res/values-bg-rBG/alert_titles.xml @@ -3,6 +3,7 @@ Доставен болус Пропуснат болус Аларма часовник + Сменете сет Временен базал приключен Малко инсулин в резервоарът Изтощена батерия diff --git a/insight/src/main/res/values-hu-rHU/alert_codes.xml b/insight/src/main/res/values-hu-rHU/alert_codes.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/insight/src/main/res/values-hu-rHU/alert_codes.xml @@ -0,0 +1,2 @@ + + diff --git a/insight/src/main/res/values-hu-rHU/alert_descriptions.xml b/insight/src/main/res/values-hu-rHU/alert_descriptions.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/insight/src/main/res/values-hu-rHU/alert_descriptions.xml @@ -0,0 +1,2 @@ + + diff --git a/insight/src/main/res/values-hu-rHU/alert_titles.xml b/insight/src/main/res/values-hu-rHU/alert_titles.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/insight/src/main/res/values-hu-rHU/alert_titles.xml @@ -0,0 +1,2 @@ + + diff --git a/insight/src/main/res/values-hu-rHU/exceptions.xml b/insight/src/main/res/values-hu-rHU/exceptions.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/insight/src/main/res/values-hu-rHU/exceptions.xml @@ -0,0 +1,2 @@ + + diff --git a/insight/src/main/res/values-hu-rHU/strings.xml b/insight/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/insight/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/insight/src/main/res/values-iw-rIL/strings.xml b/insight/src/main/res/values-iw-rIL/strings.xml index afcfa9f9e8..7076fcc849 100644 --- a/insight/src/main/res/values-iw-rIL/strings.xml +++ b/insight/src/main/res/values-iw-rIL/strings.xml @@ -20,7 +20,7 @@ מינון יומי מצטבר כולל %1$d%% למשך %2$d/%3$d דק\' בולוס רב שלבי - %1$.2f / %2$.2f יח\' במשך %3$d דק\' + %1$.2f / %2$.2f יח\' למשך %3$d דק\' בולוס אחרון מחפש התקנים… הצימוד הושלם diff --git a/insight/src/main/res/values-tr-rTR/alert_descriptions.xml b/insight/src/main/res/values-tr-rTR/alert_descriptions.xml index e78a6ed2ec..13c5d12c28 100644 --- a/insight/src/main/res/values-tr-rTR/alert_descriptions.xml +++ b/insight/src/main/res/values-tr-rTR/alert_descriptions.xml @@ -2,7 +2,9 @@ %1$d%%\nSüre: %2$s st.]]> %1$s U]]> + Pili değiştirin. Tarihi/saati ayarlayın. + Accu-Chek desteğine başvurun. %1$d%%
Süre: %2$s st.]]>
%1$s U
gönderildi: %2$s U]]>
Rezervuar yerleştirin. @@ -11,9 +13,12 @@ Pompa durumunu kontrol edin. İnfüzyon seti değiştirin. Accu-Chek desteğine başvurun. + Rezervuar değiştir. Veri karşıdan yüklemeyi yeniden başlatın. + Pompa durumunu kontrol edin. Pil tipini ayarlayın. Rezervuar türünü ayarlayın. Pil ve Rezervuarı değiştirin. + Rezervuar değiştir. Dili değiştir.
diff --git a/insight/src/main/res/values-tr-rTR/alert_titles.xml b/insight/src/main/res/values-tr-rTR/alert_titles.xml index f2e34230f4..277b39487f 100644 --- a/insight/src/main/res/values-tr-rTR/alert_titles.xml +++ b/insight/src/main/res/values-tr-rTR/alert_titles.xml @@ -1,8 +1,9 @@ - Gönderilen Bolus - Başarısız Bolus + Bolus Gönder + Eksik Bolus Çalar saat + İnfüzyon seti değiştirin Geçici Bazal Oranı tamamlandı Rezervuar düşük Pil düşük diff --git a/insight/src/main/res/values-tr-rTR/strings.xml b/insight/src/main/res/values-tr-rTR/strings.xml index 72ed8b5242..3c56eec15f 100644 --- a/insight/src/main/res/values-tr-rTR/strings.xml +++ b/insight/src/main/res/values-tr-rTR/strings.xml @@ -21,27 +21,39 @@ %1$d%% için %2$d / %3$d dak Çokdalgalı Bolus %1$.2f / %2$.2f U for %3$d dak. + Son Bolus Cihazlar aranıyor… Eşleştirme tamamlandı Bu cihazda ve pompanızda görüntülenen kodlar aynı mı? Insight eşleştirme Accu-Chek Insight + %1$.2f Ü / %2$.2f Ü gönderildi %1$s: %2$s Hortum değişti Sight + Insight Pump Uyarıları + Manuel bolus iletiminde titreşimleri devre dışı bırakın + Bolus ve yayma bolus için (yalnızca Insight üretici yazılımı 3.x ile kullanılabilir) + Otomatik bolus iletiminde titreşimleri devre dışı bırakın + TBR emülasyonlu SMB ve Geçici Bazal için (yalnızca Insight üretici yazılımı 3.x ile kullanılabilir) El sıkışma sırasında zaman aşımı olduğunda - bluetoothu sıfırla Pompa durduruldu Pompa başlatıldı Pompa duraklatıldı Son bağl: %1$d dak. önce TBR: %1$d%% für %2$d / %3$d min + Yayma: %1$.2f / %2$.2f U for %3$d dak Multiwave: %1$.2f / %2$.2f U for %3$d min GTD: %1$.2f + Rezerv.: %1$.2f Ü Pil.: %1$d%% Onaylayın Sessiz Yayın yazılım sürümü + UI işlemci yazılım sürümü PC yazılım işlemci sürümü + MD tel işlemci yazılım sürümü + Güvenlik işlemcisi yazılım sürümü BT bilgilendirme sayfası sürümü Bluetooth adresi Sistem Kimliği ID eki @@ -51,7 +63,11 @@ Rezerveor değişimini kayıt altına al Hortum değişimlerini kaydet Pil değişimlerini kaydet + Çalışma modu değişikliklerini günlüğe kaydet Günlük uyarıları + TBR emulasyonunu etkinleştir + %%250 sınırını atlamak için TBR\'ler yerine yayma bolus kullanın + Bağlantı kesme gecikmesi [s] Max. kurtarma süresi [s] Min. Kurtarma süresi [s] Pompa alarmı diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 2cc0bd06a1..5d24a8c03e 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -52,10 +52,10 @@ class MedtronicFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @Inject lateinit var rxBus: RxBus - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var warnColors: WarnColors @@ -90,7 +90,7 @@ class MedtronicFragment : DaggerFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - binding.rlStatus.text = resourceHelper.gs(RileyLinkServiceState.NotStarted.resourceId) + binding.rlStatus.text = rh.gs(RileyLinkServiceState.NotStarted.resourceId) binding.pumpStatusIcon.setTextColor(Color.WHITE) @SuppressLint("SetTextI18n") @@ -194,17 +194,17 @@ class MedtronicFragment : DaggerFragment() { val rileyLinkError = medtronicPumpPlugin.rileyLinkService.error binding.rlStatus.text = when { - rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) - rileyLinkServiceData.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) - rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) - rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) - else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted -> rh.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + rh.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + rh.gs(resourceId) + rileyLinkServiceData.rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + rh.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.MedtronicPump)) + else -> "{fa-bluetooth-b} " + rh.gs(resourceId) } binding.rlStatus.setTextColor(if (rileyLinkError != null) Color.RED else Color.WHITE) binding.errors.text = rileyLinkServiceData.rileyLinkError?.let { - resourceHelper.gs(it.getResourceId(RileyLinkTargetDevice.MedtronicPump)) + rh.gs(it.getResourceId(RileyLinkTargetDevice.MedtronicPump)) } ?: "-" when (medtronicPumpStatus.pumpDeviceState) { @@ -217,22 +217,22 @@ class MedtronicFragment : DaggerFragment() { PumpDeviceState.ErrorWhenCommunicating, PumpDeviceState.TimeoutWhenCommunicating, PumpDeviceState.InvalidConfiguration -> - binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) + binding.pumpStatusIcon.text = " " + rh.gs(medtronicPumpStatus.pumpDeviceState.resourceId) PumpDeviceState.Active -> { val cmd = medtronicUtil.getCurrentCommand() if (cmd == null) - binding.pumpStatusIcon.text = " " + resourceHelper.gs(medtronicPumpStatus.pumpDeviceState.resourceId) + binding.pumpStatusIcon.text = " " + rh.gs(medtronicPumpStatus.pumpDeviceState.resourceId) else { aapsLogger.debug(LTag.PUMP, "Command: $cmd") val cmdResourceId = cmd.resourceId //!! if (cmd == MedtronicCommandType.GetHistoryData) { binding.pumpStatusIcon.text = medtronicUtil.frameNumber?.let { - resourceHelper.gs(cmdResourceId!!, medtronicUtil.pageNumber, medtronicUtil.frameNumber) + rh.gs(cmdResourceId!!, medtronicUtil.pageNumber, medtronicUtil.frameNumber) } - ?: resourceHelper.gs(R.string.medtronic_cmd_desc_get_history_request, medtronicUtil.pageNumber) + ?: rh.gs(R.string.medtronic_cmd_desc_get_history_request, medtronicUtil.pageNumber) } else { - binding.pumpStatusIcon.text = " " + (cmdResourceId?.let { resourceHelper.gs(it) } + binding.pumpStatusIcon.text = " " + (cmdResourceId?.let { rh.gs(it) } ?: cmd.commandDescription) } } @@ -253,8 +253,8 @@ class MedtronicFragment : DaggerFragment() { private fun displayNotConfiguredDialog() { context?.let { - OKDialog.show(it, resourceHelper.gs(R.string.medtronic_warning), - resourceHelper.gs(R.string.medtronic_error_operation_not_possible_no_configuration), null) + OKDialog.show(it, rh.gs(R.string.medtronic_warning), + rh.gs(R.string.medtronic_error_operation_not_possible_no_configuration), null) } } @@ -268,7 +268,7 @@ class MedtronicFragment : DaggerFragment() { // last connection if (medtronicPumpStatus.lastConnection != 0L) { - val minAgo = dateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastConnection) + val minAgo = dateUtil.minAgo(rh, medtronicPumpStatus.lastConnection) val min = (System.currentTimeMillis() - medtronicPumpStatus.lastConnection) / 1000 / 60 if (medtronicPumpStatus.lastConnection + 60 * 1000 > System.currentTimeMillis()) { binding.lastConnection.setText(R.string.medtronic_pump_connected_now) @@ -276,17 +276,17 @@ class MedtronicFragment : DaggerFragment() { } else if (medtronicPumpStatus.lastConnection + 30 * 60 * 1000 < System.currentTimeMillis()) { if (min < 60) { - binding.lastConnection.text = resourceHelper.gs(R.string.minago, min) + binding.lastConnection.text = rh.gs(R.string.minago, min) } else if (min < 1440) { val h = (min / 60).toInt() - binding.lastConnection.text = (resourceHelper.gq(R.plurals.duration_hours, h, h) + " " - + resourceHelper.gs(R.string.ago)) + binding.lastConnection.text = (rh.gq(R.plurals.duration_hours, h, h) + " " + + rh.gs(R.string.ago)) } else { val h = (min / 60).toInt() val d = h / 24 // h = h - (d * 24); - binding.lastConnection.text = (resourceHelper.gq(R.plurals.duration_days, d, d) + " " - + resourceHelper.gs(R.string.ago)) + binding.lastConnection.text = (rh.gq(R.plurals.duration_days, d, d) + " " + + rh.gs(R.string.ago)) } binding.lastConnection.setTextColor(Color.RED) } else { @@ -301,27 +301,27 @@ class MedtronicFragment : DaggerFragment() { if (bolus != null && bolusTime != null) { val agoMsc = System.currentTimeMillis() - bolusTime.time val bolusMinAgo = agoMsc.toDouble() / 60.0 / 1000.0 - val unit = resourceHelper.gs(R.string.insulin_unit_shortname) + val unit = rh.gs(R.string.insulin_unit_shortname) val ago = when { - agoMsc < 60 * 1000 -> resourceHelper.gs(R.string.medtronic_pump_connected_now) - bolusMinAgo < 60 -> dateUtil.minAgo(resourceHelper, bolusTime.time) - else -> dateUtil.hourAgo(bolusTime.time, resourceHelper) + agoMsc < 60 * 1000 -> rh.gs(R.string.medtronic_pump_connected_now) + bolusMinAgo < 60 -> dateUtil.minAgo(rh, bolusTime.time) + else -> dateUtil.hourAgo(bolusTime.time, rh) } - binding.lastBolus.text = resourceHelper.gs(R.string.mdt_last_bolus, bolus, unit, ago) + binding.lastBolus.text = rh.gs(R.string.mdt_last_bolus, bolus, unit, ago) } else { binding.lastBolus.text = "" } // base basal rate binding.baseBasalRate.text = ("(" + medtronicPumpStatus.activeProfileName + ") " - + resourceHelper.gs(R.string.pump_basebasalrate, medtronicPumpPlugin.baseBasalRate)) + + rh.gs(R.string.pump_basebasalrate, medtronicPumpPlugin.baseBasalRate)) // TBR var tbrStr = "" val tbrRemainingTime: Int? = medtronicPumpStatus.tbrRemainingTime if (tbrRemainingTime != null) { - tbrStr = resourceHelper.gs(R.string.mdt_tbr_remaining, medtronicPumpStatus.tempBasalAmount, tbrRemainingTime) + tbrStr = rh.gs(R.string.mdt_tbr_remaining, medtronicPumpStatus.tempBasalAmount, tbrRemainingTime) } binding.tempBasal.text = tbrStr @@ -334,7 +334,7 @@ class MedtronicFragment : DaggerFragment() { warnColors.setColorInverse(binding.pumpStateBattery, medtronicPumpStatus.batteryRemaining.toDouble(), 25.0, 10.0) // reservoir - binding.reservoir.text = resourceHelper.gs(R.string.reservoirvalue, medtronicPumpStatus.reservoirRemainingUnits, medtronicPumpStatus.reservoirFullUnits) + binding.reservoir.text = rh.gs(R.string.reservoirvalue, medtronicPumpStatus.reservoirRemainingUnits, medtronicPumpStatus.reservoirFullUnits) warnColors.setColorInverse(binding.reservoir, medtronicPumpStatus.reservoirRemainingUnits, 50.0, 20.0) medtronicPumpPlugin.rileyLinkService.verifyConfiguration() diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt index b6c5933895..5b86577182 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt @@ -73,10 +73,10 @@ class MedtronicPumpPlugin @Inject constructor( aapsLogger: AAPSLogger, rxBus: RxBus, context: Context, - resourceHelper: ResourceHelper, + rh: ResourceHelper, activePlugin: ActivePlugin, sp: SP, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, fabricPrivacy: FabricPrivacy, private val medtronicUtil: MedtronicUtil, private val medtronicPumpStatus: MedtronicPumpStatus, @@ -96,7 +96,7 @@ class MedtronicPumpPlugin @Inject constructor( .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later - injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage + injector, rh, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage ), Pump, RileyLinkPumpDevice, info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator { private lateinit var rileyLinkMedtronicService: RileyLinkMedtronicService @@ -141,9 +141,9 @@ class MedtronicPumpPlugin @Inject constructor( override fun updatePreferenceSummary(pref: Preference) { super.updatePreferenceSummary(pref) - if (pref.key == resourceHelper.gs(R.string.key_rileylink_mac_address)) { + if (pref.key == rh.gs(R.string.key_rileylink_mac_address)) { val value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null) - pref.summary = value ?: resourceHelper.gs(R.string.not_set_short) + pref.summary = value ?: rh.gs(R.string.not_set_short) } } @@ -178,14 +178,14 @@ class MedtronicPumpPlugin @Inject constructor( private fun migrateSettings() { if ("US (916 MHz)" == sp.getString(MedtronicConst.Prefs.PumpFrequency, "US (916 MHz)")) { - sp.putString(MedtronicConst.Prefs.PumpFrequency, resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca)) + sp.putString(MedtronicConst.Prefs.PumpFrequency, rh.gs(R.string.key_medtronic_pump_frequency_us_ca)) } val encoding = sp.getString(MedtronicConst.Prefs.Encoding, "RileyLink 4b6b Encoding") if ("RileyLink 4b6b Encoding" == encoding) { - sp.putString(MedtronicConst.Prefs.Encoding, resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)) + sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink)) } if ("Local 4b6b Encoding" == encoding) { - sp.putString(MedtronicConst.Prefs.Encoding, resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_local)) + sp.putString(MedtronicConst.Prefs.Encoding, rh.gs(R.string.key_medtronic_pump_encoding_4b6b_local)) } } @@ -234,7 +234,7 @@ class MedtronicPumpPlugin @Inject constructor( } override fun getPumpInfo(): RileyLinkPumpInfo { - val frequency = resourceHelper.gs(if (medtronicPumpStatus.pumpFrequency == "medtronic_pump_frequency_us_ca") R.string.medtronic_pump_frequency_us_ca else R.string.medtronic_pump_frequency_worldwide) + val frequency = rh.gs(if (medtronicPumpStatus.pumpFrequency == "medtronic_pump_frequency_us_ca") R.string.medtronic_pump_frequency_us_ca else R.string.medtronic_pump_frequency_worldwide) val model = if (!medtronicUtil.isModelSet) "???" else "Medtronic " + medtronicPumpStatus.medtronicDeviceType.pumpModel val serialNumber = medtronicPumpStatus.serialNumber return RileyLinkPumpInfo(frequency, model, serialNumber) @@ -339,7 +339,7 @@ class MedtronicPumpPlugin @Inject constructor( var resetTime = false if (isPumpNotReachable) { aapsLogger.error("Pump unreachable.") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) return } medtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable, rxBus) @@ -408,7 +408,7 @@ class MedtronicPumpPlugin @Inject constructor( if (isRefresh) { if (isPumpNotReachable) { aapsLogger.error(logPrefix + "initializePump::Pump unreachable.") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable, rh, rxBus) setRefreshButtonEnabled(true) return true } @@ -421,7 +421,7 @@ class MedtronicPumpPlugin @Inject constructor( } else { if (medtronicPumpStatus.medtronicDeviceType !== medtronicUtil.medtronicPumpModel) { aapsLogger.warn(LTag.PUMP, logPrefix + "Configured pump is not the same as one detected.") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, rh, rxBus) } } pumpState = PumpDriverState.Connected @@ -567,13 +567,13 @@ class MedtronicPumpPlugin @Inject constructor( aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference is %d s. Set time on pump.", timeDiff)) rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.SetRealTimeClock) if (clock.timeDifference == 0) { - val notification = Notification(Notification.INSIGHT_DATE_TIME_UPDATED, resourceHelper.gs(R.string.pump_time_updated), Notification.INFO, 60) + val notification = Notification(Notification.INSIGHT_DATE_TIME_UPDATED, rh.gs(R.string.pump_time_updated), Notification.INFO, 60) rxBus.send(EventNewNotification(notification)) } } else { if (clock.localDeviceTime.year > 2015) { aapsLogger.error(String.format(Locale.ENGLISH, "MedtronicPumpPlugin::checkTimeAndOptionallySetTime - Time difference over 24h requested [diff=%d s]. Doing nothing.", timeDiff)) - medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.TimeChangeOver24h, rh, rxBus) } } } else { @@ -590,9 +590,9 @@ class MedtronicPumpPlugin @Inject constructor( return PumpEnactResult(injector) // .success(false) // .enacted(false) // - .comment(resourceHelper.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, - medtronicPumpStatus.reservoirRemainingUnits, - detailedBolusInfo.insulin)) + .comment(rh.gs(R.string.medtronic_cmd_bolus_could_not_be_delivered_no_insulin, + medtronicPumpStatus.reservoirRemainingUnits, + detailedBolusInfo.insulin)) } bolusDeliveryType = BolusDeliveryType.DeliveryPrepared if (isPumpNotReachable) { @@ -631,7 +631,7 @@ class MedtronicPumpPlugin @Inject constructor( // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled after Bolus started."); Thread(Runnable { SystemClock.sleep(2000) - runAlarm(context, resourceHelper.gs(R.string.medtronic_cmd_cancel_bolus_not_supported), resourceHelper.gs(R.string.medtronic_warning), R.raw.boluserror) + runAlarm(context, rh.gs(R.string.medtronic_cmd_cancel_bolus_not_supported), rh.gs(R.string.medtronic_warning), R.raw.boluserror) }).start() } val now = System.currentTimeMillis() @@ -1136,7 +1136,7 @@ class MedtronicPumpPlugin @Inject constructor( return PumpEnactResult(injector) // .success(false) // .enacted(false) // - .comment(resourceHelper.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)) + .comment(rh.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid)) } val responseTask = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.SetBasalProfileSTD, arrayListOf(basalProfile)) @@ -1200,7 +1200,7 @@ class MedtronicPumpPlugin @Inject constructor( if (rileyLinkMedtronicService.verifyConfiguration()) { serviceTaskExecutor.startTask(WakeAndTuneTask(injector)) } else { - runAlarm(context, resourceHelper.gs(R.string.medtronic_error_operation_not_possible_no_configuration), resourceHelper.gs(R.string.medtronic_warning), R.raw.boluserror) + runAlarm(context, rh.gs(R.string.medtronic_error_operation_not_possible_no_configuration), rh.gs(R.string.medtronic_warning), R.raw.boluserror) } } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt index 9d51939ed1..1288c9d279 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt @@ -28,7 +28,7 @@ import javax.inject.Singleton class MedtronicUIPostprocessor @Inject constructor( private val aapsLogger: AAPSLogger, private val rxBus: RxBus, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val medtronicUtil: MedtronicUtil, private val medtronicPumpStatus: MedtronicPumpStatus, private val medtronicPumpPlugin: MedtronicPumpPlugin) { @@ -114,7 +114,7 @@ class MedtronicUIPostprocessor @Inject constructor( MedtronicCommandType.PumpModel -> { if (medtronicPumpStatus.medtronicDeviceType !== medtronicUtil.medtronicPumpModel) { aapsLogger.warn(LTag.PUMP, "Configured pump is different then pump detected !") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpTypeNotSame, rh, rxBus) } } @@ -154,12 +154,12 @@ class MedtronicUIPostprocessor @Inject constructor( checkValue = settings["PCFG_BASAL_PROFILES_ENABLED"]!! if ("Yes" != checkValue.value) { aapsLogger.error(LTag.PUMP, "Basal profiles are not enabled on pump.") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpBasalProfilesNotEnabled, rh, rxBus) } else { checkValue = settings["PCFG_ACTIVE_BASAL_PROFILE"]!! if ("STD" != checkValue.value) { aapsLogger.error("Basal profile set on pump is incorrect (must be STD).") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpIncorrectBasalProfileSelected, rh, rxBus) } } } @@ -168,7 +168,7 @@ class MedtronicUIPostprocessor @Inject constructor( if (settings.containsKey("PCFG_TEMP_BASAL_TYPE")) { if ("Units" != settings["PCFG_TEMP_BASAL_TYPE"]!!.value) { aapsLogger.error("Wrong TBR type set on pump (must be Absolute).") - medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongTBRTypeSet, resourceHelper, rxBus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongTBRTypeSet, rh, rxBus) } } @@ -177,7 +177,7 @@ class MedtronicUIPostprocessor @Inject constructor( checkValue = settings["PCFG_MAX_BOLUS"]!! if (!MedtronicUtil.isSame(checkValue.value.toDouble(), medtronicPumpStatus.maxBolus!!)) { aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Wrong Max Bolus set on Pump (current=%s, required=%.2f).", checkValue.value, medtronicPumpStatus.maxBolus)) - medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, resourceHelper, rxBus, medtronicPumpStatus.maxBolus) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBolusSet, rh, rxBus, medtronicPumpStatus.maxBolus) } } @@ -185,7 +185,7 @@ class MedtronicUIPostprocessor @Inject constructor( checkValue = settings["PCFG_MAX_BASAL"]!! if (!MedtronicUtil.isSame(checkValue.value.toDouble(), medtronicPumpStatus.maxBasal!!)) { aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Wrong Max Basal set on Pump (current=%s, required=%.2f).", checkValue.value, medtronicPumpStatus.maxBasal)) - medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, resourceHelper, rxBus, medtronicPumpStatus.maxBasal) + medtronicUtil.sendNotification(MedtronicNotificationType.PumpWrongMaxBasalSet, rh, rxBus, medtronicPumpStatus.maxBasal) } } } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt index 4a99585508..92eee8f170 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt @@ -9,10 +9,10 @@ import org.joda.time.LocalDateTime class RLHistoryItemMedtronic(private val medtronicCommandType: MedtronicCommandType) : RLHistoryItem(LocalDateTime(), RLHistoryItemSource.MedtronicCommand, RileyLinkTargetDevice.MedtronicPump) { - override fun getDescription(resourceHelper: ResourceHelper): String { + override fun getDescription(rh: ResourceHelper): String { return if (RLHistoryItemSource.MedtronicCommand == source) { medtronicCommandType.name - } else super.getDescription(resourceHelper) + } else super.getDescription(rh) } } \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt index 492b5b9ddb..f78bc4ad35 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt @@ -23,7 +23,7 @@ import javax.inject.Inject class MedtronicHistoryActivity : DaggerActivity() { @Inject lateinit var medtronicHistoryData: MedtronicHistoryData - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper lateinit var historyTypeSpinner: Spinner lateinit var statusView: TextView @@ -96,7 +96,7 @@ class MedtronicHistoryActivity : DaggerActivity() { recyclerViewAdapter = RecyclerViewAdapter(filteredHistoryList) recyclerView.adapter = recyclerViewAdapter statusView.visibility = View.GONE - typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(resourceHelper)) + typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(rh)) val spinnerAdapter = ArrayAdapter(this, R.layout.spinner_centered, typeListFull) historyTypeSpinner.adapter = spinnerAdapter historyTypeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt index 499ad6dfb7..0351a4c391 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt @@ -22,7 +22,7 @@ import javax.inject.Singleton * Created by andy on 4/28/18. */ @Singleton -class MedtronicPumpStatus @Inject constructor(private val resourceHelper: ResourceHelper, +class MedtronicPumpStatus @Inject constructor(private val rh: ResourceHelper, private val sp: SP, private val rxBus: RxBus, private val rileyLinkUtil: RileyLinkUtil @@ -107,7 +107,7 @@ class MedtronicPumpStatus @Inject constructor(private val resourceHelper: Resour fun getBatteryTypeByDescription(batteryTypeStr: String?): BatteryType? { if (batteryTypeByDescMap.size == 0) { for (value in BatteryType.values()) { - batteryTypeByDescMap[resourceHelper.gs(value.description)] = value + batteryTypeByDescMap[rh.gs(value.description)] = value } } return if (batteryTypeByDescMap.containsKey(batteryTypeStr)) { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.kt index 30d7f123df..ee88898227 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.kt @@ -69,10 +69,10 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi * If you have customized RileyLinkServiceData you need to override this */ override fun initRileyLinkServiceData() { - frequencies = arrayOf(resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca), - resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide)) - // frequencies[0] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_us_ca) - // frequencies[1] = resourceHelper.gs(R.string.key_medtronic_pump_frequency_worldwide) + frequencies = arrayOf(rh.gs(R.string.key_medtronic_pump_frequency_us_ca), + rh.gs(R.string.key_medtronic_pump_frequency_worldwide)) + // frequencies[0] = rh.gs(R.string.key_medtronic_pump_frequency_us_ca) + // frequencies[1] = rh.gs(R.string.key_medtronic_pump_frequency_worldwide) rileyLinkServiceData.targetDevice = RileyLinkTargetDevice.MedtronicPump setPumpIDString(sp.getString(MedtronicConst.Prefs.PumpSerial, "000000")) @@ -138,11 +138,11 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi medtronicPumpStatus.errorDescription = "-" val serialNr = sp.getStringOrNull(MedtronicConst.Prefs.PumpSerial, null) if (serialNr == null) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_not_set) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_serial_not_set) return false } else { if (!serialNr.matches(regexSN.toRegex())) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_serial_invalid) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_serial_invalid) return false } else { if (serialNr != medtronicPumpStatus.serialNumber) { @@ -153,12 +153,12 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi } val pumpTypePref = sp.getStringOrNull(MedtronicConst.Prefs.PumpType, null) if (pumpTypePref == null) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_not_set) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_pump_type_not_set) return false } else { val pumpTypePart = pumpTypePref.substring(0, 3) if (!pumpTypePart.matches("[0-9]{3}".toRegex())) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_type_invalid) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_pump_type_invalid) return false } else { val pumpType = medtronicPumpStatus.medtronicPumpMap[pumpTypePart]!! @@ -170,11 +170,11 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi } val pumpFrequency = sp.getStringOrNull(MedtronicConst.Prefs.PumpFrequency, null) if (pumpFrequency == null) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_not_set) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_pump_frequency_not_set) return false } else { if (pumpFrequency != frequencies[0] && pumpFrequency != frequencies[1]) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_pump_frequency_invalid) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_pump_frequency_invalid) return false } else { medtronicPumpStatus.pumpFrequency = pumpFrequency @@ -189,11 +189,11 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi val rileyLinkAddress = sp.getStringOrNull(RileyLinkConst.Prefs.RileyLinkAddress, null) if (rileyLinkAddress == null) { aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: null") - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_rileylink_address_invalid) return false } else { if (!rileyLinkAddress.matches(regexMac.toRegex())) { - medtronicPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid) + medtronicPumpStatus.errorDescription = rh.gs(R.string.medtronic_error_rileylink_address_invalid) aapsLogger.debug(LTag.PUMP, "RileyLink address invalid: %s", rileyLinkAddress) } else { if (rileyLinkAddress != this.rileyLinkAddress) { @@ -216,7 +216,7 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi } val encodingTypeStr = sp.getStringOrNull(MedtronicConst.Prefs.Encoding, null) ?: return false - val newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr, resourceHelper) + val newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr, rh) if (encodingType == null) { encodingType = newEncodingType } else if (encodingType != newEncodingType) { @@ -231,7 +231,7 @@ class RileyLinkMedtronicService // This empty constructor must be kept, otherwi } //String bolusDebugEnabled = sp.getStringOrNull(MedtronicConst.Prefs.BolusDebugEnabled, null); - //boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(resourceHelper.gs(R.string.common_on)); + //boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(rh.gs(R.string.common_on)); //MedtronicHistoryData.doubleBolusDebug = bolusDebug; rileyLinkServiceData.showBatteryLevel = sp.getBoolean(RileyLinkConst.Prefs.ShowBatteryLevel, false) reconfigureService(forceRileyLinkAddressRenewal) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt index f057b47228..612c63f4d2 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt @@ -93,18 +93,18 @@ class MedtronicUtil @Inject constructor( return ByteUtil.concat(input.size.toByte(), input) } - fun sendNotification(notificationType: MedtronicNotificationType, resourceHelper: ResourceHelper, rxBus: RxBus) { + fun sendNotification(notificationType: MedtronicNotificationType, rh: ResourceHelper, rxBus: RxBus) { val notification = Notification( // notificationType.notificationType, // - resourceHelper.gs(notificationType.resourceId), // + rh.gs(notificationType.resourceId), // notificationType.notificationUrgency) rxBus.send(EventNewNotification(notification)) } - fun sendNotification(notificationType: MedtronicNotificationType, resourceHelper: ResourceHelper, rxBus: RxBus, vararg parameters: Any?) { + fun sendNotification(notificationType: MedtronicNotificationType, rh: ResourceHelper, rxBus: RxBus, vararg parameters: Any?) { val notification = Notification( // notificationType.notificationType, // - resourceHelper.gs(notificationType.resourceId, *parameters), // + rh.gs(notificationType.resourceId, *parameters), // notificationType.notificationUrgency) rxBus.send(EventNewNotification(notification)) } diff --git a/medtronic/src/main/res/values-bg-rBG/strings.xml b/medtronic/src/main/res/values-bg-rBG/strings.xml index fcb54883c4..0bc2bcc785 100644 --- a/medtronic/src/main/res/values-bg-rBG/strings.xml +++ b/medtronic/src/main/res/values-bg-rBG/strings.xml @@ -25,6 +25,7 @@ NiMH (батерия) Болус/Корекция подробно + Батерия на RileyLink Грешки Сериен номер не е зададен. diff --git a/medtronic/src/main/res/values-hu-rHU/strings.xml b/medtronic/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..7dd05e5965 --- /dev/null +++ b/medtronic/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/medtronic/src/main/res/values-tr-rTR/strings.xml b/medtronic/src/main/res/values-tr-rTR/strings.xml index 9e838d9313..b6cbb0dd8e 100644 --- a/medtronic/src/main/res/values-tr-rTR/strings.xml +++ b/medtronic/src/main/res/values-tr-rTR/strings.xml @@ -1,9 +1,48 @@ + Medtronic için pompa entegrasyonu, RileyLink cihazı ve özel Pompa Modeli gerektirir + Pompa Seri Numarası + Pompa Tipi + Pompa Frekansı + Bolus göndermeden önceki bekleme süresi (sn) + Pompadaki Maks Bolus (U) + Pompadaki Maks Bazal (Ü/s) + Medtronic Kodlama + ABD & Kanada (916 MHz) + Dünya geneli (868 Mhz) + Yazılım 4b6b Kodlama + Donanım 4b6b Kodlama + Uyan ve Ayarla + Bolus Bloğunu Temizle + RileyLink Yapılandırmasını Sıfırla + Pil Türü (Güç Görünümü) + Seçilmedi (Basit görünüm) + Alkali (Genişletilmiş görünüm) + Lityum (Genişletilmiş görünüm) + NiZn (Genişletilmiş görünüm) + NiMH (Genişletilmiş görünüm) + Bolus/Tedavilerde Hata Ayıklama + RileyLink Pili + Hatalar + Seri no # ayarlanmadı. + Seri no # geçersiz. + Pompa Tipi ayarlanmadı. + Pompa Tipi desteklenmiyor. + Pompa Frekansı ayarlanmadı. + Pompa Frekansı desteklenmiyor. + RileyLink Adresi geçersiz. + Algılanan pompa tipi, yapılandırılmış tiple aynı değil. + Bazal profiller/şablon ayarı pompada etkinleştirilmemiştir. Pompada etkinleştirin. + Pompada ayarlanan bazal profili yanlış (STD olmalıdır). + Pompada yanlış TBR (geçici bazal oranı) tipi ayarlanmış (Mutlak olmalıdır). + Pompada Yanlış Maksimum Bolus ayarlanmış (%1$.2f olmalıdır). + Pompada Yanlış Maksimum Bazal ayarlanmış (%1$.2f olmalıdır). + Çalıştırmak mümkün değil.\n\n Bu işlemi kullanmadan önce Medtronic Pompayı yapılandırmanız gerekir. + 24 saatten fazla zaman değişikliği istendi. @@ -11,9 +50,44 @@ + Medtronic Pompa Geçmişi + Pompa üzerinde ayarlandıktan sonra Bolus\'u iptal ettiniz. Medtronic Pompa iptali desteklemediğinden, elle iptal etmeniz gerekecektir. Pompayı Askıya Al moduna getirin ve ardından Devam et\'e basın. (yine de iptal etmek istiyorsanız). Uygulama, bir sonraki güncellemede (5 dakikadan daha kısa sürede) değişiklikleri alacaktır. + Mevcut TBR (geçici bazal oranı) okunamadı. + Mevcut TBR (geçici bazal oranı) iptal edilemedi. İşlem durduruldu. + Profil kümesi başarısız oldu, çünkü aşağıdaki şablonlar çok büyük bazal orana sahip: %1$s + Bolus gönderilemedi. + Bolus gönderilemedi, çünkü mevcut insülin miktarı (%1$.2f) gereken bolustan (%2$.2f) az. + TBR (geçici bazal oranı) ayarlanamadı. + Mevcut TBR (geçici bazal oranı) iptal edilemedi. + Bazal profil ayarlanamadı. + Bazal profil aynı olduğu için tekrar ayarlanmayacaktır. + Geçmiş Alınıyor - Sayfa %1$d (%2$d/16) + Geçmiş Alınıyor - Sayfa %1$d + Pompa zamanı alınıyor + Pompa Zamanını Ayarla + Pil Durumu alınıyor + Ayarlar alınıyor + Pompa Modeli alınıyor + Bazal Profili alınıyor + Bazal Profili Ayarla + Geçici Bazal alınıyor + Geçici Bazalı Ayarla + Geçici Bazal İptal Et + Bolusu Ayarla + Kalan İnsülin alınıyor + Pompa\'ya ulaşılamıyor + Uyarı + Şimdi + önce + Pompa saati güncellemesi gerekli + + Kapa Pompa zamanı güncellendi + Sık kullanılan Geçici Bazalları ayarla + Etkinleştirilirse, her saatin sonunda geçici bazali iptal eder. Bu yöntem, bazı pompaların saatte bip sesini/titremesini durdurmaya yardımcı olabilir. + %1$.1f U/sa (%2$d dk. kaldı) diff --git a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt index 9bf24ac19e..081d8f78cc 100644 --- a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt +++ b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt @@ -26,7 +26,7 @@ import org.mockito.Mock class MedtronicPumpHistoryDecoderUTest : TestBase() { @Mock lateinit var injector: HasAndroidInjector - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var activePlugin: ActivePlugin @Mock lateinit var rileyLinkUtil: RileyLinkUtil @Mock lateinit var sp: SP @@ -37,7 +37,7 @@ class MedtronicPumpHistoryDecoderUTest : TestBase() { var rxBusWrapper = RxBus(TestAapsSchedulers(), aapsLogger) @Before fun setup() { medtronicPumpStatus = - MedtronicPumpStatus(resourceHelper, sp, rxBusWrapper, rileyLinkUtil) + MedtronicPumpStatus(rh, sp, rxBusWrapper, rileyLinkUtil) medtronicUtil = MedtronicUtil(aapsLogger, rxBusWrapper, rileyLinkUtil, medtronicPumpStatus!!) decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil!!, ByteUtil()) diff --git a/omnipod-common/src/main/res/values-bg-rBG/strings.xml b/omnipod-common/src/main/res/values-bg-rBG/strings.xml index e35fcaa95a..a03088237f 100644 --- a/omnipod-common/src/main/res/values-bg-rBG/strings.xml +++ b/omnipod-common/src/main/res/values-bg-rBG/strings.xml @@ -2,6 +2,14 @@ + Управление на Pod + Действия + Инструменти + Активирай Pod + Деактивирай под + Премахни Pod + Ако натиснете OK, състоянието на Pod ще бъде нулирано и няма да можете да общувате с него повече. Правете това, само ако вече не можете да се свързвате с него. Ако все още можете да общувате с Pod, моля, използвайте опцията Деактивирай Pod! + Възпроизвеждане на тестов звук diff --git a/omnipod-common/src/main/res/values-hu-rHU/strings.xml b/omnipod-common/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..e35fcaa95a --- /dev/null +++ b/omnipod-common/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/omnipod-common/src/main/res/values-tr-rTR/strings.xml b/omnipod-common/src/main/res/values-tr-rTR/strings.xml index e35fcaa95a..4671b48f00 100644 --- a/omnipod-common/src/main/res/values-tr-rTR/strings.xml +++ b/omnipod-common/src/main/res/values-tr-rTR/strings.xml @@ -2,17 +2,194 @@ + Pod Yönetimi + Eylemler + Araçlar + Pod Etkinleştir + Pod\'u Devre Dışı Bırak + Pod\'u Çıkart + Pod\'u çıkartırsanız, artık onunla iletişim kuramazsınız. Bunu yalnızca Pod ile tüm iletişim sürekli olarak başarısız olduğunda yapmalısınız. Hala Pod ile iletişim kurabiliyorsanız, lütfen Pod\'u Devre Dışı Bırak seçeneğini kullanın.\n\nDevam etmek istiyorsanız, lütfen Pod\'u vücudunuzdan çıkardığınızdan emin olun! + Test Bip Sesi Çal + Test Bip Sesi Çalınıyor… + Pod Geçmişi + Aktif Pod Yok + Bazal profil ayarlanamadı. + Bolus başarılı olmadı. + Bazal profil ayarlanamadı: boş bir profil alındı. Bazal profilinizi etkinleştirdiğinizden emin olun. + Hiçbir bazal profil aktif değil. Bazal profilinizi etkinleştirdiğinizden emin olun. + Desteklenmeyen özel komut: %1$s + Yenileme Hatası + Başlangıçta yenileme hatası + Uyarılar susturulamadı + İletim durdurulamadı + Zaman ayarlanamadı + İletim devam ettirilemedi + Pod başlatılamadı + Kanül yerleştirmede hata + Pod\'un etkinleştirme süresi aşıldı. Bu Pod artık etkinleştirilemez. + Etkinleştirme ilerleme doğrulanamadı. Lütfen tekrar deneyiniz. + Pod askıya alındı + Test bip sesi çalınamadı + Pod\'daki saat senkronize değil. Lütfen Omnipod sekmesindeki saati güncelleyin. + Beklenmedik bir hata oluştu. Lütfen raporlayın! (%1$s: %2$s). + Onaylama + Pod saat ve/veya saat dilimi değişti. + Pod alarm yapılandırması güncellendi. + Pod saati güncellendi. + Tüm insülin iletimi durduruldu. + Etkin alarmlar susturuldu. + İnsülin iletimi yeniden başlatıldı. + Saati ayarla + Askıya alınan + İletime devam et + Pod Yntm + Alarmları Sustur + Pod Durumu + Toplam İletilen + %1$.2f U + Özgün kimlik + Parti Numarası + Sıra Numarası + Pod Sona Erme + Son Bağlantı + Son Bolus + Geçici Bazal Oranı + Bazal Oranı + Rezervuar + Etkin Pod Alarmları + Firmware versiyonu + Pod üzerindeki zaman + %1$.2fÜ/s @%2$s (%3$d/%4$d dakika) + %1$.2f Ü kaldı + 50 Ü üzeri + Hatalar + İptal + Bitti + Sonraki + Tekrar dene + Pod\'u Devre Dışı Bırak + Pod\'u Çıkart + Henüz tüm adımları tamamlamadınız. Çıkmak istediğinize emin misin? + Çıkış + Podu Doldur + Pod\'u Başlat + Pod\'u Ekle + İnfüzyon bölgesini hazırlayın. Pod\'un iğne kapağını ve yapışkan desteğini çıkarın ve Pod\'u infüzyon bölgesine takın.\n\nKanül dışarı çıkarsa, lütfen İptal\'e basın ve Pod\'unuzu atın.\n\nKanülü yerleştirmek ve bazal iletimini başlatmak için İleri\'ye basın. + Tamam\'a bastığınızda kanül yerleştirilecektir. Pod\'u infüzyon bölgenize taktığınızdan emin olun. + Kanül Yerleştir + Başlangıç bazal programını ayarlanacak ve kanül yerleştirilecek\n\nKanül başarıyla yerleştirildiğinde, İleri\'ye basabilirsiniz. + Pod Etkinleştirildi + Yeni Pod artık aktif.\n\nBazal planınız programlandı ve kanül yerleştirildi.\n\nLütfen kanülün doğru şekilde takıldığından emin olun. Düzgün takılmadığını düşünüyorsanız Pod\'unuzu değiştirin. + Pod\'u Devre Dışı Bırak + Pod\'u devre dışı bırakmak için İleri\'ye basın.\n\nNot: Bu, tüm insülin iletimini askıya alacak ve Pod\'u devre dışı bırakacaktır. + Pod Devre dışı bırakılıyor + Pod devre dışı bırakılıyor.\n\nDevre dışı bırakma başarıyla tamamlandığında, İleri\'ye basabilirsiniz. + Pod Devre dışı bırakıldı + Pod\'unuz devre dışı bırakıldı.\n\nLütfen Pod\'u vücudunuzdan çıkarın ve geri dönüşüme atın. + Pod Çıkarıldı + Pod durumu \"çıkarıldı\". Pod düzgün devre dışı bırakılmadığı için insülin iletimi askıya alınmadı!\n\nLütfen Podu vücudunuzdan çıkarın ve geri dönüşüme atın. + Pod\'u çıkartırsanız, artık onunla iletişim kuramazsınız. Bunu yalnızca Pod ile tüm iletişim sürekli olarak başarısız olduğunda yapmalısınız. Pod\'u çıkartmak istediğinizden emin misiniz? + Pod\'u Çıkart + Bolus bip sesleri etkinleştirildi + Bazal bip sesleri etkinleştirildi + SMB bip sesleri etkinleştirildi + GBO (TBR) bip sesleri etkinleştirildi + Omnipod sekmesinde İletimi Askıya Al düğmesini göster + DST/Saat dilimi algılama etkinleştirildi + Süre sonu hatırlatıcısı etkinleştirildi + Kapanmadan saatler önce + Düşük rezervuar uyarısı etkinleştirildi + Ünite + Pod uyarılarını otomatik olarak sustur + Diğer + Alarmlar + Onay Bipleri + Bildirimler + Belirsiz GBO(TBR) bildirimleri için ses etkinleştirildi + Belirsiz SMB bildirimleri için ses etkinleştirildi + Belirsiz bolus bildirimleri için ses etkinleştirildi + Aktif Pod Yok + Kurulum devam ediyor (Pod aktivasyonu bekleniyor) + Kurulum devam ediyor (kanül yerleştirme bekleniyor) + Çalışıyor + Askıya Alındı + Pod Hatası + Aktivasyon süresi aşıldı + İnaktif + Pod Hatası: %1$03d %2$s + Pod\'u Devre Dışı Bırak + Pod\'u Çıkart + Bolusu Ayarla + Bolusu İptal Et + Geçici Bazalı Ayarla + Geçici Bazal\'i İptal Et (dahili olarak sürücü tarafından) + Geçici Bazalı İptal Et + Bazal Planı Ayarla + Pod Durumu + Pod Bilgisi + Saati Ayarla + Alarmları Yapılandır + Sessiz Alarmlar + İletimi Askıya Al + İletime devam et + Bilinmeyen Giriş + Pod\'u Başlat + Kanül Yerleştir + Nabız Kaydını Oku + Pod askıya alındığından sahte geçici bazal ayarlayın + Sahte geçici bazalı iptal edin + İptaldeki belirsiz başarısızlık nedeniyle geçici bazal bölünmüş + Bip Yapılandırması + Test Bip Sesi Çal + Eşleştirme hatırlatıcısını bitir + Kurulum hatırlatıcısını bitir + Pod yakında sona erecek + Pod yakında sona erecek + Her an kapanabilir + Düşük Rezervuar + Bilinmeyen Alarm + Aktif Pod Yok + Son bağl: %1$d dak. önce + SonBolus: %1$s @ %2$s + Geçici: %1$s + Yayma: %1$s + Rezerv: %1$sU + Evet + Hayır + Tamam + İptal + Uyarı + Dakika önce + Bir dakikadan az bir süre önce + %1$s ve %2$s + %1$s dak önce + + %1$d dakika + %1$d dakika + + + %1$d saat + %1$d saat + + + %1$d gün + %1$d gün + + + Pod Alarmı: %1$s + Pod Alarmları: %1$s + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index 4db2aa2bc1..ce3a4a3e7b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -85,9 +85,9 @@ class OmnipodDashPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, - commandQueue: CommandQueueProvider -) : PumpPluginBase(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue), Pump { + rh: ResourceHelper, + commandQueue: CommandQueue +) : PumpPluginBase(pluginDescription, injector, aapsLogger, rh, commandQueue), Pump { @Volatile var bolusCanceled = false @Volatile var bolusDeliveryInProgress = false @@ -310,8 +310,8 @@ class OmnipodDashPumpPlugin @Inject constructor( ) private fun checkPodKaput(): Completable = Completable.defer { - val tbr = pumpSync.expectedPumpState().temporaryBasal if (podStateManager.isPodKaput) { + val tbr = pumpSync.expectedPumpState().temporaryBasal if (tbr == null || tbr.rate != 0.0) { pumpSync.syncTemporaryBasalWithPumpId( timestamp = System.currentTimeMillis(), @@ -340,20 +340,23 @@ class OmnipodDashPumpPlugin @Inject constructor( aapsLogger.info(LTag.PUMP, "syncBolusWithPumpId on CANCEL_BOLUS returned: $sync") } } - showNotification( - Notification.OMNIPOD_POD_FAULT, - podStateManager.alarmType.toString(), - Notification.URGENT, - R.raw.boluserror - ) - if (!podStateManager.alarmSynced) { - pumpSync.insertAnnouncement( - error = podStateManager.alarmType?.toString() ?: "Unknown pod failure", - pumpId = Random.Default.nextLong(), - pumpType = PumpType.OMNIPOD_DASH, - pumpSerial = serialNumber() + + podStateManager.alarmType?.let { + showNotification( + Notification.OMNIPOD_POD_FAULT, + it.toString(), + Notification.URGENT, + R.raw.boluserror ) - podStateManager.alarmSynced = true + if (!podStateManager.alarmSynced) { + pumpSync.insertAnnouncement( + error = it.toString(), + pumpId = Random.Default.nextLong(), + pumpType = PumpType.OMNIPOD_DASH, + pumpSerial = serialNumber() + ) + podStateManager.alarmSynced = true + } } } Completable.complete() @@ -454,19 +457,19 @@ class OmnipodDashPumpPlugin @Inject constructor( .subscribe( { if (it.isChanged( - resourceHelper, + rh, R.string.key_omnipod_common_expiration_reminder_enabled ) || it.isChanged( - resourceHelper, + rh, R.string.key_omnipod_common_expiration_reminder_hours_before_shutdown ) || it.isChanged( - resourceHelper, + rh, R.string.key_omnipod_common_low_reservoir_alert_enabled ) || it.isChanged( - resourceHelper, + rh, R.string.key_omnipod_common_low_reservoir_alert_units ) ) { @@ -622,15 +625,20 @@ class OmnipodDashPumpPlugin @Inject constructor( ) } } - }.toSingleDefault( + }.toSingle { PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(deliveredBolusAmount) + }.onErrorReturnItem( + // success if canceled + PumpEnactResult(injector).success(bolusCanceled).enacted(false) ) - .onErrorReturnItem( - // success if canceled - PumpEnactResult(injector).success(bolusCanceled).enacted(false) - ) .blockingGet() - aapsLogger.info(LTag.PUMP, "deliverTreatment result: $ret") + aapsLogger.info( + LTag.PUMP, + "deliverTreatment result: $ret. " + + "deliveredBolusAmount=$deliveredBolusAmount. " + + "ret bolus=${ret.bolusDelivered}" + + "bolusCanceled=$bolusCanceled" + ) return ret } finally { bolusCanceled = false @@ -686,7 +694,7 @@ class OmnipodDashPumpPlugin @Inject constructor( } val percent = (waited.toFloat() / estimatedDeliveryTimeSeconds) * 100 updateBolusProgressDialog( - resourceHelper.gs(R.string.bolusdelivering, requestedBolusAmount), + rh.gs(R.string.bolusdelivering, requestedBolusAmount), percent.toInt() ) } @@ -712,7 +720,7 @@ class OmnipodDashPumpPlugin @Inject constructor( val remainingUnits = podStateManager.lastBolus!!.bolusUnitsRemaining val percent = ((requestedBolusAmount - remainingUnits) / requestedBolusAmount) * 100 updateBolusProgressDialog( - resourceHelper.gs(R.string.bolusdelivering, requestedBolusAmount), + rh.gs(R.string.bolusdelivering, requestedBolusAmount), percent.toInt() ) @@ -1025,28 +1033,28 @@ class OmnipodDashPumpPlugin @Inject constructor( override fun shortStatus(veryShort: Boolean): String { if (!podStateManager.isActivationCompleted) { - return resourceHelper.gs(R.string.omnipod_common_short_status_no_active_pod) + return rh.gs(R.string.omnipod_common_short_status_no_active_pod) } var ret = "" if (podStateManager.lastUpdatedSystem != 0L) { val agoMsec: Long = System.currentTimeMillis() - podStateManager.lastUpdatedSystem val agoMin = (agoMsec / 60.0 / 1000.0).toInt() - ret += resourceHelper.gs(R.string.omnipod_common_short_status_last_connection, agoMin) + "\n" + ret += rh.gs(R.string.omnipod_common_short_status_last_connection, agoMin) + "\n" } podStateManager.lastBolus?.run { - ret += resourceHelper.gs( + ret += rh.gs( R.string.omnipod_common_short_status_last_bolus, to2Decimal(this.deliveredUnits() ?: this.requestedUnits), DateFormat.format("HH:mm", Date(this.startTime)) ) + "\n" } val temporaryBasal = pumpSync.expectedPumpState().temporaryBasal temporaryBasal?.run { - ret += resourceHelper.gs( + ret += rh.gs( R.string.omnipod_common_short_status_temp_basal, this.toStringFull(dateUtil) ) + "\n" } - ret += resourceHelper.gs( + ret += rh.gs( R.string.omnipod_common_short_status_reservoir, podStateManager.pulsesRemaining?.let { reservoirLevel.toString() } ?: "50+" ) @@ -1094,7 +1102,7 @@ class OmnipodDashPumpPlugin @Inject constructor( else -> { aapsLogger.warn(LTag.PUMP, "Unsupported custom command: " + customCommand.javaClass.name) PumpEnactResult(injector).success(false).enacted(false).comment( - resourceHelper.gs( + rh.gs( R.string.omnipod_common_error_unsupported_custom_command, customCommand.javaClass.name ) @@ -1165,14 +1173,14 @@ class OmnipodDashPumpPlugin @Inject constructor( val ret = executeProgrammingCommand( historyEntry = history.createRecord(OmnipodCommandType.DEACTIVATE_POD), command = omnipodManager.deactivatePod().ignoreElements(), - checkNoActiveCommand = false, - post = createFakeTBRWhenNoActivePod(), + checkNoActiveCommand = false ).doOnComplete { if (podStateManager.activeCommand != null) { success = false + } else { + podStateManager.reset() + rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_FAULT)) } - podStateManager.reset() - rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_FAULT)) }.toPumpEnactResult() if (!success) { ret.success(false) @@ -1193,14 +1201,20 @@ class OmnipodDashPumpPlugin @Inject constructor( val lowReservoirAlertEnabled = sp.getBoolean(R.string.key_omnipod_common_low_reservoir_alert_enabled, true) val lowReservoirAlertUnits = sp.getInt(R.string.key_omnipod_common_low_reservoir_alert_units, 10) - if (podStateManager.sameAlertSettings( + when { + podStateManager.sameAlertSettings( expirationReminderEnabled, expirationHours, lowReservoirAlertEnabled, lowReservoirAlertUnits - ) - ) { - return PumpEnactResult(injector).success(true).enacted(false) + ) -> { + aapsLogger.debug(LTag.PUMP, "Ignoring updateAlertConfiguration because the settings did not change") + return PumpEnactResult(injector).success(true).enacted(false) + } + !podStateManager.isPodRunning -> { + aapsLogger.debug(LTag.PUMP, "Ignoring updateAlertConfiguration because there is no active pod") + return PumpEnactResult(injector).success(true).enacted(false) + } } val podLifeLeft = Duration.between(ZonedDateTime.now(), podStateManager.expiry) @@ -1472,7 +1486,7 @@ class OmnipodDashPumpPlugin @Inject constructor( } private fun showErrorDialog(message: String, sound: Int) { - runAlarm(context, message, resourceHelper.gs(R.string.error), sound) + runAlarm(context, message, rh.gs(R.string.error), sound) } private fun showNotification(id: Int, message: String, urgency: Int, sound: Int?) { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodHistoryActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodHistoryActivity.kt index 8cece0c509..ff04fa5b91 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodHistoryActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodHistoryActivity.kt @@ -97,6 +97,7 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { PumpHistoryEntryGroup.Unknown } } + private fun filterHistory(group: PumpHistoryEntryGroup) { filteredHistoryList.clear() aapsLogger.debug(LTag.PUMP, "Items on full list: {}", fullHistoryList.size) @@ -152,12 +153,12 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { statusView?.run { visibility = View.GONE } historyTypeSpinner = findViewById(R.id.omnipod_historytype) - typeListFull = getTypeList(PumpHistoryEntryGroup.Companion.getTranslatedList(resourceHelper)) + typeListFull = getTypeList(PumpHistoryEntryGroup.Companion.getTranslatedList(rh)) val spinnerAdapter: ArrayAdapter = ArrayAdapter(this, R.layout.spinner_centered, typeListFull!!) historyTypeSpinner?.run { adapter = spinnerAdapter onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (manualChange) return val selected = selectedItem as TypeList selectedGroup = selected.entryGroup @@ -208,30 +209,72 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { } } + private fun setTextViewColor(check_result: Boolean, textview: TextView, record: HistoryRecord) { + if (check_result && !record.isSuccess()) { + // Record says not success + textview.setTextColor(android.graphics.Color.YELLOW) + return + } + // On success set color + val textColor = when (record.commandType) { + // Operational + OmnipodCommandType.INITIALIZE_POD, + OmnipodCommandType.CONFIGURE_ALERTS, + OmnipodCommandType.INSERT_CANNULA, + OmnipodCommandType.DEACTIVATE_POD, + OmnipodCommandType.DISCARD_POD, + OmnipodCommandType.SUSPEND_DELIVERY, + OmnipodCommandType.RESUME_DELIVERY, + OmnipodCommandType.SET_BASAL_PROFILE -> { + android.graphics.Color.CYAN + } + // User action + OmnipodCommandType.PLAY_TEST_BEEP, + OmnipodCommandType.ACKNOWLEDGE_ALERTS, + OmnipodCommandType.CANCEL_BOLUS -> { + android.graphics.Color.GREEN + } + // Insulin treatment + OmnipodCommandType.SET_BOLUS, + OmnipodCommandType.SET_TEMPORARY_BASAL -> { + android.graphics.Color.WHITE + } + + else -> + // Other + android.graphics.Color.LTGRAY + } + textview.setTextColor(textColor) + } + private fun setType(record: HistoryRecord, typeView: TextView) { - typeView.text = resourceHelper.gs(record.commandType.resourceId) + typeView.text = rh.gs(record.commandType.resourceId) + // Set some color, include result + setTextViewColor(check_result = true, typeView, record) } private fun setValue(historyEntry: HistoryRecord, valueView: TextView) { valueView.text = historyEntry.toString() // val entryType = historyEntry.commandType if (!historyEntry.isSuccess()) { - valueView.text = resourceHelper.gs(translatedFailure(historyEntry)) + valueView.text = rh.gs(translatedFailure(historyEntry)) return } valueView.text = when (historyEntry.commandType) { OmnipodCommandType.SET_TEMPORARY_BASAL -> { val tbr = historyEntry.record as TempBasalRecord tbr.let { - resourceHelper.gs(R.string.omnipod_common_history_tbr_value, it.rate, it.duration) + rh.gs(R.string.omnipod_common_history_tbr_value, it.rate, it.duration) } } + OmnipodCommandType.SET_BOLUS -> { val bolus = historyEntry.record as BolusRecord bolus.let { - resourceHelper.gs(R.string.omnipod_common_history_bolus_value, it.amout) + rh.gs(R.string.omnipod_common_history_bolus_value, it.amout) } } + OmnipodCommandType.SET_BASAL_PROFILE, OmnipodCommandType.SET_TIME, OmnipodCommandType.INSERT_CANNULA, @@ -239,9 +282,12 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { val basal = historyEntry.record as BasalValuesRecord ProfileUtil.getBasalProfilesDisplayable(basal.segments.toTypedArray(), PumpType.OMNIPOD_DASH) } + else -> "" } + // Set some color + setTextViewColor(check_result = false, valueView, historyEntry) } override fun getItemCount(): Int { @@ -249,6 +295,7 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { } inner class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { + val timeView: TextView = itemView.findViewById(R.id.omnipod_history_time) val typeView: TextView = itemView.findViewById(R.id.omnipod_history_source) val valueView: TextView = itemView.findViewById(R.id.omnipod_history_description) @@ -270,6 +317,7 @@ class DashPodHistoryActivity : NoSplashAppCompatActivity() { } companion object { + private var selectedGroup: PumpHistoryEntryGroup = PumpHistoryEntryGroup.All const val DAYS_TO_DISPLAY = 5 } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt index c2bb6240ea..f29988232e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt @@ -7,7 +7,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.extensions.toVisibility -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandPlayTestBeep import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.PodActivationWizardActivity @@ -30,7 +30,7 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var context: Context @Inject lateinit var aapsSchedulers: AapsSchedulers @@ -66,7 +66,7 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { binding.buttonDiscardPod.setOnClickListener { OKDialog.showConfirmation( this, - resourceHelper.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), + rh.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), Thread { podStateManager.reset() } @@ -83,10 +83,10 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { override fun run() { if (!result.success) { displayErrorDialog( - resourceHelper.gs(R.string.omnipod_common_warning), - resourceHelper.gs( + rh.gs(R.string.omnipod_common_warning), + rh.gs( R.string.omnipod_common_two_strings_concatenated_by_colon, - resourceHelper.gs(R.string.omnipod_common_error_failed_to_play_test_beep), + rh.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment ), false diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt index e74f87396e..4703b82d0c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPumpStatusChanged -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification @@ -57,9 +57,9 @@ import kotlin.collections.ArrayList class OmnipodDashOverviewFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var omnipodDashPumpPlugin: OmnipodDashPumpPlugin @Inject lateinit var podStateManager: OmnipodDashPodStateManager @Inject lateinit var sp: SP @@ -119,9 +119,9 @@ class OmnipodDashOverviewFragment : DaggerFragment() { commandQueue.customCommand( CommandResumeDelivery(), DisplayResultDialogCallback( - resourceHelper.gs(R.string.omnipod_common_error_failed_to_resume_delivery), + rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true - ).messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_delivery_resumed)) + ).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed)) ) } @@ -130,7 +130,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { commandQueue.readStatus( "REQUESTED BY USER", DisplayResultDialogCallback( - resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status), + rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false ) ) @@ -141,10 +141,10 @@ class OmnipodDashOverviewFragment : DaggerFragment() { commandQueue.customCommand( CommandSilenceAlerts(), DisplayResultDialogCallback( - resourceHelper.gs(R.string.omnipod_common_error_failed_to_silence_alerts), + rh.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false ) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_silenced_alerts)) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_silenced_alerts)) .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) } ) } @@ -154,10 +154,10 @@ class OmnipodDashOverviewFragment : DaggerFragment() { commandQueue.customCommand( CommandSuspendDelivery(), DisplayResultDialogCallback( - resourceHelper.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), + rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true ) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_suspended_delivery)) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery)) ) } @@ -165,8 +165,8 @@ class OmnipodDashOverviewFragment : DaggerFragment() { disablePodActionButtons() commandQueue.customCommand( CommandHandleTimeChange(true), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_set_time), true) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated)) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated)) ) } if (buildHelper.isEngineeringMode()) { @@ -245,7 +245,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { } private fun updateBluetoothConnectionStatus(event: EventPumpStatusChanged) { - var status = event.getStatus(resourceHelper) + var status = event.getStatus(rh) bluetoothStatusBinding.omnipodDashBluetoothStatus.text = status } @@ -297,7 +297,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { podInfoBinding.uniqueId.text = podStateManager.uniqueId.toString() podInfoBinding.podLot.text = podStateManager.lotNumber.toString() podInfoBinding.podSequenceNumber.text = podStateManager.podSequenceNumber.toString() - podInfoBinding.firmwareVersion.text = resourceHelper.gs( + podInfoBinding.firmwareVersion.text = rh.gs( R.string.omnipod_dash_overview_firmware_version_value, podStateManager.firmwareVersion.toString(), podStateManager.bluetoothVersion.toString() @@ -305,7 +305,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { // Update time on Pod podInfoBinding.timeOnPod.text = podStateManager.time?.let { - resourceHelper.gs( + rh.gs( R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(it.toEpochSecond() * 1000), podStateManager.timeZone.getDisplayName(true, TimeZone.SHORT) @@ -347,7 +347,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { podStateManager.alarmType?.let { errors.add( - resourceHelper.gs( + rh.gs( R.string.omnipod_common_pod_status_pod_fault_description, it.value, it.toString() @@ -358,7 +358,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { // base basal rate podInfoBinding.baseBasalRate.text = if (podStateManager.basalProgram != null && !podStateManager.isSuspended) { - resourceHelper.gs( + rh.gs( R.string.pump_basebasalrate, omnipodDashPumpPlugin.model() .determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(Date())) @@ -370,7 +370,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { // total delivered podInfoBinding.totalDelivered.text = if (podStateManager.isActivationCompleted && podStateManager.pulsesDelivered != null) { - resourceHelper.gs( + rh.gs( R.string.omnipod_common_overview_total_delivered_value, (podStateManager.pulsesDelivered!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) @@ -381,7 +381,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { // reservoir if (podStateManager.pulsesRemaining == null) { podInfoBinding.reservoir.text = - resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value_over50) + rh.gs(R.string.omnipod_common_overview_reservoir_value_over50) podInfoBinding.reservoir.setTextColor(Color.WHITE) } else { // TODO @@ -389,7 +389,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { // ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() val lowReservoirThreshold: Short = PodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD - podInfoBinding.reservoir.text = resourceHelper.gs( + podInfoBinding.reservoir.text = rh.gs( R.string.omnipod_common_overview_reservoir_value, (podStateManager.pulsesRemaining!! * PodConstants.POD_PULSE_BOLUS_UNITS) ) @@ -431,7 +431,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { else -> R.string.omnipod_common_alert_unknown_alert } - return resourceHelper.gs(id) + return rh.gs(id) } private fun updateLastConnection() { @@ -458,29 +458,29 @@ class OmnipodDashOverviewFragment : DaggerFragment() { private fun updatePodStatus() { podInfoBinding.podStatus.text = if (podStateManager.activationProgress == ActivationProgress.NOT_STARTED) { - resourceHelper.gs(R.string.omnipod_common_pod_status_no_active_pod) + rh.gs(R.string.omnipod_common_pod_status_no_active_pod) } else if (!podStateManager.isActivationCompleted) { if (!podStateManager.isUniqueIdSet) { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) } } } else { if (podStateManager.podStatus!!.isRunning()) { if (podStateManager.isSuspended) { - resourceHelper.gs(R.string.omnipod_common_pod_status_suspended) + rh.gs(R.string.omnipod_common_pod_status_suspended) } else { - resourceHelper.gs(R.string.omnipod_common_pod_status_running) + rh.gs(R.string.omnipod_common_pod_status_running) } /* } else if (podStateManager.podStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { - resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault) + rh.gs(R.string.omnipod_common_pod_status_pod_fault) } else if (podStateManager.podStatus == PodProgressStatus.INACTIVE) { - resourceHelper.gs(R.string.omnipod_common_pod_status_inactive) + rh.gs(R.string.omnipod_common_pod_status_inactive) */ } else { podStateManager.podStatus.toString() @@ -504,10 +504,10 @@ class OmnipodDashOverviewFragment : DaggerFragment() { podStateManager.activeCommand?.let { val requestedBolus = it.requestedBolus if (requestedBolus != null) { - var text = resourceHelper.gs( + var text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(requestedBolus), - resourceHelper.gs(R.string.insulin_unit_shortname), + rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(SystemClock.elapsedRealtime() - it.createdRealtime)) ) text += " (uncertain) " @@ -524,10 +524,10 @@ class OmnipodDashOverviewFragment : DaggerFragment() { val bolusSize = it.deliveredUnits() ?: it.requestedUnits - val text = resourceHelper.gs( + val text = rh.gs( R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(bolusSize), - resourceHelper.gs(R.string.insulin_unit_shortname), + rh.gs(R.string.insulin_unit_shortname), readableDuration(Duration.ofMillis(System.currentTimeMillis() - it.startTime)) ) if (!it.deliveryComplete) { @@ -547,7 +547,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { val minutesRunning = Duration.ofMillis(System.currentTimeMillis() - startTime).toMinutes() - podInfoBinding.tempBasal.text = resourceHelper.gs( + podInfoBinding.tempBasal.text = rh.gs( R.string.omnipod_common_overview_temp_basal_value, rate, dateUtil.timeString(startTime), @@ -667,34 +667,34 @@ class OmnipodDashOverviewFragment : DaggerFragment() { val seconds = duration.seconds when { seconds < 10 -> { - return resourceHelper.gs(R.string.omnipod_common_moments_ago) + return rh.gs(R.string.omnipod_common_moments_ago) } seconds < 60 -> { - return resourceHelper.gs(R.string.omnipod_common_less_than_a_minute_ago) + return rh.gs(R.string.omnipod_common_less_than_a_minute_ago) } seconds < 60 * 60 -> { // < 1 hour - return resourceHelper.gs( + return rh.gs( R.string.omnipod_common_time_ago, - resourceHelper.gq(R.plurals.omnipod_common_minutes, minutes, minutes) + rh.gq(R.plurals.omnipod_common_minutes, minutes, minutes) ) } seconds < 24 * 60 * 60 -> { // < 1 day val minutesLeft = minutes % 60 if (minutesLeft > 0) - return resourceHelper.gs( + return rh.gs( R.string.omnipod_common_time_ago, - resourceHelper.gs( + rh.gs( R.string.omnipod_common_composite_time, - resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours), - resourceHelper.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft) + rh.gq(R.plurals.omnipod_common_hours, hours, hours), + rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft) ) ) - return resourceHelper.gs( + return rh.gs( R.string.omnipod_common_time_ago, - resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours) + rh.gq(R.plurals.omnipod_common_hours, hours, hours) ) } @@ -702,17 +702,17 @@ class OmnipodDashOverviewFragment : DaggerFragment() { val days = hours / 24 val hoursLeft = hours % 24 if (hoursLeft > 0) - return resourceHelper.gs( + return rh.gs( R.string.omnipod_common_time_ago, - resourceHelper.gs( + rh.gs( R.string.omnipod_common_composite_time, - resourceHelper.gq(R.plurals.omnipod_common_days, days, days), - resourceHelper.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft) + rh.gq(R.plurals.omnipod_common_days, days, days), + rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft) ) ) - return resourceHelper.gs( + return rh.gs( R.string.omnipod_common_time_ago, - resourceHelper.gq(R.plurals.omnipod_common_days, days, days) + rh.gq(R.plurals.omnipod_common_days, days, days) ) } } @@ -744,13 +744,13 @@ class OmnipodDashOverviewFragment : DaggerFragment() { if (result.success) { val messageOnSuccess = this.messageOnSuccess if (messageOnSuccess != null) { - displayOkDialog(resourceHelper.gs(R.string.omnipod_common_confirmation), messageOnSuccess) + displayOkDialog(rh.gs(R.string.omnipod_common_confirmation), messageOnSuccess) } actionOnSuccess?.run() } else { displayErrorDialog( - resourceHelper.gs(R.string.omnipod_common_warning), - resourceHelper.gs( + rh.gs(R.string.omnipod_common_warning), + rh.gs( R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index 1f9b9fdb1a..7920b856e4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -29,7 +29,7 @@ class DashInitializePodViewModel @Inject constructor( logger: AAPSLogger, private val sp: SP, private val podStateManager: OmnipodDashPodStateManager, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val history: DashHistory, aapsSchedulers: AapsSchedulers @@ -67,7 +67,7 @@ class DashInitializePodViewModel @Inject constructor( source.onSuccess( PumpEnactResult(injector) .success(false) - .comment(I8n.textFromException(throwable, resourceHelper)) + .comment(I8n.textFromException(throwable, rh)) ) }, onComplete = { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index 4e6128eea0..743e96adbf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -40,7 +40,7 @@ class DashInsertCannulaViewModel @Inject constructor( private val podStateManager: OmnipodDashPodStateManager, private val rxBus: RxBus, private val sp: SP, - private val resourceHelper: ResourceHelper, + private val rh: ResourceHelper, private val fabricPrivacy: FabricPrivacy, private val history: DashHistory, @@ -90,7 +90,7 @@ class DashInsertCannulaViewModel @Inject constructor( .subscribeBy( onError = { throwable -> logger.error(LTag.PUMP, "Error in Pod activation part 2", throwable) - source.onSuccess(PumpEnactResult(injector).success(false).comment(I8n.textFromException(throwable, resourceHelper))) + source.onSuccess(PumpEnactResult(injector).success(false).comment(I8n.textFromException(throwable, rh))) }, onComplete = { logger.debug("Pod activation part 2 completed") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt index 1927d3eebd..6427d25004 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivat import androidx.annotation.StringRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification @@ -19,7 +19,7 @@ import javax.inject.Inject class DashDeactivatePodViewModel @Inject constructor( private val podStateManager: OmnipodDashPodStateManager, - private val commandQueueProvider: CommandQueueProvider, + private val commandQueue: CommandQueue, private val rxBus: RxBus, injector: HasAndroidInjector, logger: AAPSLogger, @@ -27,7 +27,7 @@ class DashDeactivatePodViewModel @Inject constructor( ) : DeactivatePodViewModel(injector, logger, aapsSchedulers) { override fun doExecuteAction(): Single = Single.create { source -> - commandQueueProvider.customCommand( + commandQueue.customCommand( CommandDeactivatePod(), object : Callback() { override fun run() { diff --git a/omnipod-dash/src/main/res/values-af-rZA/strings.xml b/omnipod-dash/src/main/res/values-af-rZA/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-af-rZA/strings.xml +++ b/omnipod-dash/src/main/res/values-af-rZA/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-bg-rBG/strings.xml b/omnipod-dash/src/main/res/values-bg-rBG/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-bg-rBG/strings.xml +++ b/omnipod-dash/src/main/res/values-bg-rBG/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-ca-rES/strings.xml b/omnipod-dash/src/main/res/values-ca-rES/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-ca-rES/strings.xml +++ b/omnipod-dash/src/main/res/values-ca-rES/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-cs-rCZ/strings.xml b/omnipod-dash/src/main/res/values-cs-rCZ/strings.xml index 2aa2949dc0..3e9314bea0 100644 --- a/omnipod-dash/src/main/res/values-cs-rCZ/strings.xml +++ b/omnipod-dash/src/main/res/values-cs-rCZ/strings.xml @@ -3,6 +3,15 @@ Integrace pumpy pro Omnipod Dash (nový model s funkcí Bluetooth a modrým krytem). + + Historie Podu + Popis + Zdroj + Datum + Typ: + %1$.2f U + %1$.2f U, Sach=%2$.1f g + Rychlost: %1$.2f U, doba trvání: %2$d minut Stav Bluetooth Adresa Bluetooth @@ -18,4 +27,10 @@ Nalezeno příliš mnoho Podů k aktivaci Nelze najít dostupný Pod k aktivaci Obecná chyba: %1$s + Nezdařilo se odeslat příkaz + Příkaz nebyl odeslán + Příkaz nebyl přijat podem + Neznámý stav příkazu + Rychlost: %1$.2f U, doba trvání: %2$d minut + %1$.2f U diff --git a/omnipod-dash/src/main/res/values-da-rDK/strings.xml b/omnipod-dash/src/main/res/values-da-rDK/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-da-rDK/strings.xml +++ b/omnipod-dash/src/main/res/values-da-rDK/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-de-rDE/strings.xml b/omnipod-dash/src/main/res/values-de-rDE/strings.xml index 7778e692ff..1eaa7a2eff 100644 --- a/omnipod-dash/src/main/res/values-de-rDE/strings.xml +++ b/omnipod-dash/src/main/res/values-de-rDE/strings.xml @@ -3,6 +3,15 @@ Pumpen-Integration für Omnipod Dash (das neue, bluetooth-fähige Modell mit blauer Nadelkappe). + + Pod Historie + Beschreibung + Quelle + Datum + Typ: + %1$.2f IE + %1$.2f IE, CH=%2$.1f g + Rate: %1$.2f IE, Dauer: %2$d min. Bluetooth-Status Bluetooth-Adresse @@ -18,4 +27,10 @@ Zu viele Pods für die Aktivierung gefunden Konnte keinen verfügbaren Pod für die Aktivierung finden Allgemeiner Fehler: %1$s + Fehler beim Senden des Befehls + Befehl nicht gesendet + Befehl nicht vom Pod empfangen + Unbekannter Status für den Befehl + Rate: %1$.2f IE, Dauer: %2$d min. + %1$.2f IE diff --git a/omnipod-dash/src/main/res/values-el-rGR/strings.xml b/omnipod-dash/src/main/res/values-el-rGR/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-el-rGR/strings.xml +++ b/omnipod-dash/src/main/res/values-el-rGR/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-es-rES/strings.xml b/omnipod-dash/src/main/res/values-es-rES/strings.xml index 0d89375603..a946cd2d3b 100644 --- a/omnipod-dash/src/main/res/values-es-rES/strings.xml +++ b/omnipod-dash/src/main/res/values-es-rES/strings.xml @@ -1,8 +1,22 @@ + Integración de bombas de insulina Omnipod Dash (el nuevo modelo, con bluetooth habilitado con tapa azul). + + Historial del POD + Descripción + Origen + Fecha + Tipo: + %1$.2f U + %1$.2f U, CH=%2$.1f g + Tasa: %1$.2f U, duración: %2$d minutos + Estado de Bluetooth + Dirección Bluetooth + Firmware %1$s / Bluetooth %2$s + Calidad de la conexión diff --git a/omnipod-dash/src/main/res/values-fr-rFR/strings.xml b/omnipod-dash/src/main/res/values-fr-rFR/strings.xml index a178c01d4f..d9887349b7 100644 --- a/omnipod-dash/src/main/res/values-fr-rFR/strings.xml +++ b/omnipod-dash/src/main/res/values-fr-rFR/strings.xml @@ -3,6 +3,15 @@ Intégration de la pompe Omnipod Dash (le nouveau modèle Bluetooth, avec un bouchon d\'aiguille bleue). + + Historique du Pod + Description + Source + Date + Type : + %1$.2f U + %1$.2f U, Gluc=%2$.1f g + Débit : %1$.2f U, durée : %2$d minutes État Bluetooth Adresse Bluetooth @@ -18,4 +27,10 @@ Trop de pods trouvés pour l\'activation Impossible de trouver un pod disponible pour l\'activation Erreur générique : %1$s + Échec d\'envoi de la commande + Commande non envoyée + Commande non reçue par le pod + État inconnu pour la commande + Débit : %1$.2f U, durée : %2$d minutes + %1$.2f U diff --git a/omnipod-dash/src/main/res/values-ga-rIE/strings.xml b/omnipod-dash/src/main/res/values-ga-rIE/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-ga-rIE/strings.xml +++ b/omnipod-dash/src/main/res/values-ga-rIE/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-hr-rHR/strings.xml b/omnipod-dash/src/main/res/values-hr-rHR/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-hr-rHR/strings.xml +++ b/omnipod-dash/src/main/res/values-hr-rHR/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-hu-rHU/strings.xml b/omnipod-dash/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..942b365512 --- /dev/null +++ b/omnipod-dash/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/omnipod-dash/src/main/res/values-it-rIT/strings.xml b/omnipod-dash/src/main/res/values-it-rIT/strings.xml index 6b0f3d4214..b6ce74a9d8 100644 --- a/omnipod-dash/src/main/res/values-it-rIT/strings.xml +++ b/omnipod-dash/src/main/res/values-it-rIT/strings.xml @@ -3,6 +3,15 @@ Integrazione del microinfusore Omnipod Dash (il nuovo modello, abilitato al Bluetooth e con la protezione ago di colore blu). + + Storico pod + Descrizione + Origine + Data + Tipo: + %1$.2f U + %1$.2f U, CHO=%2$.1f g + Tasso: %1$.2f U, durata: %2$d minuti Stato bluetooth Indirizzo bluetooth @@ -18,4 +27,10 @@ Trovati troppi pod per l\'attivazione Nessun pod disponibile per l\'attivazione Errore generico: %1$s + Impossibile inviare il comando + Comando non inviato + Comando non ricevuto dal pod + Stato sconosciuto per il comando + Tasso: %1$.2f U, durata: %2$d minuti + %1$.2f U diff --git a/omnipod-dash/src/main/res/values-iw-rIL/strings.xml b/omnipod-dash/src/main/res/values-iw-rIL/strings.xml index 2fb153f0c6..61e25aea1e 100644 --- a/omnipod-dash/src/main/res/values-iw-rIL/strings.xml +++ b/omnipod-dash/src/main/res/values-iw-rIL/strings.xml @@ -3,6 +3,15 @@ חיבור משאבת Omnipod Dash (הדגם החדש, התומך בבלוטות\' ובעל מכסה מחט כחול). + + היסטוריית הפוד + תיאור + מקור + תאריך + סוג: + %1$.2f יח\' + %1$.2f יח\', פחמ\'= %2$.1f גר\' + מינון: %1$.2f יח\', משך: %2$d דק\' מצב בלוטות\' כתובת בלוטות\' @@ -10,12 +19,18 @@ איכות החיבור סטטוס הזרקה - מלאו פוד חדש עם מספיק אינסולין לשלושה ימים.\n\nהקשיבו לשני צפצופים מהפוד במהלך המילוי. הם מציינים שהכמות המינימלית של 80 יחידות הוכנסה. הקפידו לרוקן לחלוטין את מזרק המילוי, גם לאחר שמיעת שני הצפצופים.\n\nלאחר מילוי הפוד, יש ללחוץ הבא.\n\nהערה: נא לא להסיר עדיין את מכסה המחט. - מנסה לצמד את הפוד החדש ולתחל אותו.\n\nכאשר תהליך התחול יסתיים בהצלחה, תוכלו ללחוץ על הבא. + מלאו פוד חדש עם מספיק אינסולין לשלושה ימים.\n\nהקשיבו לשני צפצופים מהפוד במהלך המילוי. הם מציינים שהכמות המינימלית של 80 יחידות הוכנסה. הקפידו לרוקן לחלוטין את מזרק המילוי לתוך הפוד, גם לאחר שמיעת שני הצפצופים.\n\nלאחר מילוי הפוד, יש ללחוץ הבא.\n\nהערה: נא לא להסיר עדיין את מכסה המחט. + מנסה לצמד את הפוד החדש ולתחל אותו.\n\nכאשר תהליך התיחול יסתיים בהצלחה, תוכלו ללחוץ על הבא. השמע כשהתראת הפסקת ההזרקה מאופשרת הקישור לפוד נכשל נמצאו יותר מדי פודים להפעלה לא נמצא פוד זמין להפעלה שגיאה גנרית: %1$s + שליחת הפקודה נכשלה + הפקודה לא נשלחה + הפקודה לא התקבלה ע\"י הפוד + מצב הפקודה לא ידוע + מינון: %1$.2f יח\', משך: %2$d דק\' + %1$.2f יח\' diff --git a/omnipod-dash/src/main/res/values-ko-rKR/strings.xml b/omnipod-dash/src/main/res/values-ko-rKR/strings.xml index f01c43835c..91fdf1f9e3 100644 --- a/omnipod-dash/src/main/res/values-ko-rKR/strings.xml +++ b/omnipod-dash/src/main/res/values-ko-rKR/strings.xml @@ -3,6 +3,7 @@ 옴니파드 대쉬(파란색 바늘 캡이 달린 새로운 블루투스 연결 모델)를 위한 펌프 통합 + diff --git a/omnipod-dash/src/main/res/values-lt-rLT/strings.xml b/omnipod-dash/src/main/res/values-lt-rLT/strings.xml index fe222a093a..390923037e 100644 --- a/omnipod-dash/src/main/res/values-lt-rLT/strings.xml +++ b/omnipod-dash/src/main/res/values-lt-rLT/strings.xml @@ -3,6 +3,7 @@ Pompos integracija Omnipod Dash (naujas, Bluetooth palaikantis modelis su mėlynu adatos dangteliu). + Bluetooth būklė Bluetooth adresas diff --git a/omnipod-dash/src/main/res/values-nl-rNL/strings.xml b/omnipod-dash/src/main/res/values-nl-rNL/strings.xml index 71ac7ad09e..c2a0897111 100644 --- a/omnipod-dash/src/main/res/values-nl-rNL/strings.xml +++ b/omnipod-dash/src/main/res/values-nl-rNL/strings.xml @@ -3,6 +3,7 @@ Pomp integratie voor Omnipod Dash (het nieuwe, Bluetooth-enabled model met een blauwe naalddop). + Bluetooth status Bluetooth adres diff --git a/omnipod-dash/src/main/res/values-no-rNO/strings.xml b/omnipod-dash/src/main/res/values-no-rNO/strings.xml index 6f3619cf85..a6f98fd074 100644 --- a/omnipod-dash/src/main/res/values-no-rNO/strings.xml +++ b/omnipod-dash/src/main/res/values-no-rNO/strings.xml @@ -3,6 +3,15 @@ Pumpeintegrering for Omnipod Dash (den nye, Bluetooth-aktiverte modellen med en blå kanylehette). + + Pod historikk + Beskrivelse + Kilde + Dato + Type: + %1$.2f E + %1$.2f E, KH=%2$.1f g + Dosering: %1$.2f E, varighet: %2$d min Bluetooth status Bluetooth adresse @@ -18,4 +27,10 @@ Fant for mange podder for aktivering Fant ingen pod tilgjengelig for aktivering Generell feil: %1$s + Feilet i å sende kommandoen + Kommando ikke sendt + Kommandoen ikke mottatt av podden + Ukjent tilstand for kommandoen + Dosering: %1$.2f E, varighet: %2$d min + %1$.2f E diff --git a/omnipod-dash/src/main/res/values-pl-rPL/strings.xml b/omnipod-dash/src/main/res/values-pl-rPL/strings.xml index 5faa140ff9..cd2dc79a7a 100644 --- a/omnipod-dash/src/main/res/values-pl-rPL/strings.xml +++ b/omnipod-dash/src/main/res/values-pl-rPL/strings.xml @@ -3,6 +3,7 @@ Integracja dla pompy Omnipod Dash (nowy, posiadając Bluetooth model z niebieską osłonką na igłę). + Status Bluetooth Adres Bluetooth diff --git a/omnipod-dash/src/main/res/values-pt-rBR/strings.xml b/omnipod-dash/src/main/res/values-pt-rBR/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-pt-rBR/strings.xml +++ b/omnipod-dash/src/main/res/values-pt-rBR/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-pt-rPT/strings.xml b/omnipod-dash/src/main/res/values-pt-rPT/strings.xml index d01a3acdfe..6cf06aa469 100644 --- a/omnipod-dash/src/main/res/values-pt-rPT/strings.xml +++ b/omnipod-dash/src/main/res/values-pt-rPT/strings.xml @@ -3,6 +3,7 @@ Integração para a Omnipod Dash (o novo modelo, habilitado para o Bluetooth com uma proteção de agulha azul). + diff --git a/omnipod-dash/src/main/res/values-ro-rRO/strings.xml b/omnipod-dash/src/main/res/values-ro-rRO/strings.xml index d338e79f73..fa0ac1d4f6 100644 --- a/omnipod-dash/src/main/res/values-ro-rRO/strings.xml +++ b/omnipod-dash/src/main/res/values-ro-rRO/strings.xml @@ -3,6 +3,15 @@ Integrarea pompei pentru Omnipod Dash (modelul nou, cu Bluetooth, cu un capac de ac albastru). + + Istoric Pod + Descriere + Sursă + Data + Tip: + %1$.2f U + %1$.2f U, CH=%2$.1f g + Rata: %1$.2f U, durata: %2$d minute Stare Bluetooth Adresă Bluetooth @@ -19,4 +28,10 @@ S-au găsit prea multe Pod-uri de activat Nu s-a putut găsi un Pod pentru activare Eroare generică: %1$s + Nu s-a reușit trimiterea comenzii + Comanda nu a fost trimisă + Comanda nu a fost primită de Pod + Stare necunoscută pentru comandă + Rata: %1$.2f U, durata: %2$d minute + %1$.2f U diff --git a/omnipod-dash/src/main/res/values-ru-rRU/strings.xml b/omnipod-dash/src/main/res/values-ru-rRU/strings.xml index 73452811e8..51e31a2ee1 100644 --- a/omnipod-dash/src/main/res/values-ru-rRU/strings.xml +++ b/omnipod-dash/src/main/res/values-ru-rRU/strings.xml @@ -3,6 +3,15 @@ Интеграция с помпой Omnipod Dash (новая модель с поддержкой Bluetooth, с синим колпачком на игле). + + Журнал помпы + Описание + Источник + Дата + Тип: + %1$.2f ед + %1$.2f ед %2$.1f ГУ + Баз Скорость: %1$.2f ед, Продолжительность: %2$d мин Состояние Bluetooth Адрес Bluetooth @@ -18,4 +27,10 @@ Cлишком много pod\'ов для активации Pod для активации не найден Общая ошибка: %1$s + Не удалось отправить команду + Команда не отправлена + Команда не получена помпой + Состояние команды неясно + Баз Скорость: %1$.2f ед, Продолжительность: %2$d мин + %1$.2f ед diff --git a/omnipod-dash/src/main/res/values-sk-rSK/strings.xml b/omnipod-dash/src/main/res/values-sk-rSK/strings.xml index bb75fed0a6..6b81edbeb9 100644 --- a/omnipod-dash/src/main/res/values-sk-rSK/strings.xml +++ b/omnipod-dash/src/main/res/values-sk-rSK/strings.xml @@ -3,6 +3,15 @@ Integrácia pumpy pre Omnipod Dash (nový model s funkciou Bluetooth a modrým krytom). + + História Podu + Popis + Zdroj + Dátum + Typ: + %1$.2f JI + %1$.2f JI, Sach=%2$.1f g + Rýchlosť: %1$.2f JI, Doba trvania: %2$d minút Stav Bluetooth Adresa Bluetooth @@ -18,4 +27,10 @@ Našlo sa príliš veľa Podov na aktiváciu Nemôžem nájsť dostupný Pod na aktiváciu Všeobecná chyba: %1$s + Nepodarilo sa odoslať príkaz + Príkaz nebol odoslaný + Príkaz nebol prijatý Podom + Neznámy stav príkazu + Rýchlosť: %1$.2f JI, Doba trvania: %2$d minút + %1$.2f JI diff --git a/omnipod-dash/src/main/res/values-sl-rSI/strings.xml b/omnipod-dash/src/main/res/values-sl-rSI/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-sl-rSI/strings.xml +++ b/omnipod-dash/src/main/res/values-sl-rSI/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-sv-rSE/strings.xml b/omnipod-dash/src/main/res/values-sv-rSE/strings.xml index e9c744f38a..867f67dbf3 100644 --- a/omnipod-dash/src/main/res/values-sv-rSE/strings.xml +++ b/omnipod-dash/src/main/res/values-sv-rSE/strings.xml @@ -3,6 +3,15 @@ Pumpintegration för Omnipod Dash (den nya, Bluetooth-aktiverade modellen med blå nålskydd). + + Pod-historik + Beskrivning + Källa + Datum + Typ: + %1$.2fU + %1$.2f U, KH=%2$.1f g + Dos: %1$.2f U, Duration: %2$d min Bluetooth-status Bluetooth-adress @@ -18,4 +27,10 @@ Hittade för många poddar för aktivering Kunde inte hitta en tillgänglig pod för aktivering Allmänt fel: %1$s + Det gick inte att skicka kommandot + Kommandot har inte skickats + Kommando ej mottaget av poden + Okänt tillstånd för kommandot + Dos: %1$.2f U, Duration: %2$d min + %1$.2fU diff --git a/omnipod-dash/src/main/res/values-ta-rIN/strings.xml b/omnipod-dash/src/main/res/values-ta-rIN/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-ta-rIN/strings.xml +++ b/omnipod-dash/src/main/res/values-ta-rIN/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-dash/src/main/res/values-tr-rTR/strings.xml b/omnipod-dash/src/main/res/values-tr-rTR/strings.xml index 0d89375603..1115d7f022 100644 --- a/omnipod-dash/src/main/res/values-tr-rTR/strings.xml +++ b/omnipod-dash/src/main/res/values-tr-rTR/strings.xml @@ -1,8 +1,37 @@ + Omnipod Dash için pompa entegrasyonu (mavi iğne başlıklı, Bluetooth özellikli model). + + Pod Geçmişi + Açıklama + Kaynak + Tarih + Tip: + %1$.2f Ü + %1$.2f Ü, CH=%2$.1f g + Oran: %1$.2f Ü, süre: %2$d dakika + Bluetooth Durumu + Bluetooth Adresi + Firmware %1$s / Bluetooth %2$s + Bağlantı kalitesi + İletim Durumu + Yeni bir Pod doldurun + 3 gün boyunca yeterli insülinle.\n\nDoldurma işlemi sırasında Pod\'tan iki bip sesi dinleyin. Bu ses, minimum 80Ü eklendiğini gösterir. İki bip sesini duyduktan sonra bile doldurma şırıngasını tamamen boşalttığınızdan emin olun.\n\nPod\'u doldurduktan sonra lütfen İleri\'ye basın.\n\nNot: bu sırada Pod\'un iğne kapağını çıkarmayın. + Yeni Pod ile eşleşmeye ve kullanıma hazırlanmaya çalışılıyor.\n\nBaşlatma işlemi başarıyla tamamlandığında, İleri\'ye basabilirsiniz. + İletimin askıya alındığı bildirimi etkinleştirildiğinde sesle uyar + Pod bağlantı hatası + Aktivasyon için çok fazla Pod bulundu + Etkinleştirme için uygun bir Pod bulunamadı + Genel hata: %1$s + Komut gönderilirken hata + Komut gönderilmedi + Pod\'dan komut alınmadı + Bilinmeyen komut durumu + Oran: %1$.2f Ü, süre: %2$d dakika + %1$.2f Ü diff --git a/omnipod-dash/src/main/res/values-zh-rCN/strings.xml b/omnipod-dash/src/main/res/values-zh-rCN/strings.xml index 0d89375603..942b365512 100644 --- a/omnipod-dash/src/main/res/values-zh-rCN/strings.xml +++ b/omnipod-dash/src/main/res/values-zh-rCN/strings.xml @@ -2,6 +2,7 @@ + diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index f8e6d54732..7cd7b8f199 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -7,7 +7,6 @@ import android.content.ServiceConnection; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; -import android.os.Looper; import android.os.SystemClock; import android.text.TextUtils; @@ -38,7 +37,7 @@ import info.nightscout.androidaps.events.EventAppInitialized; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.Profile; @@ -140,7 +139,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley private final ActivePlugin activePlugin; private final Context context; private final FabricPrivacy fabricPrivacy; - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final SP sp; private final DateUtil dateUtil; private final PumpDescription pumpDescription; @@ -172,13 +171,13 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley AapsSchedulers aapsSchedulers, RxBus rxBus, Context context, - ResourceHelper resourceHelper, + ResourceHelper rh, ActivePlugin activePlugin, SP sp, ErosPodStateManager podStateManager, ErosHistory erosHistory, AapsOmnipodErosManager aapsOmnipodErosManager, - CommandQueueProvider commandQueue, + CommandQueue commandQueue, FabricPrivacy fabricPrivacy, RileyLinkServiceData rileyLinkServiceData, DateUtil dateUtil, @@ -196,14 +195,14 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley .shortName(R.string.omnipod_eros_name_short) // .preferencesId(R.xml.omnipod_eros_preferences) // .description(R.string.omnipod_eros_pump_description), // - injector, aapsLogger, resourceHelper, commandQueue); + injector, aapsLogger, rh, commandQueue); this.aapsLogger = aapsLogger; this.aapsSchedulers = aapsSchedulers; this.rxBus = rxBus; this.activePlugin = activePlugin; this.context = context; this.fabricPrivacy = fabricPrivacy; - this.resourceHelper = resourceHelper; + this.rh = rh; this.sp = sp; this.dateUtil = dateUtil; this.podStateManager = podStateManager; @@ -328,25 +327,25 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley .toObservable(EventPreferenceChange.class) .observeOn(aapsSchedulers.getIo()) .subscribe(event -> { - if (event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.BASAL_BEEPS_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.BOLUS_BEEPS_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.TBR_BEEPS_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.SMB_BEEPS_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.SUSPEND_DELIVERY_BUTTON_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.PULSE_LOG_BUTTON_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.RILEY_LINK_STATS_BUTTON_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.SHOW_RILEY_LINK_BATTERY_LEVEL) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.BATTERY_CHANGE_LOGGING_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.TIME_CHANGE_EVENT_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_TBR_SOUND_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_SMB_SOUND_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_BOLUS_SOUND_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.AUTOMATICALLY_ACKNOWLEDGE_ALERTS_ENABLED)) { + if (event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.BASAL_BEEPS_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.BOLUS_BEEPS_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.TBR_BEEPS_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.SMB_BEEPS_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.SUSPEND_DELIVERY_BUTTON_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.PULSE_LOG_BUTTON_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.RILEY_LINK_STATS_BUTTON_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.SHOW_RILEY_LINK_BATTERY_LEVEL) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.BATTERY_CHANGE_LOGGING_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.TIME_CHANGE_EVENT_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_TBR_SOUND_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_SMB_SOUND_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.NOTIFICATION_UNCERTAIN_BOLUS_SOUND_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.AUTOMATICALLY_ACKNOWLEDGE_ALERTS_ENABLED)) { aapsOmnipodErosManager.reloadSettings(); - } else if (event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.EXPIRATION_REMINDER_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.EXPIRATION_REMINDER_HOURS_BEFORE_SHUTDOWN) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.LOW_RESERVOIR_ALERT_ENABLED) || - event.isChanged(getResourceHelper(), OmnipodErosStorageKeys.Preferences.LOW_RESERVOIR_ALERT_UNITS)) { + } else if (event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.EXPIRATION_REMINDER_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.EXPIRATION_REMINDER_HOURS_BEFORE_SHUTDOWN) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.LOW_RESERVOIR_ALERT_ENABLED) || + event.isChanged(getRh(), OmnipodErosStorageKeys.Preferences.LOW_RESERVOIR_ALERT_UNITS)) { if (!verifyPodAlertConfiguration()) { getCommandQueue().customCommand(new CommandUpdateAlertConfiguration(), null); } @@ -408,7 +407,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley } else { // Not sure what's going on. Notify the user aapsLogger.error(LTag.PUMP, "Unknown TBR in both Pod state and AAPS"); - rxBus.send(new EventNewNotification(new Notification(Notification.OMNIPOD_UNKNOWN_TBR, resourceHelper.gs(R.string.omnipod_eros_error_tbr_running_but_aaps_not_aware), Notification.NORMAL).sound(R.raw.boluserror))); + rxBus.send(new EventNewNotification(new Notification(Notification.OMNIPOD_UNKNOWN_TBR, rh.gs(R.string.omnipod_eros_error_tbr_running_but_aaps_not_aware), Notification.NORMAL).sound(R.raw.boluserror))); } } else if (!podStateManager.isTempBasalRunning() && tempBasal != null) { aapsLogger.warn(LTag.PUMP, "Removing AAPS TBR that actually hadn't succeeded"); @@ -423,7 +422,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley AlertSet activeAlerts = podStateManager.getActiveAlerts(); if (activeAlerts.size() > 0) { String alerts = TextUtils.join(", ", aapsOmnipodUtil.getTranslatedActiveAlerts(podStateManager)); - String notificationText = resourceHelper.gq(R.plurals.omnipod_common_pod_alerts, activeAlerts.size(), alerts); + String notificationText = rh.gq(R.plurals.omnipod_common_pod_alerts, activeAlerts.size(), alerts); Notification notification = new Notification(Notification.OMNIPOD_POD_ALERTS, notificationText, Notification.URGENT); rxBus.send(new EventNewNotification(notification)); pumpSync.insertAnnouncement(notificationText, null, PumpType.OMNIPOD_EROS, serialNumber()); @@ -437,7 +436,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley private void handlePodFaultEvent() { if (podStateManager.isPodFaulted()) { - String notificationText = resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault_description, podStateManager.getFaultEventCode().getValue(), podStateManager.getFaultEventCode().name()); + String notificationText = rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, podStateManager.getFaultEventCode().getValue(), podStateManager.getFaultEventCode().name()); pumpSync.insertAnnouncement(notificationText, null, PumpType.OMNIPOD_EROS, serialNumber()); } } @@ -467,19 +466,19 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley private void updatePodWarningNotifications() { if (System.currentTimeMillis() > this.nextPodWarningCheck) { if (!podStateManager.isPodRunning()) { - Notification notification = new Notification(Notification.OMNIPOD_POD_NOT_ATTACHED, resourceHelper.gs(R.string.omnipod_common_error_pod_not_attached), Notification.NORMAL); + Notification notification = new Notification(Notification.OMNIPOD_POD_NOT_ATTACHED, rh.gs(R.string.omnipod_common_error_pod_not_attached), Notification.NORMAL); rxBus.send(new EventNewNotification(notification)); } else { rxBus.send(new EventDismissNotification(Notification.OMNIPOD_POD_NOT_ATTACHED)); if (podStateManager.isSuspended()) { - Notification notification = new Notification(Notification.OMNIPOD_POD_SUSPENDED, resourceHelper.gs(R.string.omnipod_common_error_pod_suspended), Notification.NORMAL); + Notification notification = new Notification(Notification.OMNIPOD_POD_SUSPENDED, rh.gs(R.string.omnipod_common_error_pod_suspended), Notification.NORMAL); rxBus.send(new EventNewNotification(notification)); } else { rxBus.send(new EventDismissNotification(Notification.OMNIPOD_POD_SUSPENDED)); if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) { - Notification notification = new Notification(Notification.OMNIPOD_TIME_OUT_OF_SYNC, resourceHelper.gs(R.string.omnipod_common_error_time_out_of_sync), Notification.NORMAL); + Notification notification = new Notification(Notification.OMNIPOD_TIME_OUT_OF_SYNC, rh.gs(R.string.omnipod_common_error_time_out_of_sync), Notification.NORMAL); rxBus.send(new EventNewNotification(notification)); } else { rxBus.send(new EventDismissNotification(Notification.OMNIPOD_TIME_OUT_OF_SYNC)); @@ -540,7 +539,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley } @Override public RileyLinkPumpInfo getPumpInfo() { - String frequency = resourceHelper.gs(R.string.omnipod_eros_frequency); + String frequency = rh.gs(R.string.omnipod_eros_frequency); String connectedModel = "Eros"; String serialNumber = podStateManager.isPodInitialized() ? String.valueOf(podStateManager.getAddress()) : "-"; return new RileyLinkPumpInfo(frequency, connectedModel, serialNumber); @@ -692,7 +691,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute: rate: {}, duration={}", absoluteRate, durationInMinutes); if (durationInMinutes <= 0 || durationInMinutes % BASAL_STEP_DURATION.getStandardMinutes() != 0) { - return new PumpEnactResult(getInjector()).success(false).comment(resourceHelper.gs(R.string.omnipod_eros_error_set_temp_basal_failed_validation, BASAL_STEP_DURATION.getStandardMinutes())); + return new PumpEnactResult(getInjector()).success(false).comment(rh.gs(R.string.omnipod_eros_error_set_temp_basal_failed_validation, BASAL_STEP_DURATION.getStandardMinutes())); } // read current TBR @@ -818,28 +817,28 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley @NonNull @Override public String shortStatus(boolean veryShort) { if (!podStateManager.isPodActivationCompleted()) { - return resourceHelper.gs(R.string.omnipod_common_short_status_no_active_pod); + return rh.gs(R.string.omnipod_common_short_status_no_active_pod); } String ret = ""; if (lastConnectionTimeMillis != 0) { long agoMsec = System.currentTimeMillis() - lastConnectionTimeMillis; int agoMin = (int) (agoMsec / 60d / 1000d); - ret += resourceHelper.gs(R.string.omnipod_common_short_status_last_connection, agoMin) + "\n"; + ret += rh.gs(R.string.omnipod_common_short_status_last_connection, agoMin) + "\n"; } if (podStateManager.getLastBolusStartTime() != null) { - ret += resourceHelper.gs(R.string.omnipod_common_short_status_last_bolus, DecimalFormatter.INSTANCE.to2Decimal(podStateManager.getLastBolusAmount()), + ret += rh.gs(R.string.omnipod_common_short_status_last_bolus, DecimalFormatter.INSTANCE.to2Decimal(podStateManager.getLastBolusAmount()), android.text.format.DateFormat.format("HH:mm", podStateManager.getLastBolusStartTime().toDate())) + "\n"; } PumpSync.PumpState pumpState = pumpSync.expectedPumpState(); if (pumpState.getTemporaryBasal() != null && pumpState.getProfile() != null) { - ret += resourceHelper.gs(R.string.omnipod_common_short_status_temp_basal, toStringFull(pumpState.getTemporaryBasal(), dateUtil) + "\n"); + ret += rh.gs(R.string.omnipod_common_short_status_temp_basal, toStringFull(pumpState.getTemporaryBasal(), dateUtil) + "\n"); } if (pumpState.getExtendedBolus() != null) { - ret += resourceHelper.gs(R.string.omnipod_common_short_status_extended_bolus, toStringFull(pumpState.getExtendedBolus(), dateUtil) + "\n"); + ret += rh.gs(R.string.omnipod_common_short_status_extended_bolus, toStringFull(pumpState.getExtendedBolus(), dateUtil) + "\n"); } - ret += resourceHelper.gs(R.string.omnipod_common_short_status_reservoir, (getReservoirLevel() > OmnipodConstants.MAX_RESERVOIR_READING ? "50+" : DecimalFormatter.INSTANCE.to0Decimal(getReservoirLevel()))) + "\n"; + ret += rh.gs(R.string.omnipod_common_short_status_reservoir, (getReservoirLevel() > OmnipodConstants.MAX_RESERVOIR_READING ? "50+" : DecimalFormatter.INSTANCE.to0Decimal(getReservoirLevel()))) + "\n"; if (isUseRileyLinkBatteryLevel()) { - ret += resourceHelper.gs(R.string.omnipod_eros_short_status_riley_link_battery, getBatteryLevel()) + "\n"; + ret += rh.gs(R.string.omnipod_eros_short_status_riley_link_battery, getBatteryLevel()) + "\n"; } return ret.trim(); } @@ -880,7 +879,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley } aapsLogger.warn(LTag.PUMP, "Unsupported custom command: " + command.getClass().getName()); - return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(resourceHelper.gs(R.string.omnipod_common_error_unsupported_custom_command, command.getClass().getName())); + return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(rh.gs(R.string.omnipod_common_error_unsupported_custom_command, command.getClass().getName())); } private PumpEnactResult retrievePulseLog() { @@ -893,8 +892,8 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra(ErrorHelperActivity.SOUND_ID, 0); - i.putExtra(ErrorHelperActivity.STATUS, resourceHelper.gs(R.string.omnipod_eros_pod_management_pulse_log_value) + ":\n" + result.toString()); - i.putExtra(ErrorHelperActivity.TITLE, resourceHelper.gs(R.string.omnipod_eros_pod_management_pulse_log)); + i.putExtra(ErrorHelperActivity.STATUS, rh.gs(R.string.omnipod_eros_pod_management_pulse_log_value) + ":\n" + result.toString()); + i.putExtra(ErrorHelperActivity.TITLE, rh.gs(R.string.omnipod_eros_pod_management_pulse_log)); i.putExtra("clipboardContent", result.toString()); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(i); @@ -921,7 +920,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley Notification notification = new Notification( Notification.OMNIPOD_POD_ALERTS_UPDATED, - resourceHelper.gs(R.string.omnipod_common_confirmation_expiration_alerts_updated), + rh.gs(R.string.omnipod_common_confirmation_expiration_alerts_updated), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); } else { @@ -950,7 +949,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley if (!requestedByUser && aapsOmnipodErosManager.isTimeChangeEventEnabled()) { Notification notification = new Notification( Notification.TIME_OR_TIMEZONE_CHANGE, - resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated), + rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); } @@ -963,7 +962,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley if (aapsOmnipodErosManager.isTimeChangeEventEnabled()) { Notification notification = new Notification( Notification.TIME_OR_TIMEZONE_CHANGE, - resourceHelper.gs(R.string.omnipod_eros_error_automatic_time_or_timezone_change_failed), + rh.gs(R.string.omnipod_eros_error_automatic_time_or_timezone_change_failed), Notification.INFO, 60); rxBus.send(new EventNewNotification(notification)); } @@ -1101,7 +1100,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley } if (!success) { aapsLogger.warn(LTag.PUMP, "Failed to retrieve Pod status on startup"); - rxBus.send(new EventNewNotification(new Notification(Notification.OMNIPOD_STARTUP_STATUS_REFRESH_FAILED, resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status_on_startup), Notification.NORMAL))); + rxBus.send(new EventNewNotification(new Notification(Notification.OMNIPOD_STARTUP_STATUS_REFRESH_FAILED, rh.gs(R.string.omnipod_common_error_failed_to_refresh_status_on_startup), Notification.NORMAL))); } } else { aapsLogger.debug(LTag.PUMP, "Not retrieving Pod status on startup: no Pod running"); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java index 7b80482987..9ef3767205 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java @@ -12,7 +12,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class RLHistoryItemOmnipod extends RLHistoryItem { - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; private final OmnipodCommandType omnipodCommandType; public RLHistoryItemOmnipod(HasAndroidInjector injector, OmnipodCommandType omnipodCommandType) { @@ -22,11 +22,11 @@ public class RLHistoryItemOmnipod extends RLHistoryItem { } @Override - public String getDescription(ResourceHelper resourceHelper) { + public String getDescription(ResourceHelper rh) { if (RLHistoryItemSource.OmnipodCommand.equals(source)) { - return resourceHelper.gs(omnipodCommandType.getResourceId()); + return rh.gs(omnipodCommandType.getResourceId()); } - return super.getDescription(resourceHelper); + return super.getDescription(rh); } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java index 097b8145bb..58bb9c8ee9 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java @@ -92,7 +92,7 @@ public class AapsOmnipodErosManager { private final AapsOmnipodUtil aapsOmnipodUtil; private final AAPSLogger aapsLogger; private final RxBus rxBus; - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final HasAndroidInjector injector; private final SP sp; private final OmnipodManager delegate; @@ -124,7 +124,7 @@ public class AapsOmnipodErosManager { AapsSchedulers aapsSchedulers, RxBus rxBus, SP sp, - ResourceHelper resourceHelper, + ResourceHelper rh, HasAndroidInjector injector, OmnipodAlertUtil omnipodAlertUtil, Context context, @@ -136,7 +136,7 @@ public class AapsOmnipodErosManager { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.sp = sp; - this.resourceHelper = resourceHelper; + this.rh = rh; this.injector = injector; this.omnipodAlertUtil = omnipodAlertUtil; this.context = context; @@ -334,7 +334,7 @@ public class AapsOmnipodErosManager { addSuccessToHistory(historyEntryType, profile.getBasalValues()); if (showNotifications) { - showNotification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, null); + showNotification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, null); } dismissNotification(Notification.FAILED_UPDATE_PROFILE); @@ -385,7 +385,7 @@ public class AapsOmnipodErosManager { if (detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB) { showNotification(Notification.OMNIPOD_UNCERTAIN_SMB, getStringResource(R.string.omnipod_eros_error_bolus_failed_uncertain_smb, detailedBolusInfo.insulin), Notification.URGENT, isNotificationUncertainSmbSoundEnabled() ? R.raw.boluserror : null); } else { - showErrorDialog(getStringResource(R.string.omnipod_eros_error_bolus_failed_uncertain), isNotificationUncertainBolusSoundEnabled() ? R.raw.boluserror : null); + showErrorDialog(getStringResource(R.string.omnipod_eros_error_bolus_failed_uncertain), isNotificationUncertainBolusSoundEnabled() ? R.raw.boluserror : 0); } } @@ -954,7 +954,7 @@ public class AapsOmnipodErosManager { } private void showErrorDialog(String message, Integer sound) { - ErrorHelperActivity.Companion.runAlarm(context, message, resourceHelper.gs(R.string.error), sound); + ErrorHelperActivity.Companion.runAlarm(context, message, rh.gs(R.string.error), sound); } private void showPodFaultNotification(FaultEventCode faultEventCode) { @@ -981,7 +981,7 @@ public class AapsOmnipodErosManager { } private String getStringResource(int id, Object... args) { - return resourceHelper.gs(id, args); + return rh.gs(id, args); } public static BasalSchedule mapProfileToBasalSchedule(Profile profile) { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java index 090e754eb2..c6901d30d9 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java @@ -19,8 +19,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin; import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; @@ -114,11 +112,11 @@ public class RileyLinkOmnipodService extends RileyLinkService { if (StringUtils.isEmpty(rileyLinkAddress)) { aapsLogger.debug(LTag.PUMPBTCOMM, "RileyLink address invalid: no address"); - errorDescription = resourceHelper.gs(R.string.omnipod_eros_error_riley_link_address_invalid); + errorDescription = rh.gs(R.string.omnipod_eros_error_riley_link_address_invalid); return false; } else { if (!rileyLinkAddress.matches(REGEX_MAC)) { - errorDescription = resourceHelper.gs(R.string.omnipod_eros_error_riley_link_address_invalid); + errorDescription = rh.gs(R.string.omnipod_eros_error_riley_link_address_invalid); aapsLogger.debug(LTag.PUMPBTCOMM, "RileyLink address invalid: {}", rileyLinkAddress); } else { if (!rileyLinkAddress.equals(this.rileyLinkAddress)) { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java index ab3f39dd38..d9bd63e49e 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java @@ -41,7 +41,7 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { @Inject AAPSLogger aapsLogger; @Inject AapsOmnipodUtil aapsOmnipodUtil; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject ErosHistory erosHistory; private Spinner historyTypeSpinner; @@ -146,7 +146,7 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { statusView.setVisibility(View.GONE); - typeListFull = getTypeList(PumpHistoryEntryGroup.Companion.getTranslatedList(resourceHelper)); + typeListFull = getTypeList(PumpHistoryEntryGroup.Companion.getTranslatedList(rh)); ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, R.layout.spinner_centered, typeListFull); historyTypeSpinner.setAdapter(spinnerAdapter); @@ -248,7 +248,7 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { case SET_TEMPORARY_BASAL: case SPLIT_TEMPORARY_BASAL: { TempBasalPair tempBasalPair = aapsOmnipodUtil.getGsonInstance().fromJson(historyEntry.getData(), TempBasalPair.class); - valueView.setText(resourceHelper.gs(R.string.omnipod_eros_history_tbr_value, tempBasalPair.getInsulinRate(), tempBasalPair.getDurationMinutes())); + valueView.setText(rh.gs(R.string.omnipod_eros_history_tbr_value, tempBasalPair.getInsulinRate(), tempBasalPair.getDurationMinutes())); } break; @@ -263,9 +263,9 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { case SET_BOLUS: { if (historyEntry.getData().contains(";")) { String[] splitVal = historyEntry.getData().split(";"); - valueView.setText(resourceHelper.gs(R.string.omnipod_eros_history_bolus_value_with_carbs, Double.valueOf(splitVal[0]), Double.valueOf(splitVal[1]))); + valueView.setText(rh.gs(R.string.omnipod_eros_history_bolus_value_with_carbs, Double.valueOf(splitVal[0]), Double.valueOf(splitVal[1]))); } else { - valueView.setText(resourceHelper.gs(R.string.omnipod_eros_history_bolus_value, Double.valueOf(historyEntry.getData()))); + valueView.setText(rh.gs(R.string.omnipod_eros_history_bolus_value, Double.valueOf(historyEntry.getData()))); } } break; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt index 06d42d307d..abf0f10318 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt @@ -8,7 +8,7 @@ import android.os.HandlerThread import dagger.android.HasAndroidInjector import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity @@ -45,7 +45,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var rxBus: RxBus @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var podStateManager: ErosPodStateManager @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @@ -85,7 +85,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { binding.buttonDiscardPod.setOnClickListener { OKDialog.showConfirmation(this, - resourceHelper.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), Thread { + rh.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), Thread { aapsOmnipodManager.discardPodState() }) } @@ -110,7 +110,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { commandQueue.customCommand(CommandPlayTestBeep(), object : Callback() { override fun run() { if (!result.success) { - displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, resourceHelper.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment), false) + displayErrorDialog(rh.gs(R.string.omnipod_common_warning), rh.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, rh.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment), false) } } }) @@ -123,7 +123,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { commandQueue.customCommand(CommandReadPulseLog(), object : Callback() { override fun run() { if (!result.success) { - displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, resourceHelper.gs(R.string.omnipod_eros_error_failed_to_read_pulse_log), result.comment), false) + displayErrorDialog(rh.gs(R.string.omnipod_common_warning), rh.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, rh.gs(R.string.omnipod_eros_error_failed_to_read_pulse_log), result.comment), false) } } }) @@ -229,8 +229,8 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { private fun displayNotConfiguredDialog() { context.let { UIRunnable { - OKDialog.show(it, resourceHelper.gs(R.string.omnipod_common_warning), - resourceHelper.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null) + OKDialog.show(it, rh.gs(R.string.omnipod_common_warning), + rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null) }.run() } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt index 710c76c37c..0ec9b83777 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt @@ -5,7 +5,6 @@ import android.graphics.Color import android.os.Bundle import android.os.Handler import android.os.HandlerThread -import android.os.Looper import android.text.TextUtils import android.view.LayoutInflater import android.view.View @@ -15,7 +14,7 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification @@ -70,9 +69,9 @@ class OmnipodErosOverviewFragment : DaggerFragment() { } @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus - @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var omnipodErosPumpPlugin: OmnipodErosPumpPlugin @Inject lateinit var podStateManager: ErosPodStateManager @@ -138,36 +137,36 @@ class OmnipodErosOverviewFragment : DaggerFragment() { buttonBinding.buttonResumeDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandResumeDelivery(), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_delivery_resumed))) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_delivery_resumed))) } buttonBinding.buttonRefreshStatus.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandGetPodStatus(), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)) } buttonBinding.buttonSilenceAlerts.setOnClickListener { disablePodActionButtons() commandQueue.customCommand( CommandSilenceAlerts(), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_silenced_alerts)) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_silenced_alerts)) .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) }) } buttonBinding.buttonSuspendDelivery.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandSuspendDelivery(), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_suspended_delivery))) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_suspended_delivery))) } buttonBinding.buttonSetTime.setOnClickListener { disablePodActionButtons() commandQueue.customCommand(CommandHandleTimeChange(true), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_set_time), true) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))) + DisplayResultDialogCallback(rh.gs(R.string.omnipod_common_error_failed_to_set_time), true) + .messageOnSuccess(rh.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))) } } @@ -232,11 +231,11 @@ class OmnipodErosOverviewFragment : DaggerFragment() { rileyLinkStatusBinding.rileyLinkStatus.text = when { - rileyLinkServiceState == RileyLinkServiceState.NotStarted -> resourceHelper.gs(resourceId) - rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + resourceHelper.gs(resourceId) - rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) - rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + resourceHelper.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.Omnipod)) - else -> "{fa-bluetooth-b} " + resourceHelper.gs(resourceId) + rileyLinkServiceState == RileyLinkServiceState.NotStarted -> rh.gs(resourceId) + rileyLinkServiceState.isConnecting -> "{fa-bluetooth-b spin} " + rh.gs(resourceId) + rileyLinkServiceState.isError && rileyLinkError == null -> "{fa-bluetooth-b} " + rh.gs(resourceId) + rileyLinkServiceState.isError && rileyLinkError != null -> "{fa-bluetooth-b} " + rh.gs(rileyLinkError.getResourceId(RileyLinkTargetDevice.Omnipod)) + else -> "{fa-bluetooth-b} " + rh.gs(resourceId) } rileyLinkStatusBinding.rileyLinkStatus.setTextColor(if (rileyLinkServiceState.isError || rileyLinkError != null) Color.RED else Color.WHITE) } @@ -276,7 +275,7 @@ class OmnipodErosOverviewFragment : DaggerFragment() { podInfoBinding.uniqueId.text = podStateManager.address.toString() podInfoBinding.podLot.text = podStateManager.lot.toString() podInfoBinding.podSequenceNumber.text = podStateManager.tid.toString() - podInfoBinding.firmwareVersion.text = resourceHelper.gs(R.string.omnipod_eros_overview_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString()) + podInfoBinding.firmwareVersion.text = rh.gs(R.string.omnipod_eros_overview_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString()) podInfoBinding.timeOnPod.text = readableZonedTime(podStateManager.time) podInfoBinding.timeOnPod.setTextColor(if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) { @@ -299,32 +298,32 @@ class OmnipodErosOverviewFragment : DaggerFragment() { if (podStateManager.isPodFaulted) { val faultEventCode = podStateManager.faultEventCode - errors.add(resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault_description, faultEventCode.value, faultEventCode.name)) + errors.add(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, faultEventCode.value, faultEventCode.name)) } // base basal rate podInfoBinding.baseBasalRate.text = if (podStateManager.isPodActivationCompleted) { - resourceHelper.gs(R.string.pump_basebasalrate, omnipodErosPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalSchedule.rateAt(TimeUtil.toDuration(DateTime.now())))) + rh.gs(R.string.pump_basebasalrate, omnipodErosPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalSchedule.rateAt(TimeUtil.toDuration(DateTime.now())))) } else { PLACEHOLDER } // total delivered podInfoBinding.totalDelivered.text = if (podStateManager.isPodActivationCompleted && podStateManager.totalInsulinDelivered != null) { - resourceHelper.gs(R.string.omnipod_common_overview_total_delivered_value, podStateManager.totalInsulinDelivered - OmnipodConstants.POD_SETUP_UNITS) + rh.gs(R.string.omnipod_common_overview_total_delivered_value, podStateManager.totalInsulinDelivered - OmnipodConstants.POD_SETUP_UNITS) } else { PLACEHOLDER } // reservoir if (podStateManager.reservoirLevel == null) { - podInfoBinding.reservoir.text = resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value_over50) + podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value_over50) podInfoBinding.reservoir.setTextColor(Color.WHITE) } else { val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() - podInfoBinding.reservoir.text = resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.reservoirLevel) + podInfoBinding.reservoir.text = rh.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.reservoirLevel) podInfoBinding.reservoir.setTextColor(if (podStateManager.reservoirLevel < lowReservoirThreshold) { Color.RED } else { @@ -370,34 +369,34 @@ class OmnipodErosOverviewFragment : DaggerFragment() { private fun updatePodStatus() { podInfoBinding.podStatus.text = if (!podStateManager.hasPodState()) { - resourceHelper.gs(R.string.omnipod_common_pod_status_no_active_pod) + rh.gs(R.string.omnipod_common_pod_status_no_active_pod) } else if (!podStateManager.isPodActivationCompleted) { if (!podStateManager.isPodInitialized) { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIMING_COMPLETED)) { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_activation) } else { - resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) + rh.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) } } } else { if (podStateManager.podProgressStatus.isRunning) { var status = if (podStateManager.isSuspended) { - resourceHelper.gs(R.string.omnipod_common_pod_status_suspended) + rh.gs(R.string.omnipod_common_pod_status_suspended) } else { - resourceHelper.gs(R.string.omnipod_common_pod_status_running) + rh.gs(R.string.omnipod_common_pod_status_running) } if (!podStateManager.isBasalCertain) { - status += " (" + resourceHelper.gs(R.string.omnipod_eros_uncertain) + ")" + status += " (" + rh.gs(R.string.omnipod_eros_uncertain) + ")" } status } else if (podStateManager.podProgressStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { - resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault) + rh.gs(R.string.omnipod_common_pod_status_pod_fault) } else if (podStateManager.podProgressStatus == PodProgressStatus.INACTIVE) { - resourceHelper.gs(R.string.omnipod_common_pod_status_inactive) + rh.gs(R.string.omnipod_common_pod_status_inactive) } else { podStateManager.podProgressStatus.toString() } @@ -413,14 +412,14 @@ class OmnipodErosOverviewFragment : DaggerFragment() { private fun updateLastBolus() { if (podStateManager.isPodActivationCompleted && podStateManager.hasLastBolus()) { - var text = resourceHelper.gs(R.string.omnipod_common_overview_last_bolus_value, omnipodErosPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount), resourceHelper.gs(R.string.insulin_unit_shortname), readableDuration(podStateManager.lastBolusStartTime)) + var text = rh.gs(R.string.omnipod_common_overview_last_bolus_value, omnipodErosPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount), rh.gs(R.string.insulin_unit_shortname), readableDuration(podStateManager.lastBolusStartTime)) val textColor: Int if (podStateManager.isLastBolusCertain) { textColor = Color.WHITE } else { textColor = Color.RED - text += " (" + resourceHelper.gs(R.string.omnipod_eros_uncertain) + ")" + text += " (" + rh.gs(R.string.omnipod_eros_uncertain) + ")" } podInfoBinding.lastBolus.text = text @@ -448,12 +447,12 @@ class OmnipodErosOverviewFragment : DaggerFragment() { var text: String val textColor: Int - text = resourceHelper.gs(R.string.omnipod_common_overview_temp_basal_value, amount, dateUtil.timeString(startTime.millis), minutesRunning, duration.standardMinutes) + text = rh.gs(R.string.omnipod_common_overview_temp_basal_value, amount, dateUtil.timeString(startTime.millis), minutesRunning, duration.standardMinutes) if (podStateManager.isTempBasalCertain) { textColor = Color.WHITE } else { textColor = Color.RED - text += " (" + resourceHelper.gs(R.string.omnipod_eros_uncertain) + ")" + text += " (" + rh.gs(R.string.omnipod_eros_uncertain) + ")" } podInfoBinding.tempBasal.text = text @@ -467,7 +466,7 @@ class OmnipodErosOverviewFragment : DaggerFragment() { textColor = Color.WHITE } else { textColor = Color.RED - text += " (" + resourceHelper.gs(R.string.omnipod_eros_uncertain) + ")" + text += " (" + rh.gs(R.string.omnipod_eros_uncertain) + ")" } podInfoBinding.tempBasal.text = text @@ -546,8 +545,8 @@ class OmnipodErosOverviewFragment : DaggerFragment() { private fun displayNotConfiguredDialog() { context?.let { UIRunnable { - OKDialog.show(it, resourceHelper.gs(R.string.omnipod_common_warning), - resourceHelper.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null) + OKDialog.show(it, rh.gs(R.string.omnipod_common_warning), + rh.gs(R.string.omnipod_eros_error_operation_not_possible_no_configuration), null) }.run() } } @@ -576,7 +575,7 @@ class OmnipodErosOverviewFragment : DaggerFragment() { val isDaylightTime = timeZone.inDaylightTime(timeAsJavaData) val locale = resources.configuration.locales.get(0) val timeZoneDisplayName = timeZone.getDisplayName(isDaylightTime, TimeZone.SHORT, locale) + " " + timeZone.getDisplayName(isDaylightTime, TimeZone.LONG, locale) - return resourceHelper.gs(R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData.time), timeZoneDisplayName) + return rh.gs(R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData.time), timeZoneDisplayName) } private fun readableDuration(dateTime: DateTime): String { @@ -586,32 +585,32 @@ class OmnipodErosOverviewFragment : DaggerFragment() { val seconds = duration.standardSeconds.toInt() when { seconds < 10 -> { - return resourceHelper.gs(R.string.omnipod_common_moments_ago) + return rh.gs(R.string.omnipod_common_moments_ago) } seconds < 60 -> { - return resourceHelper.gs(R.string.omnipod_common_less_than_a_minute_ago) + return rh.gs(R.string.omnipod_common_less_than_a_minute_ago) } seconds < 60 * 60 -> { // < 1 hour - return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_minutes, minutes, minutes)) + return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_minutes, minutes, minutes)) } seconds < 24 * 60 * 60 -> { // < 1 day val minutesLeft = minutes % 60 if (minutesLeft > 0) - return resourceHelper.gs(R.string.omnipod_common_time_ago, - resourceHelper.gs(R.string.omnipod_common_composite_time, resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours), resourceHelper.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))) - return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours)) + return rh.gs(R.string.omnipod_common_time_ago, + rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_hours, hours, hours), rh.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))) + return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_hours, hours, hours)) } else -> { val days = hours / 24 val hoursLeft = hours % 24 if (hoursLeft > 0) - return resourceHelper.gs(R.string.omnipod_common_time_ago, - resourceHelper.gs(R.string.omnipod_common_composite_time, resourceHelper.gq(R.plurals.omnipod_common_days, days, days), resourceHelper.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft))) - return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_days, days, days)) + return rh.gs(R.string.omnipod_common_time_ago, + rh.gs(R.string.omnipod_common_composite_time, rh.gq(R.plurals.omnipod_common_days, days, days), rh.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft))) + return rh.gs(R.string.omnipod_common_time_ago, rh.gq(R.plurals.omnipod_common_days, days, days)) } } } @@ -634,11 +633,11 @@ class OmnipodErosOverviewFragment : DaggerFragment() { if (result.success) { val messageOnSuccess = this.messageOnSuccess if (messageOnSuccess != null) { - displayOkDialog(resourceHelper.gs(R.string.omnipod_common_confirmation), messageOnSuccess) + displayOkDialog(rh.gs(R.string.omnipod_common_confirmation), messageOnSuccess) } actionOnSuccess?.run() } else { - displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment), withSoundOnError) + displayErrorDialog(rh.gs(R.string.omnipod_common_warning), rh.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment), withSoundOnError) } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt index 2297cb2379..20d16a5935 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.deactivat import androidx.annotation.StringRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.R import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandDeactivatePod @@ -16,7 +16,7 @@ import javax.inject.Inject class ErosDeactivatePodViewModel @Inject constructor( private val aapsOmnipodManager: AapsOmnipodErosManager, - private val commandQueueProvider: CommandQueueProvider, + private val commandQueue: CommandQueue, injector: HasAndroidInjector, logger: AAPSLogger, aapsSchedulers: AapsSchedulers @@ -24,7 +24,7 @@ class ErosDeactivatePodViewModel @Inject constructor( override fun doExecuteAction(): Single = Single.create { source -> - commandQueueProvider.customCommand(CommandDeactivatePod(), object : Callback() { + commandQueue.customCommand(CommandDeactivatePod(), object : Callback() { override fun run() { source.onSuccess(result) } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java index 2ac8d0cdf2..28aef360fa 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java @@ -29,13 +29,13 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; @Singleton public class AapsOmnipodUtil { - private final ResourceHelper resourceHelper; + private final ResourceHelper rh; private final Gson gsonInstance = createGson(); @Inject - public AapsOmnipodUtil(ResourceHelper resourceHelper) { - this.resourceHelper = resourceHelper; + public AapsOmnipodUtil(ResourceHelper rh) { + this.rh = rh; } private Gson createGson() { @@ -68,21 +68,21 @@ public class AapsOmnipodUtil { private String translateAlertType(AlertType alertType) { if (alertType == null) { - return resourceHelper.gs(R.string.omnipod_common_alert_unknown_alert); + return rh.gs(R.string.omnipod_common_alert_unknown_alert); } switch (alertType) { case FINISH_PAIRING_REMINDER: - return resourceHelper.gs(R.string.omnipod_common_alert_finish_pairing_reminder); + return rh.gs(R.string.omnipod_common_alert_finish_pairing_reminder); case FINISH_SETUP_REMINDER: - return resourceHelper.gs(R.string.omnipod_common_alert_finish_setup_reminder_reminder); + return rh.gs(R.string.omnipod_common_alert_finish_setup_reminder_reminder); case EXPIRATION_ALERT: - return resourceHelper.gs(R.string.omnipod_common_alert_expiration); + return rh.gs(R.string.omnipod_common_alert_expiration); case EXPIRATION_ADVISORY_ALERT: - return resourceHelper.gs(R.string.omnipod_common_alert_expiration_advisory); + return rh.gs(R.string.omnipod_common_alert_expiration_advisory); case SHUTDOWN_IMMINENT_ALARM: - return resourceHelper.gs(R.string.omnipod_common_alert_shutdown_imminent); + return rh.gs(R.string.omnipod_common_alert_shutdown_imminent); case LOW_RESERVOIR_ALERT: - return resourceHelper.gs(R.string.omnipod_common_alert_low_reservoir); + return rh.gs(R.string.omnipod_common_alert_low_reservoir); default: return alertType.name(); } diff --git a/omnipod-eros/src/main/res/values-bg-rBG/strings.xml b/omnipod-eros/src/main/res/values-bg-rBG/strings.xml index 5b26a40bd0..7be3613e82 100644 --- a/omnipod-eros/src/main/res/values-bg-rBG/strings.xml +++ b/omnipod-eros/src/main/res/values-bg-rBG/strings.xml @@ -65,6 +65,7 @@ Pulse лог Pulse log(копиран в клипборда) + Напълни нов Под с достатъчно инсулин за 3 дена. \n\nОслушвай се за две бипкания от Пода по време на пълненето. Те означават че минималното количество от 80 единици вече е въведено. Моля подсигурете се, че напълно сте изпразнили спринцовката, дори след като сте чули дукратното бипкане. \n\nСлед пълненето на Пода, моля натинсте Следващ.\n\nЗабележка: не махайте все още капчаката на иглата на Пода.\nЗабележка:Моля поставете RileyLink в изправена позиция и поставере Пода на няколко сантиметра от него. Опитвам се да се сдвоя с Pod.\n\nКогато всички елементи са проверени, можете да натиснете Следващ.\n\nЗабележка: задръжте Pod много близо до RileyLink в този момент. неизвестно diff --git a/omnipod-eros/src/main/res/values-hu-rHU/strings.xml b/omnipod-eros/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..bc89093c83 --- /dev/null +++ b/omnipod-eros/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/omnipod-eros/src/main/res/values-it-rIT/strings.xml b/omnipod-eros/src/main/res/values-it-rIT/strings.xml index 4aa838fcff..e868194eb9 100644 --- a/omnipod-eros/src/main/res/values-it-rIT/strings.xml +++ b/omnipod-eros/src/main/res/values-it-rIT/strings.xml @@ -17,7 +17,7 @@ Storico pod Descrizione - Fonte + Origine Data Tipo: %1$.2f U diff --git a/omnipod-eros/src/main/res/values-iw-rIL/strings.xml b/omnipod-eros/src/main/res/values-iw-rIL/strings.xml index fc5c628e92..53c96db90e 100644 --- a/omnipod-eros/src/main/res/values-iw-rIL/strings.xml +++ b/omnipod-eros/src/main/res/values-iw-rIL/strings.xml @@ -22,7 +22,7 @@ סוג: %1$.2f יח\' %1$.2f יח\', פחמ\'= %2$.1f גר\' - קצב: %1$.2f יח\', משך: %2$d דק\' + מינון: %1$.2f יח\', משך: %2$d דק\' סול\' ריילי: %1$d diff --git a/omnipod-eros/src/main/res/values-tr-rTR/strings.xml b/omnipod-eros/src/main/res/values-tr-rTR/strings.xml index bc89093c83..7fcf983132 100644 --- a/omnipod-eros/src/main/res/values-tr-rTR/strings.xml +++ b/omnipod-eros/src/main/res/values-tr-rTR/strings.xml @@ -1,13 +1,73 @@ + Omnipod Eros için pompa entegrasyonu (şeffaf iğne kapaklı eski model). En az donanım yazılımı sürümü 2.0 olan bir RileyLink cihazı gerektirir. + RileyLink Yapılandırması + Bildirimler + Pod Yönetimi menüsünde Nabız Günlüğü düğmesini göster + Pod Yönetimi menüsünde RileyLink İstatistikleri düğmesini göster + Eylemler\'de pil değişikliği günlüğünü etkinleştir + RileyLink + Belirsiz GBO bildirimleri için ses etkinleştirildi + Belirsiz SMB bildirimleri için ses etkinleştirildi + Belirsiz bolus bildirimleri için ses etkinleştirildi + Pod Geçmişi + Açıklama + Kaynak + Tarih + Tip: + %1$.2f Ü + %1$.2f Ü, CH=%2$.1f g + Oran: %1$.2f Ü, süre: %2$d dakika + RLPili: %1$d + RileyLink adresi geçersiz. + İletişim başarısız oldu: mesaj bütünlüğü doğrulaması başarısız oldu + İletişim başarısız oldu: Pod\'dan geçersiz bir paket alındı + İletişim başarısız oldu: Pod yanlış durumda + İletişim başarısız oldu: Pod\'dan geçersiz bir yanıt alındı + İletişim başarısız oldu: Pod\'dan geçersiz sıra numarasına sahip bir mesaj alındı + İletişim başarısız oldu: Pod\'dan geçersiz adres içeren bir mesaj alındı + İletişim başarısız oldu: Pod\'dan gelen mesajın kodu çözülemedi + İletişim başarısız oldu: Senkronizasyon başarısızlığı + İletişim başarısız oldu: Senkronizasyon dışı + İletişim başarısız oldu: Pod\'dan yeterli veri alınmadı + Pod hatası (%1$03d %2$s) algılandı. Lütfen Pod\'unuzu devre dışı bırakın ve yeni bir tane etkinleştirin + İletişim başarısız oldu: Pod bir hata yanıtı verdi + RileyLink yanıt vermiyor + RileyLink kesintiye uğradı + Pod yanıt vermiyor + Bazal profil ayar hatası. İletim askıya alınabilir! Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin ve gerekirse iletime devam edin. + Bazal profil ayarı hatalı olabilir. İletim askıya alınabilir! Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin ve gerekirse iletime devam edin. + Bazal profil ayar hatası. İletim askıya alındı! Lütfen insülin iletimini Omnipod sekmesinden manuel olarak devam ettirin. + Geçici bazal iptal işlemi başarısız olabilir. Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin. + Geçici bazal ayar hatası. Geçici bir bazal önceden çalışıyorsa, iptal edilmiş olabilir. Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin. + Geçici bazal ayarı hatalı olabilir. Geçici bir bazal daha önce çalışıyorsa, iptal edilmiştir. Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin. + GBO (TBR) süresi sıfırdan büyük ve %1$s dakikanın katı olmalıdır. + Zaman ayarı hatalı olabilir. İletim askıya alınabilir! Lütfen Omnipod sekmesinden Pod durumunu manuel olarak yenileyin ve gerekirse iletime devam edin. + Zaman ayarı hatalı. İletim askıya alındı! Lütfen insülin iletimini Omnipod sekmesinden manuel olarak devam ettirin. + Nabız Günlüğü okunamadı + Pod\'daki saat otomatik olarak değiştirilemedi. Omnipod sekmesinde saati manuel olarak senkronize etmelisiniz. + İşlem mümkün değil.\n\nBu işlemi kullanmadan önce Omnipod\'u yapılandırmanız gerekir. + Bolusun başarılı olup olmadığı doğrulanamıyor. Lütfen tıklamaları dinleyerek Pod\'unuzun bolus yaptığını doğrulayın. Bolusun iletilmediğinden eminseniz, bolus girişini \'Bolusu iptal et\'i tıklayarak iptal etseniz bile Tedaviler\'den de silmelisiniz! + SMB bolusunun (%1$.2f Ü) başarılı olup olmadığı doğrulanamadı. Bolusun iletilmediğinden eminseniz, SMB girişini Tedaviler\'den de silmelisiniz. + Pod\'da geçici bir bazal çalışıyor, ancak AAPS bu geçici bazaldan habersiz. Lütfen geçici bazalınızı manuel olarak iptal edin. + RileyLink Durumu + RileyLink bağlantısı bekleniyor… + RileyLink Yapılandırmasını Sıfırla + Nabız Günlüğünü Oku + Nabız Günlüğü Okunuyor… + Nabız Günlüğü + Nabız Günlüğü (panoya kopyalandı) + Yeni bir Pod\'u 3 gün yetecek kadar insülinle doldurun.\n\nDoldurma işlemi sırasında Pod\'dan iki bip sesi gelecektir. Bu ses, minimum 80Ü insülinin eklendiğini gösterir. İki bip sesini duyduktan sonra bile doldurma şırıngasını tamamen boşalttığınızdan emin olun.\n\nPod\'u doldurduktan sonra lütfen İleri\'ye basın.\n\nNot: Bu sırada Pod\'un iğne kapağını çıkarmayın.\nNot: lütfen RileyLink\'i dik konuma getirin ve Pod\'u ondan birkaç cm uzağa yerleştirin. + Yeni Pod eşleştiriliyor ve kullanıma hazırlanıyor.\n\nBaşlatma işlemi başarıyla tamamlandığında, İleri\'ye basabilirsiniz.\n\nNot: lütfen RileyLink\'i dik konuma getirin ve Pod\'u ondan birkaç cm uzağa yerleştirin. + belirsiz diff --git a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt index b0630305f1..4535d5e013 100644 --- a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt +++ b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt @@ -5,7 +5,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.bus.RxBus @@ -32,18 +32,18 @@ import java.util.* class OmnipodErosPumpPluginTest : TestBase() { @Mock lateinit var injector: HasAndroidInjector - @Mock lateinit var resourceHelper: ResourceHelper + @Mock lateinit var rh: ResourceHelper @Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var activePlugin: ActivePlugin @Mock lateinit var aapsOmnipodErosManager: AapsOmnipodErosManager @Mock lateinit var erosHistory: ErosHistory - @Mock lateinit var commandQueueProvider: CommandQueueProvider + @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var rileyLinkUtil: RileyLinkUtil @Mock lateinit var pumpSync: PumpSync var rxBusWrapper = RxBus(TestAapsSchedulers(), aapsLogger) @Before fun prepare() { - `when`(resourceHelper.gs(ArgumentMatchers.anyInt(), ArgumentMatchers.anyLong())) + `when`(rh.gs(ArgumentMatchers.anyInt(), ArgumentMatchers.anyLong())) .thenReturn("") } @@ -53,7 +53,7 @@ class OmnipodErosPumpPluginTest : TestBase() { // mock all the things val plugin = OmnipodErosPumpPlugin( injector, aapsLogger, TestAapsSchedulers(), rxBusWrapper, null, - resourceHelper, activePlugin, null, null, erosHistory, aapsOmnipodErosManager, commandQueueProvider, + rh, activePlugin, null, null, erosHistory, aapsOmnipodErosManager, commandQueue, null, null, null, null, rileyLinkUtil, null, null, pumpSync ) diff --git a/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt b/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt index 4ac5225d87..b8a8424b1a 100644 --- a/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt +++ b/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt @@ -47,7 +47,7 @@ import javax.inject.Singleton @Singleton class OpenHumansUploader @Inject internal constructor( injector: HasAndroidInjector, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, private val sp: SP, private val context: Context, @@ -66,7 +66,7 @@ class OpenHumansUploader @Inject internal constructor( .description(R.string.open_humans_description) .preferencesId(R.xml.pref_openhumans) .fragmentClass(OHFragment::class.qualifiedName), - aapsLogger, resourceHelper, injector + aapsLogger, rh, injector ) { private var openHumansState by stateDelegate @@ -591,14 +591,14 @@ class OpenHumansUploader @Inject internal constructor( notificationManagerCompat.createNotificationChannel( NotificationChannel( NOTIFICATION_CHANNEL_WORKER, - resourceHelper.gs(R.string.open_humans_uploading), + rh.gs(R.string.open_humans_uploading), NotificationManager.IMPORTANCE_MIN ) ) notificationManagerCompat.createNotificationChannel( NotificationChannel( NOTIFICATION_CHANNEL_MESSAGES, - resourceHelper.gs(R.string.open_humans_notifications), + rh.gs(R.string.open_humans_notifications), NotificationManager.IMPORTANCE_DEFAULT ) ) @@ -606,8 +606,8 @@ class OpenHumansUploader @Inject internal constructor( private suspend fun handleSignOut() { val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_MESSAGES) - .setContentTitle(resourceHelper.gs(R.string.you_have_been_signed_out_of_open_humans)) - .setContentText(resourceHelper.gs(R.string.click_here_to_sign_in_again_if_this_wasnt_on_purpose)) + .setContentTitle(rh.gs(R.string.you_have_been_signed_out_of_open_humans)) + .setContentText(rh.gs(R.string.click_here_to_sign_in_again_if_this_wasnt_on_purpose)) .setStyle(NotificationCompat.BigTextStyle()) .setSmallIcon(R.drawable.open_humans_notification) .setAutoCancel(true) diff --git a/openhumans/src/main/res/values-bg-rBG/strings.xml b/openhumans/src/main/res/values-bg-rBG/strings.xml index f5a10ce1ce..80e2ef9000 100644 --- a/openhumans/src/main/res/values-bg-rBG/strings.xml +++ b/openhumans/src/main/res/values-bg-rBG/strings.xml @@ -2,9 +2,18 @@ Open Humans OH + Open Humans ви позволява да качите информация за вашия диабет и да я дарите с цел развитеи на науките. Изход + Настройка + Open Humansбеше настроен. В случай че искате да спреде качването на данни, натиснете \'Изход\'. + Open Humans в момента е неактивна. За да започнете да качвате данни, моля натиснете \'Настройка\'. + Project Member ID: %1$s Качване, само при свързано WiFi Качване само при зареждане + Качване на данни към Open Humans… + Open Humans нотификации + AndroidAPS в момента качва данни към Open Humans. Това може да отнеме известно време. Излязохте от \"Open Humans\". Натиснете тук за да влезете отново, ако това не е било нарочно. + Качи сега diff --git a/openhumans/src/main/res/values-hu-rHU/strings.xml b/openhumans/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/openhumans/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/openhumans/src/main/res/values-tr-rTR/strings.xml b/openhumans/src/main/res/values-tr-rTR/strings.xml index 3ea04e700d..e9ed6c77ce 100644 --- a/openhumans/src/main/res/values-tr-rTR/strings.xml +++ b/openhumans/src/main/res/values-tr-rTR/strings.xml @@ -1,2 +1,19 @@ - + + Open Humans + OH + Open Humans, diyabet verilerinizi yüklemenize ve bilimsel projelere bağış yapmanıza olanak tanır. + Çıkış + Kurulum + Open Humans kuruldu. Yüklemeyi durdurmak isterseniz, \'Çıkış\'ı tıklayın. + Open Humans şu anda etkin değil. Veri yüklemeye başlamak için \'Kurulum\'u tıklayın. + Proje Üye Kimliği: %1$s + Yalnızca WiFi\'ye bağlandığında yükle + Yalnızca şarj olurken yükleyin + Open Humans Yükleniyor… + Open Humans Bildirimleri + AndroidAPS, Open Humans\'a yükleniyor. Bu biraz zaman alabilir. + Open Humans\'dan çıkış yaptınız + Bu bilerek yapılmadıysa tekrar oturum açmak için burayı tıklayın. + Şimdi yükle + diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt index 7b34490067..5960258c71 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt @@ -43,9 +43,9 @@ abstract class PumpPluginAbstract protected constructor( pluginDescription: PluginDescription?, pumpType: PumpType, injector: HasAndroidInjector?, - resourceHelper: ResourceHelper, + rh: ResourceHelper, aapsLogger: AAPSLogger, - commandQueue: CommandQueueProvider, + commandQueue: CommandQueue, var rxBus: RxBus, var activePlugin: ActivePlugin, var sp: SP, @@ -55,7 +55,7 @@ abstract class PumpPluginAbstract protected constructor( var aapsSchedulers: AapsSchedulers, var pumpSync: PumpSync, var pumpSyncStorage: info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage -) : PumpPluginBase(pluginDescription!!, injector!!, aapsLogger, resourceHelper, commandQueue), Pump, Constraints, info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator { +) : PumpPluginBase(pluginDescription!!, injector!!, aapsLogger, rh, commandQueue), Pump, Constraints, info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator { private val disposable = CompositeDisposable() diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt index 21b95367ea..fd62104314 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt @@ -35,16 +35,16 @@ enum class PumpHistoryEntryGroup(val resourceId: Int) { private var translatedList: MutableList? = null - private fun doTranslation(resourceHelper: ResourceHelper) { + private fun doTranslation(rh: ResourceHelper) { translatedList = ArrayList() for (pumpHistoryEntryGroup in values()) { - pumpHistoryEntryGroup.translated = resourceHelper.gs(pumpHistoryEntryGroup.resourceId) + pumpHistoryEntryGroup.translated = rh.gs(pumpHistoryEntryGroup.resourceId) (translatedList as ArrayList).add(pumpHistoryEntryGroup) } } - fun getTranslatedList(resourceHelper: ResourceHelper): List { - if (translatedList == null) doTranslation(resourceHelper) + fun getTranslatedList(rh: ResourceHelper): List { + if (translatedList == null) doTranslation(rh) return translatedList!! } } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.java index 227b642d8c..783372ffd4 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.java @@ -49,7 +49,7 @@ public class RileyLinkBLEConfigActivity extends NoSplashAppCompatActivity { @Inject AAPSLogger aapsLogger; @Inject SP sp; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject BlePreCheck blePrecheck; @Inject RileyLinkUtil rileyLinkUtil; @Inject ActivePlugin activePlugin; @@ -233,7 +233,7 @@ public class RileyLinkBLEConfigActivity extends NoSplashAppCompatActivity { @Override public void onScanFailed(int errorCode) { Log.e("Scan Failed", "Error Code: " + errorCode); - Toast.makeText(RileyLinkBLEConfigActivity.this, resourceHelper.gs(R.string.riley_link_ble_config_scan_error, errorCode), + Toast.makeText(RileyLinkBLEConfigActivity.this, rh.gs(R.string.riley_link_ble_config_scan_error, errorCode), Toast.LENGTH_LONG).show(); } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt index 130d018f56..d49d5c9529 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt @@ -33,16 +33,16 @@ open class EventRileyLinkDeviceStatusChange : EventStatus { this.errorDescription = errorDescription } - override fun getStatus(resourceHelper: ResourceHelper): String { + override fun getStatus(rh: ResourceHelper): String { val rileyLinkServiceState = this.rileyLinkServiceState ?: return "" val resourceId = rileyLinkServiceState.resourceId val rileyLinkError = this.rileyLinkError if (rileyLinkServiceState.isError && rileyLinkError != null) { val rileyLinkTargetDevice = this.rileyLinkTargetDevice ?: return "" - return resourceHelper.gs(rileyLinkError.getResourceId(rileyLinkTargetDevice)) + return rh.gs(rileyLinkError.getResourceId(rileyLinkTargetDevice)) } - return resourceHelper.gs(resourceId) + return rh.gs(resourceId) } } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java index d17bcdb5ce..383bd761aa 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java @@ -51,7 +51,7 @@ public class RFSpy { private static final int LOW_BATTERY_PERCENTAGE_THRESHOLD = 20; @Inject AAPSLogger aapsLogger; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject SP sp; @Inject RileyLinkServiceData rileyLinkServiceData; @Inject RileyLinkUtil rileyLinkUtil; @@ -367,7 +367,7 @@ public class RFSpy { if (rileyLinkServiceData.firmwareVersion != null && rileyLinkServiceData.firmwareVersion.isSameVersion(RileyLinkFirmwareVersion.Version2AndHigher)) { if (sp.getString(RileyLinkConst.Prefs.Encoding, "None") - .equals(resourceHelper.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { + .equals(rh.gs(R.string.key_medtronic_pump_encoding_4b6b_rileylink))) { encoding = RileyLinkEncodingType.FourByteSixByteRileyLink; } } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java index 64d6950020..8ade0413e1 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java @@ -29,18 +29,18 @@ public enum RileyLinkEncodingType { this.resourceId = resourceId; } - private static void doTranslation(ResourceHelper resourceHelper) { + private static void doTranslation(ResourceHelper rh) { encodingTypeMap = new HashMap<>(); for (RileyLinkEncodingType encType : values()) { if (encType.resourceId != null) { - encodingTypeMap.put(resourceHelper.gs(encType.resourceId), encType); + encodingTypeMap.put(rh.gs(encType.resourceId), encType); } } } - public static RileyLinkEncodingType getByDescription(String description, ResourceHelper resourceHelper) { - if (encodingTypeMap == null) doTranslation(resourceHelper); + public static RileyLinkEncodingType getByDescription(String description, ResourceHelper rh) { + if (encodingTypeMap == null) doTranslation(rh); if (encodingTypeMap.containsKey(description)) { return encodingTypeMap.get(description); } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java index 50bdcf4c5b..155021f457 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java @@ -57,13 +57,13 @@ public class RLHistoryItem { return errorCode; } - public String getDescription(ResourceHelper resourceHelper) { + public String getDescription(ResourceHelper rh) { switch (this.source) { case RileyLink: - return "State: " + resourceHelper.gs(serviceState.getResourceId()) + return "State: " + rh.gs(serviceState.getResourceId()) + (this.errorCode == null ? "" : ", Error Code: " + errorCode); case MedtronicPump: - return resourceHelper.gs(pumpDeviceState.getResourceId()); + return rh.gs(pumpDeviceState.getResourceId()); default: return "Unknown Description"; } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java index beff5bb026..40fc09fd55 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusActivity.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; private SectionsPagerAdapter sectionsPagerAdapter; private TabLayout tabLayout; @@ -60,8 +60,8 @@ public class RileyLinkStatusActivity extends NoSplashAppCompatActivity { public void setupViewPager() { sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - sectionsPagerAdapter.addFragment(new RileyLinkStatusGeneralFragment(), resourceHelper.gs(R.string.rileylink_settings_tab1)); - sectionsPagerAdapter.addFragment(new RileyLinkStatusHistoryFragment(), resourceHelper.gs(R.string.rileylink_settings_tab2)); + sectionsPagerAdapter.addFragment(new RileyLinkStatusGeneralFragment(), rh.gs(R.string.rileylink_settings_tab1)); + sectionsPagerAdapter.addFragment(new RileyLinkStatusHistoryFragment(), rh.gs(R.string.rileylink_settings_tab2)); viewPager.setAdapter(sectionsPagerAdapter); } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index df240c2acb..673be8f526 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -36,7 +36,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re private static final String PLACEHOLDER = "-"; @Inject ActivePlugin activePlugin; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject AAPSLogger aapsLogger; @Inject RileyLinkServiceData rileyLinkServiceData; @Inject DateUtil dateUtil; @@ -89,29 +89,29 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Override public void refreshData() { RileyLinkTargetDevice targetDevice = rileyLinkServiceData.targetDevice; - this.connectionStatus.setText(resourceHelper.gs(rileyLinkServiceData.rileyLinkServiceState.getResourceId())); + this.connectionStatus.setText(rh.gs(rileyLinkServiceData.rileyLinkServiceState.getResourceId())); this.configuredRileyLinkAddress.setText(Optional.ofNullable(rileyLinkServiceData.rileyLinkAddress).orElse(PLACEHOLDER)); this.configuredRileyLinkName.setText(Optional.ofNullable(rileyLinkServiceData.rileyLinkName).orElse(PLACEHOLDER)); - if (sp.getBoolean(resourceHelper.gs(R.string.key_riley_link_show_battery_level), false)) { + if (sp.getBoolean(rh.gs(R.string.key_riley_link_show_battery_level), false)) { batteryLevelRow.setVisibility(View.VISIBLE); Integer batteryLevel = rileyLinkServiceData.batteryLevel; - this.batteryLevel.setText(batteryLevel == null ? PLACEHOLDER : resourceHelper.gs(R.string.rileylink_battery_level_value, batteryLevel)); + this.batteryLevel.setText(batteryLevel == null ? PLACEHOLDER : rh.gs(R.string.rileylink_battery_level_value, batteryLevel)); } else { batteryLevelRow.setVisibility(View.GONE); } RileyLinkError rileyLinkError = rileyLinkServiceData.rileyLinkError; - this.connectionError.setText(rileyLinkError == null ? PLACEHOLDER : resourceHelper.gs(rileyLinkError.getResourceId(targetDevice))); + this.connectionError.setText(rileyLinkError == null ? PLACEHOLDER : rh.gs(rileyLinkError.getResourceId(targetDevice))); if (rileyLinkServiceData.isOrange && rileyLinkServiceData.versionOrangeFirmware!=null) { - this.firmwareVersion.setText(resourceHelper.gs(R.string.rileylink_firmware_version_value_orange, + this.firmwareVersion.setText(rh.gs(R.string.rileylink_firmware_version_value_orange, rileyLinkServiceData.versionOrangeFirmware, Optional.ofNullable(rileyLinkServiceData.versionOrangeHardware).orElse(PLACEHOLDER))); } else { - this.firmwareVersion.setText(resourceHelper.gs(R.string.rileylink_firmware_version_value, + this.firmwareVersion.setText(rh.gs(R.string.rileylink_firmware_version_value, Optional.ofNullable(rileyLinkServiceData.versionBLE113).orElse(PLACEHOLDER), Optional.ofNullable(rileyLinkServiceData.versionCC110).orElse(PLACEHOLDER))); } @@ -130,12 +130,12 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re this.pumpFrequency.setText(rileyLinkPumpInfo.getPumpFrequency()); if (rileyLinkServiceData.lastGoodFrequency != null) { - this.lastUsedFrequency.setText(resourceHelper.gs(R.string.rileylink_pump_frequency_value, rileyLinkServiceData.lastGoodFrequency)); + this.lastUsedFrequency.setText(rh.gs(R.string.rileylink_pump_frequency_value, rileyLinkServiceData.lastGoodFrequency)); } long lastConnectionTimeMillis = rileyLinkPumpDevice.getLastConnectionTimeMillis(); if (lastConnectionTimeMillis == 0) { - this.lastDeviceContact.setText(resourceHelper.gs(R.string.riley_link_ble_config_connected_never)); + this.lastDeviceContact.setText(rh.gs(R.string.riley_link_ble_config_connected_never)); } else { this.lastDeviceContact.setText(StringUtil.toDateTimeString(dateUtil, new LocalDateTime(lastConnectionTimeMillis))); } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java index 7ae38c4d58..862b6b343c 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java @@ -32,7 +32,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class RileyLinkStatusHistoryFragment extends DaggerFragment implements RefreshableInterface { @Inject RileyLinkUtil rileyLinkUtil; - @Inject ResourceHelper resourceHelper; + @Inject ResourceHelper rh; @Inject DateUtil dateUtil; RecyclerView recyclerView; @@ -135,7 +135,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re if (item != null) { holder.timeView.setText(dateUtil.dateAndTimeAndSecondsString(item.getDateTime().toDateTime().getMillis())); holder.typeView.setText(item.getSource().getDesc()); - holder.valueView.setText(item.getDescription(resourceHelper)); + holder.valueView.setText(item.getDescription(rh)); } } diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java index a9ac2ee579..2f45c47afe 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.java @@ -41,7 +41,7 @@ public abstract class RileyLinkService extends DaggerService { @Inject protected RxBus rxBus; @Inject protected RileyLinkUtil rileyLinkUtil; @Inject protected HasAndroidInjector injector; - @Inject protected ResourceHelper resourceHelper; + @Inject protected ResourceHelper rh; @Inject protected RileyLinkServiceData rileyLinkServiceData; @Inject protected ActivePlugin activePlugin; @Inject protected RileyLinkBLE rileyLinkBLE; // android-bluetooth management diff --git a/rileylink/src/main/res/values-bg-rBG/strings.xml b/rileylink/src/main/res/values-bg-rBG/strings.xml index a137789211..39677d33e8 100644 --- a/rileylink/src/main/res/values-bg-rBG/strings.xml +++ b/rileylink/src/main/res/values-bg-rBG/strings.xml @@ -36,6 +36,7 @@ Последно връзка: Firmware версия: BLE113: %1$s\nCC110: %2$s + Fw: %1$s\nHw: %2$s Сериен номер на помпа: Честота на помпата: %1$.2f MHz @@ -64,6 +65,7 @@ Да Не + Покажи нивото на батерията на OrangeLink/EmaLink/DiaLink НЕ работи с оригиналната RileyLink. Може да не работи с други RileyLink алтернативи. %1$d ден @@ -73,4 +75,6 @@ %1$d часа %1$d часа + Използвай сканиране + Сканирай преди да се свържеш с OrangeLink, това би трябвало да подобри връзката (също може да се използва с други RileyLink клонинги, ако е необходимо) diff --git a/rileylink/src/main/res/values-hu-rHU/strings.xml b/rileylink/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..0a73dfc845 --- /dev/null +++ b/rileylink/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/rileylink/src/main/res/values-tr-rTR/strings.xml b/rileylink/src/main/res/values-tr-rTR/strings.xml index 0a73dfc845..9658de7a8a 100644 --- a/rileylink/src/main/res/values-tr-rTR/strings.xml +++ b/rileylink/src/main/res/values-tr-rTR/strings.xml @@ -2,9 +2,79 @@ + Tarama + Dur + Seçili + RileyLink Tarama + Taranıyor + Tarama tamamlandı + Tarama Hatası:%1$d + Hiçbir zaman + Şu Anda Seçili RileyLink + Kaldır + RileyLink\'inizi kaldırmak istediğinizden emin misiniz? + RileyLink\'i Kaldır + RileyLink seçilmedi + Ayarlar + Geçmiş + RileyLink Durumu + Pompa Durumu + RileyLink Ayarları + RileyLink + Adres: + Ad: + Pil seviyesi: + %1$d%% + Bağlantı durumu: + Bağlantı Hatası: + Cihaz + Cihaz Tipi: + Yapılandırılan Cihaz Modeli: + Bağlı Cihaz Modeli: + Son Kullanılan Frekans: + Son Cihaz İletişimi: + Firmware versiyonu: + BLE113: %1$s\nCC110: %2$s + Fw: %1$s\nHw: %2$s + Pompa Seri Numarası: + Pompa Frekansı: + %1$.2f MHz + Bluetooth Başlatılıyor… + Bluetooth Hatası + Bluetooth Hazır + Başlatılmadı + RileyLink Başlatılıyor… + RileyLink Hatası + RileyLink ve Pompa Ayarlanıyor + Pompaya bağlanma sorunu + Bağlandı + RileyLink hazır + Cihaz RileyLink değil + RileyLink\'e erişilemiyor + Bluetooth devre dışı + Bluetooth Adaptörü Yok + Ayarlama Başarısız + Pompaya ulaşılamıyor + Pod\'a erişilemiyor + Medtronic Pompa + Omnipod (Eros) + Evet + Hayır + OrangeLink/EmaLink/DiaLink tarafından bildirilen pil seviyesini göster + Orijinal RileyLink ile ÇALIŞMAZ. Diğer RileyLink alternatifleriyle de çalışmayabilir. + + %1$d gün + %1$d gün + + + %1$d saat + %1$d saat + + Taramayı Kullan + OrangeLink\'e bağlanmadan önce tarayın, bağlantıları iyileştirebilir (gerekirse diğer RileyLink klonlarıyla da kullanılabilir) diff --git a/wear/src/main/res/values-bg-rBG/strings.xml b/wear/src/main/res/values-bg-rBG/strings.xml index 14b258864b..5b9a48ce59 100644 --- a/wear/src/main/res/values-bg-rBG/strings.xml +++ b/wear/src/main/res/values-bg-rBG/strings.xml @@ -69,6 +69,7 @@ уд. въгл. Настройки Статус + Ре-синхр. Пълнене на сет Без Стандартен @@ -131,4 +132,8 @@ Вашият цвят: Насищане на цвета: Вашата цветна прозрачност: + AAPS Прогрес на болуса + AAPS Прогрес на болуса Безшумно + Прогрес на болуса и отказ + Прогрес на болуса и отказ с по-малко вибрации diff --git a/wear/src/main/res/values-hu-rHU/strings.xml b/wear/src/main/res/values-hu-rHU/strings.xml new file mode 100644 index 0000000000..3ea04e700d --- /dev/null +++ b/wear/src/main/res/values-hu-rHU/strings.xml @@ -0,0 +1,2 @@ + + diff --git a/wear/src/main/res/values-iw-rIL/strings.xml b/wear/src/main/res/values-iw-rIL/strings.xml index 5702c3b293..c507be2de5 100644 --- a/wear/src/main/res/values-iw-rIL/strings.xml +++ b/wear/src/main/res/values-iw-rIL/strings.xml @@ -26,7 +26,7 @@ הצג דלתא ממוצעת הצג את סוללת הטלפון הצג את סוללת ה-Rig - הצג קצב בזאלי + הצג מינון בזאלי הצג סטטוס לולאה הצג רמת סוכר הצג חץ כיוון diff --git a/wear/src/main/res/values-tr-rTR/strings.xml b/wear/src/main/res/values-tr-rTR/strings.xml index 3ea04e700d..45b19b8a8f 100644 --- a/wear/src/main/res/values-tr-rTR/strings.xml +++ b/wear/src/main/res/values-tr-rTR/strings.xml @@ -1,2 +1,139 @@ - + + AAPS + AAPS + AAPS + AAPS(Büyük) + AAPS(BüyükGrafik) + AAPS(GrafikYok) + AAPS(Daire) + AAPSv2 + AAPS(Cockpit) + AAPS(Steampunk) + AAPS(DijitalStil) + Veri yok! + Eski veri! + %1$s den beri + AAPS ile eşitle! + %1$s\' den bu yana veri alınmıyor! Telefondaki AAPS \' nin veri gönderip göndermediğini kontrol edin + AAPS verileri %1$s eski! Sensörleri denetleyin, xDrip+, NS, AAPS yapılandırma ya da diğerleri! + Bolus\'ta Titreşim + Eylemler için Birimler + Tarihi Göster + IOB\'yi göster + COB\'u göster + Deltayı göster + OrtDelta\'yı Göster + Telefon Pilini Göster + Teçhizat Pilini Göster + Bazal Oranı Göster + Döngü Durumunu Göster + KŞ\'ni göster + Yön Oku Göster + Önce Göster + Koyu + Bazalları Vurgula + Eşleşen bölücü + Grafik Zaman Çerçevesi + 1 saat + 2 saat + 3 saat + 4 saat + 5 saat + Giriş Tasarımı + Varsayılan + Hızlı Sağ + Hızlı Sol + Modern Seyrek + Delta Tanecikliliği (Steampunk) + Düşük + Orta + Yüksek + Otomatik + Büyük Sayılar + Zil Geçmişi + Düşük zil Geçmişi + Animasyonlar + Menüdeki Sihirbaz + Menüden Başlatma + Tek hedef + Sihirbaz Yüzdesi + Komplikasyon Dokunma Eylemi + Komplikasyonlarda Unicode + Versiyon: + daha çok saatarayüz ayarı + Lütfen, Saatarayüzü yapılandırmasına bakın. + GeçiciH + Sihirbaz + Bolus + eCarb + Ayarlar + Durum + Yen-Senkr + Hazırla/doldur + Hiçbiri + Varsayılan + Menü + süre + hedef + düşük + yüksek + karbonhidrat + yüzdesi + başlat [min] + süre [h] + insülin + Ön ayar 1 + Ön ayar 2 + Ön ayar 3 + Serbest miktar + ONAYLA + vardiya + bolus + Bolus İlerlemesi + iptal etmek için basın + BOLUS İPTAL ET + Pompa + Döngü + CPP + TDD + Karb + IOB + durum yok + kırmızı + pembe + mor + koyu mor + çivit mavi + mavi + açık mavi + camgöbeği + deniz mavisi + yeşil + açık yeşil + misket limonu + sarı + kehribar + turuncu + koyu turuncu + kahverengi + gri + mavi gri + beyaz + siyah + çok renkli + Saatlik titreşim + Hafta numarasını göster + Stilin: + stil yok + minimal stil + şekil stili + tam stil + Renginiz: + Renk doygunluğunuz: + Renk opaklığınız: + AAPS Bolus İletimi + AAPS Bolus İletimi Sessiz + Bolus iletimi ve iptali + Bolus iletimi ve daha az titreşimle iptal etme +