Skip to content

Commit

Permalink
SP -> Preferences #24
Browse files Browse the repository at this point in the history
  • Loading branch information
MilosKozak committed Feb 10, 2025
1 parent 9f6f9af commit 5977ace
Show file tree
Hide file tree
Showing 12 changed files with 161 additions and 110 deletions.
2 changes: 2 additions & 0 deletions app/src/main/kotlin/app/aaps/MainApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,8 @@ class MainApp : DaggerApplication() {
val number = key.split("_")[1]
if (value is String)
preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = SafeParse.stringToDouble(value))
else if (value is Float)
preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = value.toDouble())
else
preferences.put(ProfileComposedDoubleKey.LocalProfileNumberedDia, SafeParse.stringToInt(number), value = value as Double)
sp.remove(key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ open class PluginDescription {
const val PREFERENCE_NONE = -1

/**
* Plugin generates [PreferenceScreen] directly
* Plugin generates [androidx.preference.PreferenceScreen] directly
*/
const val PREFERENCE_SCREEN = 0
}
Expand Down
1 change: 1 addition & 0 deletions pump/combov2/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ dependencies {
implementation(project(":core:objects"))
implementation(project(":core:ui"))
implementation(project(":core:utils"))
implementation(project(":core:validators"))
implementation(project(":pump:combov2:comboctl"))

api(libs.androidx.lifecycle.viewmodel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.coroutineScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import androidx.preference.PreferenceScreen
import androidx.preference.SwitchPreference
import app.aaps.core.data.model.BS
import app.aaps.core.data.model.TE
Expand Down Expand Up @@ -45,13 +48,13 @@ import app.aaps.core.interfaces.sharedPreferences.SP
import app.aaps.core.interfaces.ui.UiInteraction
import app.aaps.core.interfaces.utils.DateUtil
import app.aaps.core.interfaces.utils.DecimalFormatter
import app.aaps.core.keys.interfaces.IntNonPreferenceKey
import app.aaps.core.keys.interfaces.LongNonPreferenceKey
import app.aaps.core.keys.interfaces.Preferences
import app.aaps.core.keys.interfaces.StringNonPreferenceKey
import app.aaps.core.objects.constraints.ConstraintObject
import app.aaps.core.ui.dialogs.OKDialog
import app.aaps.core.ui.toast.ToastUtils
import app.aaps.core.validators.preferences.AdaptiveIntPreference
import app.aaps.core.validators.preferences.AdaptiveIntentPreference
import app.aaps.core.validators.preferences.AdaptiveSwitchPreference
import info.nightscout.comboctl.android.AndroidBluetoothInterface
import info.nightscout.comboctl.base.BasicProgressStage
import info.nightscout.comboctl.base.BluetoothException
Expand All @@ -69,6 +72,12 @@ import info.nightscout.comboctl.parser.AlertScreenException
import info.nightscout.comboctl.parser.BatteryState
import info.nightscout.comboctl.parser.ReservoirState
import info.nightscout.pump.combov2.activities.ComboV2PairingActivity
import info.nightscout.pump.combov2.keys.ComboBooleanKey
import info.nightscout.pump.combov2.keys.ComboIntKey
import info.nightscout.pump.combov2.keys.ComboIntNonKey
import info.nightscout.pump.combov2.keys.ComboIntentKey
import info.nightscout.pump.combov2.keys.ComboLongNonKey
import info.nightscout.pump.combov2.keys.ComboStringNonKey
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
Expand All @@ -95,6 +104,7 @@ import kotlinx.datetime.toLocalDateTime
import org.joda.time.DateTime
import org.json.JSONException
import org.json.JSONObject
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.max
Expand Down Expand Up @@ -135,50 +145,14 @@ class ComboV2Plugin @Inject constructor(
.pluginName(R.string.combov2_plugin_name)
.shortName(R.string.combov2_plugin_shortname)
.description(R.string.combov2_plugin_description)
.preferencesId(R.xml.pref_combov2),
ownPreferences = listOf(ComboStringKey::class.java, ComboIntKey::class.java, ComboLongKey::class.java),
.preferencesId(PluginDescription.PREFERENCE_SCREEN),
ownPreferences = listOf(
ComboIntentKey::class.java, ComboIntKey::class.java, ComboBooleanKey::class.java,
ComboStringNonKey::class.java, ComboIntNonKey::class.java, ComboLongNonKey::class.java
),
aapsLogger, rh, preferences, commandQueue
), Pump, PluginConstraints {

/**
* Preference classes are not used by Combo driver at the moment but needs to listed
* to make them know to AAPS preferences system
*/
@Suppress("unused")
enum class ComboStringKey(
override val key: String,
override val defaultValue: String
) : StringNonPreferenceKey {

BtAddress("combov2-bt-address-key", ""),
Nonce("combov2-nonce-key", ""),
CpCipher("combov2-cp-cipher-key", ""),
PcCipher("combov2-pc-cipher-key", ""),
PumpID("combov2-pump-id-key", ""),
TbrType("combov2-tbr-type", ""),
}

@Suppress("unused")
enum class ComboIntKey(
override val key: String,
override val defaultValue: Int
) : IntNonPreferenceKey {

KeyResponseAddress("combov2-key-response-address-key", 0),
TbrPercentage("combov2-tbr-percentage", 0),
TbrDuration("combov2-tbr-duration", 0),
UtcOffset("combov2-utc-offset", 0),
}

@Suppress("unused")
enum class ComboLongKey(
override val key: String,
override val defaultValue: Long
) : LongNonPreferenceKey {

TbrTimestamp("combov2-tbr-timestamp", 0),
}

// Coroutine scope and the associated job. All coroutines
// that are started in this plugin are part of this scope.
private var pumpCoroutineScopeJob = SupervisorJob()
Expand Down Expand Up @@ -489,13 +463,13 @@ class ComboV2Plugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)

val verboseLoggingPreference = preferenceFragment.findPreference<SwitchPreference>(rh.gs(R.string.key_combov2_verbose_logging))
val verboseLoggingPreference = preferenceFragment.findPreference<SwitchPreference>(ComboBooleanKey.VerboseLogging.key)
verboseLoggingPreference?.setOnPreferenceChangeListener { _, newValue ->
updateComboCtlLogLevel(newValue as Boolean)
true
}

val unpairPumpPreference: Preference? = preferenceFragment.findPreference(rh.gs(R.string.key_combov2_unpair_pump))
val unpairPumpPreference: Preference? = preferenceFragment.findPreference(ComboIntentKey.UnpairPump.key)
unpairPumpPreference?.setOnPreferenceClickListener {
preferenceFragment.context?.let { ctx ->
OKDialog.showConfirmation(ctx, "Confirm pump unpairing", "Do you really want to unpair the pump?", ok = Runnable {
Expand All @@ -517,10 +491,8 @@ class ComboV2Plugin @Inject constructor(
// recreates the fragment.
lifecycle.coroutineScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
val pairPref: Preference? = findPreference(rh.gs(R.string.key_combov2_pair_with_pump))
val unpairPref: Preference? = findPreference(rh.gs(R.string.key_combov2_unpair_pump))

pairPref?.intent = Intent(activity, ComboV2PairingActivity::class.java)
val pairPref: Preference? = findPreference(ComboIntentKey.PairWithPump.key)
val unpairPref: Preference? = findPreference(ComboIntentKey.UnpairPump.key)

val isInitiallyPaired = pairedStateUIFlow.value
pairPref?.isEnabled = !isInitiallyPaired
Expand Down Expand Up @@ -1014,7 +986,7 @@ class ComboV2Plugin @Inject constructor(
pumpStatus?.availableUnitsInReservoir?.let { newLevel ->
_reservoirLevel?.let { currentLevel ->
aapsLogger.debug(LTag.PUMP, "Current/new reservoir levels: $currentLevel / $newLevel")
if (sp.getBoolean(R.string.key_combov2_automatic_reservoir_entry, true) && (newLevel > currentLevel)) {
if (preferences.get(ComboBooleanKey.AutomaticReservoirEntry) && (newLevel > currentLevel)) {
aapsLogger.debug(LTag.PUMP, "Auto-inserting reservoir change therapy event")
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp = System.currentTimeMillis(),
Expand All @@ -1038,7 +1010,7 @@ class ComboV2Plugin @Inject constructor(

_batteryLevel?.let { currentLevel ->
aapsLogger.debug(LTag.PUMP, "Current/new battery levels: $currentLevel / $newLevel")
if (sp.getBoolean(R.string.key_combov2_automatic_battery_entry, true) && (newLevel > currentLevel)) {
if (preferences.get(ComboBooleanKey.AutomaticBatteryEntry) && (newLevel > currentLevel)) {
aapsLogger.debug(LTag.PUMP, "Auto-inserting battery change therapy event")
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp = System.currentTimeMillis(),
Expand Down Expand Up @@ -1524,7 +1496,7 @@ class ComboV2Plugin @Inject constructor(
val localBolusTimestamp = it.timestamp.toLocalDateTime(TimeZone.currentSystemDefault())
lines += rh.gs(
R.string.combov2_short_status_last_bolus, decimalFormatter.to2Decimal(it.bolusAmount.cctlBolusToIU()),
String.format("%02d:%02d", localBolusTimestamp.hour, localBolusTimestamp.minute)
String.format(Locale.getDefault(), "%02d:%02d", localBolusTimestamp.hour, localBolusTimestamp.minute)
)
}

Expand Down Expand Up @@ -1689,7 +1661,7 @@ class ComboV2Plugin @Inject constructor(
private var pairingPINChannel: Channel<PairingPIN>? = null

fun startPairing() {
val discoveryDuration = sp.getInt(R.string.key_combov2_discovery_duration, 300)
val discoveryDuration = preferences.get(ComboIntKey.DiscoveryDuration)

val newPINChannel = Channel<PairingPIN>(capacity = Channel.RENDEZVOUS)
pairingPINChannel = newPINChannel
Expand Down Expand Up @@ -2148,6 +2120,7 @@ class ComboV2Plugin @Inject constructor(
is ComboCtlPump.Event.UnknownTbrDetected -> {
// Inform about this unknown TBR that was observed (and automatically aborted).
val remainingDurationString = String.format(
Locale.getDefault(),
"%02d:%02d",
event.remainingTbrDurationInMinutes / 60,
event.remainingTbrDurationInMinutes % 60
Expand Down Expand Up @@ -2265,7 +2238,7 @@ class ComboV2Plugin @Inject constructor(
private fun isPaired() = pairedStateUIFlow.value

private fun updateComboCtlLogLevel() =
updateComboCtlLogLevel(sp.getBoolean(R.string.key_combov2_verbose_logging, false))
updateComboCtlLogLevel(preferences.get(ComboBooleanKey.VerboseLogging))

private fun updateComboCtlLogLevel(enableVerbose: Boolean) {
aapsLogger.debug(LTag.PUMP, "${if (enableVerbose) "Enabling" else "Disabling"} verbose logging")
Expand Down Expand Up @@ -2485,4 +2458,26 @@ class ComboV2Plugin @Inject constructor(

else -> false
}

override fun addPreferenceScreen(preferenceManager: PreferenceManager, parent: PreferenceScreen, context: Context, requiredKey: String?) {
if (requiredKey != null) return

val category = PreferenceCategory(context)
parent.addPreference(category)
category.apply {
key = "combov2_settings"
title = rh.gs(R.string.combov2_title)
initialExpandedChildrenCount = 0
addPreference(
AdaptiveIntentPreference(
ctx = context, intentKey = ComboIntentKey.PairWithPump, title = R.string.combov2_pair_with_pump_title, summary = R.string.combov2_pair_with_pump_summary,
intent = Intent(context, ComboV2PairingActivity::class.java)
)
)
addPreference(AdaptiveIntentPreference(ctx = context, intentKey = ComboIntentKey.UnpairPump, title = R.string.combov2_unpair_pump_title, summary = R.string.combov2_unpair_pump_summary))
addPreference(AdaptiveIntPreference(ctx = context, intKey = ComboIntKey.DiscoveryDuration, title = R.string.combov2_discovery_duration))
addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = ComboBooleanKey.AutomaticReservoirEntry, title = R.string.combov2_automatic_reservoir_entry))
addPreference(AdaptiveSwitchPreference(ctx = context, booleanKey = ComboBooleanKey.AutomaticBatteryEntry, title = R.string.combov2_automatic_battery_entry))
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.BooleanPreferenceKey

enum class ComboBooleanKey(
override val key: String,
override val defaultValue: Boolean,
override val calculatedDefaultValue: Boolean = false,
override val engineeringModeOnly: Boolean = false,
override val defaultedBySM: Boolean = false,
override val showInApsMode: Boolean = true,
override val showInNsClientMode: Boolean = true,
override val showInPumpControlMode: Boolean = true,
override val dependency: BooleanPreferenceKey? = null,
override val negativeDependency: BooleanPreferenceKey? = null,
override val hideParentScreenIfHidden: Boolean = false
) : BooleanPreferenceKey {


AutomaticReservoirEntry("combov2_automatic_reservoir_entry", true),
AutomaticBatteryEntry("combov2_automatic_battery_entry", true),
VerboseLogging("combov2_verbose_logging", false),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.BooleanPreferenceKey
import app.aaps.core.keys.interfaces.IntPreferenceKey

enum class ComboIntKey(
override val key: String,
override val defaultValue: Int,
override val min: Int = Int.MIN_VALUE,
override val max: Int = Int.MAX_VALUE,
override val calculatedDefaultValue: Boolean = false,
override val engineeringModeOnly: Boolean = false,
override val defaultedBySM: Boolean = false,
override val showInApsMode: Boolean = true,
override val showInNsClientMode: Boolean = true,
override val showInPumpControlMode: Boolean = true,
override val dependency: BooleanPreferenceKey? = null,
override val negativeDependency: BooleanPreferenceKey? = null,
override val hideParentScreenIfHidden: Boolean = false
) : IntPreferenceKey {

DiscoveryDuration("combov2_bt_discovery_duration", defaultValue = 300, min = 30, max = 300),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.IntNonPreferenceKey

enum class ComboIntNonKey(
override val key: String,
override val defaultValue: Int
) : IntNonPreferenceKey {

KeyResponseAddress("combov2-key-response-address-key", 0),
TbrPercentage("combov2-tbr-percentage", 0),
TbrDuration("combov2-tbr-duration", 0),
UtcOffset("combov2-utc-offset", 0),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.BooleanPreferenceKey
import app.aaps.core.keys.interfaces.IntentPreferenceKey

enum class ComboIntentKey(
override val key: String,
override val defaultedBySM: Boolean = false,
override val showInApsMode: Boolean = true,
override val showInNsClientMode: Boolean = true,
override val showInPumpControlMode: Boolean = true,
override val dependency: BooleanPreferenceKey? = null,
override val negativeDependency: BooleanPreferenceKey? = null,
override val hideParentScreenIfHidden: Boolean = false
) : IntentPreferenceKey {

PairWithPump(key = "combov2_pair_with_pump"),
UnpairPump(key = "combov2_unpair_pump"),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.LongNonPreferenceKey

@Suppress("unused")
enum class ComboLongNonKey(
override val key: String,
override val defaultValue: Long
) : LongNonPreferenceKey {

TbrTimestamp("combov2-tbr-timestamp", 0),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package info.nightscout.pump.combov2.keys

import app.aaps.core.keys.interfaces.StringNonPreferenceKey

enum class ComboStringNonKey(
override val key: String,
override val defaultValue: String
) : StringNonPreferenceKey {

BtAddress("combov2-bt-address-key", ""),
Nonce("combov2-nonce-key", ""),
CpCipher("combov2-cp-cipher-key", ""),
PcCipher("combov2-pc-cipher-key", ""),
PumpID("combov2-pump-id-key", ""),
TbrType("combov2-tbr-type", ""),
}
6 changes: 0 additions & 6 deletions pump/combov2/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
<string name="combov2_current_activity_label">Current activity</string>
<string name="bluetooth_address">Bluetooth address</string>
<string name="key_combov2_settings" translatable="false">combov2_settings</string>
<string name="key_combov2_pair_with_pump" translatable="false">combov2_pair_with_pump</string>
<string name="key_combov2_unpair_pump" translatable="false">combov2_unpair_pump</string>
<string name="combov2_start_pairing">Start pairing</string>
<string name="combov2_pairing_in_progress">Combo pairing in progress</string>
<string name="combov2_pairing_start_steps">Steps to perform pairing with your Combo:\n\n
Expand Down Expand Up @@ -77,9 +75,7 @@ buttons at the same time to cancel pairing)\n
<string name="combov2_updating_pump_datetime_cmddesc">Updating pump datetime</string>
<string name="combov2_updating_pump_status_cmddesc">Updating pump status</string>
<string name="combov2_pairing_pin_failure">PIN did not work. Check if there was a typo. If this keeps happening, cancel and retry pairing.</string>
<string name="key_combov2_discovery_duration" translatable="false">combov2_bt_discovery_duration</string>
<string name="combov2_discovery_duration">Discovery duration (in seconds)</string>
<string name="key_combov2_verbose_logging" translatable="false">combov2_verbose_logging</string>
<string name="combov2_verbose_logging">Enable verbose Combo logging</string>
<string name="combov2_getting_basal_profile">Getting basal profile; %1$d factor(s) read</string>
<string name="combov2_setting_basal_profile">Setting basal profile; %1$d factor(s) written</string>
Expand Down Expand Up @@ -125,8 +121,6 @@ buttons at the same time to cancel pairing)\n
<string name="combov2_short_status_battery_state_low">low</string>
<string name="combov2_short_status_battery_state_full">full</string>
<string name="combov2_short_status_battery_state">Batt: %s</string>
<string name="key_combov2_automatic_reservoir_entry" translatable="false">combov2_automatic_reservoir_entry</string>
<string name="key_combov2_automatic_battery_entry" translatable="false">combov2_automatic_battery_entry</string>
<string name="combov2_automatic_reservoir_entry">Autodetect and automatically enter insulin reservoir change</string>
<string name="combov2_automatic_battery_entry">Autodetect and automatically enter battery change</string>
<string name="combov2_timezone_changed">Timezone changed</string>
Expand Down
Loading

0 comments on commit 5977ace

Please sign in to comment.