resourceHelper -> rh

This commit is contained in:
Milos Kozak 2021-11-04 10:56:12 +01:00
parent 7b07178b93
commit 756957ed8c
376 changed files with 3186 additions and 3197 deletions

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -74,13 +74,13 @@ open class AppModule {
@Provides @Provides
@Singleton @Singleton
fun provideProfileFunction( fun provideProfileFunction(
aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, resourceHelper: aapsLogger: AAPSLogger, sp: SP, rxBus: RxBus, rh:
ResourceHelper, activePlugin: ResourceHelper, activePlugin:
ActivePlugin, repository: AppRepository, dateUtil: DateUtil, config: Config, hardLimits: HardLimits, ActivePlugin, repository: AppRepository, dateUtil: DateUtil, config: Config, hardLimits: HardLimits,
aapsSchedulers: AapsSchedulers, fabricPrivacy: FabricPrivacy, deviceStatusData: DeviceStatusData aapsSchedulers: AapsSchedulers, fabricPrivacy: FabricPrivacy, deviceStatusData: DeviceStatusData
): ProfileFunction = ): ProfileFunction =
ProfileFunctionImplementation( ProfileFunctionImplementation(
aapsLogger, sp, rxBus, resourceHelper, activePlugin, repository, dateUtil, aapsLogger, sp, rxBus, rh, activePlugin, repository, dateUtil,
config, hardLimits, aapsSchedulers, fabricPrivacy, deviceStatusData config, hardLimits, aapsSchedulers, fabricPrivacy, deviceStatusData
) )

View file

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

View file

@ -44,7 +44,7 @@ import kotlin.math.max
class CarbsDialog : DialogFragmentWithDate() { class CarbsDialog : DialogFragmentWithDate() {
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@ -79,15 +79,15 @@ class CarbsDialog : DialogFragmentWithDate() {
val time = binding.time.value.toInt() val time = binding.time.value.toInt()
if (time > 12 * 60 || time < -12 * 60) { if (time > 12 * 60 || time < -12 * 60) {
binding.time.value = 0.0 binding.time.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.constraintapllied))
} }
if (binding.duration.value > 10) { if (binding.duration.value > 10) {
binding.duration.value = 0.0 binding.duration.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.constraintapllied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.constraintapllied))
} }
if (binding.carbs.value.toInt() > maxCarbs) { if (binding.carbs.value.toInt() > maxCarbs) {
binding.carbs.value = 0.0 binding.carbs.value = 0.0
ToastUtils.showToastInUiThread(ctx, resourceHelper.gs(R.string.carbsconstraintapplied)) ToastUtils.showToastInUiThread(ctx, rh.gs(R.string.carbsconstraintapplied))
} }
} }
@ -190,45 +190,45 @@ class CarbsDialog : DialogFragmentWithDate() {
val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() val hypoTTDuration = defaultValueHelper.determineHypoTTDuration()
val hypoTT = defaultValueHelper.determineHypoTT() val hypoTT = defaultValueHelper.determineHypoTT()
val actions: LinkedList<String?> = LinkedList() val actions: LinkedList<String?> = LinkedList()
val unitLabel = if (units == GlucoseUnit.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl)
val useAlarm = binding.alarmCheckBox.isChecked val useAlarm = binding.alarmCheckBox.isChecked
val remindBolus = binding.bolusReminderCheckBox.isChecked val remindBolus = binding.bolusReminderCheckBox.isChecked
val activitySelected = binding.activityTt.isChecked val activitySelected = binding.activityTt.isChecked
if (activitySelected) if (activitySelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, activityTTDuration) + ")").formatColor(rh, R.color.tempTargetConfirmation))
val eatingSoonSelected = binding.eatingSoonTt.isChecked val eatingSoonSelected = binding.eatingSoonTt.isChecked
if (eatingSoonSelected) if (eatingSoonSelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(rh, R.color.tempTargetConfirmation))
val hypoSelected = binding.hypoTt.isChecked val hypoSelected = binding.hypoTt.isChecked
if (hypoSelected) if (hypoSelected)
actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) actions.add(rh.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + rh.gs(R.string.format_mins, hypoTTDuration) + ")").formatColor(rh, R.color.tempTargetConfirmation))
val timeOffset = binding.time.value.toInt() val timeOffset = binding.time.value.toInt()
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
val time = eventTime + timeOffset * 1000 * 60 val time = eventTime + timeOffset * 1000 * 60
if (timeOffset != 0) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
if (useAlarm && carbs > 0 && timeOffset > 0) if (useAlarm && carbs > 0 && timeOffset > 0)
actions.add(resourceHelper.gs(R.string.alarminxmin, timeOffset).formatColor(resourceHelper, R.color.info)) actions.add(rh.gs(R.string.alarminxmin, timeOffset).formatColor(rh, R.color.info))
val duration = binding.duration.value.toInt() val duration = binding.duration.value.toInt()
if (duration > 0) if (duration > 0)
actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) actions.add(rh.gs(R.string.duration) + ": " + duration + rh.gs(R.string.shorthour))
if (carbsAfterConstraints > 0) { if (carbsAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.carbs) + ": " + "<font color='" + resourceHelper.gc(R.color.carbs) + "'>" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>") actions.add(rh.gs(R.string.carbs) + ": " + "<font color='" + rh.gc(R.color.carbs) + "'>" + rh.gs(R.string.format_carbs, carbsAfterConstraints) + "</font>")
if (carbsAfterConstraints != carbs) if (carbsAfterConstraints != carbs)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.carbsconstraintapplied) + "</font>") actions.add("<font color='" + rh.gc(R.color.warning) + "'>" + rh.gs(R.string.carbsconstraintapplied) + "</font>")
} }
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
when { when {
activitySelected -> { activitySelected -> {
uel.log(Action.TT, Sources.CarbDialog, uel.log(Action.TT, Sources.CarbDialog,
@ -305,7 +305,7 @@ class CarbsDialog : DialogFragmentWithDate() {
override fun run() { override fun run() {
carbTimer.removeEatReminder() carbTimer.removeEatReminder()
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
} else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus) } else if (sp.getBoolean(R.string.key_usebolusreminder, false) && remindBolus)
bolusTimer.scheduleBolusReminder() bolusTimer.scheduleBolusReminder()
} }
@ -318,7 +318,7 @@ class CarbsDialog : DialogFragmentWithDate() {
} }
} else } else
activity?.let { activity -> activity?.let { activity ->
OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected)) OKDialog.show(activity, rh.gs(R.string.carbs), rh.gs(R.string.no_action_selected))
} }
return true return true
} }

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -42,7 +42,7 @@ import kotlin.collections.ArrayList
class ProfileSwitchDialog : DialogFragmentWithDate() { class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -118,7 +118,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
val profileList = ArrayList<CharSequence>() val profileList = ArrayList<CharSequence>()
for (profileName in profileListToCheck) { for (profileName in profileListToCheck) {
val profileToCheck = activePlugin.activeProfileSource.profile?.getSpecificProfile(profileName.toString()) val profileToCheck = activePlugin.activeProfileSource.profile?.getSpecificProfile(profileName.toString())
if (profileToCheck != null && ProfileSealed.Pure(profileToCheck).isValid("ProfileSwitch", activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false).isValid) if (profileToCheck != null && ProfileSealed.Pure(profileToCheck).isValid("ProfileSwitch", activePlugin.activePump, config, rh, rxBus, hardLimits, false).isValid)
profileList.add(profileName) profileList.add(profileName)
} }
if (profileList.isEmpty()) { if (profileList.isEmpty()) {
@ -140,7 +140,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
if (profile is ProfileSealed.EPS) if (profile is ProfileSealed.EPS)
if (profile.value.originalPercentage != 100 || profile.value.originalTimeshift != 0L) { if (profile.value.originalPercentage != 100 || profile.value.originalTimeshift != 0L) {
binding.reuselayout.visibility = View.VISIBLE binding.reuselayout.visibility = View.VISIBLE
binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, profile.value.originalPercentage, T.msecs(profile.value.originalTimeshift).hours().toInt()) binding.reusebutton.text = rh.gs(R.string.reuse_profile_pct_hours, profile.value.originalPercentage, T.msecs(profile.value.originalTimeshift).hours().toInt())
binding.reusebutton.setOnClickListener { binding.reusebutton.setOnClickListener {
binding.percentage.value = profile.value.originalPercentage.toDouble() binding.percentage.value = profile.value.originalPercentage.toDouble()
binding.timeshift.value = profile.value.originalTimeshift.toDouble() binding.timeshift.value = profile.value.originalTimeshift.toDouble()
@ -167,32 +167,32 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
val duration = binding.duration.value?.toInt() ?: return false val duration = binding.duration.value?.toInt() ?: return false
if (duration > 0L) if (duration > 0L)
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, duration))
val profileName = binding.profile.selectedItem.toString() val profileName = binding.profile.selectedItem.toString()
actions.add(resourceHelper.gs(R.string.profile) + ": " + profileName) actions.add(rh.gs(R.string.profile) + ": " + profileName)
val percent = binding.percentage.value.toInt() val percent = binding.percentage.value.toInt()
if (percent != 100) if (percent != 100)
actions.add(resourceHelper.gs(R.string.percent) + ": " + percent + "%") actions.add(rh.gs(R.string.percent) + ": " + percent + "%")
val timeShift = binding.timeshift.value.toInt() val timeShift = binding.timeshift.value.toInt()
if (timeShift != 0) if (timeShift != 0)
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + resourceHelper.gs(R.string.format_hours, timeShift.toDouble())) actions.add(rh.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + rh.gs(R.string.format_hours, timeShift.toDouble()))
val notes = binding.notesLayout.notes.text.toString() val notes = binding.notesLayout.notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.notes_label) + ": " + notes) actions.add(rh.gs(R.string.notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) actions.add(rh.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
val isTT = binding.duration.value > 0 && binding.percentage.value < 100 && binding.tt.isChecked val isTT = binding.duration.value > 0 && binding.percentage.value < 100 && binding.tt.isChecked
val target = defaultValueHelper.determineActivityTT() val target = defaultValueHelper.determineActivityTT()
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
if (isTT) if (isTT)
actions.add(resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + resourceHelper.gs(R.string.activity)) actions.add(rh.gs(R.string.careportal_temporarytarget) + ": " + rh.gs(R.string.activity))
activity?.let { activity -> activity?.let { activity ->
val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) ?: return@let val ps = profileFunction.buildProfileSwitch(profileStore, profileName, duration, percent, timeShift, eventTime) ?: return@let
val validity = ProfileSealed.PS(ps).isValid(resourceHelper.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) val validity = ProfileSealed.PS(ps).isValid(rh.gs(R.string.careportal_profileswitch), activePlugin.activePump, config, rh, rxBus, hardLimits, false)
if (validity.isValid) if (validity.isValid)
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { OKDialog.showConfirmation(activity, rh.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
if (profileFunction.createProfileSwitch( if (profileFunction.createProfileSwitch(
profileStore, profileStore,
profileName = profileName, profileName = profileName,
@ -237,7 +237,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
else { else {
OKDialog.show( OKDialog.show(
activity, activity,
resourceHelper.gs(R.string.careportal_profileswitch), rh.gs(R.string.careportal_profileswitch),
HtmlHelper.fromHtml(Joiner.on("<br/>").join(validity.reasons)) HtmlHelper.fromHtml(Joiner.on("<br/>").join(validity.reasons))
) )
return false return false

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -35,7 +35,7 @@ class OpenAPSAMAPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -54,7 +54,7 @@ class OpenAPSAMAPlugin @Inject constructor(
.shortName(R.string.oaps_shortname) .shortName(R.string.oaps_shortname)
.preferencesId(R.xml.pref_openapsama) .preferencesId(R.xml.pref_openapsama)
.description(R.string.description_ama), .description(R.string.description_ama),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), APS { ), APS {
// last values // last values
@ -86,18 +86,18 @@ class OpenAPSAMAPlugin @Inject constructor(
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (profile == null) { if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileselected)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileselected))
return return
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return return
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return return
} }
val inputConstraints = Constraint(0.0) // fake. only for collecting all results val inputConstraints = Constraint(0.0) // fake. only for collecting all results
@ -134,7 +134,7 @@ class OpenAPSAMAPlugin @Inject constructor(
if (constraintChecker.isAutosensModeEnabled().value()) { if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) { if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return return
} }
lastAutosensResult = autosensData.autosensResult lastAutosensResult = autosensData.autosensResult

View file

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

View file

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

View file

@ -35,7 +35,7 @@ class OpenAPSSMBPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val context: Context, private val context: Context,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -55,7 +55,7 @@ class OpenAPSSMBPlugin @Inject constructor(
.preferencesId(R.xml.pref_openapssmb) .preferencesId(R.xml.pref_openapssmb)
.description(R.string.description_smb) .description(R.string.description_smb)
.setDefault(), .setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), APS, Constraints { ), APS, Constraints {
// last values // last values
@ -81,9 +81,9 @@ class OpenAPSSMBPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) super.preprocessPreferences(preferenceFragment)
val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false) val smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false)
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_COB))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_with_temptarget))?.isVisible = !smbAlwaysEnabled
preferenceFragment.findPreference<SwitchPreference>(resourceHelper.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_enableSMB_after_carbs))?.isVisible = !smbAlwaysEnabled
} }
override fun invoke(initiator: String, tempBasalFallback: Boolean) { override fun invoke(initiator: String, tempBasalFallback: Boolean) {
@ -93,18 +93,18 @@ class OpenAPSSMBPlugin @Inject constructor(
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePump val pump = activePlugin.activePump
if (profile == null) { if (profile == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.noprofileselected))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.noprofileselected)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.noprofileselected)) aapsLogger.debug(LTag.APS, rh.gs(R.string.noprofileselected))
return return
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_disabled))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_disabled)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_disabled)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_disabled))
return return
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openapsma_noglucosedata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openapsma_noglucosedata)))
aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.openapsma_noglucosedata)) aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_noglucosedata))
return return
} }
@ -139,7 +139,7 @@ class OpenAPSSMBPlugin @Inject constructor(
if (constraintChecker.isAutosensModeEnabled().value()) { if (constraintChecker.isAutosensModeEnabled().value()) {
val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin") val autosensData = iobCobCalculator.getLastAutosensDataWithWaitForCalculationFinish("OpenAPSPlugin")
if (autosensData == null) { if (autosensData == null) {
rxBus.send(EventOpenAPSUpdateResultGui(resourceHelper.gs(R.string.openaps_noasdata))) rxBus.send(EventOpenAPSUpdateResultGui(rh.gs(R.string.openaps_noasdata)))
return return
} }
lastAutosensResult = autosensData.autosensResult lastAutosensResult = autosensData.autosensResult

View file

@ -32,7 +32,7 @@ class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@ -125,8 +125,8 @@ class ConfigBuilderFragment : DaggerFragment() {
if (plugins.isEmpty()) return if (plugins.isEmpty()) return
@Suppress("InflateParams") @Suppress("InflateParams")
val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout val parent = layoutInflater.inflate(R.layout.configbuilder_single_category, null) as LinearLayout
(parent.findViewById<View>(R.id.category_title) as TextView).text = resourceHelper.gs(title) (parent.findViewById<View>(R.id.category_title) as TextView).text = rh.gs(title)
(parent.findViewById<View>(R.id.category_description) as TextView).text = resourceHelper.gs(description) (parent.findViewById<View>(R.id.category_description) as TextView).text = rh.gs(description)
val pluginContainer = parent.findViewById<LinearLayout>(R.id.category_plugins) val pluginContainer = parent.findViewById<LinearLayout>(R.id.category_plugins)
for (plugin in plugins) { for (plugin in plugins) {
val pluginViewHolder = PluginViewHolder(this, pluginType, plugin) val pluginViewHolder = PluginViewHolder(this, pluginType, plugin)

View file

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

View file

@ -33,7 +33,7 @@ class ProfileFunctionImplementation @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val repository: AppRepository, private val repository: AppRepository,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -78,13 +78,13 @@ class ProfileFunctionImplementation @Inject constructor(
getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true) getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true)
fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String { fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String {
var profileName = resourceHelper.gs(R.string.noprofileselected) var profileName = rh.gs(R.string.noprofileselected)
val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet() val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet()
if (profileSwitch is ValueWrapper.Existing) { if (profileSwitch is ValueWrapper.Existing) {
profileName = if (customized) profileSwitch.value.originalCustomizedName else profileSwitch.value.originalProfileName profileName = if (customized) profileSwitch.value.originalCustomizedName else profileSwitch.value.originalProfileName
if (showRemainingTime && profileSwitch.value.originalDuration != 0L) { if (showRemainingTime && profileSwitch.value.originalDuration != 0L) {
profileName += dateUtil.untilString(profileSwitch.value.originalEnd, resourceHelper) profileName += dateUtil.untilString(profileSwitch.value.originalEnd, rh)
} }
} }
return profileName return profileName
@ -177,10 +177,10 @@ class ProfileFunctionImplementation @Inject constructor(
val profileStore = activePlugin.activeProfileSource.profile ?: return false val profileStore = activePlugin.activeProfileSource.profile ?: return false
val ps = buildProfileSwitch(profileStore, profile.profileName, durationInMinutes, percentage, 0, dateUtil.now()) ?: return false val ps = buildProfileSwitch(profileStore, profile.profileName, durationInMinutes, percentage, 0, dateUtil.now()) ?: return false
val validity = ProfileSealed.PS(ps).isValid( val validity = ProfileSealed.PS(ps).isValid(
resourceHelper.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch), rh.gs(info.nightscout.androidaps.automation.R.string.careportal_profileswitch),
activePlugin.activePump, activePlugin.activePump,
config, config,
resourceHelper, rh,
rxBus, rxBus,
hardLimits, hardLimits,
false false

View file

@ -22,7 +22,7 @@ class DstHelperPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private var rxBus: RxBus, private var rxBus: RxBus,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private var sp: SP, private var sp: SP,
private var activePlugin: ActivePlugin, private var activePlugin: ActivePlugin,
private var loopPlugin: LoopPlugin private var loopPlugin: LoopPlugin
@ -32,7 +32,7 @@ class DstHelperPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.pluginName(R.string.dst_plugin_name), .pluginName(R.string.dst_plugin_name),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Constraints { ), Constraints {
companion object { companion object {
@ -51,7 +51,7 @@ class DstHelperPlugin @Inject constructor(
if (willBeDST(cal)) { if (willBeDST(cal)) {
val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L) val snoozedTo: Long = sp.getLong(R.string.key_snooze_dst_in24h, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val notification = NotificationWithAction(injector, Notification.DST_IN_24H, resourceHelper.gs(R.string.dst_in_24h_warning), Notification.LOW) val notification = NotificationWithAction(injector, Notification.DST_IN_24H, rh.gs(R.string.dst_in_24h_warning), Notification.LOW)
notification.action(R.string.snooze, Runnable { notification.action(R.string.snooze, Runnable {
sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs()) sp.putLong(R.string.key_snooze_dst_in24h, System.currentTimeMillis() + T.hours(24).msecs())
}) })
@ -66,7 +66,7 @@ class DstHelperPlugin @Inject constructor(
if (!loopPlugin.isSuspended) { if (!loopPlugin.isSuspended) {
val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L) val snoozedTo: Long = sp.getLong(R.string.key_snooze_loopdisabled, 0L)
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, resourceHelper.gs(R.string.dst_loop_disabled_warning), Notification.LOW) val notification = NotificationWithAction(injector, Notification.DST_LOOP_DISABLED, rh.gs(R.string.dst_loop_disabled_warning), Notification.LOW)
notification.action(R.string.snooze, Runnable { notification.action(R.string.snooze, Runnable {
sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs()) sp.putLong(R.string.key_snooze_loopdisabled, System.currentTimeMillis() + T.hours(24).msecs())
}) })

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -37,7 +37,7 @@ class MaintenanceFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var maintenancePlugin: MaintenancePlugin @Inject lateinit var maintenancePlugin: MaintenancePlugin
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var importExportPrefs: ImportExportPrefs @Inject lateinit var importExportPrefs: ImportExportPrefs
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -73,7 +73,7 @@ class MaintenanceFragment : DaggerFragment() {
} }
binding.navResetdb.setOnClickListener { binding.navResetdb.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.maintenance), resourceHelper.gs(R.string.reset_db_confirm), Runnable { OKDialog.showConfirmation(activity, rh.gs(R.string.maintenance), rh.gs(R.string.reset_db_confirm), Runnable {
compositeDisposable.add( compositeDisposable.add(
fromAction { fromAction {
repository.clearDatabases() repository.clearDatabases()
@ -116,7 +116,7 @@ class MaintenanceFragment : DaggerFragment() {
binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) } binding.navLogsettings.setOnClickListener { startActivity(Intent(activity, LogSettingActivity::class.java)) }
binding.exportCsv.setOnClickListener { binding.exportCsv.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.ue_export_to_csv) + "?") { OKDialog.showConfirmation(activity, rh.gs(R.string.ue_export_to_csv) + "?") {
uel.log(Action.EXPORT_CSV, Sources.Maintenance) uel.log(Action.EXPORT_CSV, Sources.Maintenance)
importExportPrefs.exportUserEntriesCsv(activity) importExportPrefs.exportUserEntriesCsv(activity)
} }

View file

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

View file

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

View file

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

View file

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

View file

@ -76,7 +76,7 @@ import javax.inject.Singleton
class NSDeviceStatus @Inject constructor( class NSDeviceStatus @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val nsSettingsStatus: NSSettingsStatus, private val nsSettingsStatus: NSSettingsStatus,
private val config: Config, private val config: Config,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -157,8 +157,8 @@ class NSDeviceStatus @Inject constructor(
//String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"}; //String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"};
val string = StringBuilder() val string = StringBuilder()
.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") .append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
.append(resourceHelper.gs(R.string.pump)) .append(rh.gs(R.string.pump))
.append(": </span>") .append(": </span>")
// test warning level // test warning level
@ -178,7 +178,7 @@ class NSDeviceStatus @Inject constructor(
if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ") if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ")
if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ") if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ")
if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ") if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ")
if (fields.contains("clock")) string.append(dateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ") if (fields.contains("clock")) string.append(dateUtil.minAgo(rh, pumpData.clock)).append(" ")
if (fields.contains("status")) string.append(pumpData.status).append(" ") if (fields.contains("status")) string.append(pumpData.status).append(" ")
if (fields.contains("device")) string.append(device).append(" ") if (fields.contains("device")) string.append(device).append(" ")
string.append("</span>") // color string.append("</span>") // color
@ -248,8 +248,8 @@ class NSDeviceStatus @Inject constructor(
val openApsStatus: Spanned val openApsStatus: Spanned
get() { get() {
val string = StringBuilder() val string = StringBuilder()
.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") .append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
.append(resourceHelper.gs(R.string.openaps_short)) .append(rh.gs(R.string.openaps_short))
.append(": </span>") .append(": </span>")
// test warning level // test warning level
@ -259,7 +259,7 @@ class NSDeviceStatus @Inject constructor(
else -> Levels.INFO else -> Levels.INFO
} }
string.append("<span style=\"color:${level.toColor()}\">") string.append("<span style=\"color:${level.toColor()}\">")
if (deviceStatusData.openAPSData.clockSuggested != 0L) string.append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockSuggested)).append(" ") if (deviceStatusData.openAPSData.clockSuggested != 0L) string.append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockSuggested)).append(" ")
string.append("</span>") // color string.append("</span>") // color
return fromHtml(string.toString()) return fromHtml(string.toString())
} }
@ -268,8 +268,8 @@ class NSDeviceStatus @Inject constructor(
get() { get() {
val string = StringBuilder() val string = StringBuilder()
try { try {
if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockEnacted)).append("</b> ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("<br>") if (deviceStatusData.openAPSData.enacted != null && deviceStatusData.openAPSData.clockEnacted != deviceStatusData.openAPSData.clockSuggested) string.append("<b>").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockEnacted)).append("</b> ").append(deviceStatusData.openAPSData.enacted!!.getString("reason")).append("<br>")
if (deviceStatusData.openAPSData.suggested != null) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusData.openAPSData.clockSuggested)).append("</b> ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("<br>") if (deviceStatusData.openAPSData.suggested != null) string.append("<b>").append(dateUtil.minAgo(rh, deviceStatusData.openAPSData.clockSuggested)).append("</b> ").append(deviceStatusData.openAPSData.suggested!!.getString("reason")).append("<br>")
return fromHtml(string.toString()) return fromHtml(string.toString())
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
@ -321,8 +321,8 @@ class NSDeviceStatus @Inject constructor(
val uploaderStatusSpanned: Spanned val uploaderStatusSpanned: Spanned
get() { get() {
val string = StringBuilder() val string = StringBuilder()
string.append("<span style=\"color:${resourceHelper.gcs(R.color.defaulttext)}\">") string.append("<span style=\"color:${rh.gcs(R.color.defaulttext)}\">")
string.append(resourceHelper.gs(R.string.uploader_short)) string.append(rh.gs(R.string.uploader_short))
string.append(": </span>") string.append(": </span>")
val iterator: Iterator<*> = deviceStatusData.uploaderMap.entries.iterator() val iterator: Iterator<*> = deviceStatusData.uploaderMap.entries.iterator()
var minBattery = 100 var minBattery = 100

View file

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

View file

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

View file

@ -70,7 +70,7 @@ class NSClientService : DaggerService() {
@Inject lateinit var nsSettingsStatus: NSSettingsStatus @Inject lateinit var nsSettingsStatus: NSSettingsStatus
@Inject lateinit var nsDeviceStatus: NSDeviceStatus @Inject lateinit var nsDeviceStatus: NSDeviceStatus
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin
@ -130,9 +130,9 @@ class NSClientService : DaggerService() {
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange -> .subscribe({ event: EventPreferenceChange ->
if (event.isChanged(resourceHelper, R.string.key_nsclientinternal_url) || if (event.isChanged(rh, R.string.key_nsclientinternal_url) ||
event.isChanged(resourceHelper, R.string.key_nsclientinternal_api_secret) || event.isChanged(rh, R.string.key_nsclientinternal_api_secret) ||
event.isChanged(resourceHelper, R.string.key_nsclientinternal_paused)) { event.isChanged(rh, R.string.key_nsclientinternal_paused)) {
latestDateInReceivedData = 0 latestDateInReceivedData = 0
destroy() destroy()
initialize() initialize()
@ -212,7 +212,7 @@ class NSClientService : DaggerService() {
rxBus.send(EventNSClientNewLog("ERROR", "Write treatment permission not granted ")) rxBus.send(EventNSClientNewLog("ERROR", "Write treatment permission not granted "))
} }
if (!hasWriteAuth) { if (!hasWriteAuth) {
val noWritePerm = Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, resourceHelper.gs(R.string.nowritepermission), Notification.URGENT) val noWritePerm = Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, rh.gs(R.string.nowritepermission), Notification.URGENT)
rxBus.send(EventNewNotification(noWritePerm)) rxBus.send(EventNewNotification(noWritePerm))
} else { } else {
rxBus.send(EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)) rxBus.send(EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION))
@ -304,7 +304,7 @@ class NSClientService : DaggerService() {
} }
rxBus.send(EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " minutes: " + reconnections.size + "/" + WATCHDOG_MAX_CONNECTIONS)) rxBus.send(EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " minutes: " + reconnections.size + "/" + WATCHDOG_MAX_CONNECTIONS))
if (reconnections.size >= WATCHDOG_MAX_CONNECTIONS) { if (reconnections.size >= WATCHDOG_MAX_CONNECTIONS) {
val n = Notification(Notification.NS_MALFUNCTION, resourceHelper.gs(R.string.nsmalfunction), Notification.URGENT) val n = Notification(Notification.NS_MALFUNCTION, rh.gs(R.string.nsmalfunction), Notification.URGENT)
rxBus.send(EventNewNotification(n)) rxBus.send(EventNewNotification(n))
rxBus.send(EventNSClientNewLog("WATCHDOG", "pausing for $WATCHDOG_RECONNECT_IN minutes")) rxBus.send(EventNSClientNewLog("WATCHDOG", "pausing for $WATCHDOG_RECONNECT_IN minutes"))
nsClientPlugin.pause(true) nsClientPlugin.pause(true)

View file

@ -38,7 +38,7 @@ import kotlin.math.min
class OverviewData @Inject constructor( class OverviewData @Inject constructor(
private val injector: HasAndroidInjector, private val injector: HasAndroidInjector,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val sp: SP, private val sp: SP,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -145,11 +145,11 @@ class OverviewData @Inject constructor(
val lastBgColor: Int val lastBgColor: Int
get() = lastBg?.let { lastBg -> get() = lastBg?.let { lastBg ->
when { when {
lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> resourceHelper.gc(R.color.low) lastBg.valueToUnits(profileFunction.getUnits()) < defaultValueHelper.determineLowLine() -> rh.gc(R.color.low)
lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> resourceHelper.gc(R.color.high) lastBg.valueToUnits(profileFunction.getUnits()) > defaultValueHelper.determineHighLine() -> rh.gc(R.color.high)
else -> resourceHelper.gc(R.color.inrange) else -> rh.gc(R.color.inrange)
} }
} ?: resourceHelper.gc(R.color.inrange) } ?: rh.gc(R.color.inrange)
val isActualBg: Boolean val isActualBg: Boolean
get() = get() =
@ -168,17 +168,17 @@ class OverviewData @Inject constructor(
profileFunction.getProfile()?.let { profile -> profileFunction.getProfile()?.let { profile ->
if (temporaryBasal?.isInProgress == false) temporaryBasal = null if (temporaryBasal?.isInProgress == false) temporaryBasal = null
temporaryBasal?.let { "T:" + it.toStringShort() } temporaryBasal?.let { "T:" + it.toStringShort() }
?: resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal()) ?: rh.gs(R.string.pump_basebasalrate, profile.getBasal())
} ?: resourceHelper.gs(R.string.notavailable) } ?: rh.gs(R.string.notavailable)
val temporaryBasalDialogText: String val temporaryBasalDialogText: String
get() = profileFunction.getProfile()?.let { profile -> get() = profileFunction.getProfile()?.let { profile ->
temporaryBasal?.let { temporaryBasal -> temporaryBasal?.let { temporaryBasal ->
"${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal())}" + "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}" +
"\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil) "\n" + rh.gs(R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil)
} }
?: "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.getBasal())}" ?: "${rh.gs(R.string.basebasalrate_label)}: ${rh.gs(R.string.pump_basebasalrate, profile.getBasal())}"
} ?: resourceHelper.gs(R.string.notavailable) } ?: rh.gs(R.string.notavailable)
val temporaryBasalIcon: Int val temporaryBasalIcon: Int
get() = get() =
@ -194,8 +194,8 @@ class OverviewData @Inject constructor(
} ?: R.drawable.ic_cp_basal_no_tbr } ?: R.drawable.ic_cp_basal_no_tbr
val temporaryBasalColor: Int val temporaryBasalColor: Int
get() = temporaryBasal?.let { resourceHelper.gc(R.color.basal) } get() = temporaryBasal?.let { rh.gc(R.color.basal) }
?: resourceHelper.gc(R.color.defaulttextcolor) ?: rh.gc(R.color.defaulttextcolor)
/* /*
* EXTENDED BOLUS * EXTENDED BOLUS
@ -209,7 +209,7 @@ class OverviewData @Inject constructor(
if (!extendedBolus.isInProgress(dateUtil)) { if (!extendedBolus.isInProgress(dateUtil)) {
this@OverviewData.extendedBolus = null this@OverviewData.extendedBolus = null
"" ""
} else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate) } else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) rh.gs(R.string.pump_basebasalrate, extendedBolus.rate)
else "" else ""
} ?: "" } ?: ""
@ -229,19 +229,19 @@ class OverviewData @Inject constructor(
get() = get() =
bolusIob?.let { bolusIob -> bolusIob?.let { bolusIob ->
basalIob?.let { basalIob -> basalIob?.let { basalIob ->
resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
val iobDialogText: String val iobDialogText: String
get() = get() =
bolusIob?.let { bolusIob -> bolusIob?.let { bolusIob ->
basalIob?.let { basalIob -> basalIob?.let { basalIob ->
resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" + rh.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" +
resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" + rh.gs(R.string.bolus) + ": " + rh.gs(R.string.formatinsulinunits, bolusIob.iob) + "\n" +
resourceHelper.gs(R.string.basal) + ": " + resourceHelper.gs(R.string.formatinsulinunits, basalIob.basaliob) rh.gs(R.string.basal) + ": " + rh.gs(R.string.formatinsulinunits, basalIob.basaliob)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
} ?: resourceHelper.gs(R.string.value_unavailable_short) } ?: rh.gs(R.string.value_unavailable_short)
/* /*
* TEMP TARGET * TEMP TARGET
@ -324,7 +324,7 @@ class OverviewData @Inject constructor(
for (bg in bgReadingsArray) { for (bg in bgReadingsArray) {
if (bg.timestamp < fromTime || bg.timestamp > toTime) continue if (bg.timestamp < fromTime || bg.timestamp > toTime) continue
if (bg.value > maxBgValue) maxBgValue = bg.value if (bg.value > maxBgValue) maxBgValue = bg.value
bgListArray.add(GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) bgListArray.add(GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh))
} }
bgListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) } bgListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) }
bgReadingGraphSeries = PointsWithLabelGraphSeries(Array(bgListArray.size) { i -> bgListArray[i] }) bgReadingGraphSeries = PointsWithLabelGraphSeries(Array(bgListArray.size) { i -> bgListArray[i] })
@ -365,7 +365,7 @@ class OverviewData @Inject constructor(
val bgListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val bgListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val predictions: MutableList<GlucoseValueDataPoint>? = apsResult?.predictions val predictions: MutableList<GlucoseValueDataPoint>? = apsResult?.predictions
?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper) } ?.map { bg -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh) }
?.toMutableList() ?.toMutableList()
if (predictions != null) { if (predictions != null) {
predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) } predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) }
@ -387,7 +387,7 @@ class OverviewData @Inject constructor(
val bucketedListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val bucketedListArray: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
for (inMemoryGlucoseValue in bucketedData) { for (inMemoryGlucoseValue in bucketedData) {
if (inMemoryGlucoseValue.timestamp < fromTime || inMemoryGlucoseValue.timestamp > toTime) continue if (inMemoryGlucoseValue.timestamp < fromTime || inMemoryGlucoseValue.timestamp > toTime) continue
bucketedListArray.add(InMemoryGlucoseValueDataPoint(inMemoryGlucoseValue, profileFunction, resourceHelper)) bucketedListArray.add(InMemoryGlucoseValueDataPoint(inMemoryGlucoseValue, profileFunction, rh))
} }
bucketedListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) } bucketedListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) }
bucketedGraphSeries = PointsWithLabelGraphSeries(Array(bucketedListArray.size) { i -> bucketedListArray[i] }) bucketedGraphSeries = PointsWithLabelGraphSeries(Array(bucketedListArray.size) { i -> bucketedListArray[i] })
@ -466,27 +466,27 @@ class OverviewData @Inject constructor(
// create series // create series
baseBasalGraphSeries = LineGraphSeries(Array(baseBasalArray.size) { i -> baseBasalArray[i] }).also { baseBasalGraphSeries = LineGraphSeries(Array(baseBasalArray.size) { i -> baseBasalArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = resourceHelper.gc(R.color.basebasal) it.backgroundColor = rh.gc(R.color.basebasal)
it.thickness = 0 it.thickness = 0
} }
tempBasalGraphSeries = LineGraphSeries(Array(tempBasalArray.size) { i -> tempBasalArray[i] }).also { tempBasalGraphSeries = LineGraphSeries(Array(tempBasalArray.size) { i -> tempBasalArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = resourceHelper.gc(R.color.tempbasal) it.backgroundColor = rh.gc(R.color.tempbasal)
it.thickness = 0 it.thickness = 0
} }
basalLineGraphSeries = LineGraphSeries(Array(basalLineArray.size) { i -> basalLineArray[i] }).also { basalLineGraphSeries = LineGraphSeries(Array(basalLineArray.size) { i -> basalLineArray[i] }).also {
it.setCustomPaint(Paint().also { paint -> it.setCustomPaint(Paint().also { paint ->
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = resourceHelper.getDisplayMetrics().scaledDensity * 2 paint.strokeWidth = rh.getDisplayMetrics().scaledDensity * 2
paint.pathEffect = DashPathEffect(floatArrayOf(2f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(2f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.basal) paint.color = rh.gc(R.color.basal)
}) })
} }
absoluteBasalGraphSeries = LineGraphSeries(Array(absoluteBasalLineArray.size) { i -> absoluteBasalLineArray[i] }).also { absoluteBasalGraphSeries = LineGraphSeries(Array(absoluteBasalLineArray.size) { i -> absoluteBasalLineArray[i] }).also {
it.setCustomPaint(Paint().also { absolutePaint -> it.setCustomPaint(Paint().also { absolutePaint ->
absolutePaint.style = Paint.Style.STROKE absolutePaint.style = Paint.Style.STROKE
absolutePaint.strokeWidth = resourceHelper.getDisplayMetrics().scaledDensity * 2 absolutePaint.strokeWidth = rh.getDisplayMetrics().scaledDensity * 2
absolutePaint.color = resourceHelper.gc(R.color.basal) absolutePaint.color = rh.gc(R.color.basal)
}) })
} }
// profiler.log(LTag.UI, "prepareBasalData() $from", start) // profiler.log(LTag.UI, "prepareBasalData() $from", start)
@ -522,7 +522,7 @@ class OverviewData @Inject constructor(
// create series // create series
temporaryTargetSeries = LineGraphSeries(Array(targetsSeriesArray.size) { i -> targetsSeriesArray[i] }).also { temporaryTargetSeries = LineGraphSeries(Array(targetsSeriesArray.size) { i -> targetsSeriesArray[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.tempTargetBackground) it.color = rh.gc(R.color.tempTargetBackground)
it.thickness = 2 it.thickness = 2
} }
// profiler.log(LTag.UI, "prepareTemporaryTargetData() $from", start) // profiler.log(LTag.UI, "prepareTemporaryTargetData() $from", start)
@ -535,14 +535,14 @@ class OverviewData @Inject constructor(
maxTreatmentsValue = 0.0 maxTreatmentsValue = 0.0
val filteredTreatments: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val filteredTreatments: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
repository.getBolusesDataFromTimeToTime(fromTime, endTime, true).blockingGet() repository.getBolusesDataFromTimeToTime(fromTime, endTime, true).blockingGet()
.map { BolusDataPoint(it, resourceHelper, activePlugin, defaultValueHelper) } .map { BolusDataPoint(it, rh, activePlugin, defaultValueHelper) }
.filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB } .filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB }
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())
filteredTreatments.add(it) filteredTreatments.add(it)
} }
repository.getCarbsDataFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet() repository.getCarbsDataFromTimeToTimeExpanded(fromTime, endTime, true).blockingGet()
.map { CarbsDataPoint(it, resourceHelper) } .map { CarbsDataPoint(it, rh) }
.forEach { .forEach {
it.y = getNearestBg(it.x.toLong()) it.y = getNearestBg(it.x.toLong())
filteredTreatments.add(it) filteredTreatments.add(it)
@ -555,7 +555,7 @@ class OverviewData @Inject constructor(
// OfflineEvent // OfflineEvent
repository.getOfflineEventDataFromTimeToTime(fromTime, endTime, true).blockingGet() repository.getOfflineEventDataFromTimeToTime(fromTime, endTime, true).blockingGet()
.map { TherapyEventDataPoint(TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL), resourceHelper, profileFunction, translator) } .map { TherapyEventDataPoint(TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL), rh, profileFunction, translator) }
.forEach(filteredTreatments::add) .forEach(filteredTreatments::add)
// Extended bolus // Extended bolus
@ -571,7 +571,7 @@ class OverviewData @Inject constructor(
// Careportal // Careportal
repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet()
.map { TherapyEventDataPoint(it, resourceHelper, profileFunction, translator) } .map { TherapyEventDataPoint(it, rh, profileFunction, translator) }
.filterTimeframe(fromTime, endTime) .filterTimeframe(fromTime, endTime)
.forEach { .forEach {
if (it.y == 0.0) it.y = getNearestBg(it.x.toLong()) if (it.y == 0.0) it.y = getNearestBg(it.x.toLong())
@ -682,15 +682,15 @@ class OverviewData @Inject constructor(
// DEVIATIONS // DEVIATIONS
if (autosensData != null) { if (autosensData != null) {
var color = resourceHelper.gc(R.color.deviationblack) // "=" var color = rh.gc(R.color.deviationblack) // "="
if (autosensData.type == "" || autosensData.type == "non-meal") { if (autosensData.type == "" || autosensData.type == "non-meal") {
if (autosensData.pastSensitivity == "C") color = resourceHelper.gc(R.color.deviationgrey) if (autosensData.pastSensitivity == "C") color = rh.gc(R.color.deviationgrey)
if (autosensData.pastSensitivity == "+") color = resourceHelper.gc(R.color.deviationgreen) if (autosensData.pastSensitivity == "+") color = rh.gc(R.color.deviationgreen)
if (autosensData.pastSensitivity == "-") color = resourceHelper.gc(R.color.deviationred) if (autosensData.pastSensitivity == "-") color = rh.gc(R.color.deviationred)
} else if (autosensData.type == "uam") { } else if (autosensData.type == "uam") {
color = resourceHelper.gc(R.color.uam) color = rh.gc(R.color.uam)
} else if (autosensData.type == "csf") { } else if (autosensData.type == "csf") {
color = resourceHelper.gc(R.color.deviationgrey) color = rh.gc(R.color.deviationgrey)
} }
devArray.add(OverviewPlugin.DeviationDataPoint(time.toDouble(), autosensData.deviation, color, devScale)) devArray.add(OverviewPlugin.DeviationDataPoint(time.toDouble(), autosensData.deviation, color, devScale))
maxDevValueFound = maxOf(maxDevValueFound, abs(autosensData.deviation), abs(bgi)) maxDevValueFound = maxOf(maxDevValueFound, abs(autosensData.deviation), abs(bgi))
@ -716,14 +716,14 @@ class OverviewData @Inject constructor(
// IOB // IOB
iobSeries = FixedLineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also { iobSeries = FixedLineGraphSeries(Array(iobArray.size) { i -> iobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50%
it.color = resourceHelper.gc(R.color.iob) it.color = rh.gc(R.color.iob)
it.thickness = 3 it.thickness = 3
} }
absIobSeries = FixedLineGraphSeries(Array(absIobArray.size) { i -> absIobArray[i] }).also { absIobSeries = FixedLineGraphSeries(Array(absIobArray.size) { i -> absIobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.iob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.iob) //50%
it.color = resourceHelper.gc(R.color.iob) it.color = rh.gc(R.color.iob)
it.thickness = 3 it.thickness = 3
} }
@ -734,14 +734,14 @@ class OverviewData @Inject constructor(
val iobPrediction: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val iobPrediction: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
for (i in iobPredictionArray) { for (i in iobPredictionArray) {
iobPrediction.add(i.setColor(resourceHelper.gc(R.color.iobPredAS))) iobPrediction.add(i.setColor(rh.gc(R.color.iobPredAS)))
maxIobValueFound = max(maxIobValueFound, abs(i.iob)) maxIobValueFound = max(maxIobValueFound, abs(i.iob))
} }
iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] }) iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] })
val iobPrediction2: MutableList<DataPointWithLabelInterface> = java.util.ArrayList() val iobPrediction2: MutableList<DataPointWithLabelInterface> = java.util.ArrayList()
val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) val iobPredictionArray2 = iobCobCalculator.calculateIobArrayForSMB(AutosensResult(), SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
for (i in iobPredictionArray2) { for (i in iobPredictionArray2) {
iobPrediction2.add(i.setColor(resourceHelper.gc(R.color.iobPred))) iobPrediction2.add(i.setColor(rh.gc(R.color.iobPred)))
maxIobValueFound = max(maxIobValueFound, abs(i.iob)) maxIobValueFound = max(maxIobValueFound, abs(i.iob))
} }
iobPredictions2Series = PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] }) iobPredictions2Series = PointsWithLabelGraphSeries(Array(iobPrediction2.size) { i -> iobPrediction2[i] })
@ -755,8 +755,8 @@ class OverviewData @Inject constructor(
// COB // COB
cobSeries = FixedLineGraphSeries(Array(cobArray.size) { i -> cobArray[i] }).also { cobSeries = FixedLineGraphSeries(Array(cobArray.size) { i -> cobArray[i] }).also {
it.isDrawBackground = true it.isDrawBackground = true
it.backgroundColor = -0x7f000001 and resourceHelper.gc(R.color.cob) //50% it.backgroundColor = -0x7f000001 and rh.gc(R.color.cob) //50%
it.color = resourceHelper.gc(R.color.cob) it.color = rh.gc(R.color.cob)
it.thickness = 3 it.thickness = 3
} }
cobMinFailOverSeries = PointsWithLabelGraphSeries(Array(minFailOverActiveList.size) { i -> minFailOverActiveList[i] }) cobMinFailOverSeries = PointsWithLabelGraphSeries(Array(minFailOverActiveList.size) { i -> minFailOverActiveList[i] })
@ -764,7 +764,7 @@ class OverviewData @Inject constructor(
// ACTIVITY // ACTIVITY
activitySeries = FixedLineGraphSeries(Array(actArrayHist.size) { i -> actArrayHist[i] }).also { activitySeries = FixedLineGraphSeries(Array(actArrayHist.size) { i -> actArrayHist[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.activity) it.color = rh.gc(R.color.activity)
it.thickness = 3 it.thickness = 3
} }
activityPredictionSeries = FixedLineGraphSeries(Array(actArrayPrediction.size) { i -> actArrayPrediction[i] }).also { activityPredictionSeries = FixedLineGraphSeries(Array(actArrayPrediction.size) { i -> actArrayPrediction[i] }).also {
@ -772,14 +772,14 @@ class OverviewData @Inject constructor(
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = 3f paint.strokeWidth = 3f
paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.activity) paint.color = rh.gc(R.color.activity)
}) })
} }
// BGI // BGI
minusBgiSeries = FixedLineGraphSeries(Array(bgiArrayHist.size) { i -> bgiArrayHist[i] }).also { minusBgiSeries = FixedLineGraphSeries(Array(bgiArrayHist.size) { i -> bgiArrayHist[i] }).also {
it.isDrawBackground = false it.isDrawBackground = false
it.color = resourceHelper.gc(R.color.bgi) it.color = rh.gc(R.color.bgi)
it.thickness = 3 it.thickness = 3
} }
minusBgiHistSeries = FixedLineGraphSeries(Array(bgiArrayPrediction.size) { i -> bgiArrayPrediction[i] }).also { minusBgiHistSeries = FixedLineGraphSeries(Array(bgiArrayPrediction.size) { i -> bgiArrayPrediction[i] }).also {
@ -787,7 +787,7 @@ class OverviewData @Inject constructor(
paint.style = Paint.Style.STROKE paint.style = Paint.Style.STROKE
paint.strokeWidth = 3f paint.strokeWidth = 3f
paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f) paint.pathEffect = DashPathEffect(floatArrayOf(4f, 4f), 0f)
paint.color = resourceHelper.gc(R.color.bgi) paint.color = rh.gc(R.color.bgi)
}) })
} }
@ -798,17 +798,17 @@ class OverviewData @Inject constructor(
// RATIO // RATIO
ratioSeries = LineGraphSeries(Array(ratioArray.size) { i -> ratioArray[i] }).also { ratioSeries = LineGraphSeries(Array(ratioArray.size) { i -> ratioArray[i] }).also {
it.color = resourceHelper.gc(R.color.ratio) it.color = rh.gc(R.color.ratio)
it.thickness = 3 it.thickness = 3
} }
// DEV SLOPE // DEV SLOPE
dsMaxSeries = LineGraphSeries(Array(dsMaxArray.size) { i -> dsMaxArray[i] }).also { dsMaxSeries = LineGraphSeries(Array(dsMaxArray.size) { i -> dsMaxArray[i] }).also {
it.color = resourceHelper.gc(R.color.devslopepos) it.color = rh.gc(R.color.devslopepos)
it.thickness = 3 it.thickness = 3
} }
dsMinSeries = LineGraphSeries(Array(dsMinArray.size) { i -> dsMinArray[i] }).also { dsMinSeries = LineGraphSeries(Array(dsMinArray.size) { i -> dsMinArray[i] }).also {
it.color = resourceHelper.gc(R.color.devslopeneg) it.color = rh.gc(R.color.devslopeneg)
it.thickness = 3 it.thickness = 3
} }

View file

@ -93,7 +93,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@ -165,16 +165,16 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
smallHeight = screenHeight <= Constants.SMALL_HEIGHT smallHeight = screenHeight <= Constants.SMALL_HEIGHT
val landscape = screenHeight < screenWidth val landscape = screenHeight < screenWidth
skinProvider.activeSkin().preProcessLandscapeOverviewLayout(dm, view, landscape, resourceHelper.gb(R.bool.isTablet), smallHeight) skinProvider.activeSkin().preProcessLandscapeOverviewLayout(dm, view, landscape, rh.gb(R.bool.isTablet), smallHeight)
binding.nsclientLayout.visibility = config.NSCLIENT.toVisibility() binding.nsclientLayout.visibility = config.NSCLIENT.toVisibility()
binding.notifications.setHasFixedSize(false) binding.notifications.setHasFixedSize(false)
binding.notifications.layoutManager = LinearLayoutManager(view.context) binding.notifications.layoutManager = LinearLayoutManager(view.context)
axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80 axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80
binding.graphsLayout.bgGraph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) binding.graphsLayout.bgGraph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
binding.graphsLayout.bgGraph.gridLabelRenderer?.reloadStyles() binding.graphsLayout.bgGraph.gridLabelRenderer?.reloadStyles()
binding.graphsLayout.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth binding.graphsLayout.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth
binding.graphsLayout.bgGraph.layoutParams?.height = resourceHelper.dpToPx(skinProvider.activeSkin().mainGraphHeight) binding.graphsLayout.bgGraph.layoutParams?.height = rh.dpToPx(skinProvider.activeSkin().mainGraphHeight)
carbAnimation = binding.infoLayout.carbsIcon.background as AnimationDrawable? carbAnimation = binding.infoLayout.carbsIcon.background as AnimationDrawable?
carbAnimation?.setEnterFadeDuration(1200) carbAnimation?.setEnterFadeDuration(1200)
@ -189,7 +189,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
overviewData.prepareBucketedData("EventBucketedDataCreated") overviewData.prepareBucketedData("EventBucketedDataCreated")
overviewData.prepareBgData("EventBucketedDataCreated") overviewData.prepareBgData("EventBucketedDataCreated")
updateGUI("rangeChange", OverviewData.Property.GRAPH) updateGUI("rangeChange", OverviewData.Property.GRAPH)
rxBus.send(EventPreferenceChange(resourceHelper, R.string.key_rangetodisplay)) rxBus.send(EventPreferenceChange(rh, R.string.key_rangetodisplay))
sp.putBoolean(R.string.key_objectiveusescale, true) sp.putBoolean(R.string.key_objectiveusescale, true)
false false
} }
@ -257,7 +257,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.delay (30, TimeUnit.MILLISECONDS, aapsSchedulers.main) .delay (30, TimeUnit.MILLISECONDS, aapsSchedulers.main)
.subscribe({ .subscribe({
overviewData.pumpStatus = it.getStatus(resourceHelper) overviewData.pumpStatus = it.getStatus(rh)
updateGUI("EventPumpStatusChanged", OverviewData.Property.PUMPSTATUS) updateGUI("EventPumpStatusChanged", OverviewData.Property.PUMPSTATUS)
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
@ -305,7 +305,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
dexcomMediator.findDexcomPackageName()?.let { dexcomMediator.findDexcomPackageName()?.let {
openCgmApp(it) openCgmApp(it)
} }
?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed))
} }
} }
@ -317,9 +317,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
dexcomMediator.findDexcomPackageName()?.let { dexcomMediator.findDexcomPackageName()?.let {
startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it)) startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it))
} }
?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) ?: ToastUtils.showToastInUiThread(activity, rh.gs(R.string.dexcom_app_not_installed))
} catch (e: ActivityNotFoundException) { } catch (e: ActivityNotFoundException) {
ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.g5appnotdetected)) ToastUtils.showToastInUiThread(activity, rh.gs(R.string.g5appnotdetected))
} }
} }
} }
@ -332,7 +332,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
loopPlugin.invoke("Accept temp button", false) loopPlugin.invoke("Accept temp button", false)
if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) {
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable { protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned() OKDialog.showConfirmation(activity, rh.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned()
?: "".toSpanned(), { ?: "".toSpanned(), {
uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview)
binding.buttonsLayout.acceptTempButton.visibility = View.GONE binding.buttonsLayout.acceptTempButton.visibility = View.GONE
@ -366,7 +366,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
intent.addCategory(Intent.CATEGORY_LAUNCHER) intent.addCategory(Intent.CATEGORY_LAUNCHER)
it.startActivity(intent) it.startActivity(intent)
} catch (e: ActivityNotFoundException) { } catch (e: ActivityNotFoundException) {
OKDialog.show(it, "", resourceHelper.gs(R.string.error_starting_cgm)) OKDialog.show(it, "", rh.gs(R.string.error_starting_cgm))
} }
} }
} }
@ -408,7 +408,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value()
activity?.let { activity?.let {
if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) { if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) {
OKDialog.show(it, resourceHelper.gs(R.string.treatmentdeliveryerror), resourceHelper.gs(R.string.constraints_violation) + "\n" + resourceHelper.gs(R.string.changeyourinput)) OKDialog.show(it, rh.gs(R.string.treatmentdeliveryerror), rh.gs(R.string.constraints_violation) + "\n" + rh.gs(R.string.changeyourinput))
return return
} }
wizard.confirmAndExecute(it) wizard.confirmAndExecute(it)
@ -430,8 +430,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended()) { if (quickWizardEntry != null && lastBG != null && profile != null && pump.isInitialized() && !pump.isSuspended()) {
binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE
val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false) val wizard = quickWizardEntry.doCalc(profile, profileName, lastBG, false)
binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + resourceHelper.gs(R.string.format_carbs, quickWizardEntry.carbs()) + binding.buttonsLayout.quickWizardButton.text = quickWizardEntry.buttonText() + "\n" + rh.gs(R.string.format_carbs, quickWizardEntry.carbs()) +
" " + resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) " " + rh.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin)
if (wizard.calculatedTotalInsulin <= 0) binding.buttonsLayout.quickWizardButton.visibility = View.GONE if (wizard.calculatedTotalInsulin <= 0) binding.buttonsLayout.quickWizardButton.visibility = View.GONE
} else binding.buttonsLayout.quickWizardButton.visibility = View.GONE } else binding.buttonsLayout.quickWizardButton.visibility = View.GONE
@ -446,7 +446,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && loopPlugin.isEnabled(PluginType.LOOP)) { if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && loopPlugin.isEnabled(PluginType.LOOP)) {
binding.buttonsLayout.acceptTempButton.visibility = View.VISIBLE binding.buttonsLayout.acceptTempButton.visibility = View.VISIBLE
binding.buttonsLayout.acceptTempButton.text = "${resourceHelper.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}" binding.buttonsLayout.acceptTempButton.text = "${rh.gs(R.string.setbasalquestion)}\n${lastRun!!.constraintsProcessed}"
} else { } else {
binding.buttonsLayout.acceptTempButton.visibility = View.GONE binding.buttonsLayout.acceptTempButton.visibility = View.GONE
} }
@ -470,18 +470,18 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (event.isEnabled && event.trigger.shouldRun()) if (event.isEnabled && event.trigger.shouldRun())
context?.let { context -> context?.let { context ->
SingleClickButton(context).also { SingleClickButton(context).also {
it.setTextColor(resourceHelper.gc(R.color.colorTreatmentButton)) it.setTextColor(rh.gc(R.color.colorTreatmentButton))
it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f) it.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f)
it.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f).also { l -> it.layoutParams = LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 0.5f).also { l ->
l.setMargins(0, 0, resourceHelper.dpToPx(-4), 0) l.setMargins(0, 0, rh.dpToPx(-4), 0)
} }
it.setCompoundDrawablesWithIntrinsicBounds(null, resourceHelper.gd(R.drawable.ic_danar_useropt), null, null) it.setCompoundDrawablesWithIntrinsicBounds(null, rh.gd(R.drawable.ic_danar_useropt), null, null)
it.text = event.title it.text = event.title
it.setOnClickListener { it.setOnClickListener {
OKDialog.showConfirmation( OKDialog.showConfirmation(
context, context,
resourceHelper.gs(R.string.run_question, event.title), rh.gs(R.string.run_question, event.title),
{ handler.post { automationPlugin.processEvent(event, true) } } { handler.post { automationPlugin.processEvent(event, true) } }
) )
} }
@ -502,19 +502,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
when { when {
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isDisconnected -> { loopPlugin.isDisconnected -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isEnabled() && loopPlugin.isSuspended -> { loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused) binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, rh)
binding.infoLayout.apsModeText.visibility = View.VISIBLE binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
@ -558,15 +558,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
// pump status from ns // pump status from ns
binding.pump.text = nsDeviceStatus.pumpStatus binding.pump.text = nsDeviceStatus.pumpStatus
binding.pump.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.pump), nsDeviceStatus.extendedPumpStatus) } } binding.pump.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.pump), nsDeviceStatus.extendedPumpStatus) } }
// OpenAPS status from ns // OpenAPS status from ns
binding.openaps.text = nsDeviceStatus.openApsStatus binding.openaps.text = nsDeviceStatus.openApsStatus
binding.openaps.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.openaps), nsDeviceStatus.extendedOpenApsStatus) } } binding.openaps.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.openaps), nsDeviceStatus.extendedOpenApsStatus) } }
// Uploader status from ns // Uploader status from ns
binding.uploader.text = nsDeviceStatus.uploaderStatusSpanned binding.uploader.text = nsDeviceStatus.uploaderStatusSpanned
binding.uploader.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } } binding.uploader.setOnClickListener { activity?.let { OKDialog.show(it, rh.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } }
} }
private fun prepareGraphsIfNeeded(numOfGraphs: Int) { private fun prepareGraphsIfNeeded(numOfGraphs: Int) {
@ -581,8 +581,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val graph = GraphView(context) val graph = GraphView(context)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(skinProvider.activeSkin().secondaryGraphHeight)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) } graph.layoutParams = 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 = resourceHelper.gc(R.color.graphgrid) graph.gridLabelRenderer?.gridColor = rh.gc(R.color.graphgrid)
graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
@ -591,7 +591,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
relativeLayout.addView(graph) relativeLayout.addView(graph)
val label = TextView(context) val label = TextView(context)
val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) } val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) }
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
label.layoutParams = layoutParams label.layoutParams = layoutParams
@ -626,7 +626,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
// aapsLogger.debug(LTag.UI, "UpdateGui $from $what") // aapsLogger.debug(LTag.UI, "UpdateGui $from $what")
if (profileFunction.getProfile() == null) { if (profileFunction.getProfile() == null) {
binding.activeProfile.setText(R.string.noprofileset) binding.activeProfile.setText(R.string.noprofileset)
binding.activeProfile.setBackgroundColor(resourceHelper.gc(R.color.errorAlertBackground)) binding.activeProfile.setBackgroundColor(rh.gc(R.color.errorAlertBackground))
return return
} }
binding.notifications.let { notificationStore.updateNotifications(it) } binding.notifications.let { notificationStore.updateNotifications(it) }
@ -636,7 +636,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
when (what) { when (what) {
OverviewData.Property.BG -> { OverviewData.Property.BG -> {
binding.infoLayout.bg.text = overviewData.lastBg?.valueToUnitsString(units) binding.infoLayout.bg.text = overviewData.lastBg?.valueToUnitsString(units)
?: resourceHelper.gs(R.string.notavailable) ?: rh.gs(R.string.notavailable)
binding.infoLayout.bg.setTextColor(overviewData.lastBgColor) binding.infoLayout.bg.setTextColor(overviewData.lastBgColor)
binding.infoLayout.arrow.setImageResource(trendCalculator.getTrendArrow(overviewData.lastBg).directionToIcon()) binding.infoLayout.arrow.setImageResource(trendCalculator.getTrendArrow(overviewData.lastBg).directionToIcon())
binding.infoLayout.arrow.setColorFilter(overviewData.lastBgColor) binding.infoLayout.arrow.setColorFilter(overviewData.lastBgColor)
@ -650,7 +650,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units) binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units)
} else { } else {
binding.infoLayout.deltaLarge.text = "" binding.infoLayout.deltaLarge.text = ""
binding.infoLayout.delta.text = "Δ " + resourceHelper.gs(R.string.notavailable) binding.infoLayout.delta.text = "Δ " + rh.gs(R.string.notavailable)
binding.infoLayout.avgDelta.text = "" binding.infoLayout.avgDelta.text = ""
binding.infoLayout.longAvgDelta.text = "" binding.infoLayout.longAvgDelta.text = ""
} }
@ -659,7 +659,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
binding.infoLayout.bg.paintFlags = binding.infoLayout.bg.paintFlags =
if (!overviewData.isActualBg) binding.infoLayout.bg.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG 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() else binding.infoLayout.bg.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
binding.infoLayout.timeAgo.text = dateUtil.minAgo(resourceHelper, overviewData.lastBg?.timestamp) binding.infoLayout.timeAgo.text = dateUtil.minAgo(rh, overviewData.lastBg?.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(overviewData.lastBg?.timestamp) + ")" binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(overviewData.lastBg?.timestamp) + ")"
} }
@ -668,27 +668,27 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
profileFunction.getProfile()?.let { profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) { if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L) if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
resourceHelper.gc(R.color.ribbonWarning) rh.gc(R.color.ribbonWarning)
else resourceHelper.gc(R.color.ribbonDefault) else rh.gc(R.color.ribbonDefault)
} else if (it is ProfileSealed.PS) { } else if (it is ProfileSealed.PS) {
resourceHelper.gc(R.color.ribbonDefault) rh.gc(R.color.ribbonDefault)
} else { } else {
resourceHelper.gc(R.color.ribbonDefault) rh.gc(R.color.ribbonDefault)
} }
} ?: resourceHelper.gc(R.color.ribbonCritical) } ?: rh.gc(R.color.ribbonCritical)
val profileTextColor = val profileTextColor =
profileFunction.getProfile()?.let { profileFunction.getProfile()?.let {
if (it is ProfileSealed.EPS) { if (it is ProfileSealed.EPS) {
if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L) if (it.value.originalPercentage != 100 || it.value.originalTimeshift != 0L || it.value.originalDuration != 0L)
resourceHelper.gc(R.color.ribbonTextWarning) rh.gc(R.color.ribbonTextWarning)
else resourceHelper.gc(R.color.ribbonTextDefault) else rh.gc(R.color.ribbonTextDefault)
}else if (it is ProfileSealed.PS) { }else if (it is ProfileSealed.PS) {
resourceHelper.gc(R.color.ribbonTextDefault) rh.gc(R.color.ribbonTextDefault)
} else { } else {
resourceHelper.gc(R.color.ribbonTextDefault) rh.gc(R.color.ribbonTextDefault)
} }
} ?: resourceHelper.gc(R.color.ribbonTextDefault) } ?: rh.gc(R.color.ribbonTextDefault)
binding.activeProfile.text = profileFunction.getProfileNameWithRemainingTime() binding.activeProfile.text = profileFunction.getProfileNameWithRemainingTime()
binding.activeProfile.setBackgroundColor(profileBackgroundColor) binding.activeProfile.setBackgroundColor(profileBackgroundColor)
@ -700,14 +700,14 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
binding.infoLayout.baseBasal.setTextColor(overviewData.temporaryBasalColor) binding.infoLayout.baseBasal.setTextColor(overviewData.temporaryBasalColor)
binding.infoLayout.baseBasalIcon.setImageResource(overviewData.temporaryBasalIcon) binding.infoLayout.baseBasalIcon.setImageResource(overviewData.temporaryBasalIcon)
binding.infoLayout.basalLayout.setOnClickListener { binding.infoLayout.basalLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.basal), overviewData.temporaryBasalDialogText) } activity?.let { OKDialog.show(it, rh.gs(R.string.basal), overviewData.temporaryBasalDialogText) }
} }
} }
OverviewData.Property.EXTENDED_BOLUS -> { OverviewData.Property.EXTENDED_BOLUS -> {
binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText
binding.infoLayout.extendedLayout.setOnClickListener { binding.infoLayout.extendedLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) } activity?.let { OKDialog.show(it, rh.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) }
} }
binding.infoLayout.extendedLayout.visibility = (overviewData.extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() binding.infoLayout.extendedLayout.visibility = (overviewData.extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility()
@ -725,10 +725,10 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
OverviewData.Property.IOB_COB -> { OverviewData.Property.IOB_COB -> {
binding.infoLayout.iob.text = overviewData.iobText binding.infoLayout.iob.text = overviewData.iobText
binding.infoLayout.iobLayout.setOnClickListener { binding.infoLayout.iobLayout.setOnClickListener {
activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.iob), overviewData.iobDialogText) } activity?.let { OKDialog.show(it, rh.gs(R.string.iob), overviewData.iobDialogText) }
} }
// cob // cob
var cobText = overviewData.cobInfo?.displayText(resourceHelper, dateUtil, buildHelper.isEngineeringMode()) ?: resourceHelper.gs(R.string.value_unavailable_short) var cobText = overviewData.cobInfo?.displayText(rh, dateUtil, buildHelper.isEngineeringMode()) ?: rh.gs(R.string.value_unavailable_short)
val constraintsProcessed = loopPlugin.lastRun?.constraintsProcessed val constraintsProcessed = loopPlugin.lastRun?.constraintsProcessed
val lastRun = loopPlugin.lastRun val lastRun = loopPlugin.lastRun
@ -736,7 +736,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (constraintsProcessed.carbsReq > 0) { if (constraintsProcessed.carbsReq > 0) {
//only display carbsreq when carbs have not been entered recently //only display carbsreq when carbs have not been entered recently
if (overviewData.lastCarbsTime < lastRun.lastAPSRun) { if (overviewData.lastCarbsTime < lastRun.lastAPSRun) {
cobText += " | " + constraintsProcessed.carbsReq + " " + resourceHelper.gs(R.string.required) cobText += " | " + constraintsProcessed.carbsReq + " " + rh.gs(R.string.required)
} }
if (carbAnimation?.isRunning == false) if (carbAnimation?.isRunning == false)
carbAnimation?.start() carbAnimation?.start()
@ -753,9 +753,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (overviewData.temporaryTarget?.isInProgress(dateUtil) == false) overviewData.temporaryTarget = null if (overviewData.temporaryTarget?.isInProgress(dateUtil) == false) overviewData.temporaryTarget = null
val tempTarget = overviewData.temporaryTarget val tempTarget = overviewData.temporaryTarget
if (tempTarget != null) { if (tempTarget != null) {
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) binding.tempTarget.setBackgroundColor(rh.gc(R.color.ribbonWarning))
binding.tempTarget.text = Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, resourceHelper) binding.tempTarget.text = Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh)
} else { } else {
// If the target is not the same as set in the profile then oref has overridden it // If the target is not the same as set in the profile then oref has overridden it
profileFunction.getProfile()?.let { profile -> profileFunction.getProfile()?.let { profile ->
@ -764,11 +764,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) { if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) {
aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed") aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed")
binding.tempTarget.text = Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units) binding.tempTarget.text = Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units)
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextWarning))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.tempTargetBackground)) binding.tempTarget.setBackgroundColor(rh.gc(R.color.tempTargetBackground))
} else { } else {
binding.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) binding.tempTarget.setTextColor(rh.gc(R.color.ribbonTextDefault))
binding.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) binding.tempTarget.setBackgroundColor(rh.gc(R.color.ribbonDefault))
binding.tempTarget.text = Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units) binding.tempTarget.text = Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)
} }
} }

View file

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

View file

@ -41,7 +41,7 @@ class OverviewPlugin @Inject constructor(
private val sp: SP, private val sp: SP,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val config: Config, private val config: Config,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
@ -59,7 +59,7 @@ class OverviewPlugin @Inject constructor(
.shortName(R.string.overview_shortname) .shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview) .preferencesId(R.xml.pref_overview)
.description(R.string.description_overview), .description(R.string.description_overview),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Overview { ), Overview {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -152,7 +152,7 @@ class OverviewPlugin @Inject constructor(
.toObservable(EventPumpStatusChanged::class.java) .toObservable(EventPumpStatusChanged::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ .subscribe({
overviewData.pumpStatus = it.getStatus(resourceHelper) overviewData.pumpStatus = it.getStatus(rh)
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
Thread { loadAll("onResume") }.start() Thread { loadAll("onResume") }.start()
@ -166,11 +166,11 @@ class OverviewPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) super.preprocessPreferences(preferenceFragment)
if (config.NSCLIENT) { if (config.NSCLIENT) {
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let { (preferenceFragment.findPreference(rh.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let {
it.isVisible = false it.isVisible = false
it.isEnabled = false it.isEnabled = false
} }
(preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let { (preferenceFragment.findPreference(rh.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let {
it.isVisible = false it.isVisible = false
it.isEnabled = false it.isEnabled = false
} }
@ -179,57 +179,57 @@ class OverviewPlugin @Inject constructor(
override fun configuration(): JSONObject = override fun configuration(): JSONObject =
JSONObject() JSONObject()
.putString(R.string.key_units, sp, resourceHelper) .putString(R.string.key_units, sp, rh)
.putString(R.string.key_quickwizard, sp, resourceHelper) .putString(R.string.key_quickwizard, sp, rh)
.putInt(R.string.key_eatingsoon_duration, sp, resourceHelper) .putInt(R.string.key_eatingsoon_duration, sp, rh)
.putDouble(R.string.key_eatingsoon_target, sp, resourceHelper) .putDouble(R.string.key_eatingsoon_target, sp, rh)
.putInt(R.string.key_activity_duration, sp, resourceHelper) .putInt(R.string.key_activity_duration, sp, rh)
.putDouble(R.string.key_activity_target, sp, resourceHelper) .putDouble(R.string.key_activity_target, sp, rh)
.putInt(R.string.key_hypo_duration, sp, resourceHelper) .putInt(R.string.key_hypo_duration, sp, rh)
.putDouble(R.string.key_hypo_target, sp, resourceHelper) .putDouble(R.string.key_hypo_target, sp, rh)
.putDouble(R.string.key_low_mark, sp, resourceHelper) .putDouble(R.string.key_low_mark, sp, rh)
.putDouble(R.string.key_high_mark, sp, resourceHelper) .putDouble(R.string.key_high_mark, sp, rh)
.putDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_cage_warning, sp, rh)
.putDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_cage_critical, sp, rh)
.putDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_iage_warning, sp, rh)
.putDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_iage_critical, sp, rh)
.putDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_sage_warning, sp, rh)
.putDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_sage_critical, sp, rh)
.putDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_sbat_warning, sp, rh)
.putDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_sbat_critical, sp, rh)
.putDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_bage_warning, sp, rh)
.putDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_bage_critical, sp, rh)
.putDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_res_warning, sp, rh)
.putDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_res_critical, sp, rh)
.putDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) .putDouble(R.string.key_statuslights_bat_warning, sp, rh)
.putDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) .putDouble(R.string.key_statuslights_bat_critical, sp, rh)
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
configuration configuration
.storeString(R.string.key_units, sp, resourceHelper) .storeString(R.string.key_units, sp, rh)
.storeString(R.string.key_quickwizard, sp, resourceHelper) .storeString(R.string.key_quickwizard, sp, rh)
.storeInt(R.string.key_eatingsoon_duration, sp, resourceHelper) .storeInt(R.string.key_eatingsoon_duration, sp, rh)
.storeDouble(R.string.key_eatingsoon_target, sp, resourceHelper) .storeDouble(R.string.key_eatingsoon_target, sp, rh)
.storeInt(R.string.key_activity_duration, sp, resourceHelper) .storeInt(R.string.key_activity_duration, sp, rh)
.storeDouble(R.string.key_activity_target, sp, resourceHelper) .storeDouble(R.string.key_activity_target, sp, rh)
.storeInt(R.string.key_hypo_duration, sp, resourceHelper) .storeInt(R.string.key_hypo_duration, sp, rh)
.storeDouble(R.string.key_hypo_target, sp, resourceHelper) .storeDouble(R.string.key_hypo_target, sp, rh)
.storeDouble(R.string.key_low_mark, sp, resourceHelper) .storeDouble(R.string.key_low_mark, sp, rh)
.storeDouble(R.string.key_high_mark, sp, resourceHelper) .storeDouble(R.string.key_high_mark, sp, rh)
.storeDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_cage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_cage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_iage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_iage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sbat_warning, sp, rh)
.storeDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_sbat_critical, sp, rh)
.storeDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bage_warning, sp, rh)
.storeDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bage_critical, sp, rh)
.storeDouble(R.string.key_statuslights_res_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_res_warning, sp, rh)
.storeDouble(R.string.key_statuslights_res_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_res_critical, sp, rh)
.storeDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bat_warning, sp, rh)
.storeDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper) .storeDouble(R.string.key_statuslights_bat_critical, sp, rh)
} }
@Volatile @Volatile

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -34,7 +34,7 @@ class NotificationStore @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val sp: SP, private val sp: SP,
private val rxBus: RxBus, private val rxBus: RxBus,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val context: Context, private val context: Context,
private val iconsProvider: IconsProvider, private val iconsProvider: IconsProvider,
private val alarmSoundServiceHelper: AlarmSoundServiceHelper, private val alarmSoundServiceHelper: AlarmSoundServiceHelper,
@ -104,7 +104,7 @@ class NotificationStore @Inject constructor(
private fun raiseSystemNotification(n: Notification) { private fun raiseSystemNotification(n: Notification) {
val mgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 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 smallIcon = iconsProvider.getNotificationIcon()
val sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM) val sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID)
@ -117,11 +117,11 @@ class NotificationStore @Inject constructor(
.setContentIntent(notificationHolder.openAppIntent(context)) .setContentIntent(notificationHolder.openAppIntent(context))
if (n.level == Notification.URGENT) { if (n.level == Notification.URGENT) {
notificationBuilder.setVibrate(longArrayOf(1000, 1000, 1000, 1000)) 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) .setSound(sound, AudioManager.STREAM_ALARM)
} else { } else {
notificationBuilder.setVibrate(longArrayOf(0, 100, 50, 100, 50)) 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()) mgr.notify(n.id, notificationBuilder.build())
} }
@ -165,11 +165,11 @@ class NotificationStore @Inject constructor(
@Suppress("SetTextI18n") @Suppress("SetTextI18n")
holder.binding.text.text = dateUtil.timeString(notification.date) + " " + notification.text holder.binding.text.text = dateUtil.timeString(notification.date) + " " + notification.text
when (notification.level) { when (notification.level) {
Notification.URGENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent)) Notification.URGENT -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationUrgent))
Notification.NORMAL -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal)) Notification.NORMAL -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationNormal))
Notification.LOW -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow)) Notification.LOW -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationLow))
Notification.INFO -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo)) Notification.INFO -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationInfo))
Notification.ANNOUNCEMENT -> holder.binding.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationAnnouncement)) Notification.ANNOUNCEMENT -> holder.binding.cv.setBackgroundColor(rh.gc(R.color.notificationAnnouncement))
} }
} }

View file

@ -18,7 +18,7 @@ class NotificationWithAction constructor(
) : Notification() { ) : Notification() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin

View file

@ -31,7 +31,7 @@ import javax.inject.Singleton
class PersistentNotificationPlugin @Inject constructor( class PersistentNotificationPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
@ -52,7 +52,7 @@ class PersistentNotificationPlugin @Inject constructor(
.alwaysEnabled(true) .alwaysEnabled(true)
.showInList(false) .showInList(false)
.description(R.string.description_persistent_notification), .description(R.string.description_persistent_notification),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
// For Android Auto // For Android Auto
@ -142,12 +142,12 @@ class PersistentNotificationPlugin @Inject constructor(
line1aa += " " + lastBG.trendArrow.symbol line1aa += " " + lastBG.trendArrow.symbol
} else { } else {
line1 += " " + line1 += " " +
resourceHelper.gs(R.string.old_data) + rh.gs(R.string.old_data) +
" " " "
line1aa += "$line1." line1aa += "$line1."
} }
} else { } else {
line1aa = resourceHelper.gs(R.string.missed_bg_readings) line1aa = rh.gs(R.string.missed_bg_readings)
line1 = line1aa line1 = line1aa
} }
val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()) val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())
@ -159,12 +159,12 @@ class PersistentNotificationPlugin @Inject constructor(
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
line2 = line2 =
resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo( rh.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + rh.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(
false, false,
"PersistentNotificationPlugin" "PersistentNotificationPlugin"
).generateCOBString() ).generateCOBString()
val line2aa = val line2aa =
resourceHelper.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + resourceHelper.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo( rh.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + rh.gs(R.string.cob) + ": " + iobCobCalculator.getCobInfo(
false, false,
"PersistentNotificationPlugin" "PersistentNotificationPlugin"
).generateCOBString() + "." ).generateCOBString() + "."
@ -206,14 +206,14 @@ class PersistentNotificationPlugin @Inject constructor(
unreadConversationBuilder.addMessage(line3aa) unreadConversationBuilder.addMessage(line3aa)
/// End Android Auto /// End Android Auto
} else { } else {
line1 = resourceHelper.gs(R.string.noprofileset) line1 = rh.gs(R.string.noprofileset)
} }
val builder = NotificationCompat.Builder(context, notificationHolder.channelID) val builder = NotificationCompat.Builder(context, notificationHolder.channelID)
builder.setOngoing(true) builder.setOngoing(true)
builder.setOnlyAlertOnce(true) builder.setOnlyAlertOnce(true)
builder.setCategory(NotificationCompat.CATEGORY_STATUS) builder.setCategory(NotificationCompat.CATEGORY_STATUS)
builder.setSmallIcon(iconsProvider.getNotificationIcon()) builder.setSmallIcon(iconsProvider.getNotificationIcon())
builder.setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) builder.setLargeIcon(rh.decodeResource(iconsProvider.getIcon()))
builder.setContentTitle(line1) builder.setContentTitle(line1)
if (line2 != null) builder.setContentText(line2) if (line2 != null) builder.setContentText(line2)
if (line3 != null) builder.setSubText(line3) if (line3 != null) builder.setSubText(line3)

View file

@ -23,7 +23,7 @@ class AuthRequest internal constructor(
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var otp: OneTimePassword @Inject lateinit var otp: OneTimePassword
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@ -48,7 +48,7 @@ class AuthRequest internal constructor(
if (!codeIsValid(codeReceived)) { if (!codeIsValid(codeReceived)) {
processed = true processed = true
aapsLogger.debug(LTag.SMS, "Wrong code") 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 return
} }
if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
@ -62,7 +62,7 @@ class AuthRequest internal constructor(
} }
if (commandQueue.size() != 0) { if (commandQueue.size() != 0) {
aapsLogger.debug(LTag.SMS, "Command timed out: " + requester.text) 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 return
} }
} }

View file

@ -65,7 +65,7 @@ import kotlin.math.min
class SmsCommunicatorPlugin @Inject constructor( class SmsCommunicatorPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val smsManager: SmsManager, private val smsManager: SmsManager,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val sp: SP, private val sp: SP,
@ -92,7 +92,7 @@ class SmsCommunicatorPlugin @Inject constructor(
.shortName(R.string.smscommunicator_shortname) .shortName(R.string.smscommunicator_shortname)
.preferencesId(R.xml.pref_smscommunicator) .preferencesId(R.xml.pref_smscommunicator)
.description(R.string.description_sms_communicator), .description(R.string.description_sms_communicator),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), SmsCommunicator { ), SmsCommunicator {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -133,28 +133,28 @@ class SmsCommunicatorPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) 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 ?: 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 ?: return
if (!areMoreNumbers(allowedNumbers.text)) { if (!areMoreNumbers(allowedNumbers.text)) {
distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance)
+ ".\n" + ".\n"
+ resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
distance.isEnabled = false distance.isEnabled = false
} else { } else {
distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance)
distance.isEnabled = true distance.isEnabled = true
} }
allowedNumbers.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any -> allowedNumbers.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _: Preference?, newValue: Any ->
if (!areMoreNumbers(newValue as String)) { if (!areMoreNumbers(newValue as String)) {
distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString() distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString()
distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.title = (rh.gs(R.string.smscommunicator_remotebolusmindistance)
+ ".\n" + ".\n"
+ resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + rh.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
distance.isEnabled = false distance.isEnabled = false
} else { } else {
distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.title = rh.gs(R.string.smscommunicator_remotebolusmindistance)
distance.isEnabled = true distance.isEnabled = true
} }
true true
@ -165,7 +165,7 @@ class SmsCommunicatorPlugin @Inject constructor(
super.updatePreferenceSummary(pref) super.updatePreferenceSummary(pref)
if (pref is EditTextPreference) { if (pref is EditTextPreference) {
if (pref.getKey().contains("smscommunicator_allowednumbers") && (pref.text == null || TextUtils.isEmpty(pref.text.trim { it <= ' ' }))) { 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?) { 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, "") val settings = sp.getString(R.string.key_smscommunicator_allowednumbers, "")
allowedNumbers.clear() allowedNumbers.clear()
val substrings = settings.split(";").toTypedArray() val substrings = settings.split(";").toTypedArray()
@ -253,56 +253,56 @@ class SmsCommunicatorPlugin @Inject constructor(
when (divided[0].uppercase(Locale.getDefault())) { when (divided[0].uppercase(Locale.getDefault())) {
"BG" -> "BG" ->
if (divided.size == 1) processBG(receivedSms) 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" -> "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 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" -> "NSCLIENT" ->
if (divided.size == 2) processNSCLIENT(divided, receivedSms) 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" -> "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 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" -> "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 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" -> "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 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" -> "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 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" -> "BOLUS" ->
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 (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_another_bolus_in_queue))) 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, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed))) 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, resourceHelper.gs(R.string.pumpsuspended))) 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 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" -> "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 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" -> "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 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" -> "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 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" -> "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 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" -> "HELP" ->
if (divided.size == 1 || divided.size == 2) processHELP(divided, receivedSms) 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 -> else ->
if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) { if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) {
val execute = messageToConfirm val execute = messageToConfirm
@ -310,7 +310,7 @@ class SmsCommunicatorPlugin @Inject constructor(
execute?.action(divided[0]) execute?.action(divided[0])
} else { } else {
messageToConfirm = null 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 = "" var reply = ""
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
if (actualBG != null) { 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) { } else if (lastBG != null) {
val agoMilliseconds = dateUtil.now() - lastBG.timestamp val agoMilliseconds = dateUtil.now() - lastBG.timestamp
val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt() 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 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 bolusIob = iobCobCalculator.calculateIobFromBolus().round()
val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round()
val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB") val cobInfo = iobCobCalculator.getCobInfo(false, "SMS COB")
reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" reply += (rh.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + rh.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ resourceHelper.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + rh.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), "
+ resourceHelper.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) + rh.gs(R.string.cob) + ": " + cobInfo.generateCOBString())
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
receivedSms.processed = true receivedSms.processed = true
} }
@ -347,7 +347,7 @@ class SmsCommunicatorPlugin @Inject constructor(
"DISABLE", "STOP" -> { "DISABLE", "STOP" -> {
if (loop.enabled) { if (loop.enabled) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() { override fun run() {
@ -356,49 +356,49 @@ class SmsCommunicatorPlugin @Inject constructor(
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
rxBus.send(EventRefreshOverview("SMS_LOOP_STOP")) rxBus.send(EventRefreshOverview("SMS_LOOP_STOP"))
val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + val replyText = rh.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
} }
}) })
} }
}) })
} else } else
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.loopisdisabled))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.loopisdisabled)))
receivedSms.processed = true receivedSms.processed = true
} }
"ENABLE", "START" -> { "ENABLE", "START" -> {
if (!loop.enabled) { if (!loop.enabled) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() { override fun run() {
uel.log(Action.LOOP_ENABLED, Sources.SMS) uel.log(Action.LOOP_ENABLED, Sources.SMS)
loop.enabled = true 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")) rxBus.send(EventRefreshOverview("SMS_LOOP_START"))
} }
}) })
} else } else
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopisenabled))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_loopisenabled)))
receivedSms.processed = true receivedSms.processed = true
} }
"STATUS" -> { "STATUS" -> {
val reply = if (loop.enabled) { val reply = if (loop.enabled) {
if (loop.isSuspended) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loop.minutesToEndOfSuspend()) if (loop.isSuspended) String.format(rh.gs(R.string.loopsuspendedfor), loop.minutesToEndOfSuspend())
else resourceHelper.gs(R.string.smscommunicator_loopisenabled) else rh.gs(R.string.smscommunicator_loopisenabled)
} else } else
resourceHelper.gs(R.string.loopisdisabled) rh.gs(R.string.loopisdisabled)
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
receivedSms.processed = true receivedSms.processed = true
} }
"RESUME" -> { "RESUME" -> {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() { override fun run() {
@ -413,13 +413,13 @@ class SmsCommunicatorPlugin @Inject constructor(
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) 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) duration = min(180, duration)
if (duration == 0) { if (duration == 0) {
receivedSms.processed = true receivedSms.processed = true
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_wrongduration))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration)))
return return
} else { } else {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) {
override fun run() { override fun run() {
@ -451,11 +451,11 @@ class SmsCommunicatorPlugin @Inject constructor(
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it)
}) })
rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED"))
val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " + val replyText = rh.gs(R.string.smscommunicator_loopsuspended) + " " +
resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) rh.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) 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")) sendSMS(Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT"))
receivedSms.processed = true receivedSms.processed = true
} else } else
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
} }
private fun processHELP(divided: Array<String>, receivedSms: Sms) { private fun processHELP(divided: Array<String>, 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) val reply = pump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
} else { } else {
val reply = resourceHelper.gs(R.string.readstatusfailed) val reply = rh.gs(R.string.readstatusfailed)
sendSMS(Sms(receivedSms.phoneNumber, reply)) sendSMS(Sms(receivedSms.phoneNumber, reply))
} }
} }
@ -514,7 +514,7 @@ class SmsCommunicatorPlugin @Inject constructor(
receivedSms.processed = true receivedSms.processed = true
} else if ((divided.size == 2) && (divided[1].equals("CONNECT", ignoreCase = true))) { } else if ((divided.size == 2) && (divided[1].equals("CONNECT", ignoreCase = true))) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() { override fun run() {
@ -522,7 +522,7 @@ class SmsCommunicatorPlugin @Inject constructor(
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_pumpconnectfail))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_pumpconnectfail)))
} else { } else {
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now())) disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
.subscribe({ result -> .subscribe({ result ->
@ -530,7 +530,7 @@ class SmsCommunicatorPlugin @Inject constructor(
}, { }, {
aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) 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")) rxBus.send(EventRefreshOverview("SMS_PUMP_START"))
} }
} }
@ -543,11 +543,11 @@ class SmsCommunicatorPlugin @Inject constructor(
duration = min(120, duration) duration = min(120, duration)
if (duration == 0) { if (duration == 0) {
receivedSms.processed = true receivedSms.processed = true
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_wrongduration))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.smscommunicator_wrongduration)))
return return
} else { } else {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() { override fun run() {
@ -555,12 +555,12 @@ class SmsCommunicatorPlugin @Inject constructor(
val profile = profileFunction.getProfile() ?: return val profile = profileFunction.getProfile() ?: return
loop.goToZeroTemp(duration, profile, OfflineEvent.Reason.DISCONNECT_PUMP) loop.goToZeroTemp(duration, profile, OfflineEvent.Reason.DISCONNECT_PUMP)
rxBus.send(EventRefreshOverview("SMS_PUMP_DISCONNECT")) 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 { } else {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
return return
} }
} }
@ -569,7 +569,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val anInterface = activePlugin.activeProfileSource val anInterface = activePlugin.activeProfileSource
val store = anInterface.profile val store = anInterface.profile
if (store == null) { if (store == null) {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.notconfigured))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.notconfigured)))
receivedSms.processed = true receivedSms.processed = true
return return
} }
@ -578,7 +578,7 @@ class SmsCommunicatorPlugin @Inject constructor(
if (divided[1].uppercase(Locale.getDefault()) == "STATUS") { if (divided[1].uppercase(Locale.getDefault()) == "STATUS") {
sendSMS(Sms(receivedSms.phoneNumber, profileName)) sendSMS(Sms(receivedSms.phoneNumber, profileName))
} else if (divided[1].uppercase(Locale.getDefault()) == "LIST") { } 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 { else {
var reply = "" var reply = ""
for (i in list.indices) { for (i in list.indices) {
@ -592,28 +592,28 @@ class SmsCommunicatorPlugin @Inject constructor(
val pIndex = SafeParse.stringToInt(divided[1]) val pIndex = SafeParse.stringToInt(divided[1])
var percentage = 100 var percentage = 100
if (divided.size > 2) percentage = SafeParse.stringToInt(divided[2]) if (divided.size > 2) percentage = SafeParse.stringToInt(divided[2])
if (pIndex > list.size) 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, resourceHelper.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, resourceHelper.gs(R.string.wrongformat))) else if (pIndex == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
else { else {
val profile = store.getSpecificProfile(list[pIndex - 1] as String) 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 { else {
val passCode = generatePassCode() 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 receivedSms.processed = true
val finalPercentage = percentage val finalPercentage = percentage
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) {
override fun run() { override fun run() {
if (profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())) { if (profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())) {
val replyText = resourceHelper.gs(R.string.profileswitchcreated) val replyText = rh.gs(R.string.profileswitchcreated)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log( uel.log(
Action.PROFILE_SWITCH, Sources.SMS, resourceHelper.gs(R.string.profileswitchcreated), Action.PROFILE_SWITCH, Sources.SMS, rh.gs(R.string.profileswitchcreated),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.profileswitchcreated)) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.profileswitchcreated))
) )
} else { } else {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.invalidprofile))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.invalidprofile)))
} }
} }
}) })
@ -626,24 +626,24 @@ class SmsCommunicatorPlugin @Inject constructor(
private fun processBASAL(divided: Array<String>, receivedSms: Sms) { private fun processBASAL(divided: Array<String>, receivedSms: Sms) {
if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") { if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() { override fun run() {
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (result.success) { 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled), uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcanceled),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcanceled)))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) var replyText = rh.gs(R.string.smscommunicator_tempbasalcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed), uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalcancelfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalcancelfailed))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalcancelfailed)))
} }
} }
}) })
@ -655,38 +655,38 @@ class SmsCommunicatorPlugin @Inject constructor(
var duration = 30 var duration = 30
if (divided.size > 2) duration = SafeParse.stringToInt(divided[2]) if (divided.size > 2) duration = SafeParse.stringToInt(divided[2])
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
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 if (tempBasalPct == 0 && divided[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) 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, resourceHelper.gs(R.string.wrongTbrDuration, durationStep))) else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep)))
else { else {
tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value()
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) {
override fun run() { override fun run() {
commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() { commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() { override fun run() {
if (result.success) { 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result.isPercent) if (result.isPercent)
uel.log(Action.TEMP_BASAL, Sources.SMS, uel.log(Action.TEMP_BASAL, Sources.SMS,
activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration), activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset_percent, result.percent, result.duration),
ValueWithUnit.Percent(result.percent), ValueWithUnit.Percent(result.percent),
ValueWithUnit.Minute(result.duration)) ValueWithUnit.Minute(result.duration))
else else
uel.log(Action.TEMP_BASAL, Sources.SMS, uel.log(Action.TEMP_BASAL, Sources.SMS,
activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration), activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalset, result.absolute, result.duration),
ValueWithUnit.UnitPerHour(result.absolute), ValueWithUnit.UnitPerHour(result.absolute),
ValueWithUnit.Minute(result.duration)) ValueWithUnit.Minute(result.duration))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalfailed), uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed)))
} }
} }
}) })
@ -699,37 +699,37 @@ class SmsCommunicatorPlugin @Inject constructor(
var duration = 30 var duration = 30
if (divided.size > 2) duration = SafeParse.stringToInt(divided[2]) if (divided.size > 2) duration = SafeParse.stringToInt(divided[2])
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
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 if (tempBasal == 0.0 && divided[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) 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, resourceHelper.gs(R.string.wrongTbrDuration, durationStep))) else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongTbrDuration, durationStep)))
else { else {
tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value() tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value()
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) {
override fun run() { override fun run() {
commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() { commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() { override fun run() {
if (result.success) { if (result.success) {
var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) var replyText = if (result.isPercent) String.format(rh.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration)
else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) else String.format(rh.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result.isPercent) 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), 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.Percent(result.percent),
ValueWithUnit.Minute(result.duration)) ValueWithUnit.Minute(result.duration))
else else
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalset, result.absolute, 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.UnitPerHour(result.absolute),
ValueWithUnit.Minute(result.duration)) ValueWithUnit.Minute(result.duration))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) var replyText = rh.gs(R.string.smscommunicator_tempbasalfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_tempbasalfailed), uel.log(Action.TEMP_BASAL, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_tempbasalfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tempbasalfailed))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tempbasalfailed)))
} }
} }
}) })
@ -742,62 +742,62 @@ class SmsCommunicatorPlugin @Inject constructor(
private fun processEXTENDED(divided: Array<String>, receivedSms: Sms) { private fun processEXTENDED(divided: Array<String>, receivedSms: Sms) {
if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") { if (divided[1].uppercase(Locale.getDefault()) == "CANCEL" || divided[1].uppercase(Locale.getDefault()) == "STOP") {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() { override fun run() {
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
if (result.success) { 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed) var replyText = rh.gs(R.string.smscommunicator_extendedcancelfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedcanceled), uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedcanceled),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_extendedcanceled))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedcanceled)))
} }
} }
}) })
} }
}) })
} else if (divided.size != 3) { } else if (divided.size != 3) {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
} else { } else {
var extended = SafeParse.stringToDouble(divided[1]) var extended = SafeParse.stringToDouble(divided[1])
val duration = SafeParse.stringToInt(divided[2]) val duration = SafeParse.stringToInt(divided[2])
extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value() 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 { else {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) {
override fun run() { override fun run() {
commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() {
override fun run() { override fun run() {
if (result.success) { if (result.success) {
var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) var replyText = String.format(rh.gs(R.string.smscommunicator_extendedset), aDouble, duration)
if (config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) if (config.APS) replyText += "\n" + rh.gs(R.string.loopsuspended)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (config.APS) 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), 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.Insulin(aDouble ?: 0.0),
ValueWithUnit.Minute(duration), ValueWithUnit.Minute(duration),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.loopsuspended))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.loopsuspended)))
else else
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedset, aDouble, 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.Insulin(aDouble ?: 0.0),
ValueWithUnit.Minute(duration)) ValueWithUnit.Minute(duration))
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) var replyText = rh.gs(R.string.smscommunicator_extendedfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_extendedfailed), uel.log(Action.EXTENDED_BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_extendedfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_extendedfailed))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_extendedfailed)))
} }
} }
}) })
@ -812,13 +812,13 @@ class SmsCommunicatorPlugin @Inject constructor(
val isMeal = divided.size > 2 && divided[2].equals("MEAL", ignoreCase = true) val isMeal = divided.size > 2 && divided[2].equals("MEAL", ignoreCase = true)
bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value() bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value()
if (divided.size == 3 && !isMeal) { 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) { } else if (bolus > 0.0) {
val passCode = generatePassCode() val passCode = generatePassCode()
val reply = if (isMeal) 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 else
String.format(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode) String.format(rh.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode)
receivedSms.processed = true receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) {
override fun run() { override fun run() {
@ -832,9 +832,9 @@ class SmsCommunicatorPlugin @Inject constructor(
override fun run() { override fun run() {
if (resultSuccess) { if (resultSuccess) {
var replyText = if (isMeal) var replyText = if (isMeal)
String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) String.format(rh.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered)
else 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
lastRemoteBolusTime = dateUtil.now() lastRemoteBolusTime = dateUtil.now()
if (isMeal) { if (isMeal) {
@ -865,17 +865,17 @@ class SmsCommunicatorPlugin @Inject constructor(
val tt = if (currentProfile.units == GlucoseUnit.MMOL) { val tt = if (currentProfile.units == GlucoseUnit.MMOL) {
DecimalFormatter.to1Decimal(eatingSoonTT) DecimalFormatter.to1Decimal(eatingSoonTT)
} else DecimalFormatter.to0Decimal(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)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.BOLUS, Sources.SMS, replyText) uel.log(Action.BOLUS, Sources.SMS, replyText)
} else { } else {
var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed) var replyText = rh.gs(R.string.smscommunicator_bolusfailed)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + resourceHelper.gs(R.string.smscommunicator_bolusfailed), uel.log(Action.BOLUS, Sources.SMS, activePlugin.activePump.shortStatus(true) + "\n" + rh.gs(R.string.smscommunicator_bolusfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_bolusfailed))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_bolusfailed)))
} }
} }
}) })
@ -883,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 { private fun toTodayTime(hh_colon_mm: String): Long {
@ -911,15 +911,15 @@ class SmsCommunicatorPlugin @Inject constructor(
if (divided.size > 2) { if (divided.size > 2) {
time = toTodayTime(divided[2].uppercase(Locale.getDefault())) time = toTodayTime(divided[2].uppercase(Locale.getDefault()))
if (time == 0L) { if (time == 0L) {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
return return
} }
} }
grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value() 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 { else {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) {
override fun run() { override fun run() {
@ -929,17 +929,17 @@ class SmsCommunicatorPlugin @Inject constructor(
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (result.success) { 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + resourceHelper.gs(R.string.smscommunicator_carbsset, anInteger), uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsset, anInteger),
ValueWithUnit.Gram(anInteger ?: 0)) ValueWithUnit.Gram(anInteger ?: 0))
} else { } 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) replyText += "\n" + activePlugin.activePump.shortStatus(true)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + resourceHelper.gs(R.string.smscommunicator_carbsfailed, anInteger), uel.log(Action.CARBS, Sources.SMS, activePlugin.activePump.shortStatus(true) + ": " + rh.gs(R.string.smscommunicator_carbsfailed, anInteger),
ValueWithUnit.Gram(anInteger ?: 0)) ValueWithUnit.Gram(anInteger ?: 0))
} }
} }
}) })
@ -955,7 +955,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val isStop = divided[1].equals("STOP", ignoreCase = true) || divided[1].equals("CANCEL", ignoreCase = true) val isStop = divided[1].equals("STOP", ignoreCase = true) || divided[1].equals("CANCEL", ignoreCase = true)
if (isMeal || isActivity || isHypo) { if (isMeal || isActivity || isHypo) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() { override fun run() {
@ -1008,7 +1008,7 @@ class SmsCommunicatorPlugin @Inject constructor(
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
}) })
val ttString = if (units == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) 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)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.TT, Sources.SMS, uel.log(Action.TT, Sources.SMS,
ValueWithUnit.fromGlucoseUnit(tt, units.asText), ValueWithUnit.fromGlucoseUnit(tt, units.asText),
@ -1017,7 +1017,7 @@ class SmsCommunicatorPlugin @Inject constructor(
}) })
} else if (isStop) { } else if (isStop) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() { override fun run() {
@ -1027,14 +1027,14 @@ class SmsCommunicatorPlugin @Inject constructor(
}, { }, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) 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)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.CANCEL_TT, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_tt_canceled), uel.log(Action.CANCEL_TT, Sources.SMS, rh.gs(R.string.smscommunicator_tt_canceled),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_tt_canceled))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_tt_canceled)))
} }
}) })
} else } else
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrongformat)))
} }
private fun processSMS(divided: Array<String>, receivedSms: Sms) { private fun processSMS(divided: Array<String>, receivedSms: Sms) {
@ -1042,41 +1042,41 @@ class SmsCommunicatorPlugin @Inject constructor(
|| divided[1].equals("DISABLE", ignoreCase = true)) || divided[1].equals("DISABLE", ignoreCase = true))
if (isStop) { if (isStop) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() { override fun run() {
sp.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false) 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)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.STOP_SMS, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_stoppedsms), uel.log(Action.STOP_SMS, Sources.SMS, rh.gs(R.string.smscommunicator_stoppedsms),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(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<String>, receivedSms: Sms) { private fun processCAL(divided: Array<String>, receivedSms: Sms) {
val cal = SafeParse.stringToDouble(divided[1]) val cal = SafeParse.stringToDouble(divided[1])
if (cal > 0.0) { if (cal > 0.0) {
val passCode = generatePassCode() 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 receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) {
override fun run() { override fun run() {
val result = xdripCalibrations.sendIntent(aDouble!!) val result = xdripCalibrations.sendIntent(aDouble!!)
val replyText = 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)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
if (result) if (result)
uel.log(Action.CALIBRATION, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_calibrationsent), uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationsent),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(R.string.smscommunicator_calibrationsent))) ValueWithUnit.SimpleString(rh.gsNotLocalised(R.string.smscommunicator_calibrationsent)))
else else
uel.log(Action.CALIBRATION, Sources.SMS, resourceHelper.gs(R.string.smscommunicator_calibrationfailed), uel.log(Action.CALIBRATION, Sources.SMS, rh.gs(R.string.smscommunicator_calibrationfailed),
ValueWithUnit.SimpleString(resourceHelper.gsNotLocalised(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 { override fun sendNotificationToAllNumbers(text: String): Boolean {
@ -1108,16 +1108,16 @@ class SmsCommunicatorPlugin @Inject constructor(
messages.add(sms) messages.add(sms)
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
return if (e.message == "Invalid message body") { 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)) rxBus.send(EventNewNotification(notification))
false false
} else { } 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)) rxBus.send(EventNewNotification(notification))
false false
} }
} catch (e: SecurityException) { } 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)) rxBus.send(EventNewNotification(notification))
return false return false
} }
@ -1126,7 +1126,7 @@ class SmsCommunicatorPlugin @Inject constructor(
} }
private fun generatePassCode(): String = 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 { private fun stripAccents(str: String): String {
var s = str var s = str

View file

@ -20,7 +20,7 @@ import javax.inject.Singleton
@Singleton @Singleton
class OneTimePassword @Inject constructor( class OneTimePassword @Inject constructor(
private val sp: SP, private val sp: SP,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val dateUtil: DateUtil private val dateUtil: DateUtil
) { ) {
@ -36,7 +36,7 @@ class OneTimePassword @Inject constructor(
* Name of master device (target of OTP) * Name of master device (target of OTP)
*/ */
fun name(): String { 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() var userName = sp.getString(R.string.key_patient_name, defaultUserName).replace(":", "").trim()
if (userName.isEmpty()) if (userName.isEmpty())
userName = defaultUserName userName = defaultUserName

View file

@ -43,7 +43,7 @@ import javax.inject.Singleton
class TidepoolPlugin @Inject constructor( class TidepoolPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val rxBus: RxBus, private val rxBus: RxBus,
private val context: Context, private val context: Context,
@ -60,7 +60,7 @@ class TidepoolPlugin @Inject constructor(
.fragmentClass(TidepoolFragment::class.qualifiedName) .fragmentClass(TidepoolFragment::class.qualifiedName)
.preferencesId(R.xml.pref_tidepool) .preferencesId(R.xml.pref_tidepool)
.description(R.string.description_tidepool), .description(R.string.description_tidepool),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -108,9 +108,9 @@ class TidepoolPlugin @Inject constructor(
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event -> .subscribe({ event ->
if (event.isChanged(resourceHelper, R.string.key_tidepool_dev_servers) if (event.isChanged(rh, R.string.key_tidepool_dev_servers)
|| event.isChanged(resourceHelper, R.string.key_tidepool_username) || event.isChanged(rh, R.string.key_tidepool_username)
|| event.isChanged(resourceHelper, R.string.key_tidepool_password) || event.isChanged(rh, R.string.key_tidepool_password)
) )
tidepoolUploader.resetInstance() tidepoolUploader.resetInstance()
}, fabricPrivacy::logException) }, fabricPrivacy::logException)
@ -129,7 +129,7 @@ class TidepoolPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) 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 { tidepoolTestLogin?.setOnPreferenceClickListener {
preferenceFragment.context?.let { preferenceFragment.context?.let {
tidepoolUploader.testLogin(it) tidepoolUploader.testLogin(it)

View file

@ -34,7 +34,7 @@ class TidepoolUploader @Inject constructor(
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private val ctx: Context, private val ctx: Context,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val uploadChunk: UploadChunk, private val uploadChunk: UploadChunk,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -130,13 +130,13 @@ class TidepoolUploader @Inject constructor(
val call = session.service?.getLogin(it) val call = session.service?.getLogin(it)
call?.enqueue(TidepoolCallback<AuthReplyMessage>(aapsLogger, rxBus, session, "Login", { call?.enqueue(TidepoolCallback<AuthReplyMessage>(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")
} }

View file

@ -59,7 +59,7 @@ class ActionStringHandler @Inject constructor(
private val rxBus: RxBus, private val rxBus: RxBus,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val resourceHelper: ResourceHelper, private val rh: ResourceHelper,
private val injector: HasAndroidInjector, private val injector: HasAndroidInjector,
private val context: Context, private val context: Context,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
@ -122,24 +122,24 @@ class ActionStringHandler @Inject constructor(
else -> return else -> return
} }
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value()
rMessage += resourceHelper.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"
if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied)
rAction += "fill $insulinAfterConstraints" rAction += "fill $insulinAfterConstraints"
} else if ("fill" == act[0]) { ////////////////////////////////////////////// PRIME/FILL } else if ("fill" == act[0]) { ////////////////////////////////////////////// PRIME/FILL
val amount = SafeParse.stringToDouble(act[1]) val amount = SafeParse.stringToDouble(act[1])
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value()
rMessage += resourceHelper.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"
if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied)
rAction += "fill $insulinAfterConstraints" rAction += "fill $insulinAfterConstraints"
} else if ("bolus" == act[0]) { ////////////////////////////////////////////// BOLUS } else if ("bolus" == act[0]) { ////////////////////////////////////////////// BOLUS
val insulin = SafeParse.stringToDouble(act[1]) val insulin = SafeParse.stringToDouble(act[1])
val carbs = SafeParse.stringToInt(act[2]) val carbs = SafeParse.stringToInt(act[2])
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
rMessage += resourceHelper.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" rMessage += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n"
rMessage += resourceHelper.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"
if (insulinAfterConstraints - insulin != 0.0 || carbsAfterConstraints - carbs != 0) { 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" rAction += "bolus $insulinAfterConstraints $carbsAfterConstraints"
} else if ("temptarget" == act[0]) { ///////////////////////////////////////////////////////// TEMPTARGET } else if ("temptarget" == act[0]) { ///////////////////////////////////////////////////////// TEMPTARGET
@ -280,7 +280,7 @@ class ActionStringHandler @Inject constructor(
rMessage = "OLD DATA - " rMessage = "OLD DATA - "
//if pump is not busy: try to fetch data //if pump is not busy: try to fetch data
if (activePump.isBusy()) { if (activePump.isBusy()) {
rMessage += resourceHelper.gs(R.string.pumpbusy) rMessage += rh.gs(R.string.pumpbusy)
} else { } else {
rMessage += "trying to fetch data from pump." rMessage += "trying to fetch data from pump."
commandQueue.loadTDDs(object : Callback() { commandQueue.loadTDDs(object : Callback() {
@ -306,11 +306,11 @@ class ActionStringHandler @Inject constructor(
val duration = SafeParse.stringToInt(act[3]) val duration = SafeParse.stringToInt(act[3])
val starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000 val starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
rMessage += resourceHelper.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"
rMessage += "\n" + resourceHelper.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp) rMessage += "\n" + rh.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp)
rMessage += "\n" + resourceHelper.gs(R.string.duration) + ": " + duration + "h" rMessage += "\n" + rh.gs(R.string.duration) + ": " + duration + "h"
if (carbsAfterConstraints - carbs != 0) { if (carbsAfterConstraints - carbs != 0) {
rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) rMessage += "\n" + rh.gs(R.string.constraintapllied)
} }
if (carbsAfterConstraints <= 0) { if (carbsAfterConstraints <= 0) {
sendError("Carbs = 0! No action taken!") sendError("Carbs = 0! No action taken!")
@ -318,7 +318,7 @@ class ActionStringHandler @Inject constructor(
} }
rAction += "ecarbs $carbsAfterConstraints $starttimestamp $duration" rAction += "ecarbs $carbsAfterConstraints $starttimestamp $duration"
} else if ("changeRequest" == act[0]) { ////////////////////////////////////////////// CHANGE REQUEST } else if ("changeRequest" == act[0]) { ////////////////////////////////////////////// CHANGE REQUEST
rTitle = resourceHelper.gs(R.string.openloop_newsuggestion) rTitle = rh.gs(R.string.openloop_newsuggestion)
rAction = "changeRequest" rAction = "changeRequest"
loopPlugin.lastRun?.let { loopPlugin.lastRun?.let {
rMessage += it.constraintsProcessed rMessage += it.constraintsProcessed
@ -472,15 +472,15 @@ class ActionStringHandler @Inject constructor(
val usedAPS = activePlugin.activeAPS val usedAPS = activePlugin.activeAPS
val result = usedAPS.lastAPSResult ?: return "Last result not available!" val result = usedAPS.lastAPSResult ?: return "Last result not available!"
ret += if (!result.isChangeRequested) { 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) { } else if (result.rate == 0.0 && result.duration == 0) {
resourceHelper.gs(R.string.canceltemp) + "\n" rh.gs(R.string.canceltemp) + "\n"
} else { } 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" + "(" + 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 return ret
} }
@ -540,17 +540,17 @@ class ActionStringHandler @Inject constructor(
var msg = "" var msg = ""
//check for validity //check for validity
if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) { 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) { 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() val profile = profileFunction.getProfile()
if (profile == null) { if (profile == null) {
msg += resourceHelper.gs(R.string.notloadedplugins) + "\n" msg += rh.gs(R.string.notloadedplugins) + "\n"
} }
if ("" != msg) { if ("" != msg) {
msg += resourceHelper.gs(R.string.valuesnotstored) msg += rh.gs(R.string.valuesnotstored)
val rTitle = "STATUS" val rTitle = "STATUS"
val rAction = "statusmessage" val rAction = "statusmessage"
wearPlugin.requestActionConfirmation(rTitle, msg, rAction) wearPlugin.requestActionConfirmation(rTitle, msg, rAction)
@ -605,7 +605,7 @@ class ActionStringHandler @Inject constructor(
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + sendError(rh.gs(R.string.treatmentdeliveryerror) +
"\n" + "\n" +
result.comment) result.comment)
} }
@ -642,7 +642,7 @@ class ActionStringHandler @Inject constructor(
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
sendError(resourceHelper.gs(R.string.treatmentdeliveryerror) + sendError(rh.gs(R.string.treatmentdeliveryerror) +
"\n" + "\n" +
result.comment) result.comment)
} }

View file

@ -28,7 +28,7 @@ import javax.inject.Singleton
class WearPlugin @Inject constructor( class WearPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val sp: SP, private val sp: SP,
private val ctx: Context, private val ctx: Context,
@ -45,7 +45,7 @@ class WearPlugin @Inject constructor(
.shortName(R.string.wear_shortname) .shortName(R.string.wear_shortname)
.preferencesId(R.xml.pref_wear) .preferencesId(R.xml.pref_wear)
.description(R.string.description_wear), .description(R.string.description_wear),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -95,7 +95,7 @@ class WearPlugin @Inject constructor(
.toObservable(EventBolusRequested::class.java) .toObservable(EventBolusRequested::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event: EventBolusRequested -> .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) val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS)
intent.putExtra("progresspercent", 0) intent.putExtra("progresspercent", 0)
intent.putExtra("progressstatus", status) intent.putExtra("progressstatus", status)
@ -107,9 +107,9 @@ class WearPlugin @Inject constructor(
.subscribe({ event: EventDismissBolusProgressIfRunning -> .subscribe({ event: EventDismissBolusProgressIfRunning ->
if (event.result == null) return@subscribe if (event.result == null) return@subscribe
val status: String = if (event.result!!.success) { val status: String = if (event.result!!.success) {
resourceHelper.gs(R.string.success) rh.gs(R.string.success)
} else { } else {
resourceHelper.gs(R.string.nosuccess) rh.gs(R.string.nosuccess)
} }
val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS)
intent.putExtra("progresspercent", 100) intent.putExtra("progresspercent", 100)

View file

@ -67,7 +67,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
@Inject public GlucoseStatusProvider glucoseStatusProvider; @Inject public GlucoseStatusProvider glucoseStatusProvider;
@Inject public AAPSLogger aapsLogger; @Inject public AAPSLogger aapsLogger;
@Inject public WearPlugin wearPlugin; @Inject public WearPlugin wearPlugin;
@Inject public ResourceHelper resourceHelper; @Inject public ResourceHelper rh;
@Inject public SP sp; @Inject public SP sp;
@Inject public RxBus rxBus; @Inject public RxBus rxBus;
@Inject public ProfileFunction profileFunction; @Inject public ProfileFunction profileFunction;
@ -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) { if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) {
List<GlucoseValueDataPoint> predArray = List<GlucoseValueDataPoint> predArray =
finalLastRun.getConstraintsProcessed().getPredictions() finalLastRun.getConstraintsProcessed().getPredictions()
.stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, resourceHelper)) .stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh))
.collect(Collectors.toList()); .collect(Collectors.toList());
if (!predArray.isEmpty()) { if (!predArray.isEmpty()) {
@ -658,7 +658,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
if (googleApiClient != null && googleApiClient.isConnected()) { if (googleApiClient != null && googleApiClient.isConnected()) {
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
String status = resourceHelper.gs(R.string.noprofile); String status = rh.gs(R.string.noprofile);
String iobSum, iobDetail, cobString, currentBasal, bgiString; String iobSum, iobDetail, cobString, currentBasal, bgiString;
iobSum = iobDetail = cobString = currentBasal = bgiString = ""; iobSum = iobDetail = cobString = currentBasal = bgiString = "";
if (profile != null) { if (profile != null) {
@ -722,7 +722,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH); PutDataMapRequest dataMapRequest = PutDataMapRequest.create(NEW_PREFERENCES_PATH);
//unique content //unique content
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); 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(); PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else { } else {
@ -736,12 +736,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
String status = ""; String status = "";
if (profile == null) { if (profile == null) {
status = resourceHelper.gs(R.string.noprofile); status = rh.gs(R.string.noprofile);
return status; return status;
} }
if (!loopPlugin.isEnabled(PluginType.LOOP)) { if (!loopPlugin.isEnabled(PluginType.LOOP)) {
status += resourceHelper.gs(R.string.disabledloop) + "\n"; status += rh.gs(R.string.disabledloop) + "\n";
lastLoopStatus = false; lastLoopStatus = false;
} else { } else {
lastLoopStatus = true; lastLoopStatus = true;

View file

@ -26,7 +26,7 @@ class StatusLinePlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
private val sp: SP, private val sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val context: Context, private val context: Context,
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
@ -43,7 +43,7 @@ class StatusLinePlugin @Inject constructor(
.neverVisible(true) .neverVisible(true)
.preferencesId(R.xml.pref_xdripstatus) .preferencesId(R.xml.pref_xdripstatus)
.description(R.string.description_xdrip_status_line), .description(R.string.description_xdrip_status_line),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
) { ) {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -114,7 +114,7 @@ class StatusLinePlugin @Inject constructor(
private fun buildStatusString(profile: Profile): String { private fun buildStatusString(profile: Profile): String {
var status = "" var status = ""
if (!loopPlugin.isEnabled(PluginType.LOOP)) { if (!loopPlugin.isEnabled(PluginType.LOOP)) {
status += resourceHelper.gs(R.string.disabledloop) + "\n" status += rh.gs(R.string.disabledloop) + "\n"
lastLoopStatus = false lastLoopStatus = false
} else if (loopPlugin.isEnabled(PluginType.LOOP)) { } else if (loopPlugin.isEnabled(PluginType.LOOP)) {
lastLoopStatus = true lastLoopStatus = true

View file

@ -14,7 +14,7 @@ import javax.inject.Inject
class InsulinFragment : DaggerFragment() { class InsulinFragment : DaggerFragment() {
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
private var _binding: InsulinFragmentBinding? = null private var _binding: InsulinFragmentBinding? = null
@ -32,7 +32,7 @@ class InsulinFragment : DaggerFragment() {
super.onResume() super.onResume()
binding.name.text = activePlugin.activeInsulin.friendlyName binding.name.text = activePlugin.activeInsulin.friendlyName
binding.comment.text = activePlugin.activeInsulin.comment 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) binding.graph.show(activePlugin.activeInsulin)
} }

View file

@ -14,18 +14,18 @@ import javax.inject.Singleton
@Singleton @Singleton
class InsulinLyumjevPlugin @Inject constructor( class InsulinLyumjevPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, rh: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
rxBus: RxBus, aapsLogger: AAPSLogger 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 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 configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: 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 override val peak = 45

View file

@ -27,7 +27,7 @@ import kotlin.math.pow
*/ */
abstract class InsulinOrefBasePlugin( abstract class InsulinOrefBasePlugin(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, rh: ResourceHelper,
val profileFunction: ProfileFunction, val profileFunction: ProfileFunction,
val rxBus: RxBus, aapsLogger: AAPSLogger val rxBus: RxBus, aapsLogger: AAPSLogger
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
@ -36,7 +36,7 @@ abstract class InsulinOrefBasePlugin(
.pluginIcon(R.drawable.ic_insulin) .pluginIcon(R.drawable.ic_insulin)
.shortName(R.string.insulin_shortname) .shortName(R.string.insulin_shortname)
.visibleByDefault(false), .visibleByDefault(false),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), Insulin { ), Insulin {
private var lastWarned: Long = 0 private var lastWarned: Long = 0
@ -60,7 +60,7 @@ abstract class InsulinOrefBasePlugin(
} }
private val notificationPattern: String private val notificationPattern: String
get() = resourceHelper.gs(R.string.dia_too_short) get() = rh.gs(R.string.dia_too_short)
open val userDefinedDia: Double open val userDefinedDia: Double
get() { get() {
@ -96,7 +96,7 @@ abstract class InsulinOrefBasePlugin(
var comment = commentStandardText() var comment = commentStandardText()
val userDia = userDefinedDia val userDia = userDefinedDia
if (userDia < MIN_DIA) { 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 return comment
} }

View file

@ -21,22 +21,22 @@ import javax.inject.Singleton
class InsulinOrefFreePeakPlugin @Inject constructor( class InsulinOrefFreePeakPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
private val sp: SP, private val sp: SP,
resourceHelper: ResourceHelper, rh: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
rxBus: RxBus, aapsLogger: AAPSLogger 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 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) { 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 { 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 override val peak: Int

View file

@ -17,18 +17,18 @@ import javax.inject.Singleton
@Singleton @Singleton
class InsulinOrefRapidActingPlugin @Inject constructor( class InsulinOrefRapidActingPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, rh: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
rxBus: RxBus, aapsLogger: AAPSLogger 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 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 configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: 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 override val peak = 75

View file

@ -17,18 +17,18 @@ import javax.inject.Singleton
@Singleton @Singleton
class InsulinOrefUltraRapidActingPlugin @Inject constructor( class InsulinOrefUltraRapidActingPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
resourceHelper: ResourceHelper, rh: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
rxBus: RxBus, aapsLogger: AAPSLogger 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 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 configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: 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 override val peak = 55

View file

@ -51,7 +51,7 @@ class IobCobCalculatorPlugin @Inject constructor(
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val rxBus: RxBus, private val rxBus: RxBus,
private val sp: SP, private val sp: SP,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
private val sensitivityOref1Plugin: SensitivityOref1Plugin, private val sensitivityOref1Plugin: SensitivityOref1Plugin,
@ -67,7 +67,7 @@ class IobCobCalculatorPlugin @Inject constructor(
.showInList(false) .showInList(false)
.neverVisible(true) .neverVisible(true)
.alwaysEnabled(true), .alwaysEnabled(true),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), IobCobCalculator { ), IobCobCalculator {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -102,14 +102,14 @@ class IobCobCalculatorPlugin @Inject constructor(
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.io)
.subscribe({ event -> .subscribe({ event ->
if (event.isChanged(resourceHelper, R.string.key_openapsama_autosens_period) || if (event.isChanged(rh, R.string.key_openapsama_autosens_period) ||
event.isChanged(resourceHelper, R.string.key_age) || event.isChanged(rh, R.string.key_age) ||
event.isChanged(resourceHelper, R.string.key_absorption_maxtime) || event.isChanged(rh, R.string.key_absorption_maxtime) ||
event.isChanged(resourceHelper, R.string.key_openapsama_min_5m_carbimpact) || event.isChanged(rh, R.string.key_openapsama_min_5m_carbimpact) ||
event.isChanged(resourceHelper, R.string.key_absorption_cutoff) || event.isChanged(rh, R.string.key_absorption_cutoff) ||
event.isChanged(resourceHelper, R.string.key_openapsama_autosens_max) || event.isChanged(rh, R.string.key_openapsama_autosens_max) ||
event.isChanged(resourceHelper, R.string.key_openapsama_autosens_min) || event.isChanged(rh, R.string.key_openapsama_autosens_min) ||
event.isChanged(resourceHelper, R.string.key_insulin_oref_peak) event.isChanged(rh, R.string.key_insulin_oref_peak)
) { ) {
resetDataAndRunCalculation("onEventPreferenceChange", event) resetDataAndRunCalculation("onEventPreferenceChange", event)
} }

View file

@ -51,7 +51,7 @@ class IobCobOref1Thread internal constructor(
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@ -67,7 +67,7 @@ class IobCobOref1Thread internal constructor(
init { init {
injector.androidInjector().inject(this) 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() { override fun run() {
@ -161,7 +161,7 @@ class IobCobOref1Thread internal constructor(
aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString()) aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString())
aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString()) aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString())
//aapsLogger.debug(LTag.AUTOSENS, iobCobCalculatorPlugin.getBgReadingsDataTable().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)) rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true) sp.putBoolean("log_AUTOSENS", true)
break break
@ -184,7 +184,7 @@ class IobCobOref1Thread internal constructor(
aapsLogger.debug(autosensDataTable.toString()) aapsLogger.debug(autosensDataTable.toString())
aapsLogger.debug(bucketedData.toString()) aapsLogger.debug(bucketedData.toString())
//aapsLogger.debug(iobCobCalculatorPlugin.getBgReadingsDataTable().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)) rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true) sp.putBoolean("log_AUTOSENS", true)
break break

View file

@ -50,7 +50,7 @@ class IobCobThread @Inject internal constructor(
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Inject lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@ -66,7 +66,7 @@ class IobCobThread @Inject internal constructor(
init { init {
injector.androidInjector().inject(this) 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() { override fun run() {
@ -160,7 +160,7 @@ class IobCobThread @Inject internal constructor(
aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString()) aapsLogger.debug(LTag.AUTOSENS, autosensDataTable.toString())
aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString()) aapsLogger.debug(LTag.AUTOSENS, bucketedData.toString())
//aapsLogger.debug(LTag.AUTOSENS, iobCobCalculatorPlugin.getBgReadingsDataTable().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)) rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true) sp.putBoolean("log_AUTOSENS", true)
break break
@ -183,7 +183,7 @@ class IobCobThread @Inject internal constructor(
aapsLogger.debug(autosensDataTable.toString()) aapsLogger.debug(autosensDataTable.toString())
aapsLogger.debug(bucketedData.toString()) aapsLogger.debug(bucketedData.toString())
//aapsLogger.debug(iobCobCalculatorPlugin.getBgReadingsDataTable().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)) rxBus.send(EventNewNotification(notification))
sp.putBoolean("log_AUTOSENS", true) sp.putBoolean("log_AUTOSENS", true)
break break

View file

@ -39,7 +39,7 @@ class LocalProfileFragment : DaggerFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin
@ -55,7 +55,7 @@ class LocalProfileFragment : DaggerFragment() {
private val save = Runnable { private val save = Runnable {
doEdit() 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 { localProfilePlugin.profile?.getSpecificProfile(spinner?.selectedItem.toString())?.let {
binding.basalGraph.show(ProfileSealed.Pure(it)) binding.basalGraph.show(ProfileSealed.Pure(it))
} }
@ -74,7 +74,7 @@ class LocalProfileFragment : DaggerFragment() {
private fun sumLabel(): String { private fun sumLabel(): String {
val profile = localProfilePlugin.getEditProfile() val profile = localProfilePlugin.getEditProfile()
val sum = profile?.let { ProfileSealed.Pure(profile).baseBasalSum() } ?: 0.0 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 private var _binding: LocalprofileFragmentBinding? = null
@ -128,14 +128,14 @@ class LocalProfileFragment : DaggerFragment() {
binding.name.addTextChangedListener(textWatch) binding.name.addTextChangedListener(textWatch)
binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, null, textWatch) binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, null, textWatch)
binding.dia.tag = "LP_DIA" 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) 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", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, pumpDescription.basalMaximumRate, 0.01, DecimalFormat("0.00"), 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) { 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.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", resourceHelper.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) 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 { } 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.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", resourceHelper.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) 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 // Spinner
@ -154,7 +154,7 @@ class LocalProfileFragment : DaggerFragment() {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (localProfilePlugin.isEdited) { if (localProfilePlugin.isEdited) {
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.doyouwantswitchprofile), { OKDialog.showConfirmation(activity, rh.gs(R.string.doyouwantswitchprofile), {
localProfilePlugin.currentProfileIndex = position localProfilePlugin.currentProfileIndex = position
build() build()
}, { }, {
@ -173,7 +173,7 @@ class LocalProfileFragment : DaggerFragment() {
binding.profileAdd.setOnClickListener { binding.profileAdd.setOnClickListener {
if (localProfilePlugin.isEdited) { if (localProfilePlugin.isEdited) {
activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.saveorresetchangesfirst)) } activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) }
} else { } else {
uel.log(Action.NEW_PROFILE, Sources.LocalProfile) uel.log(Action.NEW_PROFILE, Sources.LocalProfile)
localProfilePlugin.addNewProfile() localProfilePlugin.addNewProfile()
@ -183,7 +183,7 @@ class LocalProfileFragment : DaggerFragment() {
binding.profileClone.setOnClickListener { binding.profileClone.setOnClickListener {
if (localProfilePlugin.isEdited) { if (localProfilePlugin.isEdited) {
activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.saveorresetchangesfirst)) } activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) }
} else { } else {
uel.log(Action.CLONE_PROFILE, Sources.LocalProfile, ValueWithUnit.SimpleString(localProfilePlugin.currentProfile()?.name uel.log(Action.CLONE_PROFILE, Sources.LocalProfile, ValueWithUnit.SimpleString(localProfilePlugin.currentProfile()?.name
?: "")) ?: ""))
@ -194,7 +194,7 @@ class LocalProfileFragment : DaggerFragment() {
binding.profileRemove.setOnClickListener { binding.profileRemove.setOnClickListener {
activity?.let { activity -> 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 uel.log(Action.PROFILE_REMOVED, Sources.LocalProfile, ValueWithUnit.SimpleString(localProfilePlugin.currentProfile()?.name
?: "")) ?: ""))
localProfilePlugin.removeCurrentProfile() localProfilePlugin.removeCurrentProfile()
@ -207,7 +207,7 @@ class LocalProfileFragment : DaggerFragment() {
// if (!pumpDescription.isTempBasalCapable) binding.basal.visibility = View.GONE // if (!pumpDescription.isTempBasalCapable) binding.basal.visibility = View.GONE
@Suppress("SetTextI18n") @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 { binding.profileswitch.setOnClickListener {
ProfileSwitchDialog() ProfileSwitchDialog()
@ -264,7 +264,7 @@ class LocalProfileFragment : DaggerFragment() {
val isValid = localProfilePlugin.isValidEditState(activity) val isValid = localProfilePlugin.isValidEditState(activity)
val isEdited = localProfilePlugin.isEdited val isEdited = localProfilePlugin.isEdited
if (isValid) { if (isValid) {
this.view?.setBackgroundColor(resourceHelper.gc(R.color.ok_background)) this.view?.setBackgroundColor(rh.gc(R.color.ok_background))
if (isEdited) { if (isEdited) {
//edited profile -> save first //edited profile -> save first
@ -275,7 +275,7 @@ class LocalProfileFragment : DaggerFragment() {
binding.save.visibility = View.GONE binding.save.visibility = View.GONE
} }
} else { } 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.profileswitch.visibility = View.GONE
binding.save.visibility = View.GONE //don't save an invalid profile binding.save.visibility = View.GONE //don't save an invalid profile
} }
@ -289,12 +289,12 @@ class LocalProfileFragment : DaggerFragment() {
} }
private fun processVisibilityOnClick(selected: View) { private fun processVisibilityOnClick(selected: View) {
binding.diaTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.diaTab.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.icTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.icTab.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.isfTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.isfTab.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.basalTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.basalTab.setBackgroundColor(rh.gc(R.color.defaultbackground))
binding.targetTab.setBackgroundColor(resourceHelper.gc(R.color.defaultbackground)) binding.targetTab.setBackgroundColor(rh.gc(R.color.defaultbackground))
selected.setBackgroundColor(resourceHelper.gc(R.color.tabBgColorSelected)) selected.setBackgroundColor(rh.gc(R.color.tabBgColorSelected))
binding.diaPlaceholder.visibility = View.GONE binding.diaPlaceholder.visibility = View.GONE
binding.ic.visibility = View.GONE binding.ic.visibility = View.GONE
binding.isf.visibility = View.GONE binding.isf.visibility = View.GONE

View file

@ -42,7 +42,7 @@ class LocalProfilePlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val sp: SP, private val sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val activePlugin: ActivePlugin, private val activePlugin: ActivePlugin,
@ -58,7 +58,7 @@ class LocalProfilePlugin @Inject constructor(
.shortName(R.string.localprofile_shortname) .shortName(R.string.localprofile_shortname)
.description(R.string.description_profile_local) .description(R.string.description_profile_local)
.setDefault(), .setDefault(),
aapsLogger, resourceHelper, injector aapsLogger, rh, injector
), ProfileSource { ), ProfileSource {
private var rawProfile: ProfileStore? = null private var rawProfile: ProfileStore? = null
@ -109,58 +109,58 @@ class LocalProfilePlugin @Inject constructor(
val pumpDescription = activePlugin.activePump.pumpDescription val pumpDescription = activePlugin.activePump.pumpDescription
with(profiles[currentProfileIndex]) { with(profiles[currentProfileIndex]) {
if (dia < hardLimits.minDia() || dia > hardLimits.maxDia()) { 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 return false
} }
if (name.isNullOrEmpty()){ 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 return false
} }
if (blockFromJsonArray(ic, dateUtil)?.any { it.amount < hardLimits.minIC() || it.amount > hardLimits.maxIC() } != 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 return false
} }
val low = blockFromJsonArray(targetLow, dateUtil) val low = blockFromJsonArray(targetLow, dateUtil)
val high = blockFromJsonArray(targetHigh, dateUtil) val high = blockFromJsonArray(targetHigh, dateUtil)
if (mgdl) { if (mgdl) {
if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(it.amount, HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(it.amount, HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) {
ToastUtils.errorToast(activity, resourceHelper.gs(R.string.error_in_isf_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_isf_values))
return false return false
} }
if (blockFromJsonArray(basal, dateUtil)?.any { it.amount < pumpDescription.basalMinimumRate || it.amount > 10.0 } != 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 return false
} }
if (low?.any { hardLimits.isInRange(it.amount, HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]) } == false) { 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, resourceHelper.gs(R.string.error_in_target_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values))
return false return false
} }
if (high?.any { hardLimits.isInRange(it.amount, HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]) } == false) { 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,resourceHelper.gs(R.string.error_in_target_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values))
return false return false
} }
} else { } else {
if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { if (blockFromJsonArray(isf, dateUtil)?.any { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) {
ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_isf_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_isf_values))
return false return false
} }
if (blockFromJsonArray(basal, dateUtil)?.any { it.amount < pumpDescription.basalMinimumRate || it.amount > 10.0 } != 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 return false
} }
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) { 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, resourceHelper.gs(R.string.error_in_target_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values))
return false return false
} }
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) { 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,resourceHelper.gs(R.string.error_in_target_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values))
return false return false
} }
} }
low?.let { low?.let {
high?.let { high?.let {
for (i in low.indices) if (low[i].amount > high[i].amount) { for (i in low.indices) if (low[i].amount > high[i].amount) {
ToastUtils.errorToast(activity,resourceHelper.gs(R.string.error_in_target_values)) ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values))
return false return false
} }
} }
@ -216,7 +216,7 @@ class LocalProfilePlugin @Inject constructor(
if (name.contains(".")) namesOK = false if (name.contains(".")) namesOK = false
} }
if (!namesOK) activity?.let { if (!namesOK) activity?.let {
OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot)) OKDialog.show(it, "", rh.gs(R.string.profilenamecontainsdot))
} }
} }
@ -256,7 +256,7 @@ class LocalProfilePlugin @Inject constructor(
val newProfiles: ArrayList<SingleProfile> = ArrayList() val newProfiles: ArrayList<SingleProfile> = ArrayList()
for (p in store.getProfileList()) { for (p in store.getProfileList()) {
val profile = store.getSpecificProfile(p.toString()) val profile = store.getSpecificProfile(p.toString())
val validityCheck = profile?.let { ProfileSealed.Pure(profile).isValid("NS", activePlugin.activePump, config, resourceHelper, rxBus, hardLimits, false) } ?: Profile.ValidityCheck() val validityCheck = profile?.let { ProfileSealed.Pure(profile).isValid("NS", activePlugin.activePump, config, rh, rxBus, hardLimits, false) } ?: Profile.ValidityCheck()
if (profile != null && validityCheck.isValid) { if (profile != null && validityCheck.isValid) {
val sp = copyFrom(profile, p.toString()) val sp = copyFrom(profile, p.toString())
sp.name = p.toString() sp.name = p.toString()
@ -265,12 +265,12 @@ class LocalProfilePlugin @Inject constructor(
val n = NotificationWithAction( val n = NotificationWithAction(
injector, injector,
Notification.INVALID_PROFILE_NOT_ACCEPTED, Notification.INVALID_PROFILE_NOT_ACCEPTED,
resourceHelper.gs(R.string.invalid_profile_not_accepted, p.toString()), rh.gs(R.string.invalid_profile_not_accepted, p.toString()),
Notification.NORMAL Notification.NORMAL
) )
n.action(R.string.view) { n.action(R.string.view) {
n.contextForAction?.let { n.contextForAction?.let {
OKDialog.show(it, resourceHelper.gs(R.string.errors), validityCheck.reasons.joinToString(separator = "\n"), null) OKDialog.show(it, rh.gs(R.string.errors), validityCheck.reasons.joinToString(separator = "\n"), null)
} }
} }
rxBus.send(EventNewNotification(n)) rxBus.send(EventNewNotification(n))

View file

@ -21,7 +21,7 @@ import javax.inject.Singleton
class MDIPlugin @Inject constructor( class MDIPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
commandQueue: CommandQueueProvider, commandQueue: CommandQueueProvider,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val pumpSync: PumpSync private val pumpSync: PumpSync
@ -30,7 +30,7 @@ class MDIPlugin @Inject constructor(
.pluginIcon(R.drawable.ic_ict) .pluginIcon(R.drawable.ic_ict)
.pluginName(R.string.mdi) .pluginName(R.string.mdi)
.description(R.string.description_pump_mdi), .description(R.string.description_pump_mdi),
injector, aapsLogger, resourceHelper, commandQueue injector, aapsLogger, rh, commandQueue
), Pump { ), Pump {
override val pumpDescription = PumpDescription() override val pumpDescription = PumpDescription()
@ -71,7 +71,7 @@ class MDIPlugin @Inject constructor(
result.success = true result.success = true
result.bolusDelivered = detailedBolusInfo.insulin result.bolusDelivered = detailedBolusInfo.insulin
result.carbsDelivered = detailedBolusInfo.carbs result.carbsDelivered = detailedBolusInfo.carbs
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = rh.gs(R.string.virtualpump_resultok)
if (detailedBolusInfo.insulin > 0) if (detailedBolusInfo.insulin > 0)
pumpSync.syncBolusWithPumpId( pumpSync.syncBolusWithPumpId(
timestamp = detailedBolusInfo.timestamp, 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 { override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = false 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") aapsLogger.debug(LTag.PUMPBTCOMM, "Setting temp basal absolute: $result")
return 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 { override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = false 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") aapsLogger.debug(LTag.PUMPBTCOMM, "Settings temp basal percent: $result")
return result return result
} }
@ -110,7 +110,7 @@ class MDIPlugin @Inject constructor(
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = false 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") aapsLogger.debug(LTag.PUMPBTCOMM, "Setting extended bolus: $result")
return result return result
} }
@ -118,7 +118,7 @@ class MDIPlugin @Inject constructor(
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = false 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") aapsLogger.debug(LTag.PUMPBTCOMM, "Cancel temp basal: $result")
return result return result
} }
@ -126,7 +126,7 @@ class MDIPlugin @Inject constructor(
override fun cancelExtendedBolus(): PumpEnactResult { override fun cancelExtendedBolus(): PumpEnactResult {
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = false 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") aapsLogger.debug(LTag.PUMPBTCOMM, "Canceling extended bolus: $result")
return result return result
} }

View file

@ -28,7 +28,7 @@ import javax.inject.Inject
class VirtualPumpFragment : DaggerFragment() { class VirtualPumpFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin @Inject lateinit var virtualPumpPlugin: VirtualPumpPlugin
@ -96,19 +96,19 @@ class VirtualPumpFragment : DaggerFragment() {
private fun updateGui() { private fun updateGui() {
if (_binding == null) return if (_binding == null) return
val profile = profileFunction.getProfile() ?: 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.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil.now())?.toStringFull(profile, dateUtil)
?: "" ?: ""
binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil)
?: "" ?: ""
binding.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent) binding.battery.text = rh.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent)
binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) binding.reservoir.text = rh.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble())
virtualPumpPlugin.refreshConfiguration() virtualPumpPlugin.refreshConfiguration()
val pumpType = virtualPumpPlugin.pumpType val pumpType = virtualPumpPlugin.pumpType
binding.type.text = pumpType?.description 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() binding.serialNumber.text = virtualPumpPlugin.serialNumber()
} }
} }

View file

@ -42,7 +42,7 @@ open class VirtualPumpPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
private val rxBus: RxBus, private val rxBus: RxBus,
private var fabricPrivacy: FabricPrivacy, private var fabricPrivacy: FabricPrivacy,
resourceHelper: ResourceHelper, rh: ResourceHelper,
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val sp: SP, private val sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
@ -62,7 +62,7 @@ open class VirtualPumpPlugin @Inject constructor(
.description(R.string.description_pump_virtual) .description(R.string.description_pump_virtual)
.setDefault() .setDefault()
.neverVisible(config.NSCLIENT), .neverVisible(config.NSCLIENT),
injector, aapsLogger, resourceHelper, commandQueue injector, aapsLogger, rh, commandQueue
), Pump { ), Pump {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -108,7 +108,7 @@ open class VirtualPumpPlugin @Inject constructor(
disposable += rxBus disposable += rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io) .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() refreshConfiguration()
} }
@ -119,7 +119,7 @@ open class VirtualPumpPlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment) 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 ?: return
uploadStatus.isVisible = !config.NSCLIENT uploadStatus.isVisible = !config.NSCLIENT
} }
@ -151,7 +151,7 @@ open class VirtualPumpPlugin @Inject constructor(
override fun setNewBasalProfile(profile: Profile): PumpEnactResult { override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
lastDataTime = System.currentTimeMillis() 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 // Do nothing here. we are using database profile
return PumpEnactResult(injector).success(true).enacted(true) return PumpEnactResult(injector).success(true).enacted(true)
} }
@ -180,18 +180,18 @@ open class VirtualPumpPlugin @Inject constructor(
.bolusDelivered(detailedBolusInfo.insulin) .bolusDelivered(detailedBolusInfo.insulin)
.carbsDelivered(detailedBolusInfo.carbs) .carbsDelivered(detailedBolusInfo.carbs)
.enacted(detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) .enacted(detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
.comment(resourceHelper.gs(R.string.virtualpump_resultok)) .comment(rh.gs(R.string.virtualpump_resultok))
val bolusingEvent = EventOverviewBolusProgress val bolusingEvent = EventOverviewBolusProgress
var delivering = 0.0 var delivering = 0.0
while (delivering < detailedBolusInfo.insulin) { while (delivering < detailedBolusInfo.insulin) {
SystemClock.sleep(200) 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) bolusingEvent.percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100)
rxBus.send(bolusingEvent) rxBus.send(bolusingEvent)
delivering += 0.1 delivering += 0.1
} }
SystemClock.sleep(200) SystemClock.sleep(200)
bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) bolusingEvent.status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin)
bolusingEvent.percent = 100 bolusingEvent.percent = 100
rxBus.send(bolusingEvent) rxBus.send(bolusingEvent)
SystemClock.sleep(1000) SystemClock.sleep(1000)
@ -226,7 +226,7 @@ open class VirtualPumpPlugin @Inject constructor(
result.isTempCancel = false result.isTempCancel = false
result.absolute = absoluteRate result.absolute = absoluteRate
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = rh.gs(R.string.virtualpump_resultok)
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil.now(), timestamp = dateUtil.now(),
rate = absoluteRate, rate = absoluteRate,
@ -251,7 +251,7 @@ open class VirtualPumpPlugin @Inject constructor(
result.isPercent = true result.isPercent = true
result.isTempCancel = false result.isTempCancel = false
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = rh.gs(R.string.virtualpump_resultok)
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil.now(), timestamp = dateUtil.now(),
rate = percent.toDouble(), rate = percent.toDouble(),
@ -276,7 +276,7 @@ open class VirtualPumpPlugin @Inject constructor(
result.bolusDelivered = insulin result.bolusDelivered = insulin
result.isTempCancel = false result.isTempCancel = false
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = rh.gs(R.string.virtualpump_resultok)
pumpSync.syncExtendedBolusWithPumpId( pumpSync.syncExtendedBolusWithPumpId(
timestamp = dateUtil.now(), timestamp = dateUtil.now(),
amount = insulin, amount = insulin,
@ -296,7 +296,7 @@ open class VirtualPumpPlugin @Inject constructor(
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
result.success = true result.success = true
result.isTempCancel = 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) { if (pumpSync.expectedPumpState().temporaryBasal != null) {
result.enacted = true result.enacted = true
pumpSync.syncStopTemporaryBasalWithPumpId( pumpSync.syncStopTemporaryBasalWithPumpId(
@ -325,7 +325,7 @@ open class VirtualPumpPlugin @Inject constructor(
result.success = true result.success = true
result.enacted = true result.enacted = true
result.isTempCancel = 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") aapsLogger.debug(LTag.PUMP, "Canceling extended bolus: $result")
rxBus.send(EventVirtualPumpUpdateGui()) rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis() lastDataTime = System.currentTimeMillis()

View file

@ -20,9 +20,9 @@ abstract class AbstractSensitivityPlugin(
pluginDescription: PluginDescription, pluginDescription: PluginDescription,
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
val sp: SP 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 abstract override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult

View file

@ -33,7 +33,7 @@ import kotlin.math.roundToInt
class SensitivityAAPSPlugin @Inject constructor( class SensitivityAAPSPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
sp: SP, sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -45,15 +45,15 @@ class SensitivityAAPSPlugin @Inject constructor(
.shortName(R.string.sensitivity_shortname) .shortName(R.string.sensitivity_shortname)
.preferencesId(R.xml.pref_absorption_aaps) .preferencesId(R.xml.pref_absorption_aaps)
.description(R.string.description_sensitivity_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 { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult {
val age = sp.getString(R.string.key_age, "") val age = sp.getString(R.string.key_age, "")
var defaultHours = 24 var defaultHours = 24
if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 if (age == rh.gs(R.string.key_adult)) defaultHours = 24
if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 if (age == rh.gs(R.string.key_teenage)) defaultHours = 4
if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 if (age == rh.gs(R.string.key_child)) defaultHours = 4
val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours)
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
if (profile == null) { if (profile == null) {
@ -141,10 +141,10 @@ class SensitivityAAPSPlugin @Inject constructor(
override fun configuration(): JSONObject { override fun configuration(): JSONObject {
val c = JSONObject() val c = JSONObject()
try { try {
c.put(resourceHelper.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_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(rh.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(rh.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_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }
@ -153,10 +153,10 @@ class SensitivityAAPSPlugin @Inject constructor(
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
try { 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(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(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(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(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(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(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_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min)))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }

View file

@ -34,7 +34,7 @@ import kotlin.math.roundToInt
class SensitivityOref1Plugin @Inject constructor( class SensitivityOref1Plugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
sp: SP, sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -48,7 +48,7 @@ class SensitivityOref1Plugin @Inject constructor(
.preferencesId(R.xml.pref_absorption_oref1) .preferencesId(R.xml.pref_absorption_oref1)
.description(R.string.description_sensitivity_oref1) .description(R.string.description_sensitivity_oref1)
.setDefault(), .setDefault(),
injector, aapsLogger, resourceHelper, sp injector, aapsLogger, rh, sp
) { ) {
override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult {
@ -206,10 +206,10 @@ class SensitivityOref1Plugin @Inject constructor(
override fun configuration(): JSONObject { override fun configuration(): JSONObject {
val c = JSONObject() val c = JSONObject()
try { 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(rh.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(rh.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(rh.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_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }
@ -218,10 +218,10 @@ class SensitivityOref1Plugin @Inject constructor(
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
try { 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(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(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(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(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(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(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_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min)))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }

View file

@ -32,7 +32,7 @@ import kotlin.math.roundToInt
class SensitivityWeightedAveragePlugin @Inject constructor( class SensitivityWeightedAveragePlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, rh: ResourceHelper,
sp: SP, sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
@ -44,15 +44,15 @@ class SensitivityWeightedAveragePlugin @Inject constructor(
.shortName(R.string.sensitivity_shortname) .shortName(R.string.sensitivity_shortname)
.preferencesId(R.xml.pref_absorption_aaps) .preferencesId(R.xml.pref_absorption_aaps)
.description(R.string.description_sensitivity_weighted_average), .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 { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult {
val age = sp.getString(R.string.key_age, "") val age = sp.getString(R.string.key_age, "")
var defaultHours = 24 var defaultHours = 24
if (age == resourceHelper.gs(R.string.key_adult)) defaultHours = 24 if (age == rh.gs(R.string.key_adult)) defaultHours = 24
if (age == resourceHelper.gs(R.string.key_teenage)) defaultHours = 4 if (age == rh.gs(R.string.key_teenage)) defaultHours = 4
if (age == resourceHelper.gs(R.string.key_child)) defaultHours = 4 if (age == rh.gs(R.string.key_child)) defaultHours = 4
val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours) val hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours)
if (ads.autosensDataTable.size() < 4) { if (ads.autosensDataTable.size() < 4) {
aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + ads.lastDataTime(dateUtil)) aapsLogger.debug(LTag.AUTOSENS, "No autosens data available. lastDataTime=" + ads.lastDataTime(dateUtil))
@ -161,10 +161,10 @@ class SensitivityWeightedAveragePlugin @Inject constructor(
override fun configuration(): JSONObject { override fun configuration(): JSONObject {
val c = JSONObject() val c = JSONObject()
try { try {
c.put(resourceHelper.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_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(rh.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(rh.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_autosens_min), sp.getDouble(R.string.key_openapsama_autosens_min, 0.7))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }
@ -173,10 +173,10 @@ class SensitivityWeightedAveragePlugin @Inject constructor(
override fun applyConfiguration(configuration: JSONObject) { override fun applyConfiguration(configuration: JSONObject) {
try { 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(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(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(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(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(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(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_autosens_min))) sp.getDouble(R.string.key_openapsama_autosens_min, configuration.getDouble(rh.gs(R.string.key_openapsama_autosens_min)))
} catch (e: JSONException) { } catch (e: JSONException) {
e.printStackTrace() e.printStackTrace()
} }

View file

@ -41,7 +41,7 @@ class BGSourceFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rh: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@ -131,7 +131,7 @@ class BGSourceFragment : DaggerFragment() {
val glucoseValue = v.tag as GlucoseValue val glucoseValue = v.tag as GlucoseValue
activity?.let { activity -> activity?.let { activity ->
val text = dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + glucoseValue.valueToUnitsString(profileFunction.getUnits()) 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) { val source = when((activePlugin.activeBgSource as PluginBase).pluginDescription.pluginName) {
R.string.dexcom_app_patched -> Sources.Dexcom R.string.dexcom_app_patched -> Sources.Dexcom
R.string.eversense -> Sources.Eversense R.string.eversense -> Sources.Eversense

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