diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt index 47c712fbb5..cb2ceb610f 100644 --- a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt @@ -9,13 +9,18 @@ import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.database.entities.EffectiveProfileSwitch import info.nightscout.database.entities.embedments.InsulinConfiguration import info.nightscout.implementation.profile.ProfileStoreObject +import info.nightscout.implementation.profile.ProfileUtilImpl +import info.nightscout.implementation.utils.DecimalFormatterImpl import info.nightscout.interfaces.Config +import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileStore +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -41,6 +46,8 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var sp: SP lateinit var dateUtil: DateUtil + lateinit var profileUtil: ProfileUtil + lateinit var decimalFormatter: DecimalFormatter lateinit var hardLimits: HardLimits val rxBus = RxBus(aapsSchedulers, aapsLogger) @@ -76,9 +83,12 @@ open class TestBaseWithProfile : TestBase() { "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" dateUtil = Mockito.spy(DateUtil(context)) + decimalFormatter = DecimalFormatterImpl(rh) + profileUtil = ProfileUtilImpl(sp, decimalFormatter) testPumpPlugin = TestPumpPlugin(profileInjector) Mockito.`when`(dateUtil.now()).thenReturn(now) Mockito.`when`(activePlugin.activePump).thenReturn(testPumpPlugin) + Mockito.`when`(sp.getString(info.nightscout.core.utils.R.string.key_units, GlucoseUnit.MGDL.asText)).thenReturn(GlucoseUnit.MGDL.asText) hardLimits = HardLimitsMock(sp, rh) validProfile = ProfileSealed.Pure(pureProfileFromJson(JSONObject(validProfileJSON), dateUtil)!!) effectiveProfileSwitch = EffectiveProfileSwitch( diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt b/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt new file mode 100644 index 0000000000..c0e7fb1d4d --- /dev/null +++ b/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt @@ -0,0 +1,17 @@ +package info.nightscout.interfaces + +@Suppress("SpellCheckingInspection") +enum class GlucoseUnit(val asText: String) { + + // This is Nightscout's representation + MGDL("mg/dl"), + MMOL("mmol"); + + companion object { + + const val MMOLL_TO_MGDL = 18.0 // 18.0182; + const val MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL + + fun fromText(name: String) = values().firstOrNull { it.asText == name } ?: MGDL + } +} \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt b/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt new file mode 100644 index 0000000000..241492911e --- /dev/null +++ b/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt @@ -0,0 +1,21 @@ +package info.nightscout.interfaces.utils + +import java.text.DecimalFormat + +/** + * Format double values to strings + */ +interface DecimalFormatter { + + fun to0Decimal(value: Double): String + fun to0Decimal(value: Double, unit: String): String + fun to1Decimal(value: Double): String + fun to1Decimal(value: Double, unit: String): String + fun to2Decimal(value: Double): String + fun to2Decimal(value: Double, unit: String): String + fun to3Decimal(value: Double): String + fun to3Decimal(value: Double, unit: String): String + fun toPumpSupportedBolus(value: Double, bolusStep: Double): String + fun toPumpSupportedBolusWithUnits(value: Double, bolusStep: Double): String + fun pumpSupportedBolusFormat(bolusStep: Double): DecimalFormat +} \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt b/app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt new file mode 100644 index 0000000000..9d503d0b3d --- /dev/null +++ b/app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt @@ -0,0 +1,146 @@ +package info.nightscout.shared.interfaces + +import info.nightscout.interfaces.GlucoseUnit + +interface ProfileUtil { + + /** + * Units selected in [info.nightscout.shared.sharedPreferences.SP] + * + * @return GlucoseUnit for UI + */ + val units: GlucoseUnit + + /** + * Convert value from mg/dl to selected units + * + * @param valueInMgdl glucose value in mgdl + * @param targetUnits target units + * @return value in target units + */ + fun fromMgdlToUnits(valueInMgdl: Double, targetUnits: GlucoseUnit = units): Double + + /** + * Convert value from mmol/l to selected units + * + * @param value glucose value in mmol/l + * @param targetUnits target units + * @return value in target units + */ + fun fromMmolToUnits(value: Double, targetUnits: GlucoseUnit = units): Double + + /** + * Convert to currently used units + * + * @param anyBg glycemia + * @return value in mg/dl or mmol/l + */ + fun valueInCurrentUnitsDetect(anyBg: Double): Double + + /** + * Detect units of [anyBg] and return string in currently used units. + * Values >= 39 are expected to be in mmol/l, below in mg/dl. + * + * @param anyBg value either in mmol/l or mg/dl + * @return formatted string in current units + */ + fun stringInCurrentUnitsDetect(anyBg: Double): String + + /** + * Value based on [targetUnits] parameter as a formatted string + * + * @param valueInMgdl known value in mg/dl + * @param targetUnits wanted units + * @return formatted one of the values based on [targetUnits] parameter + */ + fun fromMgdlToStringInUnits(valueInMgdl: Double?, targetUnits: GlucoseUnit = units): String + + /** + * Pick from values based on [targetUnits] parameter as a formatted string with +/- sign + * + * @param valueInMgdl known value in mg/dl + * @param targetUnits wanted units + * @return formatted one of the values based on [targetUnits] parameter + */ + fun fromMgdlToSignedStringInUnits(valueInMgdl: Double, targetUnits: GlucoseUnit = units): String + + /** + * Test if value is in mg/dl. + * + * @param anyBg glycemia + * @return true if value < 39 + */ + fun isMgdl(anyBg: Double): Boolean + + /** + * Test if value is in mmol/l + * + * @param anyBg glycemia + * @return true if value >= 39 + */ + fun isMmol(anyBg: Double): Boolean + + /** + * Detect units of [anyBg] + * + * @param anyBg glycemia + * @return [GlucoseUnit.MMOL] if value >= 39 otherwise [GlucoseUnit.MGDL] + */ + fun unitsDetect(anyBg: Double): GlucoseUnit + + /** + * Convert to selected units + * + * @param anyBg glycemia + * @param targetUnits target units + * @return value in mg/dl or mmol/l + */ + fun valueInUnitsDetect(anyBg: Double, targetUnits: GlucoseUnit): Double + + /** + * Detect units of [anyBg] and return string in [targetUnits] + * Values >= 39 are expected to be in mmol/l, below in mg/dl. + * + * @param anyBg value either in mmol/l or mg/dl + * @return formatted string + */ + fun stringInUnitsDetect(anyBg: Double, targetUnits: GlucoseUnit): String + + /** + * Detect units and convert value to mg/dl + * Values >= 39 are expected to be in mmol/l, below in mg/dl. + * + * @param anyBg in any units + * @return value in mg/dl + */ + fun convertToMgdlDetect(anyBg: Double): Double + + /** + * Convert value to mg/dl + * + * @param value value in [sourceUnits] + * @return value in mg/dl + */ + fun convertToMgdl(value: Double, sourceUnits: GlucoseUnit): Double + + /** + * Convert value to mmol/l + * + * @param value value in [sourceUnits] + * @return value in mmol/l + */ + fun convertToMmol(value: Double, sourceUnits: GlucoseUnit): Double + + /** + * Create properly formatted string of range "low - high". + * Targets are stored in mg/dl but profile vary + * + * @param low low range value + * @param high high range value + * @param sourceUnits units of source values + * @param targetUnits target units for formatting + * @return formatted range string + */ + // + fun toTargetRangeString(low: Double, high: Double, sourceUnits: GlucoseUnit, targetUnits: GlucoseUnit = units): String +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowserData.kt b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowserData.kt index 1ed2951d14..509a1d5a24 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowserData.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowserData.kt @@ -9,6 +9,7 @@ import info.nightscout.implementation.overview.OverviewDataImpl import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus @@ -33,7 +34,8 @@ class HistoryBrowserData @Inject constructor( profileFunction: ProfileFunction, repository: AppRepository, fabricPrivacy: FabricPrivacy, - calculationWorkflow: CalculationWorkflow + calculationWorkflow: CalculationWorkflow, + decimalFormatter: DecimalFormatter ) { var iobCobCalculator: IobCobCalculatorPlugin @@ -50,7 +52,8 @@ class HistoryBrowserData @Inject constructor( activePlugin, defaultValueHelper, profileFunction, - repository + repository, + decimalFormatter ) iobCobCalculator = IobCobCalculatorPlugin( @@ -66,7 +69,8 @@ class HistoryBrowserData @Inject constructor( dateUtil, repository, overviewData, - calculationWorkflow + calculationWorkflow, + decimalFormatter ) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 7467304b22..e5da97282b 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -20,7 +20,6 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.DanaRPlugin -import info.nightscout.plugins.sync.openhumans.OpenHumansUploaderPlugin import info.nightscout.androidaps.plugins.pump.eopatch.EopatchPumpPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin @@ -32,8 +31,6 @@ import info.nightscout.insulin.InsulinOrefFreePeakPlugin import info.nightscout.interfaces.Config import info.nightscout.interfaces.nsclient.NSSettingsStatus import info.nightscout.interfaces.plugin.PluginBase -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.PasswordCheck import info.nightscout.interfaces.protection.ProtectionCheck.ProtectionType.BIOMETRIC import info.nightscout.interfaces.protection.ProtectionCheck.ProtectionType.CUSTOM_PASSWORD @@ -49,6 +46,7 @@ import info.nightscout.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.plugins.general.wear.WearPlugin import info.nightscout.plugins.sync.nsclient.NSClientPlugin import info.nightscout.plugins.sync.nsclientV3.NSClientV3Plugin +import info.nightscout.plugins.sync.openhumans.OpenHumansUploaderPlugin import info.nightscout.plugins.sync.tidepool.TidepoolPlugin import info.nightscout.plugins.sync.xdrip.XdripPlugin import info.nightscout.pump.combo.ComboPlugin @@ -63,6 +61,7 @@ import info.nightscout.sensitivity.SensitivityAAPSPlugin import info.nightscout.sensitivity.SensitivityOref1Plugin import info.nightscout.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.source.AidexPlugin @@ -83,7 +82,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var sp: SP - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var pluginStore: PluginStore @Inject lateinit var config: Config @@ -326,7 +325,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang rh.gs(info.nightscout.core.utils.R.string.key_low_mark) ) if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) { - val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text)) + val converted = profileUtil.valueInCurrentUnitsDetect(SafeParse.stringToDouble(pref.text)) pref.summary = converted.toString() } } diff --git a/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt index 22b030152a..fb423910eb 100644 --- a/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt @@ -39,6 +39,7 @@ import info.nightscout.pump.combo.ruffyscripter.RuffyScripter import info.nightscout.pump.dana.DanaPump import info.nightscout.pump.dana.R import info.nightscout.pump.dana.database.DanaHistoryDatabase +import info.nightscout.pump.danars.DanaRSPlugin import info.nightscout.pump.virtual.VirtualPumpPlugin import info.nightscout.sharedtests.TestBaseWithProfile import info.nightscout.source.GlimpPlugin @@ -78,7 +79,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { private lateinit var objectivesPlugin: ObjectivesPlugin private lateinit var comboPlugin: ComboPlugin private lateinit var danaRPlugin: DanaRPlugin - private lateinit var danaRSPlugin: info.nightscout.pump.danars.DanaRSPlugin + private lateinit var danaRSPlugin: DanaRSPlugin private lateinit var insightPlugin: LocalInsightPlugin private lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @@ -135,36 +136,21 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { //SafetyPlugin constraintChecker = ConstraintsImpl(activePlugin) - val glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) + val glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtil, decimalFormatter) insightDbHelper = InsightDbHelper(insightDatabaseDao) - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, activePlugin, sp, config) comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, rh, profileFunction, sp, commandQueue, pumpSync, dateUtil, ruffyScripter, uiInteraction) danaRPlugin = DanaRPlugin( injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync, - uiInteraction, danaHistoryDatabase + uiInteraction, danaHistoryDatabase, decimalFormatter ) danaRSPlugin = - info.nightscout.pump.danars.DanaRSPlugin( - injector, - aapsLogger, - aapsSchedulers, - rxBus, - context, - rh, - constraintChecker, - profileFunction, - sp, - commandQueue, - danaPump, - pumpSync, - detailedBolusInfoStorage, - temporaryBasalStorage, - fabricPrivacy, - dateUtil, - uiInteraction, - danaHistoryDatabase + DanaRSPlugin( + injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, + sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, + fabricPrivacy, dateUtil, uiInteraction, danaHistoryDatabase, decimalFormatter ) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, rh, sp, commandQueue, profileFunction, context, config, dateUtil, insightDbHelper, pumpSync, insightDatabase) openAPSSMBPlugin = @@ -228,18 +214,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { ) safetyPlugin = SafetyPlugin( - injector, - aapsLogger, - rh, - sp, - rxBus, - constraintChecker, - activePlugin, - hardLimits, - ConfigImpl(fileListProvider), - iobCobCalculator, - dateUtil, - uiInteraction + injector, aapsLogger, rh, sp, constraintChecker, activePlugin, hardLimits, + ConfigImpl(fileListProvider), iobCobCalculator, dateUtil, uiInteraction, decimalFormatter ) val constraintsPluginsList = ArrayList() constraintsPluginsList.add(safetyPlugin) diff --git a/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt index 73071d01ec..eb79869c31 100644 --- a/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt @@ -72,7 +72,7 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) `when`(config.APS).thenReturn(true) - safetyPlugin = SafetyPlugin(injector, aapsLogger, rh, sp, rxBus, constraintChecker, activePlugin, hardLimits, config, iobCobCalculator, dateUtil, uiInteraction) + safetyPlugin = SafetyPlugin(injector, aapsLogger, rh, sp, constraintChecker, activePlugin, hardLimits, config, iobCobCalculator, dateUtil, uiInteraction, decimalFormatter) openAPSAMAPlugin = OpenAPSAMAPlugin( injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider, sp diff --git a/app/src/test/java/info/nightscout/pump/PumpEnactResultTest.kt b/app/src/test/java/info/nightscout/pump/PumpEnactResultTest.kt index 7a0de59162..cb6f88c370 100644 --- a/app/src/test/java/info/nightscout/pump/PumpEnactResultTest.kt +++ b/app/src/test/java/info/nightscout/pump/PumpEnactResultTest.kt @@ -159,15 +159,15 @@ class PumpEnactResultTest : TestBaseWithProfile() { @Test fun toHtmlTest() { var per: PumpEnactResult = PumpEnactResult(injector).enacted(true).bolusDelivered(10.0).comment("AAA") - Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
SMB: 10.0 U", per.toHtml(rh)) + Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
SMB: 10.0 U", per.toHtml(rh, decimalFormatter)) per = PumpEnactResult(injector).enacted(true).isTempCancel(true).comment("AAA") - Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Cancel temp basal", per.toHtml(rh)) + Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Cancel temp basal", per.toHtml(rh, decimalFormatter)) per = PumpEnactResult(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA") - Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Duration: 20 min
Percent: 90%", per.toHtml(rh)) + Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Duration: 20 min
Percent: 90%", per.toHtml(rh, decimalFormatter)) per = PumpEnactResult(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA") - Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Duration: 30 min
Absolute: 1.00 U/h", per.toHtml(rh)) + Assertions.assertEquals("Success: false
Enacted: true
Comment: AAA
Duration: 30 min
Absolute: 1.00 U/h", per.toHtml(rh, decimalFormatter)) per = PumpEnactResult(injector).enacted(false).comment("AAA") - Assertions.assertEquals("Success: false
Comment: AAA", per.toHtml(rh)) + Assertions.assertEquals("Success: false
Comment: AAA", per.toHtml(rh, decimalFormatter)) } @Test fun jsonTest() { diff --git a/core/graph/src/main/java/info/nightscout/core/graph/data/BolusDataPoint.kt b/core/graph/src/main/java/info/nightscout/core/graph/data/BolusDataPoint.kt index c1f0cd165c..2c390d06c6 100644 --- a/core/graph/src/main/java/info/nightscout/core/graph/data/BolusDataPoint.kt +++ b/core/graph/src/main/java/info/nightscout/core/graph/data/BolusDataPoint.kt @@ -12,7 +12,8 @@ class BolusDataPoint( val data: Bolus, private val rh: ResourceHelper, private val activePlugin: ActivePlugin, - private val defaultValueHelper: DefaultValueHelper + private val defaultValueHelper: DefaultValueHelper, + private val decimalFormatter: DecimalFormatter ) : DataPointWithLabelInterface { private var yValue = 0.0 @@ -20,7 +21,7 @@ class BolusDataPoint( override fun getX(): Double = data.timestamp.toDouble() override fun getY(): Double = if (data.type == Bolus.Type.SMB) defaultValueHelper.determineLowLine() else yValue override val label - get() = DecimalFormatter.toPumpSupportedBolus(data.amount, activePlugin.activePump, rh) + get() = decimalFormatter.toPumpSupportedBolus(data.amount, activePlugin.activePump.pumpDescription.bolusStep) override val duration = 0L override val size = 2f override val paintStyle: Paint.Style = Paint.Style.FILL // not used diff --git a/core/graph/src/main/java/info/nightscout/core/graph/data/ExtendedBolusDataPoint.kt b/core/graph/src/main/java/info/nightscout/core/graph/data/ExtendedBolusDataPoint.kt index a8d1b4a5da..c4b8fb5d07 100644 --- a/core/graph/src/main/java/info/nightscout/core/graph/data/ExtendedBolusDataPoint.kt +++ b/core/graph/src/main/java/info/nightscout/core/graph/data/ExtendedBolusDataPoint.kt @@ -8,7 +8,8 @@ import info.nightscout.shared.interfaces.ResourceHelper class ExtendedBolusDataPoint( val data: ExtendedBolus, - private val rh: ResourceHelper + private val rh: ResourceHelper, + private val decimalFormatter: DecimalFormatter ) : DataPointWithLabelInterface { private var yValue = 0.0 @@ -28,5 +29,5 @@ class ExtendedBolusDataPoint( yValue = y } - private fun ExtendedBolus.toStringTotal(): String = "${DecimalFormatter.to2Decimal(amount)}U ( ${DecimalFormatter.to2Decimal(rate)} U/h )" + private fun ExtendedBolus.toStringTotal(): String = "${decimalFormatter.to2Decimal(amount)}U ( ${decimalFormatter.to2Decimal(rate)} U/h )" } \ No newline at end of file diff --git a/core/graph/src/main/java/info/nightscout/core/graph/data/GlucoseValueDataPoint.kt b/core/graph/src/main/java/info/nightscout/core/graph/data/GlucoseValueDataPoint.kt index f844ea127d..04f30c1877 100644 --- a/core/graph/src/main/java/info/nightscout/core/graph/data/GlucoseValueDataPoint.kt +++ b/core/graph/src/main/java/info/nightscout/core/graph/data/GlucoseValueDataPoint.kt @@ -5,24 +5,23 @@ import android.graphics.Paint import info.nightscout.database.entities.GlucoseValue import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper class GlucoseValueDataPoint( val data: GlucoseValue, - private val profileFunction: ProfileFunction, - private val rh: ResourceHelper + private val profileUtil: ProfileUtil, + private val rh: ResourceHelper, ) : DataPointWithLabelInterface { private fun valueToUnits(units: GlucoseUnit): Double = if (units == GlucoseUnit.MGDL) data.value else data.value * Constants.MGDL_TO_MMOLL override fun getX(): Double = data.timestamp.toDouble() - override fun getY(): Double = valueToUnits(profileFunction.getUnits()) + override fun getY(): Double = valueToUnits(profileUtil.units) override fun setY(y: Double) {} - override val label: String = Profile.toCurrentUnitsString(profileFunction, data.value) + override val label: String = profileUtil.fromMgdlToStringInUnits(data.value) override val duration = 0L override val shape get() = if (isPrediction) PointsWithLabelGraphSeries.Shape.PREDICTION else PointsWithLabelGraphSeries.Shape.BG override val size = if (isPrediction) 1f else 0.6f @@ -30,8 +29,8 @@ class GlucoseValueDataPoint( override fun color(context: Context?): Int { return when { - isPrediction -> predictionColor(context) - else -> rh.gac(context, info.nightscout.core.ui.R.attr.originalBgValueColor) + isPrediction -> predictionColor(context) + else -> rh.gac(context, info.nightscout.core.ui.R.attr.originalBgValueColor) } } diff --git a/core/graph/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt b/core/graph/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt index 5f75092ecd..2d5e6bc024 100644 --- a/core/graph/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt +++ b/core/graph/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt @@ -5,14 +5,13 @@ import android.graphics.Paint import info.nightscout.database.entities.TherapyEvent import info.nightscout.interfaces.Constants import info.nightscout.interfaces.Translator -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper class TherapyEventDataPoint( val data: TherapyEvent, private val rh: ResourceHelper, - private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val translator: Translator ) : DataPointWithLabelInterface { @@ -21,20 +20,13 @@ class TherapyEventDataPoint( override fun getX(): Double = data.timestamp.toDouble() override fun getY(): Double { - val units = profileFunction.getUnits() - if (data.type == TherapyEvent.Type.NS_MBG) return Profile.fromMgdlToUnits(data.glucose!!, units) + if (data.type == TherapyEvent.Type.NS_MBG) return profileUtil.fromMgdlToUnits(data.glucose!!) if (data.glucose != null && data.glucose != 0.0) { - var mmol = 0.0 - var mgdl = 0.0 - if (data.glucoseUnit == TherapyEvent.GlucoseUnit.MGDL) { - mgdl = data.glucose!! - mmol = data.glucose!! * Constants.MGDL_TO_MMOLL + val mgdl: Double = when (data.glucoseUnit) { + TherapyEvent.GlucoseUnit.MGDL -> data.glucose!! + TherapyEvent.GlucoseUnit.MMOL -> data.glucose!! * Constants.MMOLL_TO_MGDL } - if (data.glucoseUnit == TherapyEvent.GlucoseUnit.MMOL) { - mmol = data.glucose!! - mgdl = data.glucose!! * Constants.MMOLL_TO_MGDL - } - return Profile.toUnits(mgdl, mmol, units) + return profileUtil.fromMgdlToUnits(mgdl) } return yValue } diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt deleted file mode 100644 index 9ecfbc6ad2..0000000000 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt +++ /dev/null @@ -1,12 +0,0 @@ -package info.nightscout.interfaces - -enum class GlucoseUnit(val asText: String) { - MGDL(Constants.MGDL), - MMOL(Constants.MMOL); - - companion object { - - fun fromText(name: String) = values().firstOrNull { it.asText == name } ?: MGDL - } - -} \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/profile/Profile.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/profile/Profile.kt index bcd17df2db..1ee7af23b7 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/profile/Profile.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/profile/Profile.kt @@ -1,10 +1,8 @@ package info.nightscout.interfaces.profile import info.nightscout.interfaces.Config -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.pump.Pump -import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits import info.nightscout.interfaces.utils.Round import info.nightscout.rx.bus.RxBus @@ -133,62 +131,4 @@ interface Profile { return result } } - - companion object { - /* - * Units conversion - */ - - fun fromMgdlToUnits(value: Double, units: GlucoseUnit): Double = - if (units == GlucoseUnit.MGDL) value else value * Constants.MGDL_TO_MMOLL - - fun fromMmolToUnits(value: Double, units: GlucoseUnit): Double = - if (units == GlucoseUnit.MMOL) value else value * Constants.MMOLL_TO_MGDL - - fun toUnits(valueInMgdl: Double, valueInMmol: Double, units: GlucoseUnit): Double = - if (units == GlucoseUnit.MGDL) valueInMgdl else valueInMmol - - fun toUnitsString(valueInMgdl: Double, valueInMmol: Double, units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(valueInMgdl) else DecimalFormatter.to1Decimal(valueInMmol) - - fun toSignedUnitsString(valueInMgdl: Double, valueInMmol: Double, units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) (if (valueInMgdl > 0) "+" else "") + DecimalFormatter.to0Decimal(valueInMgdl) - else (if (valueInMmol > 0) "+" else "") + DecimalFormatter.to1Decimal(valueInMmol) - - fun isMgdl(anyBg: Double) = anyBg >= 39 - fun isMmol(anyBg: Double) = anyBg < 39 - fun unit(anyBg: Double) = if (isMgdl(anyBg)) GlucoseUnit.MGDL else GlucoseUnit.MMOL - - fun toCurrentUnits(profileFunction: ProfileFunction, anyBg: Double): Double = - if (isMmol(anyBg)) fromMmolToUnits(anyBg, profileFunction.getUnits()) - else fromMgdlToUnits(anyBg, profileFunction.getUnits()) - - fun toCurrentUnits(units: GlucoseUnit, anyBg: Double): Double = - if (isMmol(anyBg)) fromMmolToUnits(anyBg, units) - else fromMgdlToUnits(anyBg, units) - - fun toCurrentUnitsString(profileFunction: ProfileFunction, anyBg: Double): String = - if (isMmol(anyBg)) toUnitsString(anyBg * Constants.MMOLL_TO_MGDL, anyBg, profileFunction.getUnits()) - else toUnitsString(anyBg, anyBg * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) - - fun toMgdl(value: Double): Double = - if (isMgdl(value)) value else value * Constants.MMOLL_TO_MGDL - - fun toMgdl(value: Double, units: GlucoseUnit): Double = - if (units == GlucoseUnit.MGDL) value else value * Constants.MMOLL_TO_MGDL - - fun toMmol(value: Double, units: GlucoseUnit): Double = - if (units == GlucoseUnit.MGDL) value * Constants.MGDL_TO_MMOLL else value - - // targets are stored in mg/dl but profile vary - fun toTargetRangeString(low: Double, high: Double, sourceUnits: GlucoseUnit, units: GlucoseUnit): String { - val lowMgdl = toMgdl(low, sourceUnits) - val highMgdl = toMgdl(high, sourceUnits) - val lowMmol = toMmol(low, sourceUnits) - val highMmol = toMmol(high, sourceUnits) - return if (low == high) toUnitsString(lowMgdl, lowMmol, units) - else toUnitsString(lowMgdl, lowMmol, units) + " - " + toUnitsString(highMgdl, highMmol, units) - } - - } } \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/pump/PumpSync.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/pump/PumpSync.kt index 89d378b927..52d64d2113 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/pump/PumpSync.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/pump/PumpSync.kt @@ -91,10 +91,10 @@ interface PumpSync { if (isAbsolute) rate else profile.getBasal(time) * rate / 100 - fun toStringFull(dateUtil: DateUtil): String { + fun toStringFull(dateUtil: DateUtil, decimalFormatter: DecimalFormatter): String { return when { isAbsolute -> { - DecimalFormatter.to2Decimal(rate) + "U/h @" + + decimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } @@ -130,10 +130,12 @@ interface PumpSync { val plannedRemainingMinutes: Long get() = max(T.msecs(end - System.currentTimeMillis()).mins(), 0L) + private fun getPassedDurationToTimeInMinutes(time: Long): Int = ((min(time, end) - timestamp) / 60.0 / 1000).roundToInt() - fun toStringFull(dateUtil: DateUtil): String = - "E " + DecimalFormatter.to2Decimal(rate) + "U/h @" + + + fun toStringFull(dateUtil: DateUtil, decimalFormatter: DecimalFormatter): String = + "E " + decimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "min" } diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/stats/DexcomTIR.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/stats/DexcomTIR.kt index 463dd3d0f8..090f8c5d8b 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/stats/DexcomTIR.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/stats/DexcomTIR.kt @@ -3,14 +3,14 @@ package info.nightscout.interfaces.stats import android.content.Context import android.widget.TableRow import android.widget.TextView -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil interface DexcomTIR { fun calculateSD(): Double fun toHbA1cView(context: Context): TextView - fun toSDView(context: Context, profileFunction: ProfileFunction): TextView - fun toRangeHeaderView(context: Context, profileFunction: ProfileFunction): TextView + fun toSDView(context: Context, profileUtil: ProfileUtil): TextView + fun toRangeHeaderView(context: Context, profileUtil: ProfileUtil): TextView fun toTableRowHeader(context: Context): TableRow fun toTableRow(context: Context): TableRow } diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt deleted file mode 100644 index 636d1fc8cd..0000000000 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.interfaces.utils - -import info.nightscout.interfaces.R -import info.nightscout.interfaces.pump.Pump -import info.nightscout.shared.interfaces.ResourceHelper -import java.text.DecimalFormat - -object DecimalFormatter { - - private val format0dec = DecimalFormat("0") - private val format1dec = DecimalFormat("0.0") - private val format2dec = DecimalFormat("0.00") - private val format3dec = DecimalFormat("0.000") - - fun to0Decimal(value: Double): String = format0dec.format(value) - fun to0Decimal(value: Double, unit: String): String = format0dec.format(value) + unit - fun to1Decimal(value: Double): String = format1dec.format(value) - fun to1Decimal(value: Double, unit: String): String = format1dec.format(value) + unit - fun to2Decimal(value: Double): String = format2dec.format(value) - fun to2Decimal(value: Double, unit: String): String = format2dec.format(value) + unit - fun to3Decimal(value: Double): String = format3dec.format(value) - fun to3Decimal(value: Double, unit: String): String = format3dec.format(value) + unit - fun toPumpSupportedBolus(value: Double, pump: Pump): String = if (pump.pumpDescription.bolusStep <= 0.051) to2Decimal(value) else to1Decimal(value) - fun toPumpSupportedBolus(value: Double, pump: Pump, rh: ResourceHelper): String = - if (pump.pumpDescription.bolusStep <= 0.051) rh.gs(R.string.format_insulin_units, value) - else rh.gs(R.string.format_insulin_units1, value) - - fun pumpSupportedBolusFormat(pump: Pump): DecimalFormat = if (pump.pumpDescription.bolusStep <= 0.051) DecimalFormat("0.00") else DecimalFormat("0.0") -} \ No newline at end of file diff --git a/core/main/src/main/java/info/nightscout/core/extensions/ExtendedBolusExtension.kt b/core/main/src/main/java/info/nightscout/core/extensions/ExtendedBolusExtension.kt index e03011f3e3..e9d3b6e605 100644 --- a/core/main/src/main/java/info/nightscout/core/extensions/ExtendedBolusExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/extensions/ExtendedBolusExtension.kt @@ -23,12 +23,12 @@ fun ExtendedBolus.isInProgress(dateUtil: DateUtil): Boolean = val ExtendedBolus.plannedRemainingMinutes: Int get() = max(round((end - System.currentTimeMillis()) / 1000.0 / 60).toInt(), 0) -fun ExtendedBolus.toStringFull(dateUtil: DateUtil): String = - "E " + DecimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + +fun ExtendedBolus.toStringFull(dateUtil: DateUtil, decimalFormatter: DecimalFormatter): String = + "E " + decimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "min" -fun ExtendedBolus.toStringMedium(dateUtil: DateUtil): String = - DecimalFormatter.to2Decimal(rate) + "U/h " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "'" +fun ExtendedBolus.toStringMedium(dateUtil: DateUtil, decimalFormatter: DecimalFormatter): String = + decimalFormatter.to2Decimal(rate) + "U/h " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "'" fun ExtendedBolus.getPassedDurationToTimeInMinutes(time: Long): Int = ((min(time, end) - timestamp) / 60.0 / 1000).roundToInt() diff --git a/core/main/src/main/java/info/nightscout/core/extensions/GlucoseValueExtension.kt b/core/main/src/main/java/info/nightscout/core/extensions/GlucoseValueExtension.kt index bbff5637dc..1f8a2c80a0 100644 --- a/core/main/src/main/java/info/nightscout/core/extensions/GlucoseValueExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/extensions/GlucoseValueExtension.kt @@ -5,14 +5,9 @@ import info.nightscout.database.entities.GlucoseValue import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.iob.InMemoryGlucoseValue -import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.shared.utils.DateUtil import org.json.JSONObject -fun GlucoseValue.valueToUnitsString(units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(value) - else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) - fun GlucoseValue.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject = JSONObject() .put("device", sourceSensor.text) @@ -28,10 +23,6 @@ fun InMemoryGlucoseValue.valueToUnits(units: GlucoseUnit): Double = if (units == GlucoseUnit.MGDL) recalculated else recalculated * Constants.MGDL_TO_MMOLL -fun InMemoryGlucoseValue.valueToUnitsString(units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(recalculated) - else DecimalFormatter.to1Decimal(recalculated * Constants.MGDL_TO_MMOLL) - fun GlucoseValue.TrendArrow.directionToIcon(): Int = when (this) { GlucoseValue.TrendArrow.TRIPLE_DOWN -> R.drawable.ic_invalid diff --git a/core/main/src/main/java/info/nightscout/core/extensions/ProfileSwitchExtension.kt b/core/main/src/main/java/info/nightscout/core/extensions/ProfileSwitchExtension.kt index f813f8125f..926b52c153 100644 --- a/core/main/src/main/java/info/nightscout/core/extensions/ProfileSwitchExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/extensions/ProfileSwitchExtension.kt @@ -12,10 +12,10 @@ import info.nightscout.shared.utils.T import org.json.JSONObject import java.util.TimeZone -fun ProfileSwitch.getCustomizedName(): String { +fun ProfileSwitch.getCustomizedName(decimalFormatter: DecimalFormatter): String { var name: String = profileName if (Constants.LOCAL_PROFILE == name) { - name = DecimalFormatter.to2Decimal(ProfileSealed.PS(this).percentageBasalSum()) + "U " + name = decimalFormatter.to2Decimal(ProfileSealed.PS(this).percentageBasalSum()) + "U " } if (timeshift != 0L || percentage != 100) { name += "($percentage%" diff --git a/core/main/src/main/java/info/nightscout/core/extensions/TemporaryBasalExtension.kt b/core/main/src/main/java/info/nightscout/core/extensions/TemporaryBasalExtension.kt index cc935543b9..b146aaad22 100644 --- a/core/main/src/main/java/info/nightscout/core/extensions/TemporaryBasalExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/extensions/TemporaryBasalExtension.kt @@ -34,16 +34,16 @@ private fun TemporaryBasal.netExtendedRate(profile: Profile) = rate - profile.ge val TemporaryBasal.durationInMinutes get() = T.msecs(duration).mins() -fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil): String { +fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil, decimalFormatter: DecimalFormatter): String { return when { type == TemporaryBasal.Type.FAKE_EXTENDED -> { - DecimalFormatter.to2Decimal(rate) + "U/h (" + DecimalFormatter.to2Decimal(netExtendedRate(profile)) + "E) @" + + decimalFormatter.to2Decimal(rate) + "U/h (" + decimalFormatter.to2Decimal(netExtendedRate(profile)) + "E) @" + dateUtil.timeString(timestamp) + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } isAbsolute -> { - DecimalFormatter.to2Decimal(rate) + "U/h @" + + decimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } @@ -56,9 +56,9 @@ fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil): String { } } -fun TemporaryBasal.toStringShort(): String = - if (isAbsolute || type == TemporaryBasal.Type.FAKE_EXTENDED) DecimalFormatter.to2Decimal(rate) + "U/h" - else "${DecimalFormatter.to0Decimal(rate)}%" +fun TemporaryBasal.toStringShort(decimalFormatter: DecimalFormatter): String = + if (isAbsolute || type == TemporaryBasal.Type.FAKE_EXTENDED) decimalFormatter.to2Decimal(rate) + "U/h" + else "${decimalFormatter.to0Decimal(rate)}%" fun TemporaryBasal.iobCalc(time: Long, profile: Profile, insulinInterface: Insulin): IobTotal { if (!isValid) return IobTotal(time) diff --git a/core/main/src/main/java/info/nightscout/core/extensions/TemporaryTargetExtension.kt b/core/main/src/main/java/info/nightscout/core/extensions/TemporaryTargetExtension.kt index 7772a76014..f0879499bd 100644 --- a/core/main/src/main/java/info/nightscout/core/extensions/TemporaryTargetExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/extensions/TemporaryTargetExtension.kt @@ -3,23 +3,23 @@ package info.nightscout.core.extensions import info.nightscout.database.entities.TemporaryTarget import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.DecimalFormatter +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import java.util.concurrent.TimeUnit -fun TemporaryTarget.lowValueToUnitsToString(units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(this.lowTarget) - else DecimalFormatter.to1Decimal(this.lowTarget * Constants.MGDL_TO_MMOLL) +fun TemporaryTarget.lowValueToUnitsToString(units: GlucoseUnit, decimalFormatter: DecimalFormatter): String = + if (units == GlucoseUnit.MGDL) decimalFormatter.to0Decimal(this.lowTarget) + else decimalFormatter.to1Decimal(this.lowTarget * Constants.MGDL_TO_MMOLL) -fun TemporaryTarget.highValueToUnitsToString(units: GlucoseUnit): String = - if (units == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(this.highTarget) - else DecimalFormatter.to1Decimal(this.highTarget * Constants.MGDL_TO_MMOLL) +fun TemporaryTarget.highValueToUnitsToString(units: GlucoseUnit, decimalFormatter: DecimalFormatter): String = + if (units == GlucoseUnit.MGDL) decimalFormatter.to0Decimal(this.highTarget) + else decimalFormatter.to1Decimal(this.highTarget * Constants.MGDL_TO_MMOLL) fun TemporaryTarget.target(): Double = (this.lowTarget + this.highTarget) / 2 -fun TemporaryTarget.friendlyDescription(units: GlucoseUnit, rh: ResourceHelper): String = - Profile.toTargetRangeString(lowTarget, highTarget, GlucoseUnit.MGDL, units) + +fun TemporaryTarget.friendlyDescription(units: GlucoseUnit, rh: ResourceHelper, profileUtil: ProfileUtil): String = + profileUtil.toTargetRangeString(lowTarget, highTarget, GlucoseUnit.MGDL, units) + units.asText + "@" + rh.gs(info.nightscout.core.ui.R.string.format_mins, TimeUnit.MILLISECONDS.toMinutes(duration)) + "(" + reason.text + ")" diff --git a/core/main/src/main/java/info/nightscout/core/iob/CobInfoExtension.kt b/core/main/src/main/java/info/nightscout/core/iob/CobInfoExtension.kt index e2aa5f329b..59c87752f8 100644 --- a/core/main/src/main/java/info/nightscout/core/iob/CobInfoExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/iob/CobInfoExtension.kt @@ -4,20 +4,20 @@ import info.nightscout.interfaces.iob.CobInfo import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.shared.interfaces.ResourceHelper -fun CobInfo.generateCOBString(): String { +fun CobInfo.generateCOBString(decimalFormatter: DecimalFormatter): String { var cobStringResult = "--g" displayCob?.let { displayCob -> - cobStringResult = DecimalFormatter.to0Decimal(displayCob) + cobStringResult = decimalFormatter.to0Decimal(displayCob) if (futureCarbs > 0) - cobStringResult += "(${DecimalFormatter.to0Decimal(futureCarbs)})" + cobStringResult += "(${decimalFormatter.to0Decimal(futureCarbs)})" cobStringResult += "g" } return cobStringResult } -fun CobInfo.displayText(rh: ResourceHelper): String? = +fun CobInfo.displayText(rh: ResourceHelper, decimalFormatter: DecimalFormatter): String? = displayCob?.let { displayCob -> var cobText = rh.gs(info.nightscout.core.ui.R.string.format_carbs, displayCob.toInt()) - if (futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(futureCarbs) + ")" + if (futureCarbs > 0) cobText += "(" + decimalFormatter.to0Decimal(futureCarbs) + ")" cobText } diff --git a/core/main/src/main/java/info/nightscout/core/iob/GlucoseStatusExtension.kt b/core/main/src/main/java/info/nightscout/core/iob/GlucoseStatusExtension.kt index df11fb89ab..927195dcad 100644 --- a/core/main/src/main/java/info/nightscout/core/iob/GlucoseStatusExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/iob/GlucoseStatusExtension.kt @@ -4,11 +4,11 @@ import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.Round -fun GlucoseStatus.log(): String = "Glucose: " + DecimalFormatter.to0Decimal(glucose) + " mg/dl " + - "Noise: " + DecimalFormatter.to0Decimal(noise) + " " + - "Delta: " + DecimalFormatter.to0Decimal(delta) + " mg/dl" + - "Short avg. delta: " + " " + DecimalFormatter.to2Decimal(shortAvgDelta) + " mg/dl " + - "Long avg. delta: " + DecimalFormatter.to2Decimal(longAvgDelta) + " mg/dl" +fun GlucoseStatus.log(decimalFormatter: DecimalFormatter): String = "Glucose: " + decimalFormatter.to0Decimal(glucose) + " mg/dl " + + "Noise: " + decimalFormatter.to0Decimal(noise) + " " + + "Delta: " + decimalFormatter.to0Decimal(delta) + " mg/dl" + + "Short avg. delta: " + " " + decimalFormatter.to2Decimal(shortAvgDelta) + " mg/dl " + + "Long avg. delta: " + decimalFormatter.to2Decimal(longAvgDelta) + " mg/dl" fun GlucoseStatus.asRounded() = copy( glucose = Round.roundTo(glucose, 0.1), diff --git a/core/main/src/main/java/info/nightscout/core/profile/ProfileSealed.kt b/core/main/src/main/java/info/nightscout/core/profile/ProfileSealed.kt index e0b3dcac5d..cbf5592b0e 100644 --- a/core/main/src/main/java/info/nightscout/core/profile/ProfileSealed.kt +++ b/core/main/src/main/java/info/nightscout/core/profile/ProfileSealed.kt @@ -156,14 +156,20 @@ sealed class ProfileSealed( break } for (isf in isfBlocks) - if (!hardLimits.isInRange(Profile.toMgdl(isf.amount * 100.0 / percentage, units), HardLimits.MIN_ISF, HardLimits.MAX_ISF)) { + if (!hardLimits.isInRange(toMgdl(isf.amount * 100.0 / percentage, units), HardLimits.MIN_ISF, HardLimits.MAX_ISF)) { validityCheck.isValid = false - validityCheck.reasons.add(rh.gs(info.nightscout.core.ui.R.string.value_out_of_hard_limits, rh.gs(info.nightscout.core.ui.R.string.profile_sensitivity_value), isf.amount * 100.0 / percentage)) + validityCheck.reasons.add( + rh.gs( + info.nightscout.core.ui.R.string.value_out_of_hard_limits, + rh.gs(info.nightscout.core.ui.R.string.profile_sensitivity_value), + isf.amount * 100.0 / percentage + ) + ) break } for (target in targetBlocks) { if (!hardLimits.isInRange( - Profile.toMgdl(target.lowTarget, units), + toMgdl(target.lowTarget, units), HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1] ) @@ -173,7 +179,7 @@ sealed class ProfileSealed( break } if (!hardLimits.isInRange( - Profile.toMgdl(target.highTarget, units), + toMgdl(target.highTarget, units), HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1] ) @@ -227,23 +233,25 @@ sealed class ProfileSealed( override fun getBasal(timestamp: Long): Double = basalBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), percentage / 100.0, timeshift) override fun getIc(): Double = icBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(), 100.0 / percentage, timeshift) override fun getIc(timestamp: Long): Double = icBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), 100.0 / percentage, timeshift) - override fun getIsfMgdl(): Double = Profile.toMgdl(isfBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(), 100.0 / percentage, timeshift), units) - override fun getIsfMgdl(timestamp: Long): Double = Profile.toMgdl(isfBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), 100.0 / percentage, timeshift), units) - override fun getTargetMgdl(): Double = Profile.toMgdl(targetBlocks.targetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) - override fun getTargetLowMgdl(): Double = Profile.toMgdl(targetBlocks.lowTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) - override fun getTargetLowMgdl(timestamp: Long): Double = Profile.toMgdl(targetBlocks.lowTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), timeshift), units) - override fun getTargetHighMgdl(): Double = Profile.toMgdl(targetBlocks.highTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) - override fun getTargetHighMgdl(timestamp: Long): Double = Profile.toMgdl(targetBlocks.highTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), timeshift), units) + override fun getIsfMgdl(): Double = toMgdl(isfBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(), 100.0 / percentage, timeshift), units) + override fun getIsfMgdl(timestamp: Long): Double = toMgdl(isfBlocks.blockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), 100.0 / percentage, timeshift), units) + override fun getTargetMgdl(): Double = toMgdl(targetBlocks.targetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) + override fun getTargetLowMgdl(): Double = toMgdl(targetBlocks.lowTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) + override fun getTargetLowMgdl(timestamp: Long): Double = toMgdl(targetBlocks.lowTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), timeshift), units) + override fun getTargetHighMgdl(): Double = toMgdl(targetBlocks.highTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(), timeshift), units) + override fun getTargetHighMgdl(timestamp: Long): Double = toMgdl(targetBlocks.highTargetBlockValueBySeconds(MidnightUtils.secondsFromMidnight(timestamp), timeshift), units) override fun getBasalTimeFromMidnight(timeAsSeconds: Int): Double = basalBlocks.blockValueBySeconds(timeAsSeconds, percentage / 100.0, timeshift) override fun getIcTimeFromMidnight(timeAsSeconds: Int): Double = icBlocks.blockValueBySeconds(timeAsSeconds, 100.0 / percentage, timeshift) fun getIsfTimeFromMidnight(timeAsSeconds: Int): Double = isfBlocks.blockValueBySeconds(timeAsSeconds, 100.0 / percentage, timeshift) - override fun getIsfMgdlTimeFromMidnight(timeAsSeconds: Int): Double = Profile.toMgdl(isfBlocks.blockValueBySeconds(timeAsSeconds, 100.0 / percentage, timeshift), units) - override fun getTargetLowMgdlTimeFromMidnight(timeAsSeconds: Int): Double = Profile.toMgdl(targetBlocks.lowTargetBlockValueBySeconds(timeAsSeconds, timeshift), units) + override fun getIsfMgdlTimeFromMidnight(timeAsSeconds: Int): Double = toMgdl(isfBlocks.blockValueBySeconds(timeAsSeconds, 100.0 / percentage, timeshift), units) + override fun getTargetLowMgdlTimeFromMidnight(timeAsSeconds: Int): Double = toMgdl(targetBlocks.lowTargetBlockValueBySeconds(timeAsSeconds, timeshift), units) private fun getTargetLowTimeFromMidnight(timeAsSeconds: Int): Double = targetBlocks.lowTargetBlockValueBySeconds(timeAsSeconds, timeshift) private fun getTargetHighTimeFromMidnight(timeAsSeconds: Int): Double = targetBlocks.highTargetBlockValueBySeconds(timeAsSeconds, timeshift) - override fun getTargetHighMgdlTimeFromMidnight(timeAsSeconds: Int): Double = Profile.toMgdl(targetBlocks.highTargetBlockValueBySeconds(timeAsSeconds, timeshift), units) + override fun getTargetHighMgdlTimeFromMidnight(timeAsSeconds: Int): Double = toMgdl(targetBlocks.highTargetBlockValueBySeconds(timeAsSeconds, timeshift), units) + + override fun getIcList(rh: ResourceHelper, dateUtil: DateUtil): String = + getValuesList(icBlocks, 100.0 / percentage, DecimalFormat("0.0"), rh.gs(info.nightscout.core.ui.R.string.profile_carbs_per_unit), dateUtil) - override fun getIcList(rh: ResourceHelper, dateUtil: DateUtil): String = getValuesList(icBlocks, 100.0 / percentage, DecimalFormat("0.0"), rh.gs(info.nightscout.core.ui.R.string.profile_carbs_per_unit), dateUtil) override fun getIsfList(rh: ResourceHelper, dateUtil: DateUtil): String = getValuesList(isfBlocks, 100.0 / percentage, DecimalFormat("0.0"), units.asText + rh.gs(info.nightscout.core.ui.R.string.profile_per_unit), dateUtil) @@ -355,7 +363,7 @@ sealed class ProfileSealed( val ret = Array(shifted.size) { ProfileValue(0, 0.0) } var elapsed = 0 for (index in shifted.indices) { - ret[index] = ProfileValue(elapsed, Profile.toMgdl(shifted[index].amount, units)) + ret[index] = ProfileValue(elapsed, toMgdl(shifted[index].amount, units)) elapsed += T.msecs(shifted[index].duration).secs().toInt() } return ret @@ -377,7 +385,7 @@ sealed class ProfileSealed( val ret = Array(shifted.size) { ProfileValue(0, 0.0) } var elapsed = 0 for (index in shifted.indices) { - ret[index] = ProfileValue(elapsed, Profile.toMgdl((shifted[index].lowTarget + shifted[index].highTarget) / 2.0, units)) + ret[index] = ProfileValue(elapsed, toMgdl((shifted[index].lowTarget + shifted[index].highTarget) / 2.0, units)) elapsed += T.msecs(shifted[index].duration).secs().toInt() } return ret @@ -414,4 +422,6 @@ sealed class ProfileSealed( fun isInProgress(dateUtil: DateUtil): Boolean = dateUtil.now() in timestamp..timestamp + (duration ?: 0L) + private fun toMgdl(value: Double, units: GlucoseUnit): Double = + if (units == GlucoseUnit.MGDL) value else value * GlucoseUnit.MMOLL_TO_MGDL } diff --git a/core/main/src/main/java/info/nightscout/core/pump/PumpEnactResultExtension.kt b/core/main/src/main/java/info/nightscout/core/pump/PumpEnactResultExtension.kt index ec2ae586cb..de04dcaa2a 100644 --- a/core/main/src/main/java/info/nightscout/core/pump/PumpEnactResultExtension.kt +++ b/core/main/src/main/java/info/nightscout/core/pump/PumpEnactResultExtension.kt @@ -4,7 +4,7 @@ import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.shared.interfaces.ResourceHelper -fun PumpEnactResult.toHtml(rh: ResourceHelper): String { +fun PumpEnactResult.toHtml(rh: ResourceHelper, decimalFormatter: DecimalFormatter): String { var ret = "" + rh.gs(info.nightscout.core.ui.R.string.success) + ": " + success if (queued) { ret = rh.gs(info.nightscout.core.ui.R.string.waitingforpumpresult) @@ -33,7 +33,7 @@ fun PumpEnactResult.toHtml(rh: ResourceHelper): String { ret += "
" + rh.gs(info.nightscout.core.ui.R.string.enacted) + ": " + enacted if (comment.isNotEmpty()) ret += "
" + rh.gs(info.nightscout.core.ui.R.string.comment) + ": " + comment ret += "
" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + duration + " min" - ret += "
" + rh.gs(info.nightscout.core.ui.R.string.absolute) + ": " + DecimalFormatter.to2Decimal(absolute) + " U/h" + ret += "
" + rh.gs(info.nightscout.core.ui.R.string.absolute) + ": " + decimalFormatter.to2Decimal(absolute) + " U/h" } } } else { diff --git a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt index 91a9f088f4..7bf6c1f716 100644 --- a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt +++ b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt @@ -35,12 +35,14 @@ import info.nightscout.interfaces.pump.defs.PumpDescription import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.interfaces.utils.Round import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventRefreshOverview import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -60,6 +62,7 @@ class BolusWizard @Inject constructor( @Inject lateinit var rxBus: RxBus @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var constraintChecker: Constraints @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueue @@ -72,16 +75,15 @@ class BolusWizard @Inject constructor( @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var persistenceLayer: PersistenceLayer + @Inject lateinit var decimalFormatter: DecimalFormatter - - var timeStamp : Long + var timeStamp: Long init { injector.androidInjector().inject(this) timeStamp = dateUtil.now() } - // Intermediate var sens = 0.0 private set @@ -197,12 +199,12 @@ class BolusWizard @Inject constructor( this.totalPercentage = totalPercentage // Insulin from BG - sens = Profile.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) - targetBGLow = Profile.fromMgdlToUnits(profile.getTargetLowMgdl(), profileFunction.getUnits()) - targetBGHigh = Profile.fromMgdlToUnits(profile.getTargetHighMgdl(), profileFunction.getUnits()) + sens = profileUtil.fromMgdlToUnits(profile.getIsfMgdl()) + targetBGLow = profileUtil.fromMgdlToUnits(profile.getTargetLowMgdl()) + targetBGHigh = profileUtil.fromMgdlToUnits(profile.getTargetHighMgdl()) if (useTT && tempTarget != null) { - targetBGLow = Profile.fromMgdlToUnits(tempTarget.lowTarget, profileFunction.getUnits()) - targetBGHigh = Profile.fromMgdlToUnits(tempTarget.highTarget, profileFunction.getUnits()) + targetBGLow = profileUtil.fromMgdlToUnits(tempTarget.lowTarget) + targetBGHigh = profileUtil.fromMgdlToUnits(tempTarget.highTarget) } if (useBg && bg > 0) { bgDiff = when { @@ -218,7 +220,7 @@ class BolusWizard @Inject constructor( glucoseStatus?.let { if (useTrend) { trend = it.shortAvgDelta - insulinFromTrend = Profile.fromMgdlToUnits(trend, profileFunction.getUnits()) * 3 / sens + insulinFromTrend = profileUtil.fromMgdlToUnits(trend) * 3 / sens } } @@ -281,19 +283,19 @@ class BolusWizard @Inject constructor( val unit = profileFunction.getUnits() return BolusCalculatorResult( timestamp = dateUtil.now(), - targetBGLow = Profile.toMgdl(targetBGLow, unit), - targetBGHigh = Profile.toMgdl(targetBGHigh, unit), - isf = Profile.toMgdl(sens, unit), + targetBGLow = profileUtil.convertToMgdl(targetBGLow, unit), + targetBGHigh = profileUtil.convertToMgdl(targetBGHigh, unit), + isf = profileUtil.convertToMgdl(sens, unit), ic = ic, bolusIOB = insulinFromBolusIOB, wasBolusIOBUsed = includeBolusIOB, basalIOB = insulinFromBasalIOB, wasBasalIOBUsed = includeBasalIOB, - glucoseValue = Profile.toMgdl(bg, unit), + glucoseValue = profileUtil.convertToMgdl(bg, unit), wasGlucoseUsed = useBg && bg > 0, glucoseDifference = bgDiff, glucoseInsulin = insulinFromBG, - glucoseTrend = Profile.fromMgdlToUnits(trend, unit), + glucoseTrend = profileUtil.fromMgdlToUnits(trend, unit), wasTrendUsed = useTrend, trendInsulin = insulinFromTrend, cob = cob, @@ -318,8 +320,10 @@ class BolusWizard @Inject constructor( val actions: LinkedList = LinkedList() if (insulinAfterConstraints > 0) { val pct = if (percentageCorrection != 100) " ($percentageCorrection%)" else "" - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + rh.gs(info.nightscout.interfaces.R.string.format_insulin_units, insulinAfterConstraints).formatColor - (context, rh, info.nightscout.core.ui.R.attr.bolusColor) + pct) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + rh.gs(info.nightscout.interfaces.R.string.format_insulin_units, insulinAfterConstraints).formatColor + (context, rh, info.nightscout.core.ui.R.attr.bolusColor) + pct + ) } if (carbs > 0 && !advisor) { var timeShift = "" @@ -328,19 +332,30 @@ class BolusWizard @Inject constructor( } else if (carbTime < 0) { timeShift += " (" + rh.gs(info.nightscout.core.ui.R.string.mins, carbTime) + ")" } - actions.add(rh.gs(info.nightscout.core.ui.R.string.carbs) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_carbs, carbs).formatColor(context, rh, info.nightscout.core.ui.R.attr.carbsColor) + timeShift) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.carbs) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_carbs, carbs) + .formatColor(context, rh, info.nightscout.core.ui.R.attr.carbsColor) + timeShift + ) } if (insulinFromCOB > 0) { actions.add( - rh.gs(info.nightscout.core.ui.R.string.cobvsiob) + ": " + rh.gs(info.nightscout.core.ui.R.string.formatsignedinsulinunits, insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG).formatColor(context, rh, info.nightscout.core.ui.R.attr - .cobAlertColor) + rh.gs(info.nightscout.core.ui.R.string.cobvsiob) + ": " + rh.gs( + info.nightscout.core.ui.R.string.formatsignedinsulinunits, + insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCOB + insulinFromBG + ).formatColor( + context, rh, info.nightscout.core.ui.R.attr + .cobAlertColor + ) ) val absorptionRate = iobCobCalculator.ads.slowAbsorptionPercentage(60) if (absorptionRate > .25) actions.add(rh.gs(info.nightscout.core.ui.R.string.slowabsorptiondetected, rh.gac(context, info.nightscout.core.ui.R.attr.cobAlertColor), (absorptionRate * 100).toInt())) } if (abs(insulinAfterConstraints - calculatedTotalInsulin) > activePlugin.activePump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_constraint_applied_warn, calculatedTotalInsulin, insulinAfterConstraints).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus_constraint_applied_warn, calculatedTotalInsulin, insulinAfterConstraints) + .formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor) + ) if (config.NSCLIENT && insulinAfterConstraints > 0) actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_recorded_only).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) if (useAlarm && !advisor && carbs > 0 && carbTime > 0) @@ -362,10 +377,10 @@ class BolusWizard @Inject constructor( automation.removeAutomationEventBolusReminder() if (carbs > 0.0) automation.removeAutomationEventEatReminder() - if (sp.getBoolean(info.nightscout.core.ui.R.string.key_usebolusadvisor, false) && Profile.toMgdl(bg, profile.units) > 180 && carbs > 0 && carbTime >= 0) + if (sp.getBoolean(info.nightscout.core.ui.R.string.key_usebolusadvisor, false) && profileUtil.convertToMgdl(bg, profile.units) > 180 && carbs > 0 && carbTime >= 0) OKDialog.showYesNoCancel(ctx, rh.gs(info.nightscout.core.ui.R.string.bolus_advisor), rh.gs(info.nightscout.core.ui.R.string.bolus_advisor_message), - { bolusAdvisorProcessing(ctx) }, - { commonProcessing(ctx) } + { bolusAdvisorProcessing(ctx) }, + { commonProcessing(ctx) } ) else commonProcessing(ctx) @@ -382,7 +397,7 @@ class BolusWizard @Inject constructor( insulin = insulinAfterConstraints carbs = 0.0 context = ctx - mgdlGlucose = Profile.toMgdl(bg, profile.units) + mgdlGlucose = profileUtil.convertToMgdl(bg, profile.units) glucoseType = DetailedBolusInfo.MeterType.MANUAL carbTime = 0 bolusCalculatorResult = createBolusCalculatorResult() @@ -412,8 +427,12 @@ class BolusWizard @Inject constructor( var message = rh.gs(info.nightscout.core.ui.R.string.wizard_explain_calc, ic, sens) message += "\n" + rh.gs(info.nightscout.core.ui.R.string.wizard_explain_carbs, insulinFromCarbs) if (useTT && tempTarget != null) { - val tt = if (tempTarget?.lowTarget == tempTarget?.highTarget) tempTarget?.lowValueToUnitsToString(profile.units) - else rh.gs(info.nightscout.core.ui.R.string.wizard_explain_tt_to, tempTarget?.lowValueToUnitsToString(profile.units), tempTarget?.highValueToUnitsToString(profile.units)) + val tt = if (tempTarget?.lowTarget == tempTarget?.highTarget) tempTarget?.lowValueToUnitsToString(profile.units, decimalFormatter) + else rh.gs( + info.nightscout.core.ui.R.string.wizard_explain_tt_to, + tempTarget?.lowValueToUnitsToString(profile.units, decimalFormatter), + tempTarget?.highValueToUnitsToString(profile.units, decimalFormatter) + ) message += "\n" + rh.gs(info.nightscout.core.ui.R.string.wizard_explain_tt, tt) } if (useCob) message += "\n" + rh.gs(info.nightscout.core.ui.R.string.wizard_explain_cob, cob, insulinFromCOB) @@ -464,16 +483,16 @@ class BolusWizard @Inject constructor( insulin = insulinAfterConstraints carbs = this@BolusWizard.carbs.toDouble() context = ctx - mgdlGlucose = Profile.toMgdl(bg, profile.units) + mgdlGlucose = profileUtil.convertToMgdl(bg, profile.units) glucoseType = DetailedBolusInfo.MeterType.MANUAL carbsTimestamp = dateUtil.now() + T.mins(this@BolusWizard.carbTime.toLong()).msecs() bolusCalculatorResult = createBolusCalculatorResult() notes = this@BolusWizard.notes if (insulin > 0 || carbs > 0) { val action = when { - insulinAfterConstraints.equals(0.0) -> Action.CARBS - carbs.equals(0.0) -> Action.BOLUS - else -> Action.TREATMENT + insulinAfterConstraints == 0.0 -> Action.CARBS + carbs == 0.0 -> Action.BOLUS + else -> Action.TREATMENT } uel.log(action, if (quickWizard) Sources.QuickWizard else Sources.WizardDialog, notes, diff --git a/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt b/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt index b20b75ee2f..c26357af2e 100644 --- a/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt +++ b/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt @@ -5,9 +5,7 @@ import dagger.android.AndroidInjector import info.nightscout.core.extensions.pureProfileFromJson import info.nightscout.core.profile.ProfileSealed import info.nightscout.interfaces.Config -import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.HardLimits import info.nightscout.rx.TestAapsSchedulers import info.nightscout.rx.bus.RxBus @@ -115,18 +113,6 @@ class ProfileTest : TestBase() { Assertions.assertEquals("00:00 5,0 - 5,0 mmol", p.getTargetList(rh, dateUtil).replace(".", ",")) Assertions.assertEquals(100, p.percentage) Assertions.assertEquals(0, p.timeshift) - Assertions.assertEquals(0.1, Profile.toMgdl(0.1, GlucoseUnit.MGDL), 0.01) - Assertions.assertEquals(18.0, Profile.toMgdl(1.0, GlucoseUnit.MMOL), 0.01) - Assertions.assertEquals(1.0, Profile.toMmol(18.0, GlucoseUnit.MGDL), 0.01) - Assertions.assertEquals(18.0, Profile.toMmol(18.0, GlucoseUnit.MMOL), 0.01) - Assertions.assertEquals(18.0, Profile.fromMgdlToUnits(18.0, GlucoseUnit.MGDL), 0.01) - Assertions.assertEquals(1.0, Profile.fromMgdlToUnits(18.0, GlucoseUnit.MMOL), 0.01) - Assertions.assertEquals(18.0, Profile.toUnits(18.0, 1.0, GlucoseUnit.MGDL), 0.01) - Assertions.assertEquals(1.0, Profile.toUnits(18.0, 1.0, GlucoseUnit.MMOL), 0.01) - Assertions.assertEquals("18", Profile.toUnitsString(18.0, 1.0, GlucoseUnit.MGDL)) - Assertions.assertEquals("1,0", Profile.toUnitsString(18.0, 1.0, GlucoseUnit.MMOL).replace(".", ",")) - Assertions.assertEquals("5 - 6", Profile.toTargetRangeString(5.0, 6.0, GlucoseUnit.MGDL, GlucoseUnit.MGDL)) - Assertions.assertEquals("4", Profile.toTargetRangeString(4.0, 4.0, GlucoseUnit.MGDL, GlucoseUnit.MGDL)) //Test basal profile below limit p = ProfileSealed.Pure(pureProfileFromJson(JSONObject(belowLimitValidProfile), dateUtil)!!) diff --git a/core/main/src/test/java/info/nightscout/core/utils/DecimalFormatterTest.kt b/core/main/src/test/java/info/nightscout/core/utils/DecimalFormatterTest.kt deleted file mode 100644 index 2238d16c96..0000000000 --- a/core/main/src/test/java/info/nightscout/core/utils/DecimalFormatterTest.kt +++ /dev/null @@ -1,28 +0,0 @@ -package info.nightscout.core.utils - -import info.nightscout.interfaces.utils.DecimalFormatter -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Test - -class DecimalFormatterTest { - - @Test fun to0DecimalTest() { - Assertions.assertEquals("1", DecimalFormatter.to0Decimal(1.33).replace(",", ".")) - Assertions.assertEquals("1U", DecimalFormatter.to0Decimal(1.33, "U").replace(",", ".")) - } - - @Test fun to1DecimalTest() { - Assertions.assertEquals("1.3", DecimalFormatter.to1Decimal(1.33).replace(",", ".")) - Assertions.assertEquals("1.3U", DecimalFormatter.to1Decimal(1.33, "U").replace(",", ".")) - } - - @Test fun to2DecimalTest() { - Assertions.assertEquals("1.33", DecimalFormatter.to2Decimal(1.3333).replace(",", ".")) - Assertions.assertEquals("1.33U", DecimalFormatter.to2Decimal(1.3333, "U").replace(",", ".")) - } - - @Test fun to3DecimalTest() { - Assertions.assertEquals("1.333", DecimalFormatter.to3Decimal(1.3333).replace(",", ".")) - Assertions.assertEquals("1.333U", DecimalFormatter.to3Decimal(1.3333, "U").replace(",", ".")) - } -} \ No newline at end of file diff --git a/core/validators/build.gradle b/core/validators/build.gradle index a53ff874e0..b864f8f969 100644 --- a/core/validators/build.gradle +++ b/core/validators/build.gradle @@ -17,6 +17,5 @@ android { dependencies { implementation project(':app-wear-shared:shared') - implementation project(':core:interfaces') api "com.google.android.material:material:$material_version" } \ No newline at end of file diff --git a/core/validators/src/main/java/info/nightscout/core/validators/DefaultEditTextValidator.kt b/core/validators/src/main/java/info/nightscout/core/validators/DefaultEditTextValidator.kt index 5c6af47b62..5d0034c2ba 100644 --- a/core/validators/src/main/java/info/nightscout/core/validators/DefaultEditTextValidator.kt +++ b/core/validators/src/main/java/info/nightscout/core/validators/DefaultEditTextValidator.kt @@ -34,8 +34,7 @@ import info.nightscout.core.validators.validators.PinStrengthValidator import info.nightscout.core.validators.validators.RegexpValidator import info.nightscout.core.validators.validators.Validator import info.nightscout.core.validators.validators.WebUrlValidator -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil import javax.inject.Inject @Suppress("SpellCheckingInspection") @@ -61,7 +60,7 @@ class DefaultEditTextValidator : EditTextValidator { private var floatminNumber = 0f private var floatmaxNumber = 0f - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Suppress("unused") constructor(editTextView: EditText, context: Context) { @@ -98,7 +97,6 @@ class DefaultEditTextValidator : EditTextValidator { } private fun setEditText(editText: EditText) { - //editTextView?.removeTextChangedListener(textWatcher) editTextView = editText editText.addTextChangedListener(getTextWatcher()) } @@ -110,7 +108,9 @@ class DefaultEditTextValidator : EditTextValidator { testValidity() } - override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { /* not needed */ + } + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { if (!TextUtils.isEmpty(s) && isErrorShown) { try { @@ -156,9 +156,12 @@ class DefaultEditTextValidator : EditTextValidator { EditTextValidator.TEST_PERSONNAME -> PersonNameValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_notvalid_personname) else testErrorString) EditTextValidator.TEST_PERSONFULLNAME -> PersonFullNameValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_notvalid_personfullname) else testErrorString) EditTextValidator.TEST_MIN_LENGTH -> MinDigitLengthValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_not_a_minimum_length) else testErrorString, minLength) - EditTextValidator.TEST_BG_RANGE -> BgRangeValidator(if (TextUtils.isEmpty(testErrorString)) context.getString(R.string.error_only_numeric_digits_range_allowed, - Profile.fromMgdlToUnits(minMgdl.toDouble(), profileFunction.getUnits()).toString(), Profile.fromMgdlToUnits(maxMgdl.toDouble(), profileFunction.getUnits()).toString()) else - testErrorString, minMgdl, maxMgdl, profileFunction) + EditTextValidator.TEST_BG_RANGE -> BgRangeValidator( + if (TextUtils.isEmpty(testErrorString)) context.getString( + R.string.error_only_numeric_digits_range_allowed, + profileUtil.fromMgdlToUnits(minMgdl.toDouble()).toString(), profileUtil.fromMgdlToUnits(maxMgdl.toDouble()).toString() + ) else testErrorString, minMgdl, maxMgdl, profileUtil + ) EditTextValidator.TEST_CUSTOM -> { // must specify the fully qualified class name & an error message diff --git a/core/validators/src/main/java/info/nightscout/core/validators/ValidatingEditTextPreference.kt b/core/validators/src/main/java/info/nightscout/core/validators/ValidatingEditTextPreference.kt index eb4431f79e..ede01391e0 100644 --- a/core/validators/src/main/java/info/nightscout/core/validators/ValidatingEditTextPreference.kt +++ b/core/validators/src/main/java/info/nightscout/core/validators/ValidatingEditTextPreference.kt @@ -5,9 +5,8 @@ import android.util.AttributeSet import androidx.preference.EditTextPreference import androidx.preference.PreferenceViewHolder import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import javax.inject.Inject class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : EditTextPreference(ctx, attrs, defStyleAttr, defStyleRes) { @@ -15,7 +14,7 @@ class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAt private val validatorParameters: DefaultEditTextValidator.Parameters = obtainValidatorParameters(attrs) private var validator: DefaultEditTextValidator? = null - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil init { (ctx.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -75,14 +74,14 @@ class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAt override fun onSetInitialValue(defaultValue: Any?) { text = if (validatorParameters.testType == EditTextValidator.TEST_BG_RANGE) - Profile.fromMgdlToUnits(SafeParse.stringToDouble(getPersistedString(defaultValue as String?)), profileFunction.getUnits()).toString() + profileUtil.fromMgdlToUnits(SafeParse.stringToDouble(getPersistedString(defaultValue as String?)), profileUtil.units).toString() else getPersistedString(defaultValue as String?) } override fun persistString(value: String?): Boolean = when (validatorParameters.testType) { - EditTextValidator.TEST_BG_RANGE -> super.persistString(Profile.toMgdl(SafeParse.stringToDouble(value, 0.0), profileFunction.getUnits()).toString()) + EditTextValidator.TEST_BG_RANGE -> super.persistString(profileUtil.convertToMgdl(SafeParse.stringToDouble(value, 0.0), profileUtil.units).toString()) EditTextValidator.TEST_FLOAT_NUMERIC_RANGE -> super.persistString(SafeParse.stringToDouble(value, 0.0).toString()) else -> super.persistString(value) } diff --git a/core/validators/src/main/java/info/nightscout/core/validators/validators/BgRangeValidator.kt b/core/validators/src/main/java/info/nightscout/core/validators/validators/BgRangeValidator.kt index a490205f80..170c2dc2de 100644 --- a/core/validators/src/main/java/info/nightscout/core/validators/validators/BgRangeValidator.kt +++ b/core/validators/src/main/java/info/nightscout/core/validators/validators/BgRangeValidator.kt @@ -1,15 +1,14 @@ package info.nightscout.core.validators.validators import android.widget.EditText -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil -class BgRangeValidator(_customErrorMessage: String?, private val min: Int, private val max: Int, private val profileFunction: ProfileFunction) : Validator(_customErrorMessage) { +class BgRangeValidator(customErrorMessage: String?, private val min: Int, private val max: Int, private val profileUtil: ProfileUtil) : Validator(customErrorMessage) { override fun isValid(editText: EditText): Boolean { return try { val value = editText.text.toString().toDouble() - value in Profile.fromMgdlToUnits(min.toDouble(), profileFunction.getUnits())..Profile.fromMgdlToUnits(max.toDouble(), profileFunction.getUnits()) + value in profileUtil.fromMgdlToUnits(min.toDouble())..profileUtil.fromMgdlToUnits(max.toDouble()) } catch (e: NumberFormatException) { false } diff --git a/implementation/src/main/java/info/nightscout/implementation/DefaultValueHelperImpl.kt b/implementation/src/main/java/info/nightscout/implementation/DefaultValueHelperImpl.kt index f5ddce9f2c..30329133f3 100644 --- a/implementation/src/main/java/info/nightscout/implementation/DefaultValueHelperImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/DefaultValueHelperImpl.kt @@ -4,8 +4,7 @@ import info.nightscout.annotations.OpenForTesting import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @@ -14,7 +13,7 @@ import javax.inject.Singleton @Singleton class DefaultValueHelperImpl @Inject constructor( private val sp: SP, - private val profileFunction: ProfileFunction + private val profileUtil: ProfileUtil ) : DefaultValueHelper { /** @@ -53,9 +52,9 @@ class DefaultValueHelperImpl @Inject constructor( * @return */ override fun determineEatingSoonTT(): Double { - val units = profileFunction.getUnits() + val units = profileUtil.units var value = sp.getDouble(info.nightscout.core.utils.R.string.key_eatingsoon_target, getDefaultEatingSoonTT(units)) - value = Profile.toCurrentUnits(profileFunction, value) + value = profileUtil.valueInCurrentUnitsDetect(value) return if (value > 0) value else getDefaultEatingSoonTT(units) } @@ -70,9 +69,9 @@ class DefaultValueHelperImpl @Inject constructor( * @return */ override fun determineActivityTT(): Double { - val units = profileFunction.getUnits() + val units = profileUtil.units var value = sp.getDouble(info.nightscout.core.utils.R.string.key_activity_target, getDefaultActivityTT(units)) - value = Profile.toCurrentUnits(profileFunction, value) + value = profileUtil.valueInCurrentUnitsDetect(value) return if (value > 0) value else getDefaultActivityTT(units) } @@ -87,9 +86,9 @@ class DefaultValueHelperImpl @Inject constructor( * @return */ override fun determineHypoTT(): Double { - val units = profileFunction.getUnits() + val units = profileUtil.units var value = sp.getDouble(info.nightscout.core.utils.R.string.key_hypo_target, getDefaultHypoTT(units)) - value = Profile.toCurrentUnits(profileFunction, value) + value = profileUtil.valueInCurrentUnitsDetect(value) return if (value > 0) value else getDefaultHypoTT(units) } @@ -104,14 +103,14 @@ class DefaultValueHelperImpl @Inject constructor( override fun determineHighLine(): Double { var highLineSetting = sp.getDouble(info.nightscout.core.utils.R.string.key_high_mark, bgTargetHigh) if (highLineSetting < 1) highLineSetting = Constants.HIGH_MARK - highLineSetting = Profile.toCurrentUnits(profileFunction, highLineSetting) + highLineSetting = profileUtil.valueInCurrentUnitsDetect(highLineSetting) return highLineSetting } override fun determineLowLine(): Double { var lowLineSetting = sp.getDouble(info.nightscout.core.utils.R.string.key_low_mark, bgTargetLow) if (lowLineSetting < 1) lowLineSetting = Constants.LOW_MARK - lowLineSetting = Profile.toCurrentUnits(profileFunction, lowLineSetting) + lowLineSetting = profileUtil.valueInCurrentUnitsDetect(lowLineSetting) return lowLineSetting } } \ No newline at end of file diff --git a/implementation/src/main/java/info/nightscout/implementation/di/ImplementationModule.kt b/implementation/src/main/java/info/nightscout/implementation/di/ImplementationModule.kt index 4570cd97a0..ff7ea1f20b 100644 --- a/implementation/src/main/java/info/nightscout/implementation/di/ImplementationModule.kt +++ b/implementation/src/main/java/info/nightscout/implementation/di/ImplementationModule.kt @@ -18,6 +18,7 @@ import info.nightscout.implementation.overview.OverviewDataImpl import info.nightscout.implementation.plugin.PluginStore import info.nightscout.implementation.profile.ProfileFunctionImpl import info.nightscout.implementation.profile.ProfileStoreObject +import info.nightscout.implementation.profile.ProfileUtilImpl import info.nightscout.implementation.profiling.ProfilerImpl import info.nightscout.implementation.protection.PasswordCheckImpl import info.nightscout.implementation.protection.ProtectionCheckImpl @@ -36,6 +37,7 @@ import info.nightscout.implementation.stats.TddCalculatorImpl import info.nightscout.implementation.stats.TirCalculatorImpl import info.nightscout.implementation.storage.FileStorage import info.nightscout.implementation.userEntry.UserEntryPresentationHelperImpl +import info.nightscout.implementation.utils.DecimalFormatterImpl import info.nightscout.interfaces.LocalAlertUtils import info.nightscout.interfaces.NotificationHolder import info.nightscout.interfaces.Translator @@ -62,8 +64,10 @@ import info.nightscout.interfaces.stats.TirCalculator import info.nightscout.interfaces.storage.Storage import info.nightscout.interfaces.ui.IconsProvider import info.nightscout.interfaces.userEntry.UserEntryPresentationHelper +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits import info.nightscout.interfaces.utils.TrendCalculator +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper @Module( @@ -81,6 +85,7 @@ abstract class ImplementationModule { @Module interface Bindings { + @Binds fun bindPersistenceLayer(persistenceLayerImpl: PersistenceLayerImpl): PersistenceLayer @Binds fun bindActivePlugin(pluginStore: PluginStore): ActivePlugin @Binds fun bindOverviewData(overviewData: OverviewDataImpl): OverviewData @@ -108,9 +113,11 @@ abstract class ImplementationModule { @Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolderImpl): NotificationHolder @Binds fun bindCommandQueue(commandQueue: CommandQueueImplementation): CommandQueue @Binds fun bindsProfileFunction(profileFunctionImpl: ProfileFunctionImpl): ProfileFunction + @Binds fun bindsProfileUtil(profileUtilImpl: ProfileUtilImpl): ProfileUtil @Binds fun bindsStorage(fileStorage: FileStorage): Storage @Binds fun bindsReceiverStatusStore(receiverStatusStoreImpl: ReceiverStatusStoreImpl): ReceiverStatusStore @Binds fun bindsUserEntryPresentationHelper(userEntryPresentationHelperImpl: UserEntryPresentationHelperImpl): UserEntryPresentationHelper @Binds fun bindsGlucoseStatusProvider(glucoseStatusProviderImpl: GlucoseStatusProviderImpl): GlucoseStatusProvider + @Binds fun bindsDecimalFormatter(decimalFormatterImpl: DecimalFormatterImpl): DecimalFormatter } } \ No newline at end of file diff --git a/implementation/src/main/java/info/nightscout/implementation/iob/GlucoseStatusProviderImpl.kt b/implementation/src/main/java/info/nightscout/implementation/iob/GlucoseStatusProviderImpl.kt index 07b04c2788..5e2b1604e3 100644 --- a/implementation/src/main/java/info/nightscout/implementation/iob/GlucoseStatusProviderImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/iob/GlucoseStatusProviderImpl.kt @@ -7,6 +7,7 @@ import info.nightscout.core.iob.log import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.utils.DateUtil @@ -18,7 +19,8 @@ import kotlin.math.roundToLong class GlucoseStatusProviderImpl @Inject constructor( private val aapsLogger: AAPSLogger, private val iobCobCalculator: IobCobCalculator, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val decimalFormatter: DecimalFormatter ) : GlucoseStatusProvider { override val glucoseStatusData: GlucoseStatus? @@ -100,7 +102,7 @@ class GlucoseStatusProviderImpl @Inject constructor( shortAvgDelta = shortAverageDelta, delta = delta, longAvgDelta = average(longDeltas), - ).also { aapsLogger.debug(LTag.GLUCOSE, it.log()) }.asRounded() + ).also { aapsLogger.debug(LTag.GLUCOSE, it.log(decimalFormatter)) }.asRounded() } /* Real BG (previous) version diff --git a/implementation/src/main/java/info/nightscout/implementation/overview/OverviewDataImpl.kt b/implementation/src/main/java/info/nightscout/implementation/overview/OverviewDataImpl.kt index db143c1a1b..1aedfc003e 100644 --- a/implementation/src/main/java/info/nightscout/implementation/overview/OverviewDataImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/overview/OverviewDataImpl.kt @@ -34,6 +34,7 @@ import info.nightscout.interfaces.iob.IobTotal import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP @@ -52,7 +53,8 @@ class OverviewDataImpl @Inject constructor( private val activePlugin: ActivePlugin, private val defaultValueHelper: DefaultValueHelper, private val profileFunction: ProfileFunction, - private val repository: AppRepository + private val repository: AppRepository, + private val decimalFormatter: DecimalFormatter ) : OverviewData { override var rangeToDisplay = 6 // for graph @@ -182,7 +184,7 @@ class OverviewDataImpl @Inject constructor( profileFunction.getProfile()?.let { profile -> var temporaryBasal = iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) if (temporaryBasal?.isInProgress == false) temporaryBasal = null - temporaryBasal?.let { "T:" + it.toStringShort() } + temporaryBasal?.let { "T:" + it.toStringShort(decimalFormatter) } ?: rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, profile.getBasal()) } ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short) @@ -190,7 +192,7 @@ class OverviewDataImpl @Inject constructor( profileFunction.getProfile()?.let { profile -> iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now())?.let { temporaryBasal -> "${rh.gs(info.nightscout.core.ui.R.string.base_basal_rate_label)}: ${rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, profile.getBasal())}" + - "\n" + rh.gs(info.nightscout.core.ui.R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil) + "\n" + rh.gs(info.nightscout.core.ui.R.string.tempbasal_label) + ": " + temporaryBasal.toStringFull(profile, dateUtil, decimalFormatter) } ?: "${rh.gs(info.nightscout.core.ui.R.string.base_basal_rate_label)}: ${rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, profile.getBasal())}" } ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short) @@ -227,7 +229,7 @@ class OverviewDataImpl @Inject constructor( } ?: "" override fun extendedBolusDialogText(iobCobCalculator: IobCobCalculator): String = - iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) ?: "" + iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil, decimalFormatter) ?: "" /* * IOB, COB diff --git a/implementation/src/main/java/info/nightscout/implementation/profile/ProfileUtilImpl.kt b/implementation/src/main/java/info/nightscout/implementation/profile/ProfileUtilImpl.kt new file mode 100644 index 0000000000..4ed5ccf970 --- /dev/null +++ b/implementation/src/main/java/info/nightscout/implementation/profile/ProfileUtilImpl.kt @@ -0,0 +1,72 @@ +package info.nightscout.implementation.profile + +import info.nightscout.interfaces.GlucoseUnit +import info.nightscout.interfaces.utils.DecimalFormatter +import info.nightscout.shared.interfaces.ProfileUtil +import info.nightscout.shared.sharedPreferences.SP +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ProfileUtilImpl @Inject constructor( + private val sp: SP, + private val decimalFormatter: DecimalFormatter +) : ProfileUtil { + + override val units: GlucoseUnit + get() = + if (sp.getString(info.nightscout.core.utils.R.string.key_units, GlucoseUnit.MGDL.asText) == GlucoseUnit.MGDL.asText) GlucoseUnit.MGDL + else GlucoseUnit.MMOL + + override fun fromMgdlToUnits(valueInMgdl: Double, targetUnits: GlucoseUnit): Double = + if (targetUnits == GlucoseUnit.MGDL) valueInMgdl else valueInMgdl * GlucoseUnit.MGDL_TO_MMOLL + + override fun fromMmolToUnits(value: Double, targetUnits: GlucoseUnit): Double = + if (targetUnits == GlucoseUnit.MMOL) value else value * GlucoseUnit.MMOLL_TO_MGDL + + override fun valueInCurrentUnitsDetect(anyBg: Double): Double = + if (isMmol(anyBg)) fromMmolToUnits(anyBg, units) + else fromMgdlToUnits(anyBg, units) + + override fun stringInCurrentUnitsDetect(anyBg: Double): String = + if (isMmol(anyBg)) toUnitsString(anyBg * GlucoseUnit.MMOLL_TO_MGDL, units) + else toUnitsString(anyBg, units) + + override fun fromMgdlToStringInUnits(valueInMgdl: Double?, targetUnits: GlucoseUnit): String = + valueInMgdl?.let { toUnitsString(valueInMgdl, targetUnits) } ?: "" + + override fun fromMgdlToSignedStringInUnits(valueInMgdl: Double, targetUnits: GlucoseUnit): String = + if (targetUnits == GlucoseUnit.MGDL) (if (valueInMgdl > 0) "+" else "") + decimalFormatter.to0Decimal(valueInMgdl) + else (if (valueInMgdl > 0) "+" else "") + decimalFormatter.to1Decimal(valueInMgdl * GlucoseUnit.MGDL_TO_MMOLL) + + override fun isMgdl(anyBg: Double) = anyBg >= 39 + override fun isMmol(anyBg: Double) = anyBg < 39 + override fun unitsDetect(anyBg: Double) = if (isMgdl(anyBg)) GlucoseUnit.MGDL else GlucoseUnit.MMOL + + override fun valueInUnitsDetect(anyBg: Double, targetUnits: GlucoseUnit): Double = + if (isMmol(anyBg)) fromMmolToUnits(anyBg, targetUnits) + else fromMgdlToUnits(anyBg, targetUnits) + + override fun stringInUnitsDetect(anyBg: Double, targetUnits: GlucoseUnit): String = + if (isMmol(anyBg)) toUnitsString(anyBg * GlucoseUnit.MMOLL_TO_MGDL, targetUnits) + else toUnitsString(anyBg, targetUnits) + + override fun convertToMgdlDetect(anyBg: Double): Double = + if (isMgdl(anyBg)) anyBg else anyBg * GlucoseUnit.MMOLL_TO_MGDL + + override fun convertToMgdl(value: Double, sourceUnits: GlucoseUnit): Double = + if (sourceUnits == GlucoseUnit.MGDL) value else value * GlucoseUnit.MMOLL_TO_MGDL + + override fun convertToMmol(value: Double, sourceUnits: GlucoseUnit): Double = + if (sourceUnits == GlucoseUnit.MGDL) value * GlucoseUnit.MGDL_TO_MMOLL else value + + override fun toTargetRangeString(low: Double, high: Double, sourceUnits: GlucoseUnit, targetUnits: GlucoseUnit): String { + val lowMgdl = convertToMgdl(low, sourceUnits) + val highMgdl = convertToMgdl(high, sourceUnits) + return if (low == high) toUnitsString(lowMgdl, targetUnits) + else toUnitsString(lowMgdl, targetUnits) + " - " + toUnitsString(highMgdl, targetUnits) + } + + private fun toUnitsString(valueInMgdl: Double, targetUnits: GlucoseUnit): String = + if (targetUnits == GlucoseUnit.MGDL) decimalFormatter.to0Decimal(valueInMgdl) else decimalFormatter.to1Decimal(valueInMgdl * GlucoseUnit.MGDL_TO_MMOLL) +} \ No newline at end of file diff --git a/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt b/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt index 30bf77da5d..7d8a80b4c5 100644 --- a/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt +++ b/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt @@ -57,6 +57,7 @@ import info.nightscout.interfaces.queue.Command.CommandType import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.queue.CustomCommand import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus @@ -95,7 +96,8 @@ class CommandQueueImplementation @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val androidPermission: AndroidPermission, private val uiInteraction: UiInteraction, - private val persistenceLayer: PersistenceLayer + private val persistenceLayer: PersistenceLayer, + private val decimalFormatter: DecimalFormatter ) : CommandQueue { private val disposable = CompositeDisposable() @@ -132,7 +134,7 @@ class CommandQueueImplementation @Inject constructor( targetBlocks = nonCustomized.targetBlocks, glucoseUnit = if (it.glucoseUnit == ProfileSwitch.GlucoseUnit.MGDL) EffectiveProfileSwitch.GlucoseUnit.MGDL else EffectiveProfileSwitch.GlucoseUnit.MMOL, originalProfileName = it.profileName, - originalCustomizedName = it.getCustomizedName(), + originalCustomizedName = it.getCustomizedName(decimalFormatter), originalTimeshift = it.timeshift, originalPercentage = it.percentage, originalDuration = it.duration, @@ -234,7 +236,7 @@ class CommandQueueImplementation @Inject constructor( val tempCommandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, - config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer + config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter ) tempCommandQueue.readStatus(reason, callback) tempCommandQueue.disposable.clear() diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirCalculatorImpl.kt b/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirCalculatorImpl.kt index abd5647c32..b9317b4b52 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirCalculatorImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirCalculatorImpl.kt @@ -5,10 +5,10 @@ import android.content.Context import android.view.ViewGroup import android.widget.TableLayout import info.nightscout.database.impl.AppRepository -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.stats.DexcomTIR import info.nightscout.interfaces.stats.DexcomTirCalculator import info.nightscout.interfaces.utils.MidnightTime +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T import javax.inject.Inject @@ -16,7 +16,7 @@ import javax.inject.Singleton @Singleton class DexcomTirCalculatorImpl @Inject constructor( - private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val dateUtil: DateUtil, private val repository: AppRepository ) : DexcomTirCalculator { @@ -38,10 +38,10 @@ class DexcomTirCalculatorImpl @Inject constructor( TableLayout(context).also { layout -> val tir = calculate() layout.layoutParams = TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) - layout.addView(tir.toRangeHeaderView(context, profileFunction)) + layout.addView(tir.toRangeHeaderView(context, profileUtil)) layout.addView(tir.toTableRowHeader(context)) layout.addView(tir.toTableRow(context)) - layout.addView(tir.toSDView(context, profileFunction)) + layout.addView(tir.toSDView(context, profileUtil)) layout.addView(tir.toHbA1cView(context)) } } \ No newline at end of file diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirImpl.kt b/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirImpl.kt index 81eb8d35cb..88c58a1053 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/DexcomTirImpl.kt @@ -8,9 +8,8 @@ import android.widget.TableRow import android.widget.TextView import info.nightscout.implementation.R import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.stats.DexcomTIR +import info.nightscout.shared.interfaces.ProfileUtil import java.util.Calendar import kotlin.math.pow import kotlin.math.roundToInt @@ -86,42 +85,42 @@ class DexcomTirImpl : DexcomTIR { } @SuppressLint("SetTextI18n") - override fun toSDView(context: Context, profileFunction: ProfileFunction): TextView = + override fun toSDView(context: Context, profileUtil: ProfileUtil): TextView = TextView(context).apply { val sd = calculateSD() - text = "\n" + context.getString(R.string.std_deviation, Profile.toUnitsString(sd, sd * Constants.MGDL_TO_MMOLL, profileFunction.getUnits())) + text = "\n" + context.getString(R.string.std_deviation, profileUtil.fromMgdlToStringInUnits(sd)) setTypeface(typeface, Typeface.NORMAL) gravity = Gravity.CENTER_HORIZONTAL } - override fun toRangeHeaderView(context: Context, profileFunction: ProfileFunction): TextView = + override fun toRangeHeaderView(context: Context, profileUtil: ProfileUtil): TextView = TextView(context).apply { text = StringBuilder() .append(context.getString(R.string.detailed_14_days)) .append("\n") .append(context.getString(R.string.day_tir)) .append(" (") - .append(Profile.toUnitsString(0.0, 0.0, profileFunction.getUnits())) + .append(profileUtil.fromMgdlToStringInUnits(0.0)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, veryLowTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(veryLowTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, lowTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(lowTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, highTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(highTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, veryHighTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(veryHighTirMgdl)) .append("-∞)\n") .append(context.getString(R.string.night_tir)) .append(" (") - .append(Profile.toUnitsString(0.0, 0.0, profileFunction.getUnits())) + .append(profileUtil.fromMgdlToStringInUnits(0.0)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, veryLowTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(veryLowTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, lowTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(lowTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, highNightTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(highNightTirMgdl)) .append("-") - .append(Profile.toCurrentUnitsString(profileFunction, veryHighTirMgdl)) + .append(profileUtil.stringInCurrentUnitsDetect(veryHighTirMgdl)) .append("-∞)\n") .toString() setTypeface(typeface, Typeface.BOLD) diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/TirCalculatorImpl.kt b/implementation/src/main/java/info/nightscout/implementation/stats/TirCalculatorImpl.kt index 2e7b1ca27a..0b04b007a1 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/TirCalculatorImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/TirCalculatorImpl.kt @@ -10,11 +10,10 @@ import android.widget.TableLayout import android.widget.TextView import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.stats.TIR import info.nightscout.interfaces.stats.TirCalculator import info.nightscout.interfaces.utils.MidnightTime +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -24,7 +23,7 @@ import javax.inject.Singleton @Singleton class TirCalculatorImpl @Inject constructor( private val rh: ResourceHelper, - private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val dateUtil: DateUtil, private val repository: AppRepository ) : TirCalculator { @@ -88,7 +87,7 @@ class TirCalculatorImpl @Inject constructor( layout.layoutParams = TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) layout.addView( TextView(context).apply { - text = rh.gs(info.nightscout.core.ui.R.string.tir) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + ")" + text = rh.gs(info.nightscout.core.ui.R.string.tir) + " (" + profileUtil.stringInCurrentUnitsDetect(lowTirMgdl) + "-" + profileUtil.stringInCurrentUnitsDetect(highTirMgdl) + ")" setTypeface(typeface, Typeface.BOLD) gravity = Gravity.CENTER_HORIZONTAL setTextAppearance(android.R.style.TextAppearance_Material_Medium) @@ -97,7 +96,7 @@ class TirCalculatorImpl @Inject constructor( for (i in 0 until tir7.size()) layout.addView(tir7.valueAt(i).toTableRow(context, rh, dateUtil)) layout.addView( TextView(context).apply { - text = rh.gs(info.nightscout.core.ui.R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTirMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTirMgdl) + ")" + text = rh.gs(info.nightscout.core.ui.R.string.average) + " (" + profileUtil.stringInCurrentUnitsDetect(lowTirMgdl) + "-" + profileUtil.stringInCurrentUnitsDetect(highTirMgdl) + ")" setTypeface(typeface, Typeface.BOLD) gravity = Gravity.CENTER_HORIZONTAL setTextAppearance(android.R.style.TextAppearance_Material_Medium) @@ -106,7 +105,7 @@ class TirCalculatorImpl @Inject constructor( layout.addView(averageTir30.toTableRow(context, rh, tir30.size())) layout.addView( TextView(context).apply { - text = rh.gs(info.nightscout.core.ui.R.string.average) + " (" + Profile.toCurrentUnitsString(profileFunction, lowTitMgdl) + "-" + Profile.toCurrentUnitsString(profileFunction, highTitMgdl) + ")" + text = rh.gs(info.nightscout.core.ui.R.string.average) + " (" + profileUtil.stringInCurrentUnitsDetect(lowTitMgdl) + "-" + profileUtil.stringInCurrentUnitsDetect(highTitMgdl) + ")" setTypeface(typeface, Typeface.BOLD) gravity = Gravity.CENTER_HORIZONTAL setTextAppearance(android.R.style.TextAppearance_Material_Medium) diff --git a/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt b/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt index 825394718f..288e9f7d82 100644 --- a/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt @@ -11,11 +11,10 @@ import info.nightscout.database.entities.ValueWithUnit import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.Translator -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.userEntry.UserEntryPresentationHelper import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HtmlHelper +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import javax.inject.Inject @@ -23,9 +22,10 @@ import javax.inject.Inject @Reusable class UserEntryPresentationHelperImpl @Inject constructor( private val translator: Translator, - private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val rh: ResourceHelper, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val decimalFormatter: DecimalFormatter ) : UserEntryPresentationHelper { override fun colorId(colorGroup: ColorGroup): Int = when (colorGroup) { @@ -126,8 +126,8 @@ class UserEntryPresentationHelperImpl @Inject constructor( is ValueWithUnit.Hour -> "${valueWithUnit.value}${translator.translate(valueWithUnit)}" is ValueWithUnit.Minute -> "${valueWithUnit.value}${translator.translate(valueWithUnit)}" is ValueWithUnit.Percent -> "${valueWithUnit.value}${translator.translate(valueWithUnit)}" - is ValueWithUnit.Insulin -> DecimalFormatter.to2Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) - is ValueWithUnit.UnitPerHour -> DecimalFormatter.to2Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) + is ValueWithUnit.Insulin -> decimalFormatter.to2Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) + is ValueWithUnit.UnitPerHour -> decimalFormatter.to2Decimal(valueWithUnit.value) + translator.translate(valueWithUnit) is ValueWithUnit.SimpleInt -> valueWithUnit.value.toString() is ValueWithUnit.SimpleString -> valueWithUnit.value is ValueWithUnit.TherapyEventMeterType -> translator.translate(valueWithUnit.value) @@ -137,13 +137,13 @@ class UserEntryPresentationHelperImpl @Inject constructor( is ValueWithUnit.Timestamp -> dateUtil.dateAndTimeAndSecondsString(valueWithUnit.value) is ValueWithUnit.Mgdl -> { - if (profileFunction.getUnits() == GlucoseUnit.MGDL) DecimalFormatter.to0Decimal(valueWithUnit.value) + rh.gs(info.nightscout.core.ui.R.string.mgdl) - else DecimalFormatter.to1Decimal(valueWithUnit.value * Constants.MGDL_TO_MMOLL) + rh.gs(info.nightscout.core.ui.R.string.mmol) + if (profileUtil.units == GlucoseUnit.MGDL) decimalFormatter.to0Decimal(valueWithUnit.value) + rh.gs(info.nightscout.core.ui.R.string.mgdl) + else decimalFormatter.to1Decimal(valueWithUnit.value * Constants.MGDL_TO_MMOLL) + rh.gs(info.nightscout.core.ui.R.string.mmol) } is ValueWithUnit.Mmoll -> { - if (profileFunction.getUnits() == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(valueWithUnit.value) + rh.gs(info.nightscout.core.ui.R.string.mmol) - else DecimalFormatter.to0Decimal(valueWithUnit.value * Constants.MMOLL_TO_MGDL) + rh.gs(info.nightscout.core.ui.R.string.mgdl) + if (profileUtil.units == GlucoseUnit.MMOL) decimalFormatter.to1Decimal(valueWithUnit.value) + rh.gs(info.nightscout.core.ui.R.string.mmol) + else decimalFormatter.to0Decimal(valueWithUnit.value * Constants.MMOLL_TO_MGDL) + rh.gs(info.nightscout.core.ui.R.string.mgdl) } ValueWithUnit.UNKNOWN -> "" @@ -165,7 +165,7 @@ class UserEntryPresentationHelperImpl @Inject constructor( csvString(info.nightscout.core.ui.R.string.careportal_note), csvString(info.nightscout.core.ui.R.string.ue_string), csvString(info.nightscout.core.ui.R.string.event_time_label), - csvString(if (profileFunction.getUnits() == GlucoseUnit.MGDL) info.nightscout.core.ui.R.string.mgdl else info.nightscout.core.ui.R.string.mmol), + csvString(if (profileUtil.units == GlucoseUnit.MGDL) info.nightscout.core.ui.R.string.mgdl else info.nightscout.core.ui.R.string.mmol), csvString(info.nightscout.core.ui.R.string.shortgram), csvString(info.nightscout.core.ui.R.string.insulin_unit_shortname), csvString(info.nightscout.core.ui.R.string.profile_ins_units_per_hour), @@ -201,8 +201,8 @@ class UserEntryPresentationHelperImpl @Inject constructor( is ValueWithUnit.Hour -> hour = valueWithUnit.value.toString() is ValueWithUnit.Minute -> minute = valueWithUnit.value.toString() is ValueWithUnit.Percent -> percent = valueWithUnit.value.toString() - is ValueWithUnit.Insulin -> insulin = DecimalFormatter.to2Decimal(valueWithUnit.value) - is ValueWithUnit.UnitPerHour -> unitPerHour = DecimalFormatter.to2Decimal(valueWithUnit.value) + is ValueWithUnit.Insulin -> insulin = decimalFormatter.to2Decimal(valueWithUnit.value) + is ValueWithUnit.UnitPerHour -> unitPerHour = decimalFormatter.to2Decimal(valueWithUnit.value) is ValueWithUnit.SimpleInt -> noUnit = noUnit.addWithSeparator(valueWithUnit.value) is ValueWithUnit.SimpleString -> simpleString = simpleString.addWithSeparator(valueWithUnit.value) is ValueWithUnit.TherapyEventMeterType -> therapyEvent = therapyEvent.addWithSeparator(translator.translate(valueWithUnit.value)) @@ -212,10 +212,10 @@ class UserEntryPresentationHelperImpl @Inject constructor( is ValueWithUnit.Timestamp -> timestamp = dateUtil.dateAndTimeAndSecondsString(valueWithUnit.value) is ValueWithUnit.Mgdl -> - bg = Profile.toUnitsString(valueWithUnit.value, valueWithUnit.value * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) + bg = profileUtil.fromMgdlToStringInUnits(valueWithUnit.value) is ValueWithUnit.Mmoll -> - bg = Profile.toUnitsString(valueWithUnit.value * Constants.MMOLL_TO_MGDL, valueWithUnit.value, profileFunction.getUnits()) + bg = profileUtil.fromMgdlToStringInUnits(valueWithUnit.value * Constants.MMOLL_TO_MGDL) ValueWithUnit.UNKNOWN -> Unit } diff --git a/implementation/src/main/java/info/nightscout/implementation/utils/DecimalFormatterImpl.kt b/implementation/src/main/java/info/nightscout/implementation/utils/DecimalFormatterImpl.kt new file mode 100644 index 0000000000..db9e78da6e --- /dev/null +++ b/implementation/src/main/java/info/nightscout/implementation/utils/DecimalFormatterImpl.kt @@ -0,0 +1,33 @@ +package info.nightscout.implementation.utils + +import info.nightscout.interfaces.R +import info.nightscout.interfaces.utils.DecimalFormatter +import info.nightscout.shared.interfaces.ResourceHelper +import java.text.DecimalFormat +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class DecimalFormatterImpl @Inject constructor( + private val rh: ResourceHelper +) : DecimalFormatter { + + private val format0dec = DecimalFormat("0") + private val format1dec = DecimalFormat("0.0") + private val format2dec = DecimalFormat("0.00") + private val format3dec = DecimalFormat("0.000") + + override fun to0Decimal(value: Double): String = format0dec.format(value) + override fun to0Decimal(value: Double, unit: String): String = format0dec.format(value) + unit + override fun to1Decimal(value: Double): String = format1dec.format(value) + override fun to1Decimal(value: Double, unit: String): String = format1dec.format(value) + unit + override fun to2Decimal(value: Double): String = format2dec.format(value) + override fun to2Decimal(value: Double, unit: String): String = format2dec.format(value) + unit + override fun to3Decimal(value: Double): String = format3dec.format(value) + override fun to3Decimal(value: Double, unit: String): String = format3dec.format(value) + unit + override fun toPumpSupportedBolus(value: Double, bolusStep: Double): String = if (bolusStep <= 0.051) to2Decimal(value) else to1Decimal(value) + override fun toPumpSupportedBolusWithUnits(value: Double, bolusStep: Double): String = + if (bolusStep <= 0.051) rh.gs(R.string.format_insulin_units, value) else rh.gs(R.string.format_insulin_units1, value) + + override fun pumpSupportedBolusFormat(bolusStep: Double): DecimalFormat = if (bolusStep <= 0.051) DecimalFormat("0.00") else DecimalFormat("0.0") +} \ No newline at end of file diff --git a/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt b/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt index d4f9f6ea41..fb98cd1aaa 100644 --- a/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt @@ -7,9 +7,8 @@ import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.iob.InMemoryGlucoseValue import info.nightscout.interfaces.iob.IobCobCalculator -import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T -import info.nightscout.sharedtests.TestBase +import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @@ -19,9 +18,8 @@ import org.mockito.Mockito /** * Created by mike on 26.03.2018. */ -class GlucoseStatusTest : TestBase() { +class GlucoseStatusTest : TestBaseWithProfile() { - @Mock lateinit var dateUtil: DateUtil @Mock lateinit var iobCobCalculatorPlugin: IobCobCalculator @Mock lateinit var autosensDataStore: AutosensDataStore @@ -32,7 +30,7 @@ class GlucoseStatusTest : TestBase() { @Test fun toStringShouldBeOverloaded() { val glucoseStatus = GlucoseStatus(glucose = 0.0, noise = 0.0, delta = 0.0, shortAvgDelta = 0.0, longAvgDelta = 0.0, date = 0) - Assertions.assertEquals(true, glucoseStatus.log().contains("Delta")) + Assertions.assertEquals(true, glucoseStatus.log(decimalFormatter).contains("Delta")) } @Test fun roundTest() { @@ -42,7 +40,7 @@ class GlucoseStatusTest : TestBase() { @Test fun calculateValidGlucoseStatus() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateValidBgData()) - val glucoseStatus = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! + val glucoseStatus = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).glucoseStatusData!! Assertions.assertEquals(214.0, glucoseStatus.glucose, 0.001) Assertions.assertEquals(-2.0, glucoseStatus.delta, 0.001) Assertions.assertEquals(-2.5, glucoseStatus.shortAvgDelta, 0.001) // -2 -2.5 -3 deltas are relative to current value @@ -73,7 +71,7 @@ class GlucoseStatusTest : TestBase() { @Test fun oneRecordShouldProduceZeroDeltas() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateOneCurrentRecordBgData()) - val glucoseStatus: GlucoseStatus = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! + val glucoseStatus: GlucoseStatus = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).glucoseStatusData!! Assertions.assertEquals(214.0, glucoseStatus.glucose, 0.001) Assertions.assertEquals(0.0, glucoseStatus.delta, 0.001) Assertions.assertEquals(0.0, glucoseStatus.shortAvgDelta, 0.001) // -2 -2.5 -3 deltas are relative to current value @@ -83,19 +81,19 @@ class GlucoseStatusTest : TestBase() { @Test fun insufficientDataShouldReturnNull() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateInsufficientBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData + val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).glucoseStatusData Assertions.assertEquals(null, glucoseStatus) } @Test fun oldDataShouldReturnNull() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateOldBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData + val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).glucoseStatusData Assertions.assertEquals(null, glucoseStatus) } @Test fun returnOldDataIfAllowed() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateOldBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil).getGlucoseStatusData(true) + val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).getGlucoseStatusData(true) Assertions.assertNotEquals(null, glucoseStatus) } diff --git a/implementation/src/test/java/info/nightscout/implementation/overview/OverviewDataImplTest.kt b/implementation/src/test/java/info/nightscout/implementation/overview/OverviewDataImplTest.kt index 0b4aa6bafc..d0f483f2c9 100644 --- a/implementation/src/test/java/info/nightscout/implementation/overview/OverviewDataImplTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/overview/OverviewDataImplTest.kt @@ -6,14 +6,9 @@ import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.iob.InMemoryGlucoseValue -import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.ProfileFunction -import info.nightscout.shared.interfaces.ResourceHelper -import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T -import info.nightscout.sharedtests.TestBase +import info.nightscout.sharedtests.TestBaseWithProfile import io.reactivex.rxjava3.core.Single import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -21,14 +16,9 @@ import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito -class OverviewDataImplTest : TestBase() { +class OverviewDataImplTest : TestBaseWithProfile() { - @Mock lateinit var rh: ResourceHelper - @Mock lateinit var dateUtil: DateUtil - @Mock lateinit var sp: SP - @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var defaultValueHelper: DefaultValueHelper - @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var repository: AppRepository @Mock lateinit var autosensDataStore: AutosensDataStore @@ -40,7 +30,7 @@ class OverviewDataImplTest : TestBase() { @BeforeEach fun setup() { - sut = OverviewDataImpl(aapsLogger, rh, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, repository) + sut = OverviewDataImpl(aapsLogger, rh, dateUtil, sp, activePlugin, defaultValueHelper, profileFunction, repository, decimalFormatter) Mockito.`when`(defaultValueHelper.determineLowLine()).thenReturn(80.0) Mockito.`when`(defaultValueHelper.determineHighLine()).thenReturn(180.0) Mockito.`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) diff --git a/implementation/src/test/java/info/nightscout/implementation/profile/ProfileUtilImplTest.kt b/implementation/src/test/java/info/nightscout/implementation/profile/ProfileUtilImplTest.kt new file mode 100644 index 0000000000..b90f62884a --- /dev/null +++ b/implementation/src/test/java/info/nightscout/implementation/profile/ProfileUtilImplTest.kt @@ -0,0 +1,47 @@ +package info.nightscout.implementation.profile + +import info.nightscout.database.entities.GlucoseValue +import info.nightscout.implementation.utils.DecimalFormatterImpl +import info.nightscout.interfaces.GlucoseUnit +import info.nightscout.shared.interfaces.ResourceHelper +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.sharedtests.TestBase +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock + +class ProfileUtilImplTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var sp: SP + + private val glucoseValue = + GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = 1514766900000, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT) + + private lateinit var sut: ProfileUtilImpl + + @BeforeEach + fun setup() { + val decimalFormatter = DecimalFormatterImpl(rh) + sut = ProfileUtilImpl(sp, decimalFormatter) + } + + @Test + fun toUnitsString() { + Assertions.assertEquals("100", sut.fromMgdlToStringInUnits(glucoseValue.value, GlucoseUnit.MGDL)) + Assertions.assertEquals("5.6", sut.fromMgdlToStringInUnits(glucoseValue.value, GlucoseUnit.MMOL)) + Assertions.assertEquals(0.1, sut.convertToMgdl(0.1, GlucoseUnit.MGDL), 0.01) + Assertions.assertEquals(18.0, sut.convertToMgdl(1.0, GlucoseUnit.MMOL), 0.01) + Assertions.assertEquals(1.0, sut.convertToMmol(18.0, GlucoseUnit.MGDL), 0.01) + Assertions.assertEquals(18.0, sut.convertToMmol(18.0, GlucoseUnit.MMOL), 0.01) + Assertions.assertEquals(18.0, sut.fromMgdlToUnits(18.0, GlucoseUnit.MGDL), 0.01) + Assertions.assertEquals(1.0, sut.fromMgdlToUnits(18.0, GlucoseUnit.MMOL), 0.01) + Assertions.assertEquals(18.0, sut.fromMgdlToUnits(18.0, GlucoseUnit.MGDL), 0.01) + Assertions.assertEquals(1.0, sut.fromMgdlToUnits(18.0, GlucoseUnit.MMOL), 0.01) + Assertions.assertEquals("18", sut.fromMgdlToStringInUnits(18.0, GlucoseUnit.MGDL)) + Assertions.assertEquals("1.0", sut.fromMgdlToStringInUnits(18.0, GlucoseUnit.MMOL).replace(",", ".")) + Assertions.assertEquals("5 - 6", sut.toTargetRangeString(5.0, 6.0, GlucoseUnit.MGDL, GlucoseUnit.MGDL)) + Assertions.assertEquals("4", sut.toTargetRangeString(4.0, 4.0, GlucoseUnit.MGDL, GlucoseUnit.MGDL)) + } +} \ No newline at end of file diff --git a/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt b/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt index de9977181c..0645630ab0 100644 --- a/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt @@ -28,6 +28,7 @@ import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.queue.Command import info.nightscout.interfaces.queue.CustomCommand import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger @@ -73,11 +74,12 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { fabricPrivacy: FabricPrivacy, androidPermission: AndroidPermission, uiInteraction: UiInteraction, - persistenceLayer: PersistenceLayer + persistenceLayer: PersistenceLayer, + decimalFormatter: DecimalFormatter ) : CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, config, dateUtil, repository, fabricPrivacy, - androidPermission, uiInteraction, persistenceLayer + androidPermission, uiInteraction, persistenceLayer, decimalFormatter ) { override fun notifyAboutNewCommand(): Boolean = true @@ -120,7 +122,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, config, dateUtil, repository, - fabricPrivacy, androidPermission, uiInteraction, persistenceLayer + fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter ) testPumpPlugin = TestPumpPlugin(injector) @@ -157,7 +159,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { val commandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, - config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer + config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter ) val handler = mock(Handler::class.java) `when`(handler.post(anyObject())).thenAnswer { invocation: InvocationOnMock -> diff --git a/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt b/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt index 8695e401f6..f8e3494ac5 100644 --- a/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt @@ -55,7 +55,7 @@ class QueueThreadTest : TestBaseWithProfile() { commandQueue = CommandQueueImplementation( injector, aapsLogger, rxBus, aapsSchedulers, rh, constraintChecker, profileFunction, activePlugin, context, sp, - config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer + config, dateUtil, repository, fabricPrivacy, androidPermission, uiInteraction, persistenceLayer, decimalFormatter ) val pumpDescription = PumpDescription() diff --git a/implementation/src/test/java/info/nightscout/implementation/utils/DecimalFormatterTest.kt b/implementation/src/test/java/info/nightscout/implementation/utils/DecimalFormatterTest.kt new file mode 100644 index 0000000000..9ab168ff5b --- /dev/null +++ b/implementation/src/test/java/info/nightscout/implementation/utils/DecimalFormatterTest.kt @@ -0,0 +1,41 @@ +package info.nightscout.implementation.utils + +import info.nightscout.interfaces.utils.DecimalFormatter +import info.nightscout.shared.interfaces.ResourceHelper +import info.nightscout.sharedtests.TestBase +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock + +class DecimalFormatterTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + + private lateinit var sut: DecimalFormatter + + @BeforeEach + fun setup() { + sut = DecimalFormatterImpl(rh) + } + + @Test fun to0DecimalTest() { + Assertions.assertEquals("1", sut.to0Decimal(1.33).replace(",", ".")) + Assertions.assertEquals("1U", sut.to0Decimal(1.33, "U").replace(",", ".")) + } + + @Test fun to1DecimalTest() { + Assertions.assertEquals("1.3", sut.to1Decimal(1.33).replace(",", ".")) + Assertions.assertEquals("1.3U", sut.to1Decimal(1.33, "U").replace(",", ".")) + } + + @Test fun to2DecimalTest() { + Assertions.assertEquals("1.33", sut.to2Decimal(1.3333).replace(",", ".")) + Assertions.assertEquals("1.33U", sut.to2Decimal(1.3333, "U").replace(",", ".")) + } + + @Test fun to3DecimalTest() { + Assertions.assertEquals("1.333", sut.to3Decimal(1.3333).replace(",", ".")) + Assertions.assertEquals("1.333U", sut.to3Decimal(1.3333, "U").replace(",", ".")) + } +} \ No newline at end of file diff --git a/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt b/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt index 8aaa48ec46..bb39a0b381 100644 --- a/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt @@ -4,7 +4,6 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.core.wizard.BolusWizard import info.nightscout.implementation.iob.GlucoseStatusProviderImpl -import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.constraints.Constraint @@ -43,7 +42,8 @@ class BolusWizardTest : TestBaseWithProfile() { it.loop = loop it.dateUtil = dateUtil it.iobCobCalculator = iobCobCalculator - it.glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) + it.glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtil, decimalFormatter) + it.profileUtil = profileUtil } } } @@ -56,7 +56,6 @@ class BolusWizardTest : TestBaseWithProfile() { Mockito.`when`(profile.getIsfMgdl()).thenReturn(insulinSensitivityFactor) Mockito.`when`(profile.getIc()).thenReturn(insulinToCarbRatio) - Mockito.`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) Mockito.`when`(iobCobCalculator.calculateIobFromBolus()).thenReturn(IobTotal(System.currentTimeMillis())) Mockito.`when`(iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(System.currentTimeMillis())) testPumpPlugin.pumpDescription = PumpDescription().also { diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 0c3b483b7d..07064764eb 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -47,6 +47,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; @Inject AapsSchedulers aapsSchedulers; + @Inject DecimalFormatter decimalFormatter; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -289,7 +290,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick if (cartridgeStatus == null) return; String status; if (cartridgeStatus.isInserted()) - status = DecimalFormatter.INSTANCE.to2Decimal(cartridgeStatus.getRemainingAmount()) + "U"; + status = decimalFormatter.to2Decimal(cartridgeStatus.getRemainingAmount()) + "U"; else status = rh.gs(R.string.not_inserted); statusItems.add(getStatusItem(rh.gs(info.nightscout.core.ui.R.string.reservoir_label), status)); } @@ -297,16 +298,16 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick private void getTDDItems(List statusItems) { if (localInsightPlugin.getTotalDailyDose() == null) return; TotalDailyDose tdd = localInsightPlugin.getTotalDailyDose(); - statusItems.add(getStatusItem(rh.gs(R.string.tdd_bolus), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolus()))); - statusItems.add(getStatusItem(rh.gs(R.string.tdd_basal), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBasal()))); - statusItems.add(getStatusItem(rh.gs(info.nightscout.core.ui.R.string.tdd_total), DecimalFormatter.INSTANCE.to2Decimal(tdd.getBolusAndBasal()))); + statusItems.add(getStatusItem(rh.gs(R.string.tdd_bolus), decimalFormatter.to2Decimal(tdd.getBolus()))); + statusItems.add(getStatusItem(rh.gs(R.string.tdd_basal), decimalFormatter.to2Decimal(tdd.getBasal()))); + statusItems.add(getStatusItem(rh.gs(info.nightscout.core.ui.R.string.tdd_total), decimalFormatter.to2Decimal(tdd.getBolusAndBasal()))); } private void getBaseBasalRateItem(List statusItems) { if (localInsightPlugin.getActiveBasalRate() == null) return; ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); statusItems.add(getStatusItem(rh.gs(info.nightscout.core.ui.R.string.base_basal_rate_label), - DecimalFormatter.INSTANCE.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); + decimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); } private void getTBRItem(List statusItems) { diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt index 1e86c69c53..ab715bab53 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt @@ -41,6 +41,7 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var decimalFormatter: DecimalFormatter override var date: Long = 0 override var reason: String = "" @@ -67,7 +68,7 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) } override val carbsRequiredText: String - get() = rh.gs(info.nightscout.core.ui.R.string.carbsreq, carbsReq, carbsReqWithin) + get() = rh.gs(R.string.carbsreq, carbsReq, carbsReqWithin) override fun toString(): String { val pump = activePlugin.activePump @@ -75,18 +76,18 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) // rate var ret: String = if (rate == 0.0 && duration == 0) "${rh.gs(info.nightscout.core.ui.R.string.cancel_temp)} " else if (rate == -1.0) "${rh.gs(info.nightscout.core.ui.R.string.let_temp_basal_run)}\n" - else if (usePercent) "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + - "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " - else "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + - "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " + else if (usePercent) "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${decimalFormatter.to2Decimal(percent.toDouble())}% (${decimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + + "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " + else "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${decimalFormatter.to2Decimal(rate)} U/h (${decimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + + "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " // smb - if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh)} " + if (smb != 0.0) ret += "SMB: ${decimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump.pumpDescription.bolusStep)} " if (isCarbsRequired) { ret += "$carbsRequiredText " } // reason - ret += rh.gs(info.nightscout.core.ui.R.string.reason) + ": " + reason + ret += rh.gs(R.string.reason) + ": " + reason return ret } return if (isCarbsRequired) { @@ -99,24 +100,26 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) if (isChangeRequested) { // rate var ret: String = - if (rate == 0.0 && duration == 0) rh.gs(info.nightscout.core.ui.R.string.cancel_temp) + "
" else if (rate == -1.0) rh.gs(info.nightscout.core.ui.R.string.let_temp_basal_run) + "
" else if (usePercent) "" + rh.gs(info.nightscout.core.ui.R.string.rate) + ": " + DecimalFormatter.to2Decimal( + if (rate == 0.0 && duration == 0) rh.gs(info.nightscout.core.ui.R.string.cancel_temp) + "
" else if (rate == -1.0) rh.gs(info.nightscout.core.ui.R.string.let_temp_basal_run) + "
" else if (usePercent) "" + rh.gs( + info.nightscout.core.ui.R.string.rate + ) + ": " + decimalFormatter.to2Decimal( percent.toDouble() ) + "% " + - "(" + DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)
" + - "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + rh.gs(info.nightscout.core.ui.R.string.rate) + ": " + DecimalFormatter.to2Decimal( + "(" + decimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)
" + + "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + rh.gs(info.nightscout.core.ui.R.string.rate) + ": " + decimalFormatter.to2Decimal( rate ) + " U/h " + - "(" + DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%)
" + - "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration.toDouble()) + " min
" + "(" + decimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%)
" + + "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" // smb - if (smb != 0.0) ret += "" + "SMB" + ": " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, rh) + "
" + if (smb != 0.0) ret += "" + "SMB" + ": " + decimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump.pumpDescription.bolusStep) + "
" if (isCarbsRequired) { ret += "$carbsRequiredText
" } // reason - ret += "" + rh.gs(info.nightscout.core.ui.R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">") + ret += "" + rh.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">") return HtmlHelper.fromHtml(ret) } return if (isCarbsRequired) { diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt index e6ca338044..0c4b99e3a7 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt @@ -17,6 +17,7 @@ import info.nightscout.core.pump.toHtml import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.plugins.aps.R import info.nightscout.plugins.aps.databinding.LoopFragmentBinding @@ -42,6 +43,7 @@ class LoopFragment : DaggerFragment(), MenuProvider { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var loop: Loop @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var decimalFormatter: DecimalFormatter @Suppress("PrivatePropertyName") private val ID_MENU_RUN = 501 @@ -64,7 +66,11 @@ class LoopFragment : DaggerFragment(), MenuProvider { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - binding.swipeRefresh.setColorSchemeColors(rh.gac(context, android.R.attr.colorPrimaryDark), rh.gac(context, android.R.attr.colorPrimary), rh.gac(context,com.google.android.material.R.attr.colorSecondary)) + binding.swipeRefresh.setColorSchemeColors( + rh.gac(context, android.R.attr.colorPrimaryDark), + rh.gac(context, android.R.attr.colorPrimary), + rh.gac(context, com.google.android.material.R.attr.colorSecondary) + ) binding.swipeRefresh.setOnRefreshListener { binding.lastrun.text = rh.gs(R.string.executing) handler.post { @@ -137,9 +143,9 @@ class LoopFragment : DaggerFragment(), MenuProvider { binding.tbrrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) binding.tbrexecutionTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBREnact) - binding.tbrsetbypump.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml(rh)) } + binding.tbrsetbypump.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml(rh, decimalFormatter)) } ?: "" - binding.smbsetbypump.text = it.smbSetByPump?.let { smbSetByPump -> HtmlHelper.fromHtml(smbSetByPump.toHtml(rh)) } + binding.smbsetbypump.text = it.smbSetByPump?.let { smbSetByPump -> HtmlHelper.fromHtml(smbSetByPump.toHtml(rh, decimalFormatter)) } ?: "" var constraints = diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt index cd0c861339..9073e24655 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt @@ -22,6 +22,7 @@ import info.nightscout.plugins.aps.utils.ScriptReader import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException @@ -48,6 +49,7 @@ class DetermineBasalAdapterSMBDynamicISFJS internal constructor(private val scri @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var profileUtil: ProfileUtil private var profile = JSONObject() private var mGlucoseStatus = JSONObject() @@ -202,7 +204,7 @@ class DetermineBasalAdapterSMBDynamicISFJS internal constructor(private val scri this.profile.put("sens", profile.getIsfMgdl()) this.profile.put("max_daily_safety_multiplier", sp.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)) this.profile.put("current_basal_safety_multiplier", sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0)) - this.profile.put("lgsThreshold", Profile.toMgdl(sp.getDouble(R.string.key_lgs_threshold, 65.0))) + this.profile.put("lgsThreshold", profileUtil.convertToMgdlDetect(sp.getDouble(R.string.key_lgs_threshold, 65.0))) //mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); this.profile.put("high_temptarget_raises_sensitivity", sp.getBoolean(info.nightscout.core.utils.R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/AutotuneFragment.kt b/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/AutotuneFragment.kt index 5debba8591..53f21fb92e 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/AutotuneFragment.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/AutotuneFragment.kt @@ -30,7 +30,6 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Instantiator -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileStore import info.nightscout.interfaces.ui.UiInteraction @@ -47,6 +46,7 @@ import info.nightscout.rx.events.EventLocalProfileChanged import info.nightscout.shared.SafeParse import info.nightscout.shared.extensions.runOnUiThread import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -59,6 +59,7 @@ import javax.inject.Inject class AutotuneFragment : DaggerFragment() { @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var autotunePlugin: AutotunePlugin @Inject lateinit var autotuneFS: AutotuneFS @Inject lateinit var sp: SP @@ -389,7 +390,7 @@ class AutotuneFragment : DaggerFragment() { nl = "\n" } if (profile.isfSize > 1) { - warning += nl + rh.gs(info.nightscout.core.ui.R.string.autotune_isf_warning, profile.isfSize, Profile.fromMgdlToUnits(profile.isf, profileFunction.getUnits()), profileFunction.getUnits().asText) + warning += nl + rh.gs(info.nightscout.core.ui.R.string.autotune_isf_warning, profile.isfSize, profileUtil.fromMgdlToUnits(profile.isf), profileFunction.getUnits().asText) } } } diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/data/ATProfile.kt b/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/data/ATProfile.kt index e8861d37ef..51700b1f93 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/data/ATProfile.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/general/autotune/data/ATProfile.kt @@ -12,7 +12,6 @@ import info.nightscout.interfaces.insulin.Insulin import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileStore import info.nightscout.interfaces.profile.PureProfile import info.nightscout.interfaces.utils.Round @@ -20,6 +19,7 @@ import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -36,7 +36,7 @@ class ATProfile(profile: Profile, var localInsulin: LocalInsulin, val injector: @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var sp: SP - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var dateUtil: DateUtil @Inject lateinit var config: Config @Inject lateinit var rxBus: RxBus @@ -81,7 +81,7 @@ class ATProfile(profile: Profile, var localInsulin: LocalInsulin, val injector: fun isf(circadian: Boolean = false): JSONArray { if (circadian) return jsonArray(pumpProfile.isfBlocks, avgISF / pumpProfileAvgISF) - return jsonArray(Profile.fromMgdlToUnits(isf, profile.units)) + return jsonArray(profileUtil.fromMgdlToUnits(isf, profile.units)) } fun getProfile(circadian: Boolean = false): PureProfile { @@ -162,7 +162,7 @@ class ATProfile(profile: Profile, var localInsulin: LocalInsulin, val injector: json.put("sens", jsonArray(pumpProfile.isfBlocks, avgISF / pumpProfileAvgISF)) json.put("carbratio", jsonArray(pumpProfile.icBlocks, avgIC / pumpProfileAvgIC)) } else { - json.put("sens", jsonArray(Profile.fromMgdlToUnits(isf, profile.units))) + json.put("sens", jsonArray(profileUtil.fromMgdlToUnits(isf, profile.units))) json.put("carbratio", jsonArray(ic)) } json.put("basal", jsonArray(basal)) diff --git a/plugins/aps/src/test/java/info/nightscout/plugins/general/autotune/AutotuneCoreTest.kt b/plugins/aps/src/test/java/info/nightscout/plugins/general/autotune/AutotuneCoreTest.kt index 23e783ed27..8bf18b6d83 100644 --- a/plugins/aps/src/test/java/info/nightscout/plugins/general/autotune/AutotuneCoreTest.kt +++ b/plugins/aps/src/test/java/info/nightscout/plugins/general/autotune/AutotuneCoreTest.kt @@ -6,6 +6,7 @@ import info.nightscout.database.entities.data.TargetBlock import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.profile.PureProfile import info.nightscout.interfaces.utils.JsonHelper +import info.nightscout.plugins.general.autotune.data.ATProfile import info.nightscout.plugins.general.autotune.data.PreppedGlucose import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -85,7 +86,7 @@ class AutotuneCoreTest : TestBaseWithProfile() { * OpenAPS profile for Autotune only have one ISF value and one IC value */ @Suppress("SpellCheckingInspection") - private fun atProfileFromOapsJson(jsonObject: JSONObject, dateUtil: DateUtil, defaultUnits: String? = null): info.nightscout.plugins.general.autotune.data.ATProfile? { + private fun atProfileFromOapsJson(jsonObject: JSONObject, dateUtil: DateUtil, defaultUnits: String? = null): ATProfile? { try { min5mCarbImpact = JsonHelper.safeGetDoubleAllowNull(jsonObject, "min_5m_carbimpact") ?: return null autotuneMin = JsonHelper.safeGetDoubleAllowNull(jsonObject, "autosens_min") ?: return null @@ -122,7 +123,7 @@ class AutotuneCoreTest : TestBaseWithProfile() { timeZone = timezone, dia = dia ) - return info.nightscout.plugins.general.autotune.data.ATProfile(ProfileSealed.Pure(pure), localInsulin, profileInjector).also { it.dateUtil = dateUtil } + return ATProfile(ProfileSealed.Pure(pure), localInsulin, profileInjector).also { it.dateUtil = dateUtil; it.profileUtil = profileUtil } } catch (ignored: Exception) { return null } diff --git a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt index 85e3e50b28..96628ad1f7 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt @@ -21,13 +21,13 @@ import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.interfaces.utils.JsonHelper.safeGetDouble import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -42,6 +42,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger + @Inject lateinit var profileUtil: ProfileUtil private val disposable = CompositeDisposable() @@ -53,7 +54,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { } override fun friendlyName(): Int = R.string.starttemptarget - override fun shortDescription(): String = rh.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, rh) + override fun shortDescription(): String = rh.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, rh, profileUtil) @DrawableRes override fun icon(): Int = info.nightscout.core.main.R.drawable.ic_temptarget_high override fun doAction(callback: Callback) { @@ -110,8 +111,8 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(duration.getMinutes().toLong()), reason = TemporaryTarget.Reason.AUTOMATION, - lowTarget = Profile.toMgdl(value.value, value.units), - highTarget = Profile.toMgdl(value.value, value.units) + lowTarget = profileUtil.convertToMgdl(value.value, value.units), + highTarget = profileUtil.convertToMgdl(value.value, value.units) ) override fun isValid(): Boolean = diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/Trigger.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/Trigger.kt index 98bf38b5bb..9085e803ce 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/Trigger.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/Trigger.kt @@ -23,6 +23,7 @@ import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -35,6 +36,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var sp: SP @Inject lateinit var locationDataContainer: LastLocationDataContainer @Inject lateinit var repository: AppRepository diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt index ea7b135527..82a80eca13 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt @@ -11,7 +11,6 @@ import info.nightscout.automation.elements.LayoutBuilder import info.nightscout.automation.elements.StaticLabel import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.rx.logging.LTag import org.json.JSONObject @@ -56,7 +55,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) return false } - if (comparator.value.check(glucoseStatus.glucose, Profile.toMgdl(bg.value, bg.units))) { + if (comparator.value.check(glucoseStatus.glucose, profileUtil.convertToMgdl(bg.value, bg.units))) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt index fb1510e552..6365af9304 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt @@ -12,7 +12,6 @@ import info.nightscout.automation.elements.LayoutBuilder import info.nightscout.automation.elements.StaticLabel import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.rx.logging.LTag import org.json.JSONObject @@ -78,7 +77,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { DeltaType.LONG_AVERAGE -> glucoseStatus.longAvgDelta else -> glucoseStatus.delta } - if (comparator.value.check(calculatedDelta, Profile.toMgdl(delta.value, units))) { + if (comparator.value.check(calculatedDelta, profileUtil.convertToMgdl(delta.value, units))) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: delta is " + calculatedDelta + " " + friendlyDescription()) return true } diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt index 1493997f6d..a03333ce87 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt @@ -12,7 +12,6 @@ import info.nightscout.automation.elements.StaticLabel import info.nightscout.database.ValueWrapper import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.rx.logging.LTag import org.json.JSONObject @@ -53,7 +52,7 @@ class TriggerTempTargetValue(injector: HasAndroidInjector) : Trigger(injector) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } - if (tt is ValueWrapper.Existing && comparator.value.check(tt.value.lowTarget, Profile.toMgdl(ttValue.value, ttValue.units))) { + if (tt is ValueWrapper.Existing && comparator.value.check(tt.value.lowTarget, profileUtil.convertToMgdl(ttValue.value, ttValue.units))) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } diff --git a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt index 90bf055def..f1d920435b 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt @@ -101,6 +101,7 @@ ActionsTestBase : TestBaseWithProfile() { it.profileFunction = profileFunction it.uel = uel it.dateUtil = dateUtil + it.profileUtil = profileUtil } if (it is ActionSendSMS) { it.aapsLogger = aapsLogger diff --git a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt index f83e1f0ebc..21aed46957 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt @@ -39,8 +39,9 @@ open class TriggerTestBase : TestBaseWithProfile() { it.repository = repository it.activePlugin = activePlugin it.iobCobCalculator = iobCobCalculator - it.glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtil) + it.glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtil, decimalFormatter) it.dateUtil = dateUtil + it.profileUtil = profileUtil } if (it is TriggerBg) { it.profileFunction = profileFunction diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/setupwizard/elements/SWEditNumberWithUnits.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/setupwizard/elements/SWEditNumberWithUnits.kt index e03b1e1785..965d60e4a8 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/setupwizard/elements/SWEditNumberWithUnits.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/setupwizard/elements/SWEditNumberWithUnits.kt @@ -11,18 +11,17 @@ import info.nightscout.configuration.setupwizard.SWNumberValidator import info.nightscout.core.ui.elements.NumberPicker import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import java.text.DecimalFormat import javax.inject.Inject class SWEditNumberWithUnits(injector: HasAndroidInjector, private val init: Double, private val minMmol: Double, private val maxMmol: Double) : SWItem(injector, Type.UNIT_NUMBER) { - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil private val validator: SWNumberValidator = - if (profileFunction.getUnits() == GlucoseUnit.MMOL) + if (profileUtil.units == GlucoseUnit.MMOL) SWNumberValidator { value -> value in minMmol..maxMmol } else SWNumberValidator { value -> value in minMmol * Constants.MMOLL_TO_MGDL..maxMmol * Constants.MMOLL_TO_MGDL } @@ -46,9 +45,9 @@ class SWEditNumberWithUnits(injector: HasAndroidInjector, private val init: Doub l.setTypeface(l.typeface, Typeface.BOLD) layout.addView(l) var initValue = sp.getDouble(preferenceId, init) - initValue = Profile.toCurrentUnits(profileFunction.getUnits(), initValue) + initValue = profileUtil.valueInCurrentUnitsDetect(initValue) val numberPicker = NumberPicker(context) - if (profileFunction.getUnits() == GlucoseUnit.MMOL) + if (profileUtil.units == GlucoseUnit.MMOL) numberPicker.setParams(initValue, minMmol, maxMmol, 0.1, DecimalFormat("0.0"), false, null, watcher) else numberPicker.setParams(initValue, minMmol * Constants.MMOLL_TO_MGDL, maxMmol * Constants.MMOLL_TO_MGDL, 1.0, DecimalFormat("0"), false, null, watcher) diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt index acc1163af0..3c104f31e0 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt @@ -7,8 +7,8 @@ import info.nightscout.core.utils.extensions.putString import info.nightscout.core.utils.extensions.storeDouble import info.nightscout.core.utils.extensions.storeInt import info.nightscout.core.utils.extensions.storeString -import info.nightscout.interfaces.Config import info.nightscout.interfaces.ApsMode +import info.nightscout.interfaces.Config import info.nightscout.interfaces.constraints.Constraint import info.nightscout.interfaces.constraints.Constraints import info.nightscout.interfaces.constraints.Safety @@ -25,7 +25,6 @@ import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits import info.nightscout.interfaces.utils.Round import info.nightscout.plugins.constraints.R -import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP @@ -40,22 +39,22 @@ class SafetyPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, private val sp: SP, - private val rxBus: RxBus, private val constraintChecker: Constraints, private val activePlugin: ActivePlugin, private val hardLimits: HardLimits, private val config: Config, private val iobCobCalculator: IobCobCalculator, private val dateUtil: DateUtil, - private val uiInteraction: UiInteraction + private val uiInteraction: UiInteraction, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() - .mainType(PluginType.CONSTRAINTS) - .neverVisible(true) - .alwaysEnabled(true) - .showInList(false) - .pluginName(R.string.safety) - .preferencesId(R.xml.pref_safety), + .mainType(PluginType.CONSTRAINTS) + .neverVisible(true) + .alwaysEnabled(true) + .showInList(false) + .pluginName(R.string.safety) + .preferencesId(R.xml.pref_safety), aapsLogger, rh, injector ), Constraints, Safety { @@ -115,7 +114,11 @@ class SafetyPlugin @Inject constructor( override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { val currentBasal = profile.getBasal() val absoluteRate = currentBasal * (percentRate.originalValue().toDouble() / 100) - percentRate.addReason("Percent rate " + percentRate.originalValue() + "% recalculated to " + DecimalFormatter.to2Decimal(absoluteRate) + " U/h with current basal " + DecimalFormatter.to2Decimal(currentBasal) + " U/h", this) + percentRate.addReason( + "Percent rate " + percentRate.originalValue() + "% recalculated to " + decimalFormatter.to2Decimal(absoluteRate) + " U/h with current basal " + decimalFormatter.to2Decimal( + currentBasal + ) + " U/h", this + ) val absoluteConstraint = Constraint(absoluteRate) applyBasalConstraints(absoluteConstraint, profile) percentRate.copyReasons(absoluteConstraint) diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/actions/ActionsFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/actions/ActionsFragment.kt index b6b53de968..e47ea70c75 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/actions/ActionsFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/actions/ActionsFragment.kt @@ -29,6 +29,7 @@ import info.nightscout.interfaces.pump.actions.CustomAction import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.R import info.nightscout.plugins.databinding.ActionsFragmentBinding import info.nightscout.plugins.general.overview.ui.StatusLightHandler @@ -57,6 +58,7 @@ class ActionsFragment : DaggerFragment() { @Inject lateinit var sp: SP @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var decimalFormatter: DecimalFormatter @Inject lateinit var rh: ResourceHelper @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -243,7 +245,7 @@ class ActionsFragment : DaggerFragment() { binding.extendedBolus.visibility = View.GONE binding.extendedBolusCancel.visibility = View.VISIBLE @Suppress("SetTextI18n") - binding.extendedBolusCancel.text = rh.gs(info.nightscout.core.ui.R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil) + binding.extendedBolusCancel.text = rh.gs(info.nightscout.core.ui.R.string.cancel) + " " + activeExtendedBolus.value.toStringMedium(dateUtil, decimalFormatter) } else { binding.extendedBolus.visibility = View.VISIBLE binding.extendedBolusCancel.visibility = View.GONE @@ -259,7 +261,7 @@ class ActionsFragment : DaggerFragment() { binding.setTempBasal.visibility = View.GONE binding.cancelTempBasal.visibility = View.VISIBLE @Suppress("SetTextI18n") - binding.cancelTempBasal.text = rh.gs(info.nightscout.core.ui.R.string.cancel) + " " + activeTemp.toStringShort() + binding.cancelTempBasal.text = rh.gs(info.nightscout.core.ui.R.string.cancel) + " " + activeTemp.toStringShort(decimalFormatter) } else { binding.setTempBasal.visibility = View.VISIBLE binding.cancelTempBasal.visibility = View.GONE diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt index 4ebf5c77ad..842bbcabc4 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt @@ -28,7 +28,6 @@ import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector import dagger.android.support.DaggerFragment import info.nightscout.core.extensions.directionToIcon -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.graph.OverviewData import info.nightscout.core.iob.displayText import info.nightscout.core.profile.ProfileSealed @@ -60,13 +59,13 @@ import info.nightscout.interfaces.overview.OverviewMenus import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.source.DexcomBoyda import info.nightscout.interfaces.source.XDripSource import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.interfaces.utils.TrendCalculator import info.nightscout.plugins.R @@ -99,6 +98,7 @@ import info.nightscout.rx.weardata.EventData import info.nightscout.shared.extensions.runOnUiThread import info.nightscout.shared.extensions.toVisibility import info.nightscout.shared.extensions.toVisibilityKeepSpace +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -120,6 +120,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var constraintChecker: Constraints @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var processedDeviceStatusData: ProcessedDeviceStatusData @@ -145,6 +146,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var automation: Automation @Inject lateinit var bgQualityCheck: BgQualityCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var decimalFormatter: DecimalFormatter private val disposable = CompositeDisposable() @@ -777,7 +779,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @SuppressLint("SetTextI18n") fun updateBg() { - val units = profileFunction.getUnits() val lastBg = overviewData.lastBg(iobCobCalculator.ads) val lastBgColor = overviewData.lastBgColor(context, iobCobCalculator.ads) val isActualBg = overviewData.isActualBg(iobCobCalculator.ads) @@ -787,7 +788,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val lastBgDescription = overviewData.lastBgDescription(iobCobCalculator.ads) runOnUiThread { _binding ?: return@runOnUiThread - binding.infoLayout.bg.text = lastBg?.valueToUnitsString(units) ?: "" + binding.infoLayout.bg.text = profileUtil.fromMgdlToStringInUnits(lastBg?.value) binding.infoLayout.bg.setTextColor(lastBgColor) trendArrow?.let { binding.infoLayout.arrow.setImageResource(it.directionToIcon()) } binding.infoLayout.arrow.visibility = (trendArrow != null).toVisibilityKeepSpace() @@ -795,11 +796,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.infoLayout.arrow.contentDescription = lastBgDescription + " " + rh.gs(info.nightscout.core.ui.R.string.and) + " " + trendDescription if (glucoseStatus != null) { - binding.infoLayout.deltaLarge.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + binding.infoLayout.deltaLarge.text = profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta) binding.infoLayout.deltaLarge.setTextColor(lastBgColor) - binding.infoLayout.delta.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) - binding.infoLayout.avgDelta.text = Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units) - binding.infoLayout.longAvgDelta.text = Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units) + binding.infoLayout.delta.text = profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta) + binding.infoLayout.avgDelta.text = profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.shortAvgDelta) + binding.infoLayout.longAvgDelta.text = profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.longAvgDelta) } else { binding.infoLayout.deltaLarge.text = "" binding.infoLayout.delta.text = "Δ " + rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short) @@ -915,7 +916,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList private fun updateIobCob() { val iobText = overviewData.iobText(iobCobCalculator) val iobDialogText = overviewData.iobDialogText(iobCobCalculator) - val displayText = overviewData.cobInfo(iobCobCalculator).displayText(rh) + val displayText = overviewData.cobInfo(iobCobCalculator).displayText(rh, decimalFormatter) val lastCarbsTime = overviewData.lastCarbsTime runOnUiThread { _binding ?: return@runOnUiThread @@ -954,7 +955,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.tempTarget, info.nightscout.core.ui.R.attr.ribbonTextWarningColor, info.nightscout.core.ui.R.attr.ribbonWarningColor, - Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh) + profileUtil.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh) ) } else { // If the target is not the same as set in the profile then oref has overridden it @@ -967,14 +968,14 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.tempTarget, info.nightscout.core.ui.R.attr.ribbonTextWarningColor, info.nightscout.core.ui.R.attr.tempTargetBackgroundColor, - Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units) + profileUtil.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units) ) } else { setRibbon( binding.tempTarget, info.nightscout.core.ui.R.attr.ribbonTextDefaultColor, info.nightscout.core.ui.R.attr.ribbonDefaultColor, - Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units) + profileUtil.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units) ) } } @@ -1110,8 +1111,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.infoLayout.variableSensitivity.text = String.format( Locale.getDefault(), "%1$.1f→%2$.1f", - Profile.toUnits(isfMgdl, isfMgdl * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()), - Profile.toUnits(variableSens, variableSens * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) + profileUtil.fromMgdlToUnits(isfMgdl, profileFunction.getUnits()), + profileUtil.fromMgdlToUnits(variableSens, profileFunction.getUnits()) ) binding.infoLayout.variableSensitivity.visibility = View.VISIBLE } else binding.infoLayout.variableSensitivity.visibility = View.GONE diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt index eed06a06a8..b55d8710aa 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt @@ -32,7 +32,8 @@ class StatusLightHandler @Inject constructor( private val warnColors: WarnColors, private val config: Config, private val repository: AppRepository, - private val tddCalculator: TddCalculator + private val tddCalculator: TddCalculator, + private val decimalFormatter: DecimalFormatter ) { private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) @@ -112,7 +113,7 @@ class StatusLightHandler @Inject constructor( private fun handleLevel(view: TextView?, criticalSetting: Int, criticalDefaultValue: Double, warnSetting: Int, warnDefaultValue: Double, level: Double, units: String) { val resUrgent = sp.getDouble(criticalSetting, criticalDefaultValue) val resWarn = sp.getDouble(warnSetting, warnDefaultValue) - if (level > 0) view?.text = " " + DecimalFormatter.to0Decimal(level, units) + if (level > 0) view?.text = " " + decimalFormatter.to0Decimal(level, units) else view?.text = "" warnColors.setColorInverse(view, level, resWarn, resUrgent) } @@ -124,7 +125,7 @@ class StatusLightHandler @Inject constructor( warnDefaultValue: Double, level: Double, units: String, maxReading: Double ) { if (level >= maxReading) { - view?.text = DecimalFormatter.to0Decimal(maxReading, units) + view?.text = decimalFormatter.to0Decimal(maxReading, units) view?.setTextColor(rh.gac(view.context, info.nightscout.core.ui.R.attr.defaultTextColor)) } else { handleLevel(view, criticalSetting, criticalDefaultValue, warnSetting, warnDefaultValue, level, units) @@ -139,7 +140,7 @@ class StatusLightHandler @Inject constructor( tddCalculator.calculate(therapyEvent.value.timestamp, dateUtil.now(), allowMissingData = false)?.totalAmount ?: 0.0 } else 0.0 runOnUiThread { - view?.text = DecimalFormatter.to0Decimal(usage, units) + view?.text = decimalFormatter.to0Decimal(usage, units) } } } diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index 23f3eacc8a..765f50b76c 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -8,12 +8,10 @@ import androidx.core.app.NotificationCompat import androidx.core.app.RemoteInput import dagger.android.HasAndroidInjector import info.nightscout.core.extensions.toStringShort -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.iob.generateCOBString import info.nightscout.core.iob.round import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.Config -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.NotificationHolder import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator @@ -21,7 +19,6 @@ import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.ui.IconsProvider import info.nightscout.interfaces.utils.DecimalFormatter @@ -33,6 +30,7 @@ import info.nightscout.rx.events.EventInitializationChanged import info.nightscout.rx.events.EventPreferenceChange import info.nightscout.rx.events.EventRefreshOverview import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -47,6 +45,7 @@ class PersistentNotificationPlugin @Inject constructor( rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val fabricPrivacy: FabricPrivacy, private val activePlugins: ActivePlugin, private val iobCobCalculator: IobCobCalculator, @@ -56,7 +55,8 @@ class PersistentNotificationPlugin @Inject constructor( private val dummyServiceHelper: DummyServiceHelper, private val iconsProvider: IconsProvider, private val glucoseStatusProvider: GlucoseStatusProvider, - private val config: Config + private val config: Config, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) @@ -121,15 +121,14 @@ class PersistentNotificationPlugin @Inject constructor( var unreadConversationBuilder: NotificationCompat.CarExtender.UnreadConversation.Builder? = null if (profileFunction.isProfileValid("Notification")) { var line1aa: String - val units = profileFunction.getUnits() val lastBG = iobCobCalculator.ads.lastBg() val glucoseStatus = glucoseStatusProvider.glucoseStatusData if (lastBG != null) { - line1aa = lastBG.valueToUnitsString(units) + line1aa = profileUtil.fromMgdlToStringInUnits(lastBG.value) line1 = line1aa if (glucoseStatus != null) { - line1 += (" Δ" + Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) - + " avgΔ" + Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units)) + line1 += (" Δ" + profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta) + + " avgΔ" + profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.shortAvgDelta)) line1aa += " " + lastBG.trendArrow.symbol } else { line1 += " " + @@ -143,22 +142,28 @@ class PersistentNotificationPlugin @Inject constructor( } val activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()) if (activeTemp != null) { - line1 += " " + activeTemp.toStringShort() - line1aa += " " + activeTemp.toStringShort() + "." + line1 += " " + activeTemp.toStringShort(decimalFormatter) + line1aa += " " + activeTemp.toStringShort(decimalFormatter) + "." } //IOB val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() line2 = - rh.gs(info.nightscout.core.ui.R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + rh.gs(info.nightscout.core.ui.R.string.cob) + ": " + iobCobCalculator.getCobInfo( + rh.gs(info.nightscout.core.ui.R.string.treatments_iob_label_string) + " " + decimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + rh.gs( + info.nightscout.core.ui.R + .string.cob + ) + ": " + iobCobCalculator.getCobInfo( "PersistentNotificationPlugin" - ).generateCOBString() + ).generateCOBString(decimalFormatter) val line2aa = - rh.gs(info.nightscout.core.ui.R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + rh.gs(info.nightscout.core.ui.R.string.cob) + ": " + iobCobCalculator.getCobInfo( + rh.gs(info.nightscout.core.ui.R.string.treatments_iob_label_string) + " " + decimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + rh.gs( + info.nightscout.core.ui.R + .string.cob + ) + ": " + iobCobCalculator.getCobInfo( "PersistentNotificationPlugin" - ).generateCOBString() + "." - line3 = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" - var line3aa = DecimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h." + ).generateCOBString(decimalFormatter) + "." + line3 = decimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h" + var line3aa = decimalFormatter.to2Decimal(pump.baseBasalRate) + " U/h." line3 += " - " + profileFunction.getProfileName() line3aa += " - " + profileFunction.getProfileName() + "." /// For Android Auto diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 9f5bf71c88..b05207344e 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -12,7 +12,6 @@ import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting import info.nightscout.core.events.EventNewNotification -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.iob.generateCOBString import info.nightscout.core.iob.round import info.nightscout.core.utils.fabric.FabricPrivacy @@ -45,7 +44,6 @@ import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.DetailedBolusInfo import info.nightscout.interfaces.pump.PumpSync @@ -65,6 +63,7 @@ import info.nightscout.rx.events.EventRefreshOverview import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -95,6 +94,7 @@ class SmsCommunicatorPlugin @Inject constructor( private val constraintChecker: Constraints, private val rxBus: RxBus, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val fabricPrivacy: FabricPrivacy, private val activePlugin: ActivePlugin, private val commandQueue: CommandQueue, @@ -106,7 +106,8 @@ class SmsCommunicatorPlugin @Inject constructor( private val dateUtil: DateUtil, private val uel: UserEntryLogger, private val glucoseStatusProvider: GlucoseStatusProvider, - private val repository: AppRepository + private val repository: AppRepository, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) @@ -353,23 +354,23 @@ class SmsCommunicatorPlugin @Inject constructor( val actualBG = iobCobCalculator.ads.actualBg() val lastBG = iobCobCalculator.ads.lastBg() var reply = "" - val units = profileFunction.getUnits() + val units = profileUtil.units if (actualBG != null) { - reply = rh.gs(R.string.sms_actual_bg) + " " + actualBG.valueToUnitsString(units) + ", " + reply = rh.gs(R.string.sms_actual_bg) + " " + profileUtil.fromMgdlToStringInUnits(actualBG.value) + ", " } else if (lastBG != null) { val agoMilliseconds = dateUtil.now() - lastBG.timestamp val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt() - reply = rh.gs(R.string.sms_last_bg) + " " + lastBG.valueToUnitsString(units) + " " + rh.gs(R.string.sms_min_ago, agoMin) + ", " + reply = rh.gs(R.string.sms_last_bg) + " " + profileUtil.valueInCurrentUnitsDetect(lastBG.value) + " " + rh.gs(R.string.sms_min_ago, agoMin) + ", " } val glucoseStatus = glucoseStatusProvider.glucoseStatusData - if (glucoseStatus != null) reply += rh.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) + " " + profileUtil.fromMgdlToUnits(glucoseStatus.delta) + " " + units + ", " val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() val cobInfo = iobCobCalculator.getCobInfo("SMS COB") - reply += (rh.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" - + rh.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " - + rh.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " - + rh.gs(info.nightscout.core.ui.R.string.cob) + ": " + cobInfo.generateCOBString()) + reply += (rh.gs(R.string.sms_iob) + " " + decimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + + rh.gs(R.string.sms_bolus) + " " + decimalFormatter.to2Decimal(bolusIob.iob) + "U " + + rh.gs(R.string.sms_basal) + " " + decimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + + rh.gs(info.nightscout.core.ui.R.string.cob) + ": " + cobInfo.generateCOBString(decimalFormatter)) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -966,8 +967,8 @@ class SmsCommunicatorPlugin @Inject constructor( timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), reason = TemporaryTarget.Reason.EATING_SOON, - lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(eatingSoonTT, profileUtil.units), + highTarget = profileUtil.convertToMgdl(eatingSoonTT, profileUtil.units) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } @@ -976,8 +977,8 @@ class SmsCommunicatorPlugin @Inject constructor( aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) }) val tt = if (currentProfile.units == GlucoseUnit.MMOL) { - DecimalFormatter.to1Decimal(eatingSoonTT) - } else DecimalFormatter.to0Decimal(eatingSoonTT) + decimalFormatter.to1Decimal(eatingSoonTT) + } else decimalFormatter.to0Decimal(eatingSoonTT) replyText += "\n" + rh.gs(R.string.smscommunicator_meal_bolus_delivered_tt, tt, eatingSoonTTDuration) } } @@ -1078,7 +1079,7 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) { override fun run() { - val units = profileFunction.getUnits() + val units = profileUtil.units var keyDuration = 0 var defaultTargetDuration = 0 var keyTarget = 0 @@ -1116,15 +1117,15 @@ class SmsCommunicatorPlugin @Inject constructor( var ttDuration = sp.getInt(keyDuration, defaultTargetDuration) ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration var tt = sp.getDouble(keyTarget, if (units == GlucoseUnit.MMOL) defaultTargetMMOL else defaultTargetMGDL) - tt = Profile.toCurrentUnits(profileFunction, tt) + tt = profileUtil.valueInCurrentUnitsDetect(tt) tt = if (tt > 0) tt else if (units == GlucoseUnit.MMOL) defaultTargetMMOL else defaultTargetMGDL disposable += repository.runTransactionForResult( InsertAndCancelCurrentTemporaryTargetTransaction( timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(ttDuration.toLong()), reason = reason, - lowTarget = Profile.toMgdl(tt, profileFunction.getUnits()), - highTarget = Profile.toMgdl(tt, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(tt, profileUtil.units), + highTarget = profileUtil.convertToMgdl(tt, profileUtil.units) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } @@ -1132,7 +1133,7 @@ class SmsCommunicatorPlugin @Inject constructor( }, { aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) }) - val ttString = if (units == GlucoseUnit.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) + val ttString = if (units == GlucoseUnit.MMOL) decimalFormatter.to1Decimal(tt) else decimalFormatter.to0Decimal(tt) val replyText = rh.gs(R.string.smscommunicator_tt_set, ttString, ttDuration) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) uel.log( diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt index dd75d51ed5..c461fbab26 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -6,7 +6,6 @@ import dagger.android.HasAndroidInjector import info.nightscout.core.extensions.convertedToAbsolute import info.nightscout.core.extensions.toStringShort import info.nightscout.core.extensions.valueToUnits -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.graph.data.GlucoseValueDataPoint import info.nightscout.core.iob.generateCOBString import info.nightscout.core.iob.round @@ -64,6 +63,7 @@ import info.nightscout.rx.events.EventWearUpdateGui import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.rx.weardata.EventData +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -96,6 +96,7 @@ class DataHandlerMobile @Inject constructor( private val repository: AppRepository, private val glucoseStatusProvider: GlucoseStatusProvider, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val loop: Loop, private val processedDeviceStatusData: ProcessedDeviceStatusData, private val receiverStatusStore: ReceiverStatusStore, @@ -110,7 +111,8 @@ class DataHandlerMobile @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val uiInteraction: UiInteraction, private val persistenceLayer: PersistenceLayer, - private val importExportPrefs: ImportExportPrefs + private val importExportPrefs: ImportExportPrefs, + private val decimalFormatter: DecimalFormatter ) { private val disposable = CompositeDisposable() @@ -875,7 +877,7 @@ class DataHandlerMobile @Inject constructor( val finalLastRun = loop.lastRun if (finalLastRun?.request?.hasPredictions == true && finalLastRun.constraintsProcessed != null) { val predArray = finalLastRun.constraintsProcessed!!.predictions - .stream().map { bg: GlucoseValue -> GlucoseValueDataPoint(bg, profileFunction, rh) } + .stream().map { bg: GlucoseValue -> GlucoseValueDataPoint(bg, profileUtil, rh) } .collect(Collectors.toList()) if (predArray.isNotEmpty()) for (bg in predArray) if (bg.data.value > 39) @@ -904,15 +906,18 @@ class DataHandlerMobile @Inject constructor( if (config.appInitialized && profile != null) { val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() - iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) - iobDetail = "(${DecimalFormatter.to2Decimal(bolusIob.iob)}|${DecimalFormatter.to2Decimal(basalIob.basaliob)})" - cobString = iobCobCalculator.getCobInfo("WatcherUpdaterService").generateCOBString() + iobSum = decimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + iobDetail = "(${decimalFormatter.to2Decimal(bolusIob.iob)}|${decimalFormatter.to2Decimal(basalIob.basaliob)})" + cobString = iobCobCalculator.getCobInfo("WatcherUpdaterService").generateCOBString(decimalFormatter) currentBasal = - iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.toStringShort() ?: rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, profile.getBasal()) + iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.toStringShort(decimalFormatter) ?: rh.gs( + info.nightscout.core.ui.R.string.pump_base_basal_rate, profile + .getBasal() + ) //bgi - val bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) - bgiString = "" + (if (bgi >= 0) "+" else "") + DecimalFormatter.to1Decimal(bgi) + val bgi = -(bolusIob.activity + basalIob.activity) * 5 * profileUtil.fromMgdlToUnits(profile.getIsfMgdl()) + bgiString = "" + (if (bgi >= 0) "+" else "") + decimalFormatter.to1Decimal(bgi) status = generateStatusString(profile) } @@ -945,18 +950,19 @@ class DataHandlerMobile @Inject constructor( private fun deltaString(deltaMGDL: Double, deltaMMOL: Double, units: GlucoseUnit): String { var deltaString = if (deltaMGDL >= 0) "+" else "-" deltaString += if (units == GlucoseUnit.MGDL) { - DecimalFormatter.to0Decimal(abs(deltaMGDL)) + decimalFormatter.to0Decimal(abs(deltaMGDL)) } else { - DecimalFormatter.to1Decimal(abs(deltaMMOL)) + decimalFormatter.to1Decimal(abs(deltaMMOL)) } return deltaString } + private fun deltaStringDetailed(deltaMGDL: Double, deltaMMOL: Double, units: GlucoseUnit): String { var deltaStringDetailed = if (deltaMGDL >= 0) "+" else "-" deltaStringDetailed += if (units == GlucoseUnit.MGDL) { - DecimalFormatter.to1Decimal(abs(deltaMGDL)) + decimalFormatter.to1Decimal(abs(deltaMGDL)) } else { - DecimalFormatter.to2Decimal(abs(deltaMMOL)) + decimalFormatter.to2Decimal(abs(deltaMMOL)) } return deltaStringDetailed } @@ -964,12 +970,12 @@ class DataHandlerMobile @Inject constructor( private fun getSingleBG(glucoseValue: InMemoryGlucoseValue): EventData.SingleBg { val glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(true) val units = profileFunction.getUnits() - val lowLine = Profile.toMgdl(defaultValueHelper.determineLowLine(), units) - val highLine = Profile.toMgdl(defaultValueHelper.determineHighLine(), units) + val lowLine = profileUtil.convertToMgdl(defaultValueHelper.determineLowLine(), units) + val highLine = profileUtil.convertToMgdl(defaultValueHelper.determineHighLine(), units) return EventData.SingleBg( timeStamp = glucoseValue.timestamp, - sgvString = glucoseValue.valueToUnitsString(units), + sgvString = profileUtil.stringInCurrentUnitsDetect(glucoseValue.value), glucoseUnits = units.asText, slopeArrow = trendCalculator.getTrendArrow(glucoseValue).symbol, delta = glucoseStatus?.let { deltaString(it.delta, it.delta * Constants.MGDL_TO_MMOLL, units) } ?: "--", @@ -996,17 +1002,14 @@ class DataHandlerMobile @Inject constructor( //Check for Temp-Target: val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { - val target = Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, GlucoseUnit.MGDL, profileFunction.getUnits()) + val target = profileUtil.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, GlucoseUnit.MGDL) ret += rh.gs(R.string.temp_target) + ": " + target - ret += "\n"+ rh.gs(R.string.until) + ": " + dateUtil.timeString(tempTarget.value.end) + ret += "\n" + rh.gs(R.string.until) + ": " + dateUtil.timeString(tempTarget.value.end) ret += "\n\n" } ret += rh.gs(R.string.default_range) + ": " - ret += Profile.fromMgdlToUnits(profile.getTargetLowMgdl(), profileFunction.getUnits()).toString() + " - " + Profile.fromMgdlToUnits( - profile.getTargetHighMgdl(), - profileFunction.getUnits() - ) - ret += " " + rh.gs(R.string.target) + ": " + Profile.fromMgdlToUnits(profile.getTargetMgdl(), profileFunction.getUnits()) + ret += profileUtil.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL) + ret += " " + rh.gs(R.string.target) + ": " + profileUtil.fromMgdlToStringInUnits(profile.getTargetMgdl()) return ret } @@ -1145,8 +1148,8 @@ class DataHandlerMobile @Inject constructor( timestamp = System.currentTimeMillis(), duration = TimeUnit.MINUTES.toMillis(command.duration.toLong()), reason = TemporaryTarget.Reason.WEAR, - lowTarget = Profile.toMgdl(command.low, profileFunction.getUnits()), - highTarget = Profile.toMgdl(command.high, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(command.low, profileFunction.getUnits()), + highTarget = profileUtil.convertToMgdl(command.high, profileFunction.getUnits()) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } @@ -1253,11 +1256,11 @@ class DataHandlerMobile @Inject constructor( duration = actionHeartRate.duration, timestamp = actionHeartRate.timestamp, beatsPerMinute = actionHeartRate.beatsPerMinute, - device = actionHeartRate.device) + device = actionHeartRate.device + ) repository.runTransaction(InsertOrUpdateHeartRateTransaction(hr)).blockingAwait() } - private fun handleGetCustomWatchface(command: EventData.ActionGetCustomWatchface) { val customWatchface = command.customWatchface aapsLogger.debug(LTag.WEAR, "Custom Watchface received from ${command.sourceNodeId}: ${customWatchface.customWatchfaceData.json}") diff --git a/plugins/main/src/main/java/info/nightscout/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index d5fd54b272..84df87bdd7 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -79,7 +79,8 @@ class IobCobCalculatorPlugin @Inject constructor( private val dateUtil: DateUtil, private val repository: AppRepository, val overviewData: OverviewData, - private val calculationWorkflow: CalculationWorkflow + private val calculationWorkflow: CalculationWorkflow, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() .mainType(PluginType.GENERAL) @@ -368,7 +369,7 @@ class IobCobCalculatorPlugin @Inject constructor( val sb = StringBuilder() sb.append("[") for (i in array) { - sb.append(DecimalFormatter.to2Decimal(i.iob)) + sb.append(decimalFormatter.to2Decimal(i.iob)) sb.append(", ") } sb.append("]") diff --git a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt index 633e8713b8..1d2b6d4728 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt @@ -19,7 +19,6 @@ import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.ui.UiInteraction @@ -35,6 +34,7 @@ import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -52,12 +52,14 @@ class ProfileFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var profilePlugin: ProfilePlugin @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var hardLimits: HardLimits @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uel: UserEntryLogger @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var decimalFormatter: DecimalFormatter private var disposable: CompositeDisposable = CompositeDisposable() private var inMenu = false @@ -89,7 +91,7 @@ class ProfileFragment : DaggerFragment() { private fun sumLabel(): String { val profile = profilePlugin.getEditedProfile() val sum = profile?.let { ProfileSealed.Pure(profile).baseBasalSum() } ?: 0.0 - return " ∑" + DecimalFormatter.to2Decimal(sum) + rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname) + return " ∑" + decimalFormatter.to2Decimal(sum) + rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname) } private var _binding: ProfileFragmentBinding? = null @@ -207,19 +209,19 @@ class ProfileFragment : DaggerFragment() { ) } else { val isfRange = doubleArrayOf( - roundUp(Profile.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL)), - roundDown(Profile.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL)) + roundUp(profileUtil.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL)), + roundDown(profileUtil.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL)) ) TimeListEdit(requireContext(), aapsLogger, dateUtil, requireView(), R.id.isf_holder, "ISF", rh.gs(info.nightscout.core.ui.R.string.isf_long_label), currentProfile.isf, null, isfRange, null, 0.1, DecimalFormat ("0.0"), save) val range1 = doubleArrayOf( - roundUp(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[0], GlucoseUnit.MMOL)), - roundDown(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[1], GlucoseUnit.MMOL)) + roundUp(profileUtil.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[0], GlucoseUnit.MMOL)), + roundDown(profileUtil.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[1], GlucoseUnit.MMOL)) ) val range2 = doubleArrayOf( - roundUp(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[0], GlucoseUnit.MMOL)), - roundDown(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[1], GlucoseUnit.MMOL)) + roundUp(profileUtil.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[0], GlucoseUnit.MMOL)), + roundDown(profileUtil.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[1], GlucoseUnit.MMOL)) ) aapsLogger.info(LTag.CORE, "TimeListEdit", "build: range1" + range1[0] + " " + range1[1] + " range2" + range2[0] + " " + range2[1]) TimeListEdit( diff --git a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt index eab1010de6..1eece2e053 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt @@ -31,6 +31,7 @@ import info.nightscout.rx.events.EventLocalProfileChanged import info.nightscout.rx.events.EventProfileStoreChanged import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -50,11 +51,13 @@ class ProfilePlugin @Inject constructor( rh: ResourceHelper, private val sp: SP, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val activePlugin: ActivePlugin, private val hardLimits: HardLimits, private val dateUtil: DateUtil, private val config: Config, - private val instantiator: Instantiator + private val instantiator: Instantiator, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() .mainType(PluginType.PROFILE) @@ -121,7 +124,7 @@ class ProfilePlugin @Inject constructor( return false } } else { - if (blockFromJsonArray(isf, dateUtil)?.all { hardLimits.isInRange(Profile.toMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { + if (blockFromJsonArray(isf, dateUtil)?.all { hardLimits.isInRange(profileUtil.convertToMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.MIN_ISF, HardLimits.MAX_ISF) } == false) { ToastUtils.errorToast(activity, rh.gs(R.string.error_in_isf_values)) return false } @@ -129,11 +132,11 @@ class ProfilePlugin @Inject constructor( ToastUtils.errorToast(activity, rh.gs(R.string.error_in_basal_values)) return false } - if (low?.all { 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?.all { hardLimits.isInRange(profileUtil.convertToMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]) } == false) { ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } - if (high?.all { 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?.all { hardLimits.isInRange(profileUtil.convertToMgdl(it.amount, GlucoseUnit.MMOL), HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]) } == false) { ToastUtils.errorToast(activity, rh.gs(R.string.error_in_target_values)) return false } @@ -420,6 +423,6 @@ class ProfilePlugin @Inject constructor( override val profileName: String get() = rawProfile?.getDefaultProfile()?.let { - DecimalFormatter.to2Decimal(ProfileSealed.Pure(it).percentageBasalSum()) + "U " + decimalFormatter.to2Decimal(ProfileSealed.Pure(it).percentageBasalSum()) + "U " } ?: "INVALID" } \ No newline at end of file diff --git a/plugins/main/src/test/java/info/nightscout/core/extensions/GlucoseValueExtensionKtTest.kt b/plugins/main/src/test/java/info/nightscout/core/extensions/GlucoseValueExtensionKtTest.kt index 5aab6e98ee..6f0a684591 100644 --- a/plugins/main/src/test/java/info/nightscout/core/extensions/GlucoseValueExtensionKtTest.kt +++ b/plugins/main/src/test/java/info/nightscout/core/extensions/GlucoseValueExtensionKtTest.kt @@ -14,13 +14,6 @@ class GlucoseValueExtensionKtTest : TestBaseWithProfile() { private val inMemoryGlucoseValue = InMemoryGlucoseValue(1000, 100.0, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN) @Test fun valueToUnitsString() { - Assertions.assertEquals("100", glucoseValue.valueToUnitsString(GlucoseUnit.MGDL)) - Assertions.assertEquals("5.6", glucoseValue.valueToUnitsString(GlucoseUnit.MMOL)) - } - @Test - fun inMemoryValueToUnitsString() { - Assertions.assertEquals("100", inMemoryGlucoseValue.valueToUnitsString(GlucoseUnit.MGDL)) - Assertions.assertEquals("5.6", inMemoryGlucoseValue.valueToUnitsString(GlucoseUnit.MMOL)) } @Test fun inMemoryValueToUnits() { diff --git a/plugins/main/src/test/java/info/nightscout/core/extensions/TemporaryTargetExtensionKtTest.kt b/plugins/main/src/test/java/info/nightscout/core/extensions/TemporaryTargetExtensionKtTest.kt index c3d14454ad..a42e1ba3f9 100644 --- a/plugins/main/src/test/java/info/nightscout/core/extensions/TemporaryTargetExtensionKtTest.kt +++ b/plugins/main/src/test/java/info/nightscout/core/extensions/TemporaryTargetExtensionKtTest.kt @@ -24,13 +24,13 @@ class TemporaryTargetExtensionKtTest : TestBaseWithProfile() { ) @Test fun lowValueToUnitsToString() { - Assertions.assertEquals("110", temporaryTarget.lowValueToUnitsToString(GlucoseUnit.MGDL)) - Assertions.assertEquals("6.1", temporaryTarget.lowValueToUnitsToString(GlucoseUnit.MMOL)) + Assertions.assertEquals("110", temporaryTarget.lowValueToUnitsToString(GlucoseUnit.MGDL, decimalFormatter)) + Assertions.assertEquals("6.1", temporaryTarget.lowValueToUnitsToString(GlucoseUnit.MMOL, decimalFormatter)) } @Test fun highValueToUnitsToString() { - Assertions.assertEquals("120", temporaryTarget.highValueToUnitsToString(GlucoseUnit.MGDL)) - Assertions.assertEquals("6.7", temporaryTarget.highValueToUnitsToString(GlucoseUnit.MMOL)) + Assertions.assertEquals("120", temporaryTarget.highValueToUnitsToString(GlucoseUnit.MGDL, decimalFormatter)) + Assertions.assertEquals("6.7", temporaryTarget.highValueToUnitsToString(GlucoseUnit.MMOL, decimalFormatter)) } @Test fun target() { diff --git a/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index 283f0d0975..6030e485fe 100644 --- a/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -12,7 +12,6 @@ import info.nightscout.database.impl.transactions.Transaction import info.nightscout.implementation.iob.GlucoseStatusProviderImpl import info.nightscout.interfaces.ApsMode import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.XDripBroadcast import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.aps.Loop @@ -99,13 +98,13 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { repository.runTransactionForResult(anyObject()) ).thenReturn(Single.just(InsertAndCancelCurrentTemporaryTargetTransaction.TransactionResult().apply { })) - val glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtilMocked) + val glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtilMocked, decimalFormatter) smsCommunicatorPlugin = SmsCommunicatorPlugin( - injector, aapsLogger, rh, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, + injector, aapsLogger, rh, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, profileUtil, fabricPrivacy, activePlugin, commandQueue, loop, iobCobCalculator, xDripBroadcast, otp, config, dateUtilMocked, uel, - glucoseStatusProvider, repository + glucoseStatusProvider, repository, decimalFormatter ) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) Mockito.doAnswer { invocation: InvocationOnMock -> @@ -158,7 +157,6 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { `when`(activePlugin.activeProfileSource).thenReturn(profileSource) - `when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) `when`(otp.name()).thenReturn("User") `when`(otp.checkOTP(ArgumentMatchers.anyString())).thenReturn(OneTimePasswordValidationResult.OK) diff --git a/plugins/source/src/main/java/info/nightscout/source/BGSourceFragment.kt b/plugins/source/src/main/java/info/nightscout/source/BGSourceFragment.kt index b3557fdda4..fc33d17ffa 100644 --- a/plugins/source/src/main/java/info/nightscout/source/BGSourceFragment.kt +++ b/plugins/source/src/main/java/info/nightscout/source/BGSourceFragment.kt @@ -15,7 +15,6 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment import info.nightscout.core.extensions.directionToIcon -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.utils.ActionModeHelper import info.nightscout.core.utils.fabric.FabricPrivacy @@ -36,6 +35,7 @@ import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.toVisibility import info.nightscout.shared.extensions.toVisibilityKeepSpace +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -58,6 +58,7 @@ class BGSourceFragment : DaggerFragment(), MenuProvider { @Inject lateinit var uel: UserEntryLogger @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var profileUtil: ProfileUtil private val disposable = CompositeDisposable() private val millsToThePast = T.hours(36).msecs() @@ -142,7 +143,7 @@ class BGSourceFragment : DaggerFragment(), MenuProvider { holder.binding.date.visibility = newDay.toVisibility() holder.binding.date.text = if (newDay) dateUtil.dateStringRelative(glucoseValue.timestamp, rh) else "" holder.binding.time.text = dateUtil.timeStringWithSeconds(glucoseValue.timestamp) - holder.binding.value.text = glucoseValue.valueToUnitsString(profileFunction.getUnits()) + holder.binding.value.text = profileUtil.fromMgdlToStringInUnits(glucoseValue.value) holder.binding.direction.setImageResource(glucoseValue.trendArrow.directionToIcon()) if (position > 0) { val previous = glucoseValues[position - 1] @@ -183,7 +184,7 @@ class BGSourceFragment : DaggerFragment(), MenuProvider { private fun getConfirmationText(selectedItems: SparseArray): String { if (selectedItems.size() == 1) { val glucoseValue = selectedItems.valueAt(0) - return dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + glucoseValue.valueToUnitsString(profileFunction.getUnits()) + return dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + profileUtil.fromMgdlToUnits(glucoseValue.value) } return rh.gs(info.nightscout.core.ui.R.string.confirm_remove_multiple_items, selectedItems.size()) } diff --git a/plugins/source/src/main/java/info/nightscout/source/DexcomPlugin.kt b/plugins/source/src/main/java/info/nightscout/source/DexcomPlugin.kt index 19ecf845b0..498d11314d 100644 --- a/plugins/source/src/main/java/info/nightscout/source/DexcomPlugin.kt +++ b/plugins/source/src/main/java/info/nightscout/source/DexcomPlugin.kt @@ -24,12 +24,12 @@ import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.source.BgSource import info.nightscout.interfaces.source.DexcomBoyda import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.safeGetInstalledPackages +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -85,6 +85,7 @@ class DexcomPlugin @Inject constructor( @Inject lateinit var dataWorkerStorage: DataWorkerStorage @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger + @Inject lateinit var profileUtil: ProfileUtil override suspend fun doWorkAndLog(): Result { var ret = Result.success() @@ -110,7 +111,7 @@ class DexcomPlugin @Inject constructor( CgmSourceTransaction.Calibration( timestamp = it.getLong("timestamp") * 1000, value = value, - glucoseUnit = TherapyEvent.GlucoseUnit.fromConstant(Profile.unit(value)) + glucoseUnit = TherapyEvent.GlucoseUnit.fromConstant(profileUtil.unitsDetect(value)) ) ) } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPlugin.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPlugin.kt index 8cc229e550..6442c58a37 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPlugin.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPlugin.kt @@ -22,6 +22,7 @@ import info.nightscout.interfaces.profile.DefaultValueHelper import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.receivers.Intents import info.nightscout.interfaces.receivers.ReceiverStatusStore +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.sync.R import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus @@ -57,7 +58,8 @@ class DataBroadcastPlugin @Inject constructor( private val activePlugin: ActivePlugin, private var receiverStatusStore: ReceiverStatusStore, private val config: Config, - private val glucoseStatusProvider: GlucoseStatusProvider + private val glucoseStatusProvider: GlucoseStatusProvider, + private val decimalFormatter: DecimalFormatter ) : PluginBase( PluginDescription() .mainType(PluginType.SYNC) @@ -105,7 +107,6 @@ class DataBroadcastPlugin @Inject constructor( val bundle = Bundle() prepareData(event, bundle) - //aapsLogger.debug("Prepared bundle:\n" + BundleLogger.log(bundle)) sendBroadcast( Intent(Intents.AAPS_BROADCAST) // "info.nightscout.androidaps.status" .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) @@ -176,7 +177,7 @@ class DataBroadcastPlugin @Inject constructor( bundle.putLong("tempBasalDurationInMinutes", it.durationInMinutes) if (it.isAbsolute) bundle.putDouble("tempBasalAbsolute", it.rate) // U/h for absolute TBR else bundle.putInt("tempBasalPercent", it.rate.toInt()) // % for percent type TBR - bundle.putString("tempBasalString", it.toStringFull(profile, dateUtil)) // user friendly string + bundle.putString("tempBasalString", it.toStringFull(profile, dateUtil, decimalFormatter)) // user friendly string } } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/NSClientPlugin.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/NSClientPlugin.kt index 3d400bbee9..93a354ff42 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/NSClientPlugin.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/NSClientPlugin.kt @@ -15,15 +15,14 @@ import info.nightscout.interfaces.Config import info.nightscout.interfaces.Constants import info.nightscout.interfaces.nsclient.NSAlarm import info.nightscout.interfaces.nsclient.NSSettingsStatus -import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.sync.DataSyncSelector import info.nightscout.interfaces.sync.NsClient import info.nightscout.interfaces.sync.Sync +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.sync.R import info.nightscout.plugins.sync.nsShared.NSClientFragment import info.nightscout.plugins.sync.nsShared.events.EventNSClientStatus @@ -40,6 +39,7 @@ import info.nightscout.rx.events.EventPreferenceChange import info.nightscout.rx.events.EventSWSyncStatus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -61,10 +61,10 @@ class NSClientPlugin @Inject constructor( private val receiverDelegate: ReceiverDelegate, private val config: Config, private val dataSyncSelectorV1: DataSyncSelectorV1, - private val activePlugin: ActivePlugin, private val dateUtil: DateUtil, - private val profileFunction: ProfileFunction, - private val nsSettingsStatus: NSSettingsStatus + private val profileUtil: ProfileUtil, + private val nsSettingsStatus: NSSettingsStatus, + private val decimalFormatter: DecimalFormatter ) : NsClient, Sync, PluginBase( PluginDescription() .mainType(PluginType.SYNC) @@ -200,15 +200,15 @@ class NSClientPlugin @Inject constructor( when (dataPair) { is DataSyncSelector.PairBolus -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairCarbs -> dataPair.value.toJson(true, dateUtil) - is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(true, dateUtil, profileFunction) - is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(true, profileFunction.getUnits(), dateUtil) + is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(true, dateUtil, profileUtil) + is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(true, dateUtil, profileUtil) is DataSyncSelector.PairFood -> dataPair.value.toJson(true) is DataSyncSelector.PairGlucoseValue -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairTherapyEvent -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairDeviceStatus -> dataPair.value.toJson(dateUtil) is DataSyncSelector.PairTemporaryBasal -> dataPair.value.toJson(true, profile, dateUtil) is DataSyncSelector.PairExtendedBolus -> dataPair.value.toJson(true, profile, dateUtil) - is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(true, dateUtil) + is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(true, dateUtil, decimalFormatter) is DataSyncSelector.PairEffectiveProfileSwitch -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairOfflineEvent -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairProfileStore -> dataPair.value @@ -238,14 +238,14 @@ class NSClientPlugin @Inject constructor( when (dataPair) { is DataSyncSelector.PairBolus -> dataPair.value.toJson(false, dateUtil) is DataSyncSelector.PairCarbs -> dataPair.value.toJson(false, dateUtil) - is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(false, dateUtil, profileFunction) - is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(false, profileFunction.getUnits(), dateUtil) + is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(false, dateUtil, profileUtil) + is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(false, dateUtil, profileUtil) is DataSyncSelector.PairFood -> dataPair.value.toJson(false) is DataSyncSelector.PairGlucoseValue -> dataPair.value.toJson(false, dateUtil) is DataSyncSelector.PairTherapyEvent -> dataPair.value.toJson(false, dateUtil) is DataSyncSelector.PairTemporaryBasal -> dataPair.value.toJson(false, profile, dateUtil) is DataSyncSelector.PairExtendedBolus -> dataPair.value.toJson(false, profile, dateUtil) - is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(false, dateUtil) + is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(false, dateUtil, decimalFormatter) is DataSyncSelector.PairEffectiveProfileSwitch -> dataPair.value.toJson(false, dateUtil) is DataSyncSelector.PairOfflineEvent -> dataPair.value.toJson(false, dateUtil) else -> null diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/BolusCalculatorResultExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/BolusCalculatorResultExtension.kt index c89b2ebb18..41666a0277 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/BolusCalculatorResultExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/BolusCalculatorResultExtension.kt @@ -3,21 +3,20 @@ package info.nightscout.plugins.sync.nsclient.extensions import com.google.gson.Gson import com.google.gson.JsonSyntaxException import info.nightscout.database.entities.BolusCalculatorResult -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.utils.JsonHelper +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import org.json.JSONObject -fun BolusCalculatorResult.toJson(isAdd: Boolean, dateUtil: DateUtil, profileFunction: ProfileFunction): JSONObject = +fun BolusCalculatorResult.toJson(isAdd: Boolean, dateUtil: DateUtil, profileUtil: ProfileUtil): JSONObject = JSONObject() .put("eventType", info.nightscout.database.entities.TherapyEvent.Type.BOLUS_WIZARD.text) .put("created_at", dateUtil.toISOString(timestamp)) .put("isValid", isValid) .put("bolusCalculatorResult", Gson().toJson(this)) .put("date", timestamp) - .put("glucose", Profile.fromMgdlToUnits(glucoseValue, profileFunction.getUnits())) - .put("units", profileFunction.getUnits().asText) + .put("glucose", profileUtil.fromMgdlToUnits(glucoseValue)) + .put("units", profileUtil.units.asText) .put("notes", note) .also { if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/ProfileSwitchExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/ProfileSwitchExtension.kt index 7b7524c9d8..e8b94af8ab 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/ProfileSwitchExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/ProfileSwitchExtension.kt @@ -8,17 +8,18 @@ import info.nightscout.database.entities.ProfileSwitch import info.nightscout.database.entities.TherapyEvent import info.nightscout.database.entities.embedments.InterfaceIDs import info.nightscout.interfaces.plugin.ActivePlugin +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.JsonHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T import org.json.JSONObject -fun ProfileSwitch.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject = +fun ProfileSwitch.toJson(isAdd: Boolean, dateUtil: DateUtil, decimalFormatter: DecimalFormatter): JSONObject = JSONObject() .put("timeshift", timeshift) .put("percentage", percentage) .put("duration", T.msecs(duration).mins()) - .put("profile", getCustomizedName()) + .put("profile", getCustomizedName(decimalFormatter)) .put("originalProfileName", profileName) .put("originalDuration", duration) .put("created_at", dateUtil.toISOString(timestamp)) diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt index 8ea8642909..e275c17366 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt @@ -3,21 +3,21 @@ package info.nightscout.plugins.sync.nsclient.extensions import info.nightscout.database.entities.TemporaryTarget import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.utils.JsonHelper +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T import org.json.JSONObject -fun TemporaryTarget.Companion.fromJson(jsonObject: JSONObject): TemporaryTarget? { +fun TemporaryTarget.Companion.fromJson(jsonObject: JSONObject, profileUtil: ProfileUtil): TemporaryTarget? { val units = GlucoseUnit.fromText(JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL)) val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null val duration = JsonHelper.safeGetLongAllowNull(jsonObject, "duration", null) ?: return null val durationInMilliseconds = JsonHelper.safeGetLongAllowNull(jsonObject, "durationInMilliseconds") var low = JsonHelper.safeGetDouble(jsonObject, "targetBottom") - low = Profile.toMgdl(low, units) + low = profileUtil.convertToMgdl(low, units) var high = JsonHelper.safeGetDouble(jsonObject, "targetTop") - high = Profile.toMgdl(high, units) + high = profileUtil.convertToMgdl(high, units) val reasonString = if (duration != 0L) JsonHelper.safeGetStringAllowNull(jsonObject, "reason", null) ?: return null else "" // this string can be localized from NS, it will not work in this case CUSTOM will be used @@ -47,7 +47,7 @@ fun TemporaryTarget.Companion.fromJson(jsonObject: JSONObject): TemporaryTarget? return tt } -fun TemporaryTarget.toJson(isAdd: Boolean, units: GlucoseUnit, dateUtil: DateUtil): JSONObject = +fun TemporaryTarget.toJson(isAdd: Boolean, dateUtil: DateUtil, profileUtil: ProfileUtil): JSONObject = JSONObject() .put("eventType", info.nightscout.database.entities.TherapyEvent.Type.TEMPORARY_TARGET.text) .put("duration", T.msecs(duration).mins()) @@ -58,8 +58,8 @@ fun TemporaryTarget.toJson(isAdd: Boolean, units: GlucoseUnit, dateUtil: DateUti .put("enteredBy", "AndroidAPS").also { if (lowTarget > 0) it .put("reason", reason.text) - .put("targetBottom", Profile.fromMgdlToUnits(lowTarget, units)) - .put("targetTop", Profile.fromMgdlToUnits(highTarget, units)) - .put("units", units.asText) + .put("targetBottom", profileUtil.fromMgdlToUnits(lowTarget)) + .put("targetTop", profileUtil.fromMgdlToUnits(highTarget)) + .put("units", profileUtil.units.asText) if (isAdd && interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId) } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt index 56068fdd4c..062cbd0067 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/workers/NSClientAddUpdateWorker.kt @@ -28,6 +28,7 @@ import info.nightscout.plugins.sync.nsclient.extensions.isEffectiveProfileSwitch import info.nightscout.plugins.sync.nsclient.extensions.temporaryBasalFromJson import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil import kotlinx.coroutines.Dispatchers @@ -46,6 +47,7 @@ class NSClientAddUpdateWorker( @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rxBus: RxBus @Inject lateinit var storeDataForDb: StoreDataForDb + @Inject lateinit var profileUtil: ProfileUtil override suspend fun doWorkAndLog(): Result { val treatments = dataWorkerStorage.pickupJSONArray(inputData.getLong(DataWorkerStorage.STORE_KEY, -1)) @@ -100,7 +102,7 @@ class NSClientAddUpdateWorker( insulin > 0 || carbs > 0 -> Any() eventType == TherapyEvent.Type.TEMPORARY_TARGET.text -> if (sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_receive_temp_target, false) || config.NSCLIENT) { - TemporaryTarget.fromJson(json)?.let { temporaryTarget -> + TemporaryTarget.fromJson(json, profileUtil)?.let { temporaryTarget -> storeDataForDb.temporaryTargets.add(temporaryTarget) } ?: aapsLogger.error("Error parsing TT json $json") } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt index 8fb9a410da..23df31acdc 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt @@ -33,6 +33,7 @@ import info.nightscout.interfaces.sync.DataSyncSelector import info.nightscout.interfaces.sync.NsClient import info.nightscout.interfaces.sync.Sync import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.sync.R import info.nightscout.plugins.sync.nsShared.NSClientFragment import info.nightscout.plugins.sync.nsShared.NsIncomingDataProcessor @@ -121,7 +122,8 @@ class NSClientV3Plugin @Inject constructor( private val nsDeviceStatusHandler: NSDeviceStatusHandler, private val nsClientSource: NSClientSource, private val nsIncomingDataProcessor: NsIncomingDataProcessor, - private val storeDataForDb: StoreDataForDb + private val storeDataForDb: StoreDataForDb, + private val decimalFormatter: DecimalFormatter ) : NsClient, Sync, PluginBase( PluginDescription() .mainType(PluginType.SYNC) @@ -795,7 +797,7 @@ class NSClientV3Plugin @Inject constructor( dataPair.value.toNSExtendedBolus(profile) } - is DataSyncSelector.PairProfileSwitch -> dataPair.value.toNSProfileSwitch(dateUtil) + is DataSyncSelector.PairProfileSwitch -> dataPair.value.toNSProfileSwitch(dateUtil, decimalFormatter) is DataSyncSelector.PairEffectiveProfileSwitch -> dataPair.value.toNSEffectiveProfileSwitch(dateUtil) is DataSyncSelector.PairOfflineEvent -> dataPair.value.toNSOfflineEvent() else -> null diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtension.kt index a1aed0c13c..2da094012b 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtension.kt @@ -7,6 +7,7 @@ import info.nightscout.core.profile.ProfileSealed import info.nightscout.database.entities.ProfileSwitch import info.nightscout.database.entities.embedments.InterfaceIDs import info.nightscout.interfaces.plugin.ActivePlugin +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.sdk.localmodel.treatment.EventType import info.nightscout.sdk.localmodel.treatment.NSProfileSwitch import info.nightscout.shared.utils.DateUtil @@ -38,8 +39,8 @@ fun NSProfileSwitch.toProfileSwitch(activePlugin: ActivePlugin, dateUtil: DateUt ) } -fun ProfileSwitch.toNSProfileSwitch(dateUtil: DateUtil): NSProfileSwitch { - val unmodifiedCustomizedName = getCustomizedName() +fun ProfileSwitch.toNSProfileSwitch(dateUtil: DateUtil, decimalFormatter: DecimalFormatter): NSProfileSwitch { + val unmodifiedCustomizedName = getCustomizedName(decimalFormatter) // ProfileSealed.PS doesn't provide unmodified json -> reset it val notCustomized = this.copy() notCustomized.timeshift = 0 diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/comm/UploadChunk.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/comm/UploadChunk.kt index 069c78a2f2..bffe53e9b8 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/comm/UploadChunk.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/comm/UploadChunk.kt @@ -18,6 +18,7 @@ import info.nightscout.plugins.sync.tidepool.utils.GsonInstance import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -33,6 +34,7 @@ class UploadChunk @Inject constructor( private val rxBus: RxBus, private val aapsLogger: AAPSLogger, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, private val activePlugin: ActivePlugin, private val repository: AppRepository, private val dateUtil: DateUtil @@ -111,7 +113,7 @@ class UploadChunk @Inject constructor( private fun getBloodTests(start: Long, end: Long): List { val readings = repository.compatGetTherapyEventDataFromToTime(start, end).blockingGet() - val selection = BloodGlucoseElement.fromCareportalEvents(readings, dateUtil) + val selection = BloodGlucoseElement.fromCareportalEvents(readings, dateUtil, profileUtil) if (selection.isNotEmpty()) rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload")) return selection @@ -140,14 +142,14 @@ class UploadChunk @Inject constructor( private fun getBasals(start: Long, end: Long): List { val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(start, end, true).blockingGet() - val selection = fromTemporaryBasals(temporaryBasals, start, end) // TODO do not upload running TBR + val selection = fromTemporaryBasals(temporaryBasals, start, end) if (selection.isNotEmpty()) rxBus.send(EventTidepoolStatus("${selection.size} TBRs selected for upload")) return selection } private fun newInstanceOrNull(ps: EffectiveProfileSwitch): ProfileElement? = try { - ProfileElement(ps, activePlugin.activePump.serialNumber(), dateUtil) + ProfileElement(ps, activePlugin.activePump.serialNumber(), dateUtil, profileUtil) } catch (e: Throwable) { null } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/BloodGlucoseElement.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/BloodGlucoseElement.kt index 9bafb71ebd..a6564fd628 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/BloodGlucoseElement.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/BloodGlucoseElement.kt @@ -2,14 +2,14 @@ package info.nightscout.plugins.sync.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.database.entities.TherapyEvent -import info.nightscout.interfaces.profile.Profile import info.nightscout.plugins.sync.nsclient.extensions.toMainUnit +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import java.util.LinkedList import java.util.UUID -class BloodGlucoseElement(therapyEvent: TherapyEvent, dateUtil: DateUtil) - : BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString(), dateUtil) { +class BloodGlucoseElement(therapyEvent: TherapyEvent, dateUtil: DateUtil, profileUtil: ProfileUtil) : + BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString(), dateUtil) { @Expose var subType: String = "manual" @@ -22,21 +22,21 @@ class BloodGlucoseElement(therapyEvent: TherapyEvent, dateUtil: DateUtil) init { type = "smbg" - subType = "manual" // TODO + subType = "manual" value = if (therapyEvent.glucose != null) - Profile.toMgdl(therapyEvent.glucose!!, therapyEvent.glucoseUnit.toMainUnit()).toInt() + profileUtil.convertToMgdl(therapyEvent.glucose!!, therapyEvent.glucoseUnit.toMainUnit()).toInt() else 0 } companion object { - fun fromCareportalEvents(careportalList: List, dateUtil: DateUtil): List { + fun fromCareportalEvents(careportalList: List, dateUtil: DateUtil, profileUtil: ProfileUtil): List { val results = LinkedList() for (bt in careportalList) { if (bt.type == TherapyEvent.Type.NS_MBG || bt.type == TherapyEvent.Type.FINGER_STICK_BG_VALUE) { - val bge = BloodGlucoseElement(bt, dateUtil) + val bge = BloodGlucoseElement(bt, dateUtil, profileUtil) if (bge.value > 0) - results.add(BloodGlucoseElement(bt, dateUtil)) + results.add(BloodGlucoseElement(bt, dateUtil, profileUtil)) } } return results diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/ProfileElement.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/ProfileElement.kt index ea6ed877fb..2dd3083c4f 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/ProfileElement.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/tidepool/elements/ProfileElement.kt @@ -5,18 +5,22 @@ import info.nightscout.core.profile.ProfileSealed import info.nightscout.database.entities.EffectiveProfileSwitch import info.nightscout.interfaces.profile.Profile import info.nightscout.plugins.sync.tidepool.comm.TidepoolUploader +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import java.util.UUID -class ProfileElement(ps: EffectiveProfileSwitch, serialNumber: String, dateUtil: DateUtil) - : BaseElement(ps.timestamp, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.timestamp).toByteArray()).toString(), dateUtil) { +class ProfileElement(ps: EffectiveProfileSwitch, serialNumber: String, dateUtil: DateUtil, profileUtil: ProfileUtil) : + BaseElement(ps.timestamp, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.timestamp).toByteArray()).toString(), dateUtil) { @Expose internal var activeSchedule = "Normal" + @Expose internal var basalSchedules: BasalProfile = BasalProfile() + @Expose internal var units: Units = Units() + @Expose internal var bgTargets: TargetProfile = TargetProfile() @Expose @@ -46,7 +50,12 @@ class ProfileElement(ps: EffectiveProfileSwitch, serialNumber: String, dateUtil: for (hour in 0..23) { val seconds = hour * 3600 basalSchedules.Normal.add(BasalRate(seconds * 1000, profile.getBasalTimeFromMidnight(seconds))) - bgTargets.Normal.add(Target(seconds * 1000, Profile.toMgdl((((profile.getTargetLowMgdlTimeFromMidnight(seconds) + profile.getTargetLowMgdlTimeFromMidnight(seconds))) / 2)).toInt())) + bgTargets.Normal.add( + Target( + seconds * 1000, + profileUtil.convertToMgdlDetect((((profile.getTargetLowMgdlTimeFromMidnight(seconds) + profile.getTargetLowMgdlTimeFromMidnight(seconds))) / 2)).toInt() + ) + ) carbRatios.Normal.add(Ratio(seconds * 1000, profile.getIcTimeFromMidnight(seconds).toInt())) insulinSensitivities.Normal.add(Ratio(seconds * 1000, profile.getIsfMgdlTimeFromMidnight(seconds).toInt())) } diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/xdrip/XdripPlugin.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/xdrip/XdripPlugin.kt index b683422596..973abdcff7 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/xdrip/XdripPlugin.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/xdrip/XdripPlugin.kt @@ -11,7 +11,6 @@ import androidx.work.OneTimeWorkRequest import androidx.work.WorkInfo import androidx.work.WorkManager import dagger.android.HasAndroidInjector -import info.nightscout.core.extensions.toJson import info.nightscout.core.extensions.toStringShort import info.nightscout.core.iob.generateCOBString import info.nightscout.core.iob.round @@ -49,6 +48,7 @@ import info.nightscout.rx.events.EventXdripNewLog import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.safeQueryBroadcastReceivers +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -70,6 +70,7 @@ class XdripPlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, private val profileFunction: ProfileFunction, + private val profileUtil: ProfileUtil, rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val context: Context, @@ -79,7 +80,8 @@ class XdripPlugin @Inject constructor( private val rxBus: RxBus, private val uiInteraction: UiInteraction, private val dateUtil: DateUtil, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val decimalFormatter: DecimalFormatter ) : XDripBroadcast, Sync, PluginBase( PluginDescription() .mainType(PluginType.SYNC) @@ -238,26 +240,26 @@ class XdripPlugin @Inject constructor( //Temp basal iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.let { - status.append(it.toStringShort()).append(" ") + status.append(it.toStringShort(decimalFormatter)).append(" ") } //IOB val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() - status.append(DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob)).append(rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname)) + status.append(decimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob)).append(rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname)) if (sp.getBoolean(R.string.key_xdrip_status_detailed_iob, true)) status.append("(") - .append(DecimalFormatter.to2Decimal(bolusIob.iob)) + .append(decimalFormatter.to2Decimal(bolusIob.iob)) .append("|") - .append(DecimalFormatter.to2Decimal(basalIob.basaliob)) + .append(decimalFormatter.to2Decimal(basalIob.basaliob)) .append(")") if (sp.getBoolean(R.string.key_xdrip_status_show_bgi, true)) { - val bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) + val bgi = -(bolusIob.activity + basalIob.activity) * 5 * profileUtil.fromMgdlToUnits(profile.getIsfMgdl()) status.append(" ") .append(if (bgi >= 0) "+" else "") - .append(DecimalFormatter.to2Decimal(bgi)) + .append(decimalFormatter.to2Decimal(bgi)) } // COB - status.append(" ").append(iobCobCalculator.getCobInfo("StatusLinePlugin").generateCOBString()) + status.append(" ").append(iobCobCalculator.getCobInfo("StatusLinePlugin").generateCOBString(decimalFormatter)) return status.toString() } @@ -392,8 +394,8 @@ class XdripPlugin @Inject constructor( when (dataPair) { is DataSyncSelector.PairBolus -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairCarbs -> dataPair.value.toJson(true, dateUtil) - is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(true, dateUtil, profileFunction) - is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(true, profileFunction.getUnits(), dateUtil) + is DataSyncSelector.PairBolusCalculatorResult -> dataPair.value.toJson(true, dateUtil, profileUtil) + is DataSyncSelector.PairTemporaryTarget -> dataPair.value.toJson(true, dateUtil, profileUtil) is DataSyncSelector.PairTherapyEvent -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairTemporaryBasal -> { @@ -406,7 +408,7 @@ class XdripPlugin @Inject constructor( dataPair.value.toJson(true, profile, dateUtil) } - is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(true, dateUtil) + is DataSyncSelector.PairProfileSwitch -> dataPair.value.toJson(true, dateUtil, decimalFormatter) is DataSyncSelector.PairEffectiveProfileSwitch -> dataPair.value.toJson(true, dateUtil) is DataSyncSelector.PairOfflineEvent -> dataPair.value.toJson(true, dateUtil) else -> null diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPluginTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPluginTest.kt index 8b729ea5fb..e061835edd 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPluginTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/dataBroadcaster/DataBroadcastPluginTest.kt @@ -43,7 +43,7 @@ internal class DataBroadcastPluginTest : TestBaseWithProfile() { fun setUp() { sut = DataBroadcastPlugin( injector, aapsLogger, rh, aapsSchedulers, context, dateUtil, fabricPrivacy, rxBus, iobCobCalculator, profileFunction, defaultValueHelper, processedDeviceStatusData, - loop, activePlugin, receiverStatusStore, config, glucoseStatusProvider + loop, activePlugin, receiverStatusStore, config, glucoseStatusProvider, decimalFormatter ) Mockito.`when`(iobCobCalculator.ads).thenReturn(autosensDataStore) Mockito.`when`(autosensDataStore.lastBg()).thenReturn(InMemoryGlucoseValue(1000, 100.0, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN)) diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3PluginTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3PluginTest.kt index 6fbd027299..182fcb4566 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3PluginTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3PluginTest.kt @@ -82,7 +82,7 @@ internal class NSClientV3PluginTest : TestBaseWithProfile() { NSClientV3Plugin( injector, aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, sp, receiverDelegate, config, dateUtil, uiInteraction, dataSyncSelectorV3, repository, - nsDeviceStatusHandler, nsClientSource, nsIncomingDataProcessor, storeDataForDb + nsDeviceStatusHandler, nsClientSource, nsIncomingDataProcessor, storeDataForDb, decimalFormatter ) sut.nsAndroidClient = nsAndroidClient Mockito.`when`(mockedProfileFunction.getProfile(anyLong())).thenReturn(validProfile) diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtensionKtTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtensionKtTest.kt index 562a5d57e9..7be1c5d7eb 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtensionKtTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/extensions/ProfileSwitchExtensionKtTest.kt @@ -51,7 +51,7 @@ internal class ProfileSwitchExtensionKtTest : TestBaseWithProfile() { ) ) - var profileSwitch2 = (profileSwitch.toNSProfileSwitch(dateUtil).convertToRemoteAndBack() as NSProfileSwitch).toProfileSwitch(activePlugin, dateUtil)!! + var profileSwitch2 = (profileSwitch.toNSProfileSwitch(dateUtil, decimalFormatter).convertToRemoteAndBack() as NSProfileSwitch).toProfileSwitch(activePlugin, dateUtil)!! Assertions.assertTrue(profileSwitch.contentEqualsTo(profileSwitch2)) Assertions.assertTrue(profileSwitch.interfaceIdsEqualsTo(profileSwitch2)) @@ -78,7 +78,7 @@ internal class ProfileSwitchExtensionKtTest : TestBaseWithProfile() { ) ) - profileSwitch2 = (profileSwitch.toNSProfileSwitch(dateUtil).convertToRemoteAndBack() as NSProfileSwitch).toProfileSwitch(activePlugin, dateUtil)!! + profileSwitch2 = (profileSwitch.toNSProfileSwitch(dateUtil, decimalFormatter).convertToRemoteAndBack() as NSProfileSwitch).toProfileSwitch(activePlugin, dateUtil)!! Assertions.assertTrue(profileSwitch.contentEqualsTo(profileSwitch2)) Assertions.assertTrue(profileSwitch.interfaceIdsEqualsTo(profileSwitch2)) } diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt index 3c3b2fcced..917dd76573 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt @@ -13,11 +13,13 @@ import info.nightscout.core.utils.receivers.DataWorkerStorage import info.nightscout.database.entities.GlucoseValue import info.nightscout.database.entities.embedments.InterfaceIDs import info.nightscout.database.impl.AppRepository +import info.nightscout.implementation.utils.DecimalFormatterImpl import info.nightscout.interfaces.Config import info.nightscout.interfaces.nsclient.StoreDataForDb import info.nightscout.interfaces.receivers.ReceiverStatusStore import info.nightscout.interfaces.source.NSClientSource import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.sync.nsShared.NsIncomingDataProcessor import info.nightscout.plugins.sync.nsclient.ReceiverDelegate import info.nightscout.plugins.sync.nsclient.data.NSDeviceStatusHandler @@ -68,6 +70,7 @@ internal class LoadBgWorkerTest : TestBase() { private lateinit var nsClientV3Plugin: NSClientV3Plugin private lateinit var receiverDelegate: ReceiverDelegate private lateinit var dataWorkerStorage: DataWorkerStorage + private lateinit var decimalFormatter: DecimalFormatter private lateinit var sut: LoadBgWorker private val now = 1000000000L @@ -90,6 +93,7 @@ internal class LoadBgWorkerTest : TestBase() { @BeforeEach fun setUp() { + decimalFormatter = DecimalFormatterImpl(rh) Mockito.`when`(context.applicationContext).thenReturn(context) Mockito.`when`(context.androidInjector()).thenReturn(injector.androidInjector()) Mockito.`when`(dateUtil.now()).thenReturn(now) @@ -99,7 +103,7 @@ internal class LoadBgWorkerTest : TestBase() { nsClientV3Plugin = NSClientV3Plugin( injector, aapsLogger, aapsSchedulers, rxBus, rh, context, fabricPrivacy, sp, receiverDelegate, config, dateUtil, uiInteraction, dataSyncSelectorV3, repository, - nsDeviceStatusHandler, nsClientSource, nsIncomingDataProcessor, storeDataForDb + nsDeviceStatusHandler, nsClientSource, nsIncomingDataProcessor, storeDataForDb, decimalFormatter ) nsClientV3Plugin.newestDataOnServer = LastModified(LastModified.Collections()) } diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt index f55ad8ba4c..9c4a1e08d6 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/AAPSPumpStateStore.kt @@ -11,9 +11,6 @@ import info.nightscout.comboctl.base.toBluetoothAddress import info.nightscout.comboctl.base.toCipher import info.nightscout.comboctl.base.toNonce import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.sharedPreferences.SPDelegateInt -import info.nightscout.shared.sharedPreferences.SPDelegateLong -import info.nightscout.shared.sharedPreferences.SPDelegateString import kotlinx.datetime.Instant import kotlinx.datetime.UtcOffset import kotlin.reflect.KClassifier diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt index 0fd7b2c9ff..4cfac85c8e 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt @@ -114,7 +114,8 @@ class ComboV2Plugin @Inject constructor ( private val dateUtil: DateUtil, private val uiInteraction: UiInteraction, private val androidPermission: AndroidPermission, - private val config: Config + private val config: Config, + private val decimalFormatter: DecimalFormatter ) : PumpPluginBase( PluginDescription() @@ -1456,7 +1457,7 @@ class ComboV2Plugin @Inject constructor ( lastBolusUIFlow.value?.let { val localBolusTimestamp = it.timestamp.toLocalDateTime(TimeZone.currentSystemDefault()) lines += rh.gs( - R.string.combov2_short_status_last_bolus, DecimalFormatter.to2Decimal(it.bolusAmount.cctlBolusToIU()), + R.string.combov2_short_status_last_bolus, decimalFormatter.to2Decimal(it.bolusAmount.cctlBolusToIU()), String.format("%02d:%02d", localBolusTimestamp.hour, localBolusTimestamp.minute) ) } @@ -1465,7 +1466,7 @@ class ComboV2Plugin @Inject constructor ( temporaryBasal?.let { lines += rh.gs( R.string.combov2_short_status_temp_basal, - it.toStringFull(dateUtil) + it.toStringFull(dateUtil, decimalFormatter) ) } diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences/Delegates.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/Delegates.kt similarity index 96% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences/Delegates.kt rename to pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/Delegates.kt index a7f80f7128..fb7732f5e4 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences/Delegates.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/Delegates.kt @@ -1,5 +1,6 @@ -package info.nightscout.shared.sharedPreferences +package info.nightscout.pump.combov2 +import info.nightscout.shared.sharedPreferences.SP import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty diff --git a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt index 3999e71253..64d438997f 100644 --- a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt +++ b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt @@ -33,7 +33,8 @@ class DanaPump @Inject constructor( private val aapsLogger: AAPSLogger, private val sp: SP, private val dateUtil: DateUtil, - private val instantiator: Instantiator + private val instantiator: Instantiator, + private val decimalFormatter: DecimalFormatter ) { @Suppress("unused") @@ -196,7 +197,7 @@ class DanaPump @Inject constructor( fun extendedBolusToString(): String { if (!isExtendedInProgress) return "" - return "E " + DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + + return "E " + decimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + dateUtil.timeString(extendedBolusStart) + " " + extendedBolusPassedMinutes + "/" + extendedBolusDurationInMinutes + "'" } @@ -238,7 +239,6 @@ class DanaPump @Inject constructor( var cf24 = Array(24) { 0.0 } var cir24 = Array(24) { 0.0 } - //var pumpProfiles = arrayOf>() var pumpProfiles: Array>? = null //Limits diff --git a/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaHistoryActivity.kt b/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaHistoryActivity.kt index aa67998f34..e5e0c75bcb 100644 --- a/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaHistoryActivity.kt +++ b/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaHistoryActivity.kt @@ -10,9 +10,7 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import info.nightscout.core.ui.activities.TranslatedDaggerAppCompatActivity import info.nightscout.core.utils.fabric.FabricPrivacy -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.Callback @@ -30,6 +28,7 @@ import info.nightscout.rx.events.EventDanaRSyncStatus import info.nightscout.rx.events.EventPumpStatusChanged import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -43,12 +42,14 @@ class DanaHistoryActivity : TranslatedDaggerAppCompatActivity() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var decimalFormatter: DecimalFormatter private val disposable = CompositeDisposable() @@ -71,9 +72,9 @@ class DanaHistoryActivity : TranslatedDaggerAppCompatActivity() { .toObservable(EventDanaRSyncStatus::class.java) .observeOn(aapsSchedulers.main) .subscribe({ - aapsLogger.debug(LTag.PUMP, "EventDanaRSyncStatus: " + it.message) - binding.status.text = it.message - }, fabricPrivacy::logException) + aapsLogger.debug(LTag.PUMP, "EventDanaRSyncStatus: " + it.message) + binding.status.text = it.message + }, fabricPrivacy::logException) swapAdapter(showingType) } @@ -147,7 +148,7 @@ class DanaHistoryActivity : TranslatedDaggerAppCompatActivity() { override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { val record = historyList[position] holder.binding.time.text = dateUtil.dateAndTimeString(record.timestamp) - holder.binding.value.text = DecimalFormatter.to2Decimal(record.value) + holder.binding.value.text = decimalFormatter.to2Decimal(record.value) holder.binding.stringValue.text = record.stringValue holder.binding.bolusType.text = record.bolusType holder.binding.duration.text = record.duration.toString() @@ -194,7 +195,7 @@ class DanaHistoryActivity : TranslatedDaggerAppCompatActivity() { } RecordTypes.RECORD_TYPE_GLUCOSE -> { - holder.binding.value.text = Profile.toUnitsString(record.value, record.value * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) + holder.binding.value.text = profileUtil.fromMgdlToStringInUnits(record.value) holder.binding.time.visibility = View.VISIBLE holder.binding.value.visibility = View.VISIBLE holder.binding.stringValue.visibility = View.GONE diff --git a/pump/dana/src/test/java/info/nightscout/pump/dana/DanaPumpTest.kt b/pump/dana/src/test/java/info/nightscout/pump/dana/DanaPumpTest.kt index bea0277eff..b6c9c555d3 100644 --- a/pump/dana/src/test/java/info/nightscout/pump/dana/DanaPumpTest.kt +++ b/pump/dana/src/test/java/info/nightscout/pump/dana/DanaPumpTest.kt @@ -15,7 +15,7 @@ class DanaPumpTest : TestBaseWithProfile() { @BeforeEach fun setup() { - sut = DanaPump(aapsLogger, sp, dateUtil, instantiator) + sut = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) } @Test diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt index 87f6173f70..b2f3b92da9 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt @@ -22,6 +22,7 @@ import info.nightscout.interfaces.pump.PumpSync.TemporaryBasalType import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.Round import info.nightscout.pump.dana.DanaPump import info.nightscout.pump.dana.database.DanaHistoryDatabase @@ -59,8 +60,25 @@ class DanaRKoreanPlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, pumpSync: PumpSync, uiInteraction: UiInteraction, - danaHistoryDatabase: DanaHistoryDatabase -) : AbstractDanaRPlugin(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase) { + danaHistoryDatabase: DanaHistoryDatabase, + decimalFormatter: DecimalFormatter +) : AbstractDanaRPlugin( + injector, + danaPump, + rh, + constraintChecker, + aapsLogger, + aapsSchedulers, + commandQueue, + rxBus, + activePlugin, + sp, + dateUtil, + pumpSync, + uiInteraction, + danaHistoryDatabase, + decimalFormatter +) { init { pluginDescription.description(info.nightscout.pump.dana.R.string.description_pump_dana_r_korean) diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index 34396a7abe..7c35ab543e 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -29,6 +29,7 @@ import info.nightscout.interfaces.pump.TemporaryBasalStorage; import info.nightscout.interfaces.pump.defs.PumpType; import info.nightscout.interfaces.queue.CommandQueue; import info.nightscout.interfaces.ui.UiInteraction; +import info.nightscout.interfaces.utils.DecimalFormatter; import info.nightscout.interfaces.utils.Round; import info.nightscout.pump.dana.DanaPump; import info.nightscout.pump.dana.database.DanaHistoryDatabase; @@ -72,9 +73,10 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { FabricPrivacy fabricPrivacy, PumpSync pumpSync, UiInteraction uiInteraction, - DanaHistoryDatabase danaHistoryDatabase + DanaHistoryDatabase danaHistoryDatabase, + DecimalFormatter decimalFormatter ) { - super(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase); + super(injector, danaPump, rh, constraintChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter); this.aapsLogger = aapsLogger; this.context = context; this.rh = rh; diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index 4501712c26..f5d7c965d4 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -64,6 +64,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected PumpSync pumpSync; protected UiInteraction uiInteraction; protected DanaHistoryDatabase danaHistoryDatabase; + protected DecimalFormatter decimalFormatter; protected AbstractDanaRPlugin( HasAndroidInjector injector, DanaPump danaPump, @@ -78,7 +79,8 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump DateUtil dateUtil, PumpSync pumpSync, UiInteraction uiInteraction, - DanaHistoryDatabase danaHistoryDatabase + DanaHistoryDatabase danaHistoryDatabase, + DecimalFormatter decimalFormatter ) { super(new PluginDescription() .mainType(PluginType.PUMP) @@ -100,6 +102,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump this.pumpSync = pumpSync; this.uiInteraction = uiInteraction; this.danaHistoryDatabase = danaHistoryDatabase; + this.decimalFormatter = decimalFormatter; } @Override protected void onStart() { @@ -496,19 +499,19 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump ret += "LastConn: " + agoMin + " min ago\n"; } if (danaPump.getLastBolusTime() != 0) { - ret += "LastBolus: " + DecimalFormatter.INSTANCE.to2Decimal(danaPump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", danaPump.getLastBolusTime()) + "\n"; + ret += "LastBolus: " + decimalFormatter.to2Decimal(danaPump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", danaPump.getLastBolusTime()) + "\n"; } PumpSync.PumpState pumpState = pumpSync.expectedPumpState(); if (pumpState.getTemporaryBasal() != null) { - ret += "Temp: " + pumpState.getTemporaryBasal().toStringFull(dateUtil) + "\n"; + ret += "Temp: " + pumpState.getTemporaryBasal().toStringFull(dateUtil, decimalFormatter) + "\n"; } if (pumpState.getExtendedBolus() != null) { - ret += "Extended: " + pumpState.getExtendedBolus().toStringFull(dateUtil) + "\n"; + ret += "Extended: " + pumpState.getExtendedBolus().toStringFull(dateUtil, decimalFormatter) + "\n"; } if (!veryShort) { - ret += "TDD: " + DecimalFormatter.INSTANCE.to0Decimal(danaPump.getDailyTotalUnits()) + " / " + danaPump.getMaxDailyTotalUnits() + " U\n"; + ret += "TDD: " + decimalFormatter.to0Decimal(danaPump.getDailyTotalUnits()) + " / " + danaPump.getMaxDailyTotalUnits() + " U\n"; } - ret += "Reserv: " + DecimalFormatter.INSTANCE.to0Decimal(danaPump.getReservoirRemainingUnits()) + "U\n"; + ret += "Reserv: " + decimalFormatter.to0Decimal(danaPump.getReservoirRemainingUnits()) + "U\n"; ret += "Batt: " + danaPump.getBatteryRemaining() + "\n"; return ret; } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index ab4c9c77e4..ce102e2d25 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -25,6 +25,7 @@ import info.nightscout.interfaces.pump.PumpSync; import info.nightscout.interfaces.pump.defs.PumpType; import info.nightscout.interfaces.queue.CommandQueue; import info.nightscout.interfaces.ui.UiInteraction; +import info.nightscout.interfaces.utils.DecimalFormatter; import info.nightscout.interfaces.utils.Round; import info.nightscout.pump.dana.DanaPump; import info.nightscout.pump.dana.database.DanaHistoryDatabase; @@ -65,9 +66,10 @@ public class DanaRPlugin extends AbstractDanaRPlugin { FabricPrivacy fabricPrivacy, PumpSync pumpSync, UiInteraction uiInteraction, - DanaHistoryDatabase danaHistoryDatabase + DanaHistoryDatabase danaHistoryDatabase, + DecimalFormatter decimalFormatter ) { - super(injector, danaPump, rh, constraints, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase); + super(injector, danaPump, rh, constraints, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter); this.aapsLogger = aapsLogger; this.context = context; this.rh = rh; diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt index a53ef197b8..095d7a676e 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt @@ -45,10 +45,10 @@ class DanaRPluginTest : TestBaseWithProfile() { `when`(rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) danaRPlugin = DanaRPlugin( injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync, - uiInteraction, danaHistoryDatabase + uiInteraction, danaHistoryDatabase, decimalFormatter ) } diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt index b806b5816a..363ccba06c 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt @@ -8,7 +8,6 @@ import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.interfaces.ConfigBuilder import info.nightscout.interfaces.constraints.Constraints -import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync @@ -17,11 +16,7 @@ import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.dana.DanaPump import info.nightscout.pump.dana.database.DanaHistoryRecordDao import info.nightscout.rx.bus.RxBus -import info.nightscout.shared.interfaces.ResourceHelper -import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.utils.DateUtil -import info.nightscout.sharedtests.TestBase -import info.nightscout.sharedtests.TestPumpPlugin +import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.BeforeEach import org.mockito.ArgumentMatchers import org.mockito.Mock @@ -29,15 +24,11 @@ import org.mockito.Mockito.anyBoolean import org.mockito.Mockito.`when` import org.mockito.kotlin.doNothing -open class DanaRTestBase : TestBase() { +open class DanaRTestBase : TestBaseWithProfile() { - @Mock lateinit var sp: SP - @Mock lateinit var activePlugin: ActivePlugin - @Mock lateinit var dateUtil: DateUtil @Mock lateinit var danaRPlugin: DanaRPlugin @Mock lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Mock lateinit var danaRv2Plugin: DanaRv2Plugin - @Mock lateinit var rh: ResourceHelper @Mock lateinit var configBuilder: ConfigBuilder @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @@ -47,13 +38,9 @@ open class DanaRTestBase : TestBase() { @Mock lateinit var instantiator: Instantiator @Mock lateinit var uiInteraction: UiInteraction - private lateinit var testPumpPlugin: TestPumpPlugin - @BeforeEach fun setup() { - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) - testPumpPlugin = TestPumpPlugin(injector) - `when`(activePlugin.activePump).thenReturn(testPumpPlugin) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) doNothing().`when`(danaRKoreanPlugin).setPluginEnabled(anyObject(), anyBoolean()) doNothing().`when`(danaRPlugin).setPluginEnabled(anyObject(), anyBoolean()) doNothing().`when`(danaRKoreanPlugin).setFragmentVisible(anyObject(), anyBoolean()) diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt index d4b5969856..59c583263f 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -45,10 +45,10 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { `when`(rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) danaRPlugin = DanaRKoreanPlugin( injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, - pumpSync, uiInteraction, danaHistoryDatabase + pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter ) } diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt index 9416b48960..d19b855b65 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt @@ -49,10 +49,10 @@ class DanaRv2PluginTest : TestBaseWithProfile() { `when`(rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)).thenReturn("it must be positive value") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio)).thenReturn("Limiting max basal rate to %1\$.2f U/h because of %2\$s") `when`(rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate)).thenReturn("Limiting max percent rate to %1\$d%% because of %2\$s") - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) danaRv2Plugin = DanaRv2Plugin( injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, detailedBolusInfoStorage, - temporaryBasalStorage, dateUtil, fabricPrivacy, pumpSync, uiInteraction, danaHistoryDatabase + temporaryBasalStorage, dateUtil, fabricPrivacy, pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter ) } diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt index b1c6c51bea..2374eb15ae 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt @@ -79,7 +79,8 @@ class DanaRSPlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val dateUtil: DateUtil, private val uiInteraction: UiInteraction, - private val danaHistoryDatabase: DanaHistoryDatabase + private val danaHistoryDatabase: DanaHistoryDatabase, + private val decimalFormatter: DecimalFormatter ) : PumpPluginBase( PluginDescription() .mainType(PluginType.PUMP) @@ -617,7 +618,7 @@ class DanaRSPlugin @Inject constructor( ret += "LastConn: $agoMin minAgo\n" } if (danaPump.lastBolusTime != 0L) - ret += "LastBolus: ${DecimalFormatter.to2Decimal(danaPump.lastBolusAmount)}U @${DateFormat.format("HH:mm", danaPump.lastBolusTime)}" + ret += "LastBolus: ${decimalFormatter.to2Decimal(danaPump.lastBolusAmount)}U @${DateFormat.format("HH:mm", danaPump.lastBolusTime)}" if (danaPump.isTempBasalInProgress) ret += "Temp: ${danaPump.temporaryBasalToString()}" @@ -626,9 +627,9 @@ class DanaRSPlugin @Inject constructor( ret += "Extended: ${danaPump.extendedBolusToString()}\n" if (!veryShort) { - ret += "TDD: ${DecimalFormatter.to0Decimal(danaPump.dailyTotalUnits)} / ${danaPump.maxDailyTotalUnits} U" + ret += "TDD: ${decimalFormatter.to0Decimal(danaPump.dailyTotalUnits)} / ${danaPump.maxDailyTotalUnits} U" } - ret += "Reserv: ${DecimalFormatter.to0Decimal(danaPump.reservoirRemainingUnits)} U" + ret += "Reserv: ${decimalFormatter.to0Decimal(danaPump.reservoirRemainingUnits)} U" ret += "Batt: ${danaPump.batteryRemaining}" return ret } diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt index ad3aea9aac..24fc9f7407 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt @@ -6,6 +6,7 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.profile.Profile import info.nightscout.pump.dana.DanaPump import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import javax.inject.Inject import kotlin.math.round @@ -15,6 +16,7 @@ class DanaRSPacketBolusSet24CIRCFArray( ) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump + @Inject lateinit var profileUtil: ProfileUtil init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_24_CIR_CF_ARRAY @@ -28,7 +30,7 @@ class DanaRSPacketBolusSet24CIRCFArray( for (i in 0..23) { var isf = profile.getIsfMgdlTimeFromMidnight(i * 3600) if (danaPump.units == DanaPump.UNITS_MMOL) { - isf = Profile.fromMgdlToUnits(isf, GlucoseUnit.MMOL) + isf = profileUtil.fromMgdlToUnits(isf, GlucoseUnit.MMOL) isf *= 100 } val ic = profile.getIcTimeFromMidnight(i * 3600) diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt index 8e71a601d1..958f46f0b4 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt @@ -79,7 +79,8 @@ class DanaRSPluginTest : DanaRSTestBase() { fabricPrivacy, dateUtil, uiInteraction, - danaHistoryDatabase + danaHistoryDatabase, + decimalFormatter ) } } \ No newline at end of file diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt index 45be8dfea1..e64101e1f1 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt @@ -52,6 +52,6 @@ open class DanaRSTestBase : TestBaseWithProfile() { @BeforeEach fun setup() { - danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator) + danaPump = DanaPump(aapsLogger, sp, dateUtil, instantiator, decimalFormatter) } } \ No newline at end of file diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt index 42bc637aa5..b142a13226 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt @@ -72,7 +72,8 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { fabricPrivacy, dateUtil, uiInteraction, - danaHistoryDatabase + danaHistoryDatabase, + decimalFormatter ) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) } diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index bf8f7fd3b7..dc0cdef0e8 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -76,7 +76,8 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { fabricPrivacy, dateUtil, uiInteraction, - danaHistoryDatabase + danaHistoryDatabase, + decimalFormatter ) danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true, 0) } diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt index 0c88189a6a..caf8c0f2c0 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt @@ -78,7 +78,8 @@ class DiaconnG8Plugin @Inject constructor( private val dateUtil: DateUtil, private val aapsSchedulers: AapsSchedulers, private val uiInteraction: UiInteraction, - private val diaconnHistoryDatabase: DiaconnHistoryDatabase + private val diaconnHistoryDatabase: DiaconnHistoryDatabase, + private val decimalFormatter: DecimalFormatter ) : PumpPluginBase( PluginDescription() .mainType(PluginType.PUMP) @@ -535,7 +536,7 @@ class DiaconnG8Plugin @Inject constructor( ret += "LastConn: $agoMin minago\n" } if (diaconnG8Pump.lastBolusTime != 0L) - ret += "LastBolus: ${DecimalFormatter.to2Decimal(diaconnG8Pump.lastBolusAmount)}U @${DateFormat.format("HH:mm", diaconnG8Pump.lastBolusTime)}" + ret += "LastBolus: ${decimalFormatter.to2Decimal(diaconnG8Pump.lastBolusAmount)}U @${DateFormat.format("HH:mm", diaconnG8Pump.lastBolusTime)}" if (diaconnG8Pump.isTempBasalInProgress) ret += "Temp: ${diaconnG8Pump.temporaryBasalToString()}" @@ -544,9 +545,9 @@ class DiaconnG8Plugin @Inject constructor( ret += "Extended: ${diaconnG8Pump.extendedBolusToString()}\n" if (!veryShort) { - ret += "TDD: ${DecimalFormatter.to0Decimal(diaconnG8Pump.dailyTotalUnits)} / ${diaconnG8Pump.maxDailyTotalUnits} U" + ret += "TDD: ${decimalFormatter.to0Decimal(diaconnG8Pump.dailyTotalUnits)} / ${diaconnG8Pump.maxDailyTotalUnits} U" } - ret += "Reserv: ${DecimalFormatter.to0Decimal(diaconnG8Pump.systemRemainInsulin)} U" + ret += "Reserv: ${decimalFormatter.to0Decimal(diaconnG8Pump.systemRemainInsulin)} U" ret += "Batt: ${diaconnG8Pump.systemRemainBattery}" return ret } diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Pump.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Pump.kt index 17d87cbbcf..42f7140195 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Pump.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Pump.kt @@ -17,7 +17,8 @@ import kotlin.math.roundToInt @Singleton class DiaconnG8Pump @Inject constructor( private val aapsLogger: AAPSLogger, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val decimalFormatter: DecimalFormatter ) { var isPumpLogUploadFailed: Boolean = false @@ -136,9 +137,9 @@ class DiaconnG8Pump @Inject constructor( fun extendedBolusToString(): String { if (!isExtendedInProgress) return "" - //return "E "+ DecimalFormatter.to2Decimal(extendedBolusDeliveredSoFar) +"/" + DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + + //return "E "+ decimalFormatter.to2Decimal(extendedBolusDeliveredSoFar) +"/" + decimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + // " " + extendedBolusPassedMinutes + "/" + extendedBolusMinutes + "'" - return "E "+ DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + + return "E " + decimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + dateUtil.timeString(extendedBolusStart) + " " + extendedBolusPassedMinutes + "/" + extendedBolusDurationInMinutes + "'" } diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/activities/DiaconnG8HistoryActivity.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/activities/DiaconnG8HistoryActivity.kt index baeb1ab5e2..d611ee3d6e 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/activities/DiaconnG8HistoryActivity.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/activities/DiaconnG8HistoryActivity.kt @@ -42,6 +42,7 @@ class DiaconnG8HistoryActivity : TranslatedDaggerAppCompatActivity() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper + @Inject lateinit var decimalFormatter: DecimalFormatter private val disposable = CompositeDisposable() @@ -126,10 +127,10 @@ class DiaconnG8HistoryActivity : TranslatedDaggerAppCompatActivity() { override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { val record = historyList[position] holder.time.text = dateUtil.dateAndTimeString(record.timestamp) - holder.value.text = DecimalFormatter.to2Decimal(record.value) + holder.value.text = decimalFormatter.to2Decimal(record.value) holder.stringValue.text = record.stringValue holder.bolusType.text = record.bolusType - holder.duration.text = DecimalFormatter.to0Decimal(record.duration.toDouble()) + holder.duration.text = decimalFormatter.to0Decimal(record.duration.toDouble()) holder.alarm.text = record.alarm when (showingType) { RecordTypes.RECORD_TYPE_ALARM -> { @@ -172,18 +173,7 @@ class DiaconnG8HistoryActivity : TranslatedDaggerAppCompatActivity() { holder.alarm.visibility = View.GONE } - RecordTypes.RECORD_TYPE_BASALHOUR -> { - holder.time.visibility = View.VISIBLE - holder.value.visibility = View.VISIBLE - holder.stringValue.visibility = View.VISIBLE - holder.bolusType.visibility = View.GONE - holder.duration.visibility = View.GONE - holder.dailyBasal.visibility = View.GONE - holder.dailyBolus.visibility = View.GONE - holder.dailyTotal.visibility = View.GONE - holder.alarm.visibility = View.GONE - } - + RecordTypes.RECORD_TYPE_BASALHOUR, RecordTypes.RECORD_TYPE_REFILL -> { holder.time.visibility = View.VISIBLE holder.value.visibility = View.VISIBLE diff --git a/pump/eopatch/build.gradle b/pump/eopatch/build.gradle index 1a22f95ef7..224acbbcac 100644 --- a/pump/eopatch/build.gradle +++ b/pump/eopatch/build.gradle @@ -23,7 +23,6 @@ dependencies { implementation project(':core:libraries') implementation project(':app-wear-shared:shared') implementation project(':database:entities') - implementation project(':database:impl') implementation project(':core:interfaces') implementation project(':core:utils') implementation project(':core:ui') diff --git a/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt b/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt index 9cfb74a297..a80c4540a8 100644 --- a/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt +++ b/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt @@ -55,6 +55,7 @@ import info.nightscout.interfaces.pump.defs.ManufacturerType import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.TimeChangeType import info.nightscout.pump.common.data.PumpStatus import info.nightscout.pump.common.defs.PumpDriverState @@ -105,7 +106,8 @@ class MedtronicPumpPlugin @Inject constructor( dateUtil: DateUtil, aapsSchedulers: AapsSchedulers, pumpSync: PumpSync, - pumpSyncStorage: PumpSyncStorage + pumpSyncStorage: PumpSyncStorage, + decimalFormatter: DecimalFormatter ) : info.nightscout.pump.common.PumpPluginAbstract( PluginDescription() // .mainType(PluginType.PUMP) // @@ -116,7 +118,7 @@ class MedtronicPumpPlugin @Inject constructor( .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later - injector, rh, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage + injector, rh, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage, decimalFormatter ), Pump, RileyLinkPumpDevice, info.nightscout.pump.common.sync.PumpSyncEntriesCreator { private var rileyLinkMedtronicService: RileyLinkMedtronicService? = null @@ -182,7 +184,6 @@ class MedtronicPumpPlugin @Inject constructor( medtronicPumpStatus.lastDataTime = medtronicPumpStatus.lastConnection medtronicPumpStatus.previousConnection = medtronicPumpStatus.lastConnection - //if (rileyLinkMedtronicService != null) rileyLinkMedtronicService.verifyConfiguration(); aapsLogger.debug(LTag.PUMP, "initPumpStatusData: $medtronicPumpStatus") // this is only thing that can change, by being configured diff --git a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt index d6e97dbe88..294af1d054 100644 --- a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt +++ b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt @@ -41,8 +41,8 @@ import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.TimeChangeType import info.nightscout.pump.medtrum.comm.enums.MedtrumPumpState -import info.nightscout.pump.medtrum.ui.MedtrumOverviewFragment import info.nightscout.pump.medtrum.services.MedtrumService +import info.nightscout.pump.medtrum.ui.MedtrumOverviewFragment import info.nightscout.pump.medtrum.util.MedtrumSnUtil import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus @@ -76,7 +76,8 @@ import kotlin.math.abs private val medtrumPump: MedtrumPump, private val uiInteraction: UiInteraction, private val pumpSync: PumpSync, - private val temporaryBasalStorage: TemporaryBasalStorage + private val temporaryBasalStorage: TemporaryBasalStorage, + private val decimalFormatter: DecimalFormatter ) : PumpPluginBase( PluginDescription() .mainType(PluginType.PUMP) @@ -494,12 +495,12 @@ import kotlin.math.abs ret += "LastConn: $agoMin minAgo\n" } if (medtrumPump.lastBolusTime != 0L) - ret += "LastBolus: ${DecimalFormatter.to2Decimal(medtrumPump.lastBolusAmount)}U @${DateFormat.format("HH:mm", medtrumPump.lastBolusTime)}\n" + ret += "LastBolus: ${decimalFormatter.to2Decimal(medtrumPump.lastBolusAmount)}U @${DateFormat.format("HH:mm", medtrumPump.lastBolusTime)}\n" if (medtrumPump.tempBasalInProgress) ret += "Temp: ${medtrumPump.temporaryBasalToString()}\n" - ret += "Res: ${DecimalFormatter.to0Decimal(medtrumPump.reservoir)}U\n" + ret += "Res: ${decimalFormatter.to0Decimal(medtrumPump.reservoir)}U\n" return ret } diff --git a/pump/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/pump/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index dc3f00fe96..ec854c0aaa 100644 --- a/pump/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/pump/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash -import android.content.Context import android.os.Handler import android.os.HandlerThread import android.text.format.DateFormat @@ -58,8 +57,7 @@ import info.nightscout.interfaces.queue.Command import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.queue.CustomCommand import info.nightscout.interfaces.ui.UiInteraction -import info.nightscout.interfaces.utils.DecimalFormatter.to0Decimal -import info.nightscout.interfaces.utils.DecimalFormatter.to2Decimal +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.Round import info.nightscout.interfaces.utils.TimeChangeType import info.nightscout.rx.AapsSchedulers @@ -100,11 +98,11 @@ class OmnipodDashPumpPlugin @Inject constructor( private val history: DashHistory, private val pumpSync: PumpSync, private val rxBus: RxBus, - private val context: Context, private val aapsSchedulers: AapsSchedulers, private val fabricPrivacy: FabricPrivacy, private val dateUtil: DateUtil, private val uiInteraction: UiInteraction, + private val decimalFormatter: DecimalFormatter, injector: HasAndroidInjector, aapsLogger: AAPSLogger, rh: ResourceHelper, @@ -1063,7 +1061,7 @@ class OmnipodDashPumpPlugin @Inject constructor( } podStateManager.lastBolus?.run { ret += rh.gs( - info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_last_bolus, to2Decimal(this.deliveredUnits() ?: this.requestedUnits), + info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_last_bolus, decimalFormatter.to2Decimal(this.deliveredUnits() ?: this.requestedUnits), DateFormat.format("HH:mm", Date(this.startTime)) ) + "\n" } @@ -1071,12 +1069,12 @@ class OmnipodDashPumpPlugin @Inject constructor( temporaryBasal?.run { ret += rh.gs( info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_temp_basal, - this.toStringFull(dateUtil) + this.toStringFull(dateUtil, decimalFormatter) ) + "\n" } ret += rh.gs( info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_reservoir, - podStateManager.pulsesRemaining?.let { to0Decimal(reservoirLevel) } ?: "50+" + podStateManager.pulsesRemaining?.let { decimalFormatter.to0Decimal(reservoirLevel) } ?: "50+" ) return ret.trim() } diff --git a/pump/omnipod-eros/build.gradle b/pump/omnipod-eros/build.gradle index 26cad6c4e7..a2404ee8ed 100644 --- a/pump/omnipod-eros/build.gradle +++ b/pump/omnipod-eros/build.gradle @@ -46,4 +46,5 @@ dependencies { testImplementation project(':app-wear-shared:shared-tests') // optional - Test helpers testImplementation("androidx.room:room-testing:$room_version") + testImplementation project(':implementation') } diff --git a/pump/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/pump/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index 62dc194b43..51086f1582 100644 --- a/pump/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/pump/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -146,6 +146,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley private final PumpSync pumpSync; private final UiInteraction uiInteraction; private final ErosHistoryDatabase erosHistoryDatabase; + private final DecimalFormatter decimalFormatter; private final CompositeDisposable disposable = new CompositeDisposable(); @@ -185,7 +186,8 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley ProfileFunction profileFunction, PumpSync pumpSync, UiInteraction uiInteraction, - ErosHistoryDatabase erosHistoryDatabase + ErosHistoryDatabase erosHistoryDatabase, + DecimalFormatter decimalFormatter ) { super(new PluginDescription() // .mainType(PluginType.PUMP) // @@ -214,6 +216,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley this.pumpSync = pumpSync; this.uiInteraction = uiInteraction; this.erosHistoryDatabase = erosHistoryDatabase; + this.decimalFormatter = decimalFormatter; pumpDescription = new PumpDescription(pumpType); @@ -831,17 +834,17 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_last_connection, agoMin) + "\n"; } if (podStateManager.getLastBolusStartTime() != null) { - ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_last_bolus, DecimalFormatter.INSTANCE.to2Decimal(podStateManager.getLastBolusAmount()), + ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_last_bolus, decimalFormatter.to2Decimal(podStateManager.getLastBolusAmount()), android.text.format.DateFormat.format("HH:mm", podStateManager.getLastBolusStartTime().toDate())) + "\n"; } PumpSync.PumpState pumpState = pumpSync.expectedPumpState(); if (pumpState.getTemporaryBasal() != null && pumpState.getProfile() != null) { - ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_temp_basal, pumpState.getTemporaryBasal().toStringFull(dateUtil) + "\n"); + ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_temp_basal, pumpState.getTemporaryBasal().toStringFull(dateUtil, decimalFormatter) + "\n"); } if (pumpState.getExtendedBolus() != null) { - ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_extended_bolus, pumpState.getExtendedBolus().toStringFull(dateUtil) + "\n"); + ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_extended_bolus, pumpState.getExtendedBolus().toStringFull(dateUtil, decimalFormatter) + "\n"); } - ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_reservoir, (getReservoirLevel() > OmnipodConstants.MAX_RESERVOIR_READING ? "50+" : DecimalFormatter.INSTANCE.to0Decimal(getReservoirLevel()))) + "\n"; + ret += rh.gs(info.nightscout.androidaps.plugins.pump.omnipod.common.R.string.omnipod_common_short_status_reservoir, (getReservoirLevel() > OmnipodConstants.MAX_RESERVOIR_READING ? "50+" : decimalFormatter.to0Decimal(getReservoirLevel()))) + "\n"; if (isUseRileyLinkBatteryLevel()) { ret += rh.gs(R.string.omnipod_eros_short_status_riley_link_battery, getBatteryLevel()) + "\n"; } diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt index e4204ad91b..9b7bd7e5a3 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt @@ -5,12 +5,14 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.ErosHistoryDatabase import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager +import info.nightscout.implementation.utils.DecimalFormatterImpl import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.pump.common.defs.TempBasalPair import info.nightscout.rx.TestAapsSchedulers import info.nightscout.rx.bus.RxBus @@ -38,11 +40,13 @@ class OmnipodErosPumpPluginTest : TestBase() { @Mock lateinit var pumpSync: PumpSync @Mock lateinit var erosHistoryDatabase: ErosHistoryDatabase + private lateinit var decimalFormatter: DecimalFormatter private var rxBusWrapper = RxBus(TestAapsSchedulers(), aapsLogger) @BeforeEach fun prepare() { `when`(rh.gs(ArgumentMatchers.anyInt(), ArgumentMatchers.anyLong())) .thenReturn("") + decimalFormatter = DecimalFormatterImpl(rh) } @Test fun testSetTempBasalPercent() { @@ -53,7 +57,7 @@ class OmnipodErosPumpPluginTest : TestBase() { injector, aapsLogger, TestAapsSchedulers(), rxBusWrapper, null, rh, null, null, aapsOmnipodErosManager, commandQueue, null, null, null, null, - rileyLinkUtil, null, null, pumpSync, uiInteraction, erosHistoryDatabase + rileyLinkUtil, null, null, pumpSync, uiInteraction, erosHistoryDatabase, decimalFormatter ) val pumpState = PumpSync.PumpState(null, null, null, null, "") `when`(pumpSync.expectedPumpState()).thenReturn(pumpState) diff --git a/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt b/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt index 25b3957678..3c5517200a 100644 --- a/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt +++ b/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt @@ -22,8 +22,7 @@ import info.nightscout.interfaces.pump.defs.ManufacturerType import info.nightscout.interfaces.pump.defs.PumpDescription import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.CommandQueue -import info.nightscout.interfaces.utils.DecimalFormatter.to0Decimal -import info.nightscout.interfaces.utils.DecimalFormatter.to2Decimal +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.pump.common.data.PumpStatus import info.nightscout.pump.common.defs.PumpDriverState import info.nightscout.pump.common.sync.PumpDbEntryCarbs @@ -62,7 +61,8 @@ abstract class PumpPluginAbstract protected constructor( var dateUtil: DateUtil, var aapsSchedulers: AapsSchedulers, var pumpSync: PumpSync, - var pumpSyncStorage: PumpSyncStorage + var pumpSyncStorage: PumpSyncStorage, + var decimalFormatter: DecimalFormatter ) : PumpPluginBase(pluginDescription, injector, aapsLogger, rh, commandQueue), Pump, Constraints, PumpSyncEntriesCreator { protected val disposable = CompositeDisposable() @@ -290,13 +290,13 @@ abstract class PumpPluginAbstract protected constructor( pumpStatusData.lastBolusTime?.let { if (it.time != 0L) { - ret += "LastBolus: ${to2Decimal(pumpStatusData.lastBolusAmount!!)}U @${DateFormat.format("HH:mm", it)}\n" + ret += "LastBolus: ${decimalFormatter.to2Decimal(pumpStatusData.lastBolusAmount!!)}U @${DateFormat.format("HH:mm", it)}\n" } } - pumpSync.expectedPumpState().temporaryBasal?.let { ret += "Temp: ${it.toStringFull(dateUtil)}\n" } - pumpSync.expectedPumpState().extendedBolus?.let { ret += "Extended: ${it.toStringFull(dateUtil)}\n" } + pumpSync.expectedPumpState().temporaryBasal?.let { ret += "Temp: ${it.toStringFull(dateUtil, decimalFormatter)}\n" } + pumpSync.expectedPumpState().extendedBolus?.let { ret += "Extended: ${it.toStringFull(dateUtil, decimalFormatter)}\n" } ret += "IOB: ${pumpStatusData.iob}U\n" - ret += "Reserv: ${to0Decimal(pumpStatusData.reservoirRemainingUnits)}U\n" + ret += "Reserv: ${decimalFormatter.to0Decimal(pumpStatusData.reservoirRemainingUnits)}U\n" ret += "Batt: ${pumpStatusData.batteryRemaining}\n" return ret } diff --git a/pump/virtual/src/main/java/info/nightscout/pump/virtual/VirtualPumpFragment.kt b/pump/virtual/src/main/java/info/nightscout/pump/virtual/VirtualPumpFragment.kt index 15c1cf15b0..64f8eab66e 100644 --- a/pump/virtual/src/main/java/info/nightscout/pump/virtual/VirtualPumpFragment.kt +++ b/pump/virtual/src/main/java/info/nightscout/pump/virtual/VirtualPumpFragment.kt @@ -11,6 +11,7 @@ import info.nightscout.core.extensions.toStringFull import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.pump.virtual.databinding.VirtualPumpFragmentBinding import info.nightscout.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.rx.AapsSchedulers @@ -34,6 +35,7 @@ class VirtualPumpFragment : DaggerFragment() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var decimalFormatter: DecimalFormatter private val disposable = CompositeDisposable() @@ -90,9 +92,9 @@ class VirtualPumpFragment : DaggerFragment() { if (_binding == null) return val profile = profileFunction.getProfile() ?: return binding.baseBasalRate.text = rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, virtualPumpPlugin.baseBasalRate) - binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil.now())?.toStringFull(profile, dateUtil) + binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil.now())?.toStringFull(profile, dateUtil, decimalFormatter) ?: "" - binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) + binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil, decimalFormatter) ?: "" binding.battery.text = rh.gs(info.nightscout.core.ui.R.string.format_percent, virtualPumpPlugin.batteryPercent) binding.reservoir.text = rh.gs(info.nightscout.interfaces.R.string.format_insulin_units, virtualPumpPlugin.reservoirInUnits.toDouble()) diff --git a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsProfileSwitchFragment.kt b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsProfileSwitchFragment.kt index 4b320b337f..fdc39442f1 100644 --- a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsProfileSwitchFragment.kt +++ b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsProfileSwitchFragment.kt @@ -31,6 +31,7 @@ import info.nightscout.interfaces.Config import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventEffectiveProfileSwitchChanged @@ -69,6 +70,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment(), MenuProvider { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger + @Inject lateinit var decimalFormatter: DecimalFormatter private var _binding: TreatmentsProfileswitchFragmentBinding? = null @@ -201,7 +203,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment(), MenuProvider { holder.binding.time.text = dateUtil.timeString(profileSwitch.timestamp) holder.binding.duration.text = rh.gs(info.nightscout.core.ui.R.string.format_mins, T.msecs(profileSwitch.duration ?: 0L).mins()) holder.binding.name.text = - if (profileSwitch is ProfileSealed.PS) profileSwitch.value.getCustomizedName() else if (profileSwitch is ProfileSealed.EPS) profileSwitch.value.originalCustomizedName else "" + if (profileSwitch is ProfileSealed.PS) profileSwitch.value.getCustomizedName(decimalFormatter) else if (profileSwitch is ProfileSealed.EPS) profileSwitch.value.originalCustomizedName else "" if (profileSwitch.isInProgress(dateUtil)) holder.binding.date.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.activeColor)) else holder.binding.date.setTextColor(holder.binding.duration.currentTextColor) holder.binding.clone.tag = profileSwitch @@ -238,11 +240,11 @@ class TreatmentsProfileSwitchFragment : DaggerFragment(), MenuProvider { OKDialog.showConfirmation( activity, rh.gs(info.nightscout.core.ui.R.string.careportal_profileswitch), - rh.gs(info.nightscout.core.ui.R.string.copytolocalprofile) + "\n" + profileSwitch.getCustomizedName() + "\n" + dateUtil.dateAndTimeString(profileSwitch.timestamp), + rh.gs(info.nightscout.core.ui.R.string.copytolocalprofile) + "\n" + profileSwitch.getCustomizedName(decimalFormatter) + "\n" + dateUtil.dateAndTimeString(profileSwitch.timestamp), Runnable { uel.log( Action.PROFILE_SWITCH_CLONED, Sources.Treatments, - profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"), + profileSwitch.getCustomizedName(decimalFormatter) + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_"), ValueWithUnit.Timestamp(profileSwitch.timestamp), ValueWithUnit.SimpleString(profileSwitch.profileName) ) @@ -250,7 +252,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment(), MenuProvider { activePlugin.activeProfileSource.addProfile( activePlugin.activeProfileSource.copyFrom( nonCustomized, - profileSwitch.getCustomizedName() + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_") + profileSwitch.getCustomizedName(decimalFormatter) + " " + dateUtil.dateAndTimeString(profileSwitch.timestamp).replace(".", "_") ) ) rxBus.send(EventLocalProfileChanged()) diff --git a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTempTargetFragment.kt b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTempTargetFragment.kt index 806de9ce8b..8323e0f209 100644 --- a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTempTargetFragment.kt +++ b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTempTargetFragment.kt @@ -33,7 +33,7 @@ import info.nightscout.database.impl.transactions.InvalidateTemporaryTargetTrans import info.nightscout.interfaces.Config import info.nightscout.interfaces.Translator import info.nightscout.interfaces.logging.UserEntryLogger -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventEffectiveProfileSwitchChanged @@ -44,6 +44,7 @@ import info.nightscout.rx.events.EventTempTargetChange import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -64,7 +65,7 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator @@ -73,6 +74,7 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository + @Inject lateinit var decimalFormatter: DecimalFormatter private var _binding: TreatmentsTemptargetFragmentBinding? = null @@ -173,7 +175,7 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: TempTargetsViewHolder, position: Int) { - val units = profileFunction.getUnits() + val units = profileUtil.units val tempTarget = tempTargetList[position] holder.binding.ns.visibility = (tempTarget.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.invalid.visibility = tempTarget.isValid.not().toVisibility() @@ -193,8 +195,8 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { holder.binding.date.text = if (newDay) dateUtil.dateStringRelative(tempTarget.timestamp, rh) else "" holder.binding.time.text = dateUtil.timeRangeString(tempTarget.timestamp, tempTarget.end) holder.binding.duration.text = rh.gs(info.nightscout.core.ui.R.string.format_mins, T.msecs(tempTarget.duration).mins()) - holder.binding.low.text = tempTarget.lowValueToUnitsToString(units) - holder.binding.high.text = tempTarget.highValueToUnitsToString(units) + holder.binding.low.text = tempTarget.lowValueToUnitsToString(units, decimalFormatter) + holder.binding.high.text = tempTarget.highValueToUnitsToString(units, decimalFormatter) holder.binding.reason.text = translator.translate(tempTarget.reason) holder.binding.time.setTextColor( when { @@ -258,7 +260,7 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { private fun getConfirmationText(selectedItems: SparseArray): String { if (selectedItems.size() == 1) { val tempTarget = selectedItems.valueAt(0) - return "${rh.gs(info.nightscout.core.ui.R.string.temporary_target)}: ${tempTarget.friendlyDescription(profileFunction.getUnits(), rh)}\n" + + return "${rh.gs(info.nightscout.core.ui.R.string.temporary_target)}: ${tempTarget.friendlyDescription(profileUtil.units, rh, profileUtil)}\n" + dateUtil.dateAndTimeString(tempTarget.timestamp) } return rh.gs(info.nightscout.core.ui.R.string.confirm_remove_multiple_items, selectedItems.size()) @@ -285,5 +287,4 @@ class TreatmentsTempTargetFragment : DaggerFragment(), MenuProvider { }) } } - } diff --git a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTemporaryBasalsFragment.kt b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTemporaryBasalsFragment.kt index f5596f5f53..0e3053eb41 100644 --- a/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/ui/src/main/java/info/nightscout/ui/activities/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -36,6 +36,7 @@ import info.nightscout.interfaces.iob.IobTotal import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventTempBasalChange @@ -69,6 +70,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment(), MenuProvider { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository + @Inject lateinit var decimalFormatter: DecimalFormatter private var _binding: TreatmentsTempbasalsFragmentBinding? = null @@ -263,8 +265,13 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment(), MenuProvider { val isFakeExtended = tempBasal.type == TemporaryBasal.Type.FAKE_EXTENDED val profile = profileFunction.getProfile(dateUtil.now()) if (profile != null) - return "${if (isFakeExtended) rh.gs(info.nightscout.core.ui.R.string.extended_bolus) else rh.gs(info.nightscout.core.ui.R.string.tempbasal_label)}: ${tempBasal.toStringFull(profile, - dateUtil)}\n" + + return "${if (isFakeExtended) rh.gs(info.nightscout.core.ui.R.string.extended_bolus) else rh.gs(info.nightscout.core.ui.R.string.tempbasal_label)}: ${ + tempBasal.toStringFull( + profile, + dateUtil, + decimalFormatter + ) + }\n" + "${rh.gs(info.nightscout.core.ui.R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.timestamp)}" } return rh.gs(info.nightscout.core.ui.R.string.confirm_remove_multiple_items, selectedItems.size()) diff --git a/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfile.kt b/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfile.kt index fba8a9da96..b49f8fde41 100644 --- a/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfile.kt +++ b/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfile.kt @@ -2,9 +2,9 @@ package info.nightscout.ui.defaultProfile import info.nightscout.core.extensions.pureProfileFromJson import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.PureProfile import info.nightscout.interfaces.utils.Round +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import org.json.JSONArray import org.json.JSONObject @@ -17,7 +17,10 @@ import kotlin.math.abs @Suppress("LocalVariableName") @Singleton -class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { +class DefaultProfile @Inject constructor( + private val dateUtil: DateUtil, + private val profileUtil: ProfileUtil +) { private var oneToFive: TreeMap> = TreeMap() private var sixToEleven: TreeMap> = TreeMap() @@ -32,21 +35,21 @@ class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { val ic = Round.roundTo(250.0 / _tdd, 1.0) profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -4.0, -1.0, -2.0, -4.0, 0.0, -4.0))) val isf = Round.roundTo(200.0 / _tdd, 0.1) - profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0),units)) + profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.0, -2.0, -0.0, -0.0, -2.0, 0.0, -2.0), units)) } else if (age in 6..11) { val _tdd = if (tdd == 0.0) 0.8 * weight else tdd closest(sixToEleven, _tdd * 0.4)?.let { array -> profile.put("basal", arrayToJson(array)) } val ic = Round.roundTo(375.0 / _tdd, 1.0) profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -3.0, 0.0, -1.0, -3.0, 0.0, -2.0))) val isf = Round.roundTo(170.0 / _tdd, 0.1) - profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0),units)) + profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.0, -1.0, -0.0, -0.0, -1.0, 0.0, -1.0), units)) } else if (age in 12..18) { val _tdd = if (tdd == 0.0) 1.0 * weight else tdd closest(twelveToSeventeen, _tdd * 0.5)?.let { array -> profile.put("basal", arrayToJson(array)) } val ic = Round.roundTo(500.0 / _tdd, 1.0) profile.put("carbratio", singleValueArray(ic, arrayOf(0.0, -1.0, 0.0, 0.0, -1.0, 0.0, -1.0))) val isf = Round.roundTo(100.0 / _tdd, 0.1) - profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2),units)) + profile.put("sens", singleValueArrayFromMmolToUnits(isf, arrayOf(0.2, 0.0, 0.2, 0.2, 0.0, 0.2, 0.2), units)) } else if (age > 18) { return null } @@ -54,31 +57,49 @@ class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { profile.put("carbs_hr", 20) // not used profile.put("delay", 5.0) // not used profile.put("timezone", TimeZone.getDefault().id) - profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) - profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) + profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMgdlToUnits(108.0, units)))) + profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMgdlToUnits(108.0, units)))) profile.put("units", units.asText) return pureProfileFromJson(profile, dateUtil) } init { - oneToFive[1.00] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050) - oneToFive[1.13] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050) - oneToFive[1.25] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050) - oneToFive[1.38] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050) - oneToFive[1.50] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.100, 0.100, 0.050, 0.050) - oneToFive[1.75] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050, 0.050, 0.060, 0.060, 0.075, 0.075, 0.050, 0.050, 0.050, 0.100, 0.125, 0.100, 0.050, 0.050) - oneToFive[2.00] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.075, 0.050, 0.050, 0.065, 0.065, 0.075, 0.075, 0.050, 0.050, 0.050, 0.100, 0.125, 0.100, 0.050, 0.050) - oneToFive[2.25] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.100, 0.100, 0.075, 0.060, 0.060, 0.070, 0.070, 0.100, 0.100, 0.050, 0.050, 0.050, 0.125, 0.150, 0.125, 0.065, 0.050) - oneToFive[2.50] = arrayOf(0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.125, 0.125, 0.100, 0.065, 0.065, 0.075, 0.075, 0.125, 0.125, 0.060, 0.060, 0.060, 0.150, 0.150, 0.150, 0.070, 0.060) - oneToFive[2.75] = arrayOf(0.075, 0.075, 0.075, 0.100, 0.100, 0.100, 0.125, 0.150, 0.125, 0.100, 0.070, 0.070, 0.080, 0.080, 0.150, 0.150, 0.070, 0.070, 0.070, 0.175, 0.175, 0.175, 0.080, 0.070) - oneToFive[3.25] = arrayOf(0.100, 0.100, 0.100, 0.125, 0.125, 0.125, 0.150, 0.150, 0.150, 0.100, 0.080, 0.080, 0.100, 0.100, 0.175, 0.175, 0.075, 0.075, 0.075, 0.200, 0.200, 0.200, 0.090, 0.080) - oneToFive[3.75] = arrayOf(0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.175, 0.175, 0.175, 0.100, 0.085, 0.085, 0.110, 0.110, 0.185, 0.185, 0.080, 0.080, 0.080, 0.225, 0.225, 0.225, 0.100, 0.090) - oneToFive[4.25] = arrayOf(0.125, 0.125, 0.130, 0.140, 0.140, 0.140, 0.200, 0.200, 0.200, 0.125, 0.090, 0.090, 0.120, 0.120, 0.200, 0.200, 0.100, 0.100, 0.100, 0.250, 0.250, 0.250, 0.125, 0.100) - oneToFive[4.75] = arrayOf(0.125, 0.130, 0.135, 0.150, 0.150, 0.150, 0.200, 0.225, 0.200, 0.125, 0.100, 0.100, 0.125, 0.125, 0.250, 0.200, 0.110, 0.125, 0.125, 0.275, 0.275, 0.275, 0.130, 0.125) - oneToFive[5.25] = arrayOf(0.150, 0.150, 0.150, 0.170, 0.170, 0.170, 0.225, 0.225, 0.225, 0.130, 0.125, 0.125, 0.140, 0.140, 0.250, 0.250, 0.150, 0.150, 0.150, 0.300, 0.300, 0.300, 0.150, 0.150) - oneToFive[6.00] = arrayOf(0.170, 0.170, 0.175, 0.200, 0.200, 0.200, 0.250, 0.250, 0.250, 0.150, 0.125, 0.125, 0.150, 0.150, 0.275, 0.275, 0.170, 0.150, 0.150, 0.350, 0.350, 0.350, 0.175, 0.150) - oneToFive[6.75] = arrayOf(0.200, 0.200, 0.200, 0.225, 0.225, 0.225, 0.275, 0.275, 0.275, 0.200, 0.130, 0.130, 0.175, 0.175, 0.300, 0.300, 0.170, 0.175, 0.175, 0.375, 0.375, 0.375, 0.200, 0.175) - oneToFive[7.50] = arrayOf(0.225, 0.230, 0.235, 0.250, 0.250, 0.250, 0.300, 0.300, 0.300, 0.250, 0.150, 0.150, 0.200, 0.200, 0.325, 0.325, 0.200, 0.200, 0.200, 0.400, 0.450, 0.400, 0.350, 0.200) + oneToFive[1.00] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050) + oneToFive[1.13] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050) + oneToFive[1.25] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050) + oneToFive[1.38] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050) + oneToFive[1.50] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.075, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.050, 0.050, 0.050, 0.075, 0.100, 0.100, 0.050, 0.050) + oneToFive[1.75] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.050, 0.050, 0.050, 0.060, 0.060, 0.075, 0.075, 0.050, 0.050, 0.050, 0.100, 0.125, 0.100, 0.050, 0.050) + oneToFive[2.00] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.075, 0.050, 0.050, 0.065, 0.065, 0.075, 0.075, 0.050, 0.050, 0.050, 0.100, 0.125, 0.100, 0.050, 0.050) + oneToFive[2.25] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.100, 0.100, 0.075, 0.060, 0.060, 0.070, 0.070, 0.100, 0.100, 0.050, 0.050, 0.050, 0.125, 0.150, 0.125, 0.065, 0.050) + oneToFive[2.50] = + arrayOf(0.050, 0.050, 0.050, 0.050, 0.075, 0.075, 0.100, 0.125, 0.125, 0.100, 0.065, 0.065, 0.075, 0.075, 0.125, 0.125, 0.060, 0.060, 0.060, 0.150, 0.150, 0.150, 0.070, 0.060) + oneToFive[2.75] = + arrayOf(0.075, 0.075, 0.075, 0.100, 0.100, 0.100, 0.125, 0.150, 0.125, 0.100, 0.070, 0.070, 0.080, 0.080, 0.150, 0.150, 0.070, 0.070, 0.070, 0.175, 0.175, 0.175, 0.080, 0.070) + oneToFive[3.25] = + arrayOf(0.100, 0.100, 0.100, 0.125, 0.125, 0.125, 0.150, 0.150, 0.150, 0.100, 0.080, 0.080, 0.100, 0.100, 0.175, 0.175, 0.075, 0.075, 0.075, 0.200, 0.200, 0.200, 0.090, 0.080) + oneToFive[3.75] = + arrayOf(0.125, 0.125, 0.125, 0.125, 0.125, 0.125, 0.175, 0.175, 0.175, 0.100, 0.085, 0.085, 0.110, 0.110, 0.185, 0.185, 0.080, 0.080, 0.080, 0.225, 0.225, 0.225, 0.100, 0.090) + oneToFive[4.25] = + arrayOf(0.125, 0.125, 0.130, 0.140, 0.140, 0.140, 0.200, 0.200, 0.200, 0.125, 0.090, 0.090, 0.120, 0.120, 0.200, 0.200, 0.100, 0.100, 0.100, 0.250, 0.250, 0.250, 0.125, 0.100) + oneToFive[4.75] = + arrayOf(0.125, 0.130, 0.135, 0.150, 0.150, 0.150, 0.200, 0.225, 0.200, 0.125, 0.100, 0.100, 0.125, 0.125, 0.250, 0.200, 0.110, 0.125, 0.125, 0.275, 0.275, 0.275, 0.130, 0.125) + oneToFive[5.25] = + arrayOf(0.150, 0.150, 0.150, 0.170, 0.170, 0.170, 0.225, 0.225, 0.225, 0.130, 0.125, 0.125, 0.140, 0.140, 0.250, 0.250, 0.150, 0.150, 0.150, 0.300, 0.300, 0.300, 0.150, 0.150) + oneToFive[6.00] = + arrayOf(0.170, 0.170, 0.175, 0.200, 0.200, 0.200, 0.250, 0.250, 0.250, 0.150, 0.125, 0.125, 0.150, 0.150, 0.275, 0.275, 0.170, 0.150, 0.150, 0.350, 0.350, 0.350, 0.175, 0.150) + oneToFive[6.75] = + arrayOf(0.200, 0.200, 0.200, 0.225, 0.225, 0.225, 0.275, 0.275, 0.275, 0.200, 0.130, 0.130, 0.175, 0.175, 0.300, 0.300, 0.170, 0.175, 0.175, 0.375, 0.375, 0.375, 0.200, 0.175) + oneToFive[7.50] = + arrayOf(0.225, 0.230, 0.235, 0.250, 0.250, 0.250, 0.300, 0.300, 0.300, 0.250, 0.150, 0.150, 0.200, 0.200, 0.325, 0.325, 0.200, 0.200, 0.200, 0.400, 0.450, 0.400, 0.350, 0.200) sixToEleven[5.26] = arrayOf(0.18, 0.18, 0.18, 0.20, 0.20, 0.23, 0.25, 0.25, 0.25, 0.18, 0.15, 0.13, 0.15, 0.15, 0.25, 0.25, 0.20, 0.15, 0.18, 0.25, 0.25, 0.25, 0.23, 0.20) sixToEleven[5.61] = arrayOf(0.18, 0.20, 0.20, 0.23, 0.23, 0.25, 0.28, 0.28, 0.25, 0.20, 0.15, 0.13, 0.15, 0.18, 0.25, 0.25, 0.20, 0.15, 0.18, 0.28, 0.25, 0.25, 0.23, 0.20) @@ -157,13 +178,13 @@ class DefaultProfile @Inject constructor(val dateUtil: DateUtil) { private fun singleValueArrayFromMmolToUnits(value: Double, sample: Array, units: GlucoseUnit): JSONArray { val array = JSONArray() - array.put(JSONObject().put("time", "00:00").put("value", Profile.fromMmolToUnits(value + sample[0], units)).put("timeAsSeconds", 0 * 3600)) - array.put(JSONObject().put("time", "06:00").put("value", Profile.fromMmolToUnits(value + sample[1], units)).put("timeAsSeconds", 6 * 3600)) - array.put(JSONObject().put("time", "09:00").put("value", Profile.fromMmolToUnits(value + sample[2], units)).put("timeAsSeconds", 9 * 3600)) - array.put(JSONObject().put("time", "11:00").put("value", Profile.fromMmolToUnits(value + sample[3], units)).put("timeAsSeconds", 11 * 3600)) - array.put(JSONObject().put("time", "14:00").put("value", Profile.fromMmolToUnits(value + sample[4], units)).put("timeAsSeconds", 14 * 3600)) - array.put(JSONObject().put("time", "16:00").put("value", Profile.fromMmolToUnits(value + sample[5], units)).put("timeAsSeconds", 16 * 3600)) - array.put(JSONObject().put("time", "19:00").put("value", Profile.fromMmolToUnits(value + sample[6], units)).put("timeAsSeconds", 19 * 3600)) + array.put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMmolToUnits(value + sample[0], units)).put("timeAsSeconds", 0 * 3600)) + array.put(JSONObject().put("time", "06:00").put("value", profileUtil.fromMmolToUnits(value + sample[1], units)).put("timeAsSeconds", 6 * 3600)) + array.put(JSONObject().put("time", "09:00").put("value", profileUtil.fromMmolToUnits(value + sample[2], units)).put("timeAsSeconds", 9 * 3600)) + array.put(JSONObject().put("time", "11:00").put("value", profileUtil.fromMmolToUnits(value + sample[3], units)).put("timeAsSeconds", 11 * 3600)) + array.put(JSONObject().put("time", "14:00").put("value", profileUtil.fromMmolToUnits(value + sample[4], units)).put("timeAsSeconds", 14 * 3600)) + array.put(JSONObject().put("time", "16:00").put("value", profileUtil.fromMmolToUnits(value + sample[5], units)).put("timeAsSeconds", 16 * 3600)) + array.put(JSONObject().put("time", "19:00").put("value", profileUtil.fromMmolToUnits(value + sample[6], units)).put("timeAsSeconds", 19 * 3600)) return array } } \ No newline at end of file diff --git a/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfileDPV.kt b/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfileDPV.kt index 47c5412f08..51b364a92b 100644 --- a/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfileDPV.kt +++ b/ui/src/main/java/info/nightscout/ui/defaultProfile/DefaultProfileDPV.kt @@ -3,8 +3,8 @@ package info.nightscout.ui.defaultProfile import dagger.android.HasAndroidInjector import info.nightscout.core.extensions.pureProfileFromJson import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.PureProfile +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.utils.DateUtil import org.json.JSONArray import org.json.JSONObject @@ -14,7 +14,11 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector, val dateUtil: DateUtil) { +class DefaultProfileDPV @Inject constructor( + private val injector: HasAndroidInjector, + private val dateUtil: DateUtil, + private val profileUtil: ProfileUtil +) { private var oneToFive = arrayOf(3.97, 3.61, 3.46, 3.70, 3.76, 3.87, 4.18, 4.01, 3.76, 3.54, 3.15, 2.80, 2.86, 3.21, 3.61, 3.97, 4.43, 4.96, 5.10, 5.50, 5.81, 6.14, 5.52, 5.10) private var sixToEleven = arrayOf(4.20, 4.27, 4.41, 4.62, 4.92, 5.09, 5.01, 4.47, 3.89, 3.33, 3.10, 2.91, 2.97, 3.08, 3.36, 3.93, 4.52, 4.76, 4.69, 4.63, 4.63, 4.47, 4.47, 4.31) @@ -42,8 +46,8 @@ class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector, va profile.put("carbs_hr", 20) // not used profile.put("delay", 5.0) // not used profile.put("timezone", TimeZone.getDefault().id) - profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) - profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units)))) + profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMgdlToUnits(108.0, units)))) + profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMgdlToUnits(108.0, units)))) profile.put("units", units.asText) return pureProfileFromJson(profile, dateUtil) } @@ -67,7 +71,7 @@ class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector, va @Suppress("SameParameterValue") private fun singleValueArrayFromMmolToUnits(value: Double, units: GlucoseUnit): JSONArray { val array = JSONArray() - array.put(JSONObject().put("time", "00:00").put("value", Profile.fromMmolToUnits(value, units)).put("timeAsSeconds", 0 * 3600)) + array.put(JSONObject().put("time", "00:00").put("value", profileUtil.fromMmolToUnits(value, units)).put("timeAsSeconds", 0 * 3600)) return array } } \ No newline at end of file diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/CalibrationDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/CalibrationDialog.kt index 18371ce520..1b980a2c61 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/CalibrationDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/CalibrationDialog.kt @@ -14,9 +14,8 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.XDripBroadcast import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.logging.UserEntryLogger -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.utils.HtmlHelper +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.ui.databinding.DialogCalibrationBinding import java.text.DecimalFormat @@ -27,7 +26,7 @@ class CalibrationDialog : DialogFragmentWithDate() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var rh: ResourceHelper - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var xDripBroadcast: XDripBroadcast @Inject lateinit var uel: UserEntryLogger @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @@ -55,11 +54,8 @@ class CalibrationDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val units = profileFunction.getUnits() - val bg = Profile.fromMgdlToUnits( - glucoseStatusProvider.glucoseStatusData?.glucose - ?: 0.0, units - ) + val units = profileUtil.units + val bg = profileUtil.fromMgdlToUnits(glucoseStatusProvider.glucoseStatusData?.glucose ?: 0.0) if (units == GlucoseUnit.MMOL) binding.bg.setParams( savedInstanceState?.getDouble("bg") @@ -81,11 +77,11 @@ class CalibrationDialog : DialogFragmentWithDate() { override fun submit(): Boolean { if (_binding == null) return false - val units = profileFunction.getUnits() + val units = profileUtil.units val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(info.nightscout.core.ui.R.string.mmol) else rh.gs(info.nightscout.core.ui.R.string.mgdl) val actions: LinkedList = LinkedList() val bg = binding.bg.value - actions.add(rh.gs(info.nightscout.core.ui.R.string.bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel) + actions.add(rh.gs(info.nightscout.core.ui.R.string.bg_label) + ": " + profileUtil.stringInCurrentUnitsDetect(bg) + " " + unitLabel) if (bg > 0) { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(info.nightscout.core.ui.R.string.calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), { diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt index 6f764eabb3..1ce19dceee 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt @@ -28,8 +28,6 @@ import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.protection.ProtectionCheck.Protection.BOLUS import info.nightscout.interfaces.pump.DetailedBolusInfo @@ -39,6 +37,7 @@ import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import info.nightscout.ui.R @@ -57,7 +56,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var constraintChecker: Constraints @Inject lateinit var defaultValueHelper: DefaultValueHelper - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider @Inject lateinit var uel: UserEntryLogger @@ -66,6 +65,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var repository: AppRepository @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var decimalFormatter: DecimalFormatter private var queryingProtection = false private val disposable = CompositeDisposable() @@ -226,7 +226,7 @@ class CarbsDialog : DialogFragmentWithDate() { if (_binding == null) return false val carbs = binding.carbs.value.toInt() val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() - val units = profileFunction.getUnits() + val units = profileUtil.units val activityTTDuration = defaultValueHelper.determineActivityTTDuration() val activityTT = defaultValueHelper.determineActivityTT() val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration() @@ -241,7 +241,10 @@ class CarbsDialog : DialogFragmentWithDate() { val activitySelected = binding.activityTt.isChecked if (activitySelected) actions.add( - rh.gs(R.string.temp_target_short) + ": " + (DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + rh.gs(info.nightscout.core.ui.R.string.format_mins, activityTTDuration) + ")").formatColor( + rh.gs(R.string.temp_target_short) + ": " + (decimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + rh.gs( + info.nightscout.core.ui.R.string.format_mins, + activityTTDuration + ) + ")").formatColor( context, rh, info.nightscout.core.ui.R.attr.tempTargetConfirmation @@ -250,7 +253,7 @@ class CarbsDialog : DialogFragmentWithDate() { val eatingSoonSelected = binding.eatingSoonTt.isChecked if (eatingSoonSelected) actions.add( - rh.gs(R.string.temp_target_short) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs( + rh.gs(R.string.temp_target_short) + ": " + (decimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs( info.nightscout.core.ui.R.string.format_mins, eatingSoonTTDuration ) + ")").formatColor(context, rh, info.nightscout.core.ui.R.attr.tempTargetConfirmation) @@ -258,7 +261,10 @@ class CarbsDialog : DialogFragmentWithDate() { val hypoSelected = binding.hypoTt.isChecked if (hypoSelected) actions.add( - rh.gs(R.string.temp_target_short) + ": " + (DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + rh.gs(info.nightscout.core.ui.R.string.format_mins, hypoTTDuration) + ")").formatColor( + rh.gs(R.string.temp_target_short) + ": " + (decimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + rh.gs( + info.nightscout.core.ui.R.string.format_mins, + hypoTTDuration + ) + ")").formatColor( context, rh, info.nightscout.core.ui.R.attr.tempTargetConfirmation @@ -299,8 +305,8 @@ class CarbsDialog : DialogFragmentWithDate() { timestamp = System.currentTimeMillis(), duration = TimeUnit.MINUTES.toMillis(activityTTDuration.toLong()), reason = TemporaryTarget.Reason.ACTIVITY, - lowTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(activityTT, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(activityTT, profileUtil.units), + highTarget = profileUtil.convertToMgdl(activityTT, profileUtil.units) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } @@ -322,8 +328,8 @@ class CarbsDialog : DialogFragmentWithDate() { timestamp = System.currentTimeMillis(), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), reason = TemporaryTarget.Reason.EATING_SOON, - lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(eatingSoonTT, profileUtil.units), + highTarget = profileUtil.convertToMgdl(eatingSoonTT, profileUtil.units) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } @@ -345,8 +351,8 @@ class CarbsDialog : DialogFragmentWithDate() { timestamp = System.currentTimeMillis(), duration = TimeUnit.MINUTES.toMillis(hypoTTDuration.toLong()), reason = TemporaryTarget.Reason.HYPOGLYCEMIA, - lowTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(hypoTT, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(hypoTT, profileUtil.units), + highTarget = profileUtil.convertToMgdl(hypoTT, profileUtil.units) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/CareDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/CareDialog.kt index d95fa40f03..51e43dc544 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/CareDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/CareDialog.kt @@ -22,11 +22,11 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.Translator import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.logging.UserEntryLogger -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import info.nightscout.ui.R @@ -47,6 +47,7 @@ class CareDialog : DialogFragmentWithDate() { @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider + @Inject lateinit var profileUtil: ProfileUtil private val disposable = CompositeDisposable() @@ -131,10 +132,7 @@ class CareDialog : DialogFragmentWithDate() { } } - val bg = Profile.fromMgdlToUnits( - glucoseStatusProvider.glucoseStatusData?.glucose - ?: 0.0, profileFunction.getUnits() - ) + val bg = profileUtil.fromMgdlToUnits(glucoseStatusProvider.glucoseStatusData?.glucose ?: 0.0) val bgTextWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} @@ -200,7 +198,7 @@ class CareDialog : DialogFragmentWithDate() { else -> TherapyEvent.MeterType.MANUAL } actions.add(rh.gs(R.string.glucose_type) + ": " + translator.translate(meterType)) - actions.add(rh.gs(info.nightscout.core.ui.R.string.bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, binding.bg.value) + " " + rh.gs(unitResId)) + actions.add(rh.gs(info.nightscout.core.ui.R.string.bg_label) + ": " + profileUtil.stringInCurrentUnitsDetect(binding.bg.value) + " " + rh.gs(unitResId)) therapyEvent.glucoseType = meterType therapyEvent.glucose = binding.bg.value valuesWithUnit.add(ValueWithUnit.fromGlucoseUnit(binding.bg.value, profileFunction.getUnits().asText)) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt index 58660256ec..55a49ff99e 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt @@ -47,6 +47,7 @@ class FillDialog : DialogFragmentWithDate() { @Inject lateinit var repository: AppRepository @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var decimalFormatter: DecimalFormatter private var queryingProtection = false private val disposable = CompositeDisposable() @@ -76,12 +77,12 @@ class FillDialog : DialogFragmentWithDate() { val bolusStep = activePlugin.activePump.pumpDescription.bolusStep binding.fillInsulinAmount.setParams( savedInstanceState?.getDouble("fill_insulin_amount") - ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), true, binding.okcancel.ok + ?: 0.0, 0.0, maxInsulin, bolusStep, decimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump.pumpDescription.bolusStep), true, binding.okcancel.ok ) val amount1 = sp.getDouble("fill_button1", 0.3) if (amount1 > 0) { binding.fillPresetButton1.visibility = View.VISIBLE - binding.fillPresetButton1.text = DecimalFormatter.toPumpSupportedBolus(amount1, activePlugin.activePump) // + "U"); + binding.fillPresetButton1.text = decimalFormatter.toPumpSupportedBolus(amount1, activePlugin.activePump.pumpDescription.bolusStep) // + "U"); binding.fillPresetButton1.setOnClickListener { binding.fillInsulinAmount.value = amount1 } } else { binding.fillPresetButton1.visibility = View.GONE @@ -89,7 +90,7 @@ class FillDialog : DialogFragmentWithDate() { val amount2 = sp.getDouble("fill_button2", 0.0) if (amount2 > 0) { binding.fillPresetButton2.visibility = View.VISIBLE - binding.fillPresetButton2.text = DecimalFormatter.toPumpSupportedBolus(amount2, activePlugin.activePump) // + "U"); + binding.fillPresetButton2.text = decimalFormatter.toPumpSupportedBolus(amount2, activePlugin.activePump.pumpDescription.bolusStep) // + "U"); binding.fillPresetButton2.setOnClickListener { binding.fillInsulinAmount.value = amount2 } } else { binding.fillPresetButton2.visibility = View.GONE @@ -97,7 +98,7 @@ class FillDialog : DialogFragmentWithDate() { val amount3 = sp.getDouble("fill_button3", 0.0) if (amount3 > 0) { binding.fillPresetButton3.visibility = View.VISIBLE - binding.fillPresetButton3.text = DecimalFormatter.toPumpSupportedBolus(amount3, activePlugin.activePump) // + "U"); + binding.fillPresetButton3.text = decimalFormatter.toPumpSupportedBolus(amount3, activePlugin.activePump.pumpDescription.bolusStep) // + "U"); binding.fillPresetButton3.setOnClickListener { binding.fillInsulinAmount.value = amount3 } } else { binding.fillPresetButton3.visibility = View.GONE @@ -119,7 +120,10 @@ class FillDialog : DialogFragmentWithDate() { if (insulinAfterConstraints > 0) { actions.add(rh.gs(R.string.fill_warning)) actions.add("") - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(context, rh, info.nightscout.core.ui.R.attr.insulinButtonColor)) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + decimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump.pumpDescription.bolusStep) + .formatColor(context, rh, info.nightscout.core.ui.R.attr.insulinButtonColor) + ) if (abs(insulinAfterConstraints - insulin) > 0.01) actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_constraint_applied_warn, insulin, insulinAfterConstraints).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt index b228a2fb3b..59f0addbdf 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt @@ -28,7 +28,6 @@ import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.pump.DetailedBolusInfo @@ -40,6 +39,7 @@ import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import info.nightscout.ui.R @@ -60,6 +60,7 @@ class InsulinDialog : DialogFragmentWithDate() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var ctx: Context @@ -70,6 +71,7 @@ class InsulinDialog : DialogFragmentWithDate() { @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var persistenceLayer: PersistenceLayer + @Inject lateinit var decimalFormatter: DecimalFormatter private var queryingProtection = false private val disposable = CompositeDisposable() @@ -131,10 +133,11 @@ class InsulinDialog : DialogFragmentWithDate() { ) binding.amount.setParams( savedInstanceState?.getDouble("amount") - ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher + ?: 0.0, 0.0, maxInsulin, activePlugin.activePump.pumpDescription.bolusStep, decimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump.pumpDescription.bolusStep), false, binding + .okcancel.ok, textWatcher ) - val plus05Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_1), INSULIN_PLUS1_DEFAULT).toSignedString(activePlugin.activePump) + val plus05Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_1), INSULIN_PLUS1_DEFAULT).toSignedString(activePlugin.activePump, decimalFormatter) binding.plus05.text = plus05Text binding.plus05.contentDescription = rh.gs(info.nightscout.core.ui.R.string.overview_insulin_label) + " " + plus05Text binding.plus05.setOnClickListener { @@ -145,7 +148,7 @@ class InsulinDialog : DialogFragmentWithDate() { validateInputs() binding.amount.announceValue() } - val plus10Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_2), INSULIN_PLUS2_DEFAULT).toSignedString(activePlugin.activePump) + val plus10Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_2), INSULIN_PLUS2_DEFAULT).toSignedString(activePlugin.activePump, decimalFormatter) binding.plus10.text = plus10Text binding.plus10.contentDescription = rh.gs(info.nightscout.core.ui.R.string.overview_insulin_label) + " " + plus10Text binding.plus10.setOnClickListener { @@ -156,7 +159,7 @@ class InsulinDialog : DialogFragmentWithDate() { validateInputs() binding.amount.announceValue() } - val plus20Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_3), INSULIN_PLUS3_DEFAULT).toSignedString(activePlugin.activePump) + val plus20Text = sp.getDouble(rh.gs(info.nightscout.shared.R.string.key_insulin_button_increment_3), INSULIN_PLUS3_DEFAULT).toSignedString(activePlugin.activePump, decimalFormatter) binding.plus20.text = plus20Text binding.plus20.contentDescription = rh.gs(info.nightscout.core.ui.R.string.overview_insulin_label) + " " + plus20Text binding.plus20.setOnClickListener { @@ -194,7 +197,10 @@ class InsulinDialog : DialogFragmentWithDate() { val eatingSoonChecked = binding.startEatingSoonTt.isChecked if (insulinAfterConstraints > 0) { - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(context, rh, info.nightscout.core.ui.R.attr.bolusColor)) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + decimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump.pumpDescription.bolusStep) + .formatColor(context, rh, info.nightscout.core.ui.R.attr.bolusColor) + ) if (recordOnlyChecked) actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_recorded_only).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) @@ -204,7 +210,10 @@ class InsulinDialog : DialogFragmentWithDate() { val eatingSoonTT = defaultValueHelper.determineEatingSoonTT() if (eatingSoonChecked) actions.add( - rh.gs(R.string.temp_target_short) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs(info.nightscout.core.ui.R.string.format_mins, eatingSoonTTDuration) + ")") + rh.gs(R.string.temp_target_short) + ": " + (decimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + rh.gs( + info.nightscout.core.ui.R.string.format_mins, + eatingSoonTTDuration + ) + ")") .formatColor(context, rh, info.nightscout.core.ui.R.attr.tempTargetConfirmation) ) @@ -233,8 +242,8 @@ class InsulinDialog : DialogFragmentWithDate() { timestamp = System.currentTimeMillis(), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), reason = TemporaryTarget.Reason.EATING_SOON, - lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), - highTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(eatingSoonTT, profileFunction.getUnits()), + highTarget = profileUtil.convertToMgdl(eatingSoonTT, profileFunction.getUnits()) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/ProfileSwitchDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/ProfileSwitchDialog.kt index 70a0a637d7..28ddf76c7d 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/ProfileSwitchDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/ProfileSwitchDialog.kt @@ -22,7 +22,6 @@ import info.nightscout.interfaces.Constants import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.utils.HardLimits @@ -30,6 +29,7 @@ import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.bus.RxBus import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import info.nightscout.ui.R @@ -45,6 +45,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var repository: AppRepository @Inject lateinit var uel: UserEntryLogger @@ -220,8 +221,8 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { timestamp = eventTime, duration = TimeUnit.MINUTES.toMillis(duration.toLong()), reason = TemporaryTarget.Reason.ACTIVITY, - lowTarget = Profile.toMgdl(target, profileFunction.getUnits()), - highTarget = Profile.toMgdl(target, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(target, profileFunction.getUnits()), + highTarget = profileUtil.convertToMgdl(target, profileFunction.getUnits()) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/ProfileViewerDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/ProfileViewerDialog.kt index 8acbd63e85..288a9adfed 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/ProfileViewerDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/ProfileViewerDialog.kt @@ -16,15 +16,16 @@ import info.nightscout.core.profile.ProfileSealed import info.nightscout.database.ValueWrapper import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.Config -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.bus.RxBus import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.ui.databinding.DialogProfileviewerBinding @@ -38,11 +39,13 @@ class ProfileViewerDialog : DaggerDialogFragment() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var dateUtil: DateUtil @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var repository: AppRepository @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var config: Config @Inject lateinit var rxBus: RxBus @Inject lateinit var hardLimits: HardLimits + @Inject lateinit var decimalFormatter: DecimalFormatter private var time: Long = 0 @@ -121,11 +124,10 @@ class ProfileViewerDialog : DaggerDialogFragment() { } UiInteraction.Mode.DB_PROFILE -> { - //val profileList = databaseHelper.getProfileSwitchData(time, true) val profileList = repository.getAllProfileSwitches().blockingGet() profile = if (profileList.isNotEmpty()) ProfileSealed.PS(profileList[0]) else null profile2 = null - profileName = if (profileList.isNotEmpty()) profileList[0].getCustomizedName() else null + profileName = if (profileList.isNotEmpty()) profileList[0].getCustomizedName(decimalFormatter) else null date = if (profileList.isNotEmpty()) dateUtil.dateAndTimeString(profileList[0].timestamp) else null binding.dateLayout.visibility = View.VISIBLE } @@ -268,8 +270,8 @@ class ProfileViewerDialog : DaggerDialogFragment() { val units = profileFunction.getUnits() val s = StringBuilder() for (hour in 0..23) { - val val1 = Profile.fromMgdlToUnits(profile1.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) - val val2 = Profile.fromMgdlToUnits(profile2.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) + val val1 = profileUtil.fromMgdlToUnits(profile1.getIsfMgdlTimeFromMidnight(hour * 60 * 60)) + val val2 = profileUtil.fromMgdlToUnits(profile2.getIsfMgdlTimeFromMidnight(hour * 60 * 60)) if (val1 != prev1 || val2 != prev2) { s.append(formatColors(dateUtil.formatHHMM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), units.asText + " " + rh.gs(info.nightscout.core.ui.R.string.profile_per_unit))) s.append("
") @@ -293,17 +295,9 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val2l = profile2.getTargetLowMgdlTimeFromMidnight(hour * 60 * 60) val val2h = profile2.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60) val txt1 = - dateUtil.formatHHMM(hour * 60 * 60) + " " + Profile.toUnitsString(val1l, val1l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString( - val1h, - val1h * Constants.MGDL_TO_MMOLL, - units - ) + " " + units.asText + dateUtil.formatHHMM(hour * 60 * 60) + " " + profileUtil.fromMgdlToStringInUnits(val1l) + " - " + profileUtil.fromMgdlToStringInUnits(val1h) + " " + units.asText val txt2 = - dateUtil.formatHHMM(hour * 60 * 60) + " " + Profile.toUnitsString(val2l, val2l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString( - val2h, - val2h * Constants.MGDL_TO_MMOLL, - units - ) + " " + units.asText + dateUtil.formatHHMM(hour * 60 * 60) + " " + profileUtil.fromMgdlToStringInUnits(val2l) + " - " + profileUtil.fromMgdlToStringInUnits(val2h) + " " + units.asText if (val1l != prev1l || val1h != prev1h || val2l != prev2l || val2h != prev2h) { s.append(formatColors(txt1, txt2)) s.append("
") diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt index 078ec59db3..175c8f2d74 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt @@ -22,11 +22,11 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.constraints.Constraints import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.utils.HtmlHelper import info.nightscout.rx.logging.LTag +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.ui.R import info.nightscout.ui.databinding.DialogTemptargetBinding @@ -42,6 +42,7 @@ class TempTargetDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: Constraints @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var uel: UserEntryLogger @Inject lateinit var repository: AppRepository @@ -77,7 +78,7 @@ class TempTargetDialog : DialogFragmentWithDate() { ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, binding.okcancel.ok ) - if (profileFunction.getUnits() == GlucoseUnit.MMOL) + if (profileUtil.units == GlucoseUnit.MMOL) binding.temptarget.setParams( savedInstanceState?.getDouble("tempTarget") ?: 8.0, @@ -90,7 +91,7 @@ class TempTargetDialog : DialogFragmentWithDate() { Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, binding.okcancel.ok ) - val units = profileFunction.getUnits() + val units = profileUtil.units binding.units.text = if (units == GlucoseUnit.MMOL) rh.gs(info.nightscout.core.ui.R.string.mmol) else rh.gs(info.nightscout.core.ui.R.string.mgdl) // temp target @@ -172,7 +173,7 @@ class TempTargetDialog : DialogFragmentWithDate() { val duration = binding.duration.value.toInt() if (target != 0.0 && duration != 0) { actions.add(rh.gs(info.nightscout.core.ui.R.string.reason) + ": " + reason) - actions.add(rh.gs(info.nightscout.core.ui.R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + rh.gs(unitResId)) + actions.add(rh.gs(info.nightscout.core.ui.R.string.target_label) + ": " + profileUtil.stringInCurrentUnitsDetect(target) + " " + rh.gs(unitResId)) actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_mins, duration)) } else { actions.add(rh.gs(info.nightscout.core.ui.R.string.stoptemptarget)) @@ -227,10 +228,10 @@ class TempTargetDialog : DialogFragmentWithDate() { rh.gs(info.nightscout.core.ui.R.string.eatingsoon) -> TemporaryTarget.Reason.EATING_SOON rh.gs(info.nightscout.core.ui.R.string.activity) -> TemporaryTarget.Reason.ACTIVITY rh.gs(info.nightscout.core.ui.R.string.hypo) -> TemporaryTarget.Reason.HYPOGLYCEMIA - else -> TemporaryTarget.Reason.CUSTOM + else -> TemporaryTarget.Reason.CUSTOM }, - lowTarget = Profile.toMgdl(target, profileFunction.getUnits()), - highTarget = Profile.toMgdl(target, profileFunction.getUnits()) + lowTarget = profileUtil.convertToMgdl(target, profileFunction.getUnits()), + highTarget = profileUtil.convertToMgdl(target, profileFunction.getUnits()) ) ).subscribe({ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt index ee02169f68..1ed791a7a7 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt @@ -51,6 +51,7 @@ class TreatmentDialog : DialogFragmentWithDate() { @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var persistenceLayer: PersistenceLayer + @Inject lateinit var decimalFormatter: DecimalFormatter private var queryingProtection = false private val disposable = CompositeDisposable() @@ -111,7 +112,14 @@ class TreatmentDialog : DialogFragmentWithDate() { ) binding.insulin.setParams( savedInstanceState?.getDouble("insulin") - ?: 0.0, 0.0, maxInsulin, pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher + ?: 0.0, + 0.0, + maxInsulin, + pumpDescription.bolusStep, + decimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump.pumpDescription.bolusStep), + false, + binding.okcancel.ok, + textWatcher ) binding.recordOnlyLayout.visibility = View.GONE binding.insulinLabel.labelFor = binding.insulin.editTextId @@ -134,11 +142,19 @@ class TreatmentDialog : DialogFragmentWithDate() { val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (insulinAfterConstraints > 0) { - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump, rh).formatColor(context, rh, info.nightscout.core.ui.R.attr.bolusColor)) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus) + ": " + decimalFormatter.toPumpSupportedBolus(insulinAfterConstraints, activePlugin.activePump.pumpDescription.bolusStep) + .formatColor( + context, rh, + info.nightscout.core.ui.R.attr.bolusColor + ) + ) if (recordOnlyChecked) actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_recorded_only).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(rh.gs(info.nightscout.core.ui.R.string.bolus_constraint_applied_warn, insulin, insulinAfterConstraints).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor)) + actions.add( + rh.gs(info.nightscout.core.ui.R.string.bolus_constraint_applied_warn, insulin, insulinAfterConstraints).formatColor(context, rh, info.nightscout.core.ui.R.attr.warningColor) + ) } if (carbsAfterConstraints > 0) { actions.add(rh.gs(info.nightscout.core.ui.R.string.carbs) + ": " + rh.gs(info.nightscout.core.graph.R.string.format_carbs, carbsAfterConstraints).formatColor(context, rh, info.nightscout.core.ui.R.attr.carbsColor)) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt index 906f93992a..a574168fe9 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt @@ -47,6 +47,7 @@ import info.nightscout.rx.logging.LTag import info.nightscout.shared.SafeParse import info.nightscout.shared.extensions.runOnUiThread import info.nightscout.shared.extensions.toVisibility +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -71,11 +72,13 @@ class WizardDialog : DaggerDialogFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil @Inject lateinit var protectionCheck: ProtectionCheck + @Inject lateinit var decimalFormatter: DecimalFormatter private val handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) @@ -192,7 +195,14 @@ class WizardDialog : DaggerDialogFragment() { } else { binding.correctionInput.setParams( savedInstanceState?.getDouble("correction_input") - ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher + ?: 0.0, + -maxCorrection, + maxCorrection, + bolusStep, + decimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump.pumpDescription.bolusStep), + false, + binding.okcancel.ok, + textWatcher ) binding.correctionUnit.text = rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname) } @@ -262,7 +272,8 @@ class WizardDialog : DaggerDialogFragment() { } else { binding.correctionInput.setParams( savedInstanceState?.getDouble("correction_input") - ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump), false, binding.okcancel.ok, textWatcher + ?: 0.0, -maxCorrection, maxCorrection, bolusStep, decimalFormatter.pumpSupportedBolusFormat(activePlugin.activePump.pumpDescription.bolusStep), false, binding.okcancel.ok, + textWatcher ) binding.correctionInput.customContentDescription = rh.gs(R.string.a11_correction_units) } @@ -353,8 +364,8 @@ class WizardDialog : DaggerDialogFragment() { } private fun valueToUnitsToString(value: Double, units: String): String = - if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value) - else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) + if (units == Constants.MGDL) decimalFormatter.to0Decimal(value) + else decimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) private fun initDialog() { val profile = profileFunction.getProfile() @@ -470,7 +481,7 @@ class WizardDialog : DaggerDialogFragment() { ) wizard?.let { wizard -> - binding.bg.text = rh.gs(R.string.format_bg_isf, valueToUnitsToString(Profile.toMgdl(bg, profileFunction.getUnits()), profileFunction.getUnits().asText), wizard.sens) + binding.bg.text = rh.gs(R.string.format_bg_isf, valueToUnitsToString(profileUtil.convertToMgdl(bg, profileFunction.getUnits()), profileFunction.getUnits().asText), wizard.sens) binding.bgInsulin.text = rh.gs(info.nightscout.interfaces.R.string.format_insulin_units, wizard.insulinFromBG) binding.carbs.text = rh.gs(R.string.format_carbs_ic, carbs.toDouble(), wizard.ic) @@ -487,7 +498,7 @@ class WizardDialog : DaggerDialogFragment() { // Trend if (binding.bgTrendCheckbox.isChecked && wizard.glucoseStatus != null) { binding.bgTrend.text = ((if (wizard.trend > 0) "+" else "") - + Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, profileFunction.getUnits()) + + profileUtil.fromMgdlToStringInUnits(wizard.trend * 3) + " " + profileFunction.getUnits()) } else { binding.bgTrend.text = "" diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/WizardInfoDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/WizardInfoDialog.kt index 98169731ee..90cf8bcc14 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/WizardInfoDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/WizardInfoDialog.kt @@ -9,9 +9,8 @@ import android.view.WindowManager import com.google.gson.Gson import dagger.android.support.DaggerDialogFragment import info.nightscout.database.entities.BolusCalculatorResult -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.ui.R @@ -22,6 +21,7 @@ class WizardInfoDialog : DaggerDialogFragment() { @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var dateUtil: DateUtil private lateinit var data: BolusCalculatorResult @@ -55,10 +55,9 @@ class WizardInfoDialog : DaggerDialogFragment() { super.onViewCreated(view, savedInstanceState) binding.close.setOnClickListener { dismiss() } - val units = profileFunction.getUnits() - val bgString = Profile.toUnitsString(data.glucoseValue, data.glucoseValue * Constants.MGDL_TO_MMOLL, units) - val isf = Profile.toUnits(data.isf, data.isf * Constants.MGDL_TO_MMOLL, units) - val trend = Profile.toUnitsString(data.glucoseTrend * 3, data.glucoseTrend * 3 * Constants.MGDL_TO_MMOLL, units) + val bgString = profileUtil.fromMgdlToStringInUnits(data.glucoseValue) + val isf = profileUtil.fromMgdlToUnits(data.isf) + val trend = profileUtil.fromMgdlToStringInUnits(data.glucoseTrend * 3) // BG binding.bg.text = rh.gs(R.string.format_bg_isf, bgString, isf) binding.bgInsulin.text = rh.gs(info.nightscout.interfaces.R.string.format_insulin_units, data.glucoseInsulin) diff --git a/ui/src/main/java/info/nightscout/ui/extensions/DoubleToSignedString.kt b/ui/src/main/java/info/nightscout/ui/extensions/DoubleToSignedString.kt index 9e95d13cd9..5b3acf86bf 100644 --- a/ui/src/main/java/info/nightscout/ui/extensions/DoubleToSignedString.kt +++ b/ui/src/main/java/info/nightscout/ui/extensions/DoubleToSignedString.kt @@ -3,8 +3,8 @@ package info.nightscout.ui.extensions import info.nightscout.interfaces.pump.Pump import info.nightscout.interfaces.utils.DecimalFormatter -fun Double.toSignedString(pump: Pump): String { - val formatted = DecimalFormatter.toPumpSupportedBolus(this, pump) +fun Double.toSignedString(pump: Pump, decimalFormatter: DecimalFormatter): String { + val formatted = decimalFormatter.toPumpSupportedBolus(this, pump.pumpDescription.bolusStep) return if (this > 0) "+$formatted" else formatted } diff --git a/ui/src/main/java/info/nightscout/ui/widget/Widget.kt b/ui/src/main/java/info/nightscout/ui/widget/Widget.kt index 07cc1a6772..beaadb4a0a 100644 --- a/ui/src/main/java/info/nightscout/ui/widget/Widget.kt +++ b/ui/src/main/java/info/nightscout/ui/widget/Widget.kt @@ -14,13 +14,11 @@ import android.view.View import android.widget.RemoteViews import dagger.android.HasAndroidInjector import info.nightscout.core.extensions.directionToIcon -import info.nightscout.core.extensions.valueToUnitsString import info.nightscout.core.graph.OverviewData import info.nightscout.core.iob.displayText import info.nightscout.core.profile.ProfileSealed import info.nightscout.database.entities.interfaces.end import info.nightscout.interfaces.Config -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.aps.VariableSensitivityResult @@ -28,14 +26,15 @@ import info.nightscout.interfaces.constraints.Constraints import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.ui.UiInteraction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.TrendCalculator import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag import info.nightscout.shared.extensions.toVisibility import info.nightscout.shared.extensions.toVisibilityKeepSpace +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -50,6 +49,7 @@ import kotlin.math.abs class Widget : AppWidgetProvider() { @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var overviewData: OverviewData @Inject lateinit var trendCalculator: TrendCalculator @Inject lateinit var uiInteraction: UiInteraction @@ -63,6 +63,7 @@ class Widget : AppWidgetProvider() { @Inject lateinit var config: Config @Inject lateinit var sp: SP @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var decimalFormatter: DecimalFormatter companion object { // This object doesn't behave like singleton, @@ -127,13 +128,14 @@ class Widget : AppWidgetProvider() { } private fun updateBg(views: RemoteViews) { - val units = profileFunction.getUnits() - views.setTextViewText(R.id.bg, overviewData.lastBg(iobCobCalculator.ads)?.valueToUnitsString(units) ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short)) + views.setTextViewText( + R.id.bg, + overviewData.lastBg(iobCobCalculator.ads)?.let { profileUtil.fromMgdlToStringInUnits(it.value) } ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short)) views.setTextColor( R.id.bg, when { - overviewData.isLow(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_low) + overviewData.isLow(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_low) overviewData.isHigh(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_high) - else -> rh.gc(info.nightscout.core.ui.R.color.widget_inrange) + else -> rh.gc(info.nightscout.core.ui.R.color.widget_inrange) } ) trendCalculator.getTrendArrow(iobCobCalculator.ads)?.let { @@ -150,9 +152,9 @@ class Widget : AppWidgetProvider() { val glucoseStatus = glucoseStatusProvider.glucoseStatusData if (glucoseStatus != null) { - views.setTextViewText(R.id.delta, Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)) - views.setTextViewText(R.id.avg_delta, Profile.toSignedUnitsString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units)) - views.setTextViewText(R.id.long_avg_delta, Profile.toSignedUnitsString(glucoseStatus.longAvgDelta, glucoseStatus.longAvgDelta * Constants.MGDL_TO_MMOLL, units)) + views.setTextViewText(R.id.delta, profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.delta)) + views.setTextViewText(R.id.avg_delta, profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.shortAvgDelta)) + views.setTextViewText(R.id.long_avg_delta, profileUtil.fromMgdlToSignedStringInUnits(glucoseStatus.longAvgDelta)) } else { views.setTextViewText(R.id.delta, rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short)) views.setTextViewText(R.id.avg_delta, rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short)) @@ -183,7 +185,7 @@ class Widget : AppWidgetProvider() { private fun updateIobCob(views: RemoteViews) { views.setTextViewText(R.id.iob, overviewData.iobText(iobCobCalculator)) // cob - var cobText = overviewData.cobInfo(iobCobCalculator).displayText(rh) ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short) + var cobText = overviewData.cobInfo(iobCobCalculator).displayText(rh, decimalFormatter) ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short) val constraintsProcessed = loop.lastRun?.constraintsProcessed val lastRun = loop.lastRun @@ -206,7 +208,10 @@ class Widget : AppWidgetProvider() { //views.setTextColor(R.id.temp_target, rh.gc(R.color.ribbonTextWarning)) //views.setInt(R.id.temp_target, "setBackgroundColor", rh.gc(R.color.ribbonWarning)) views.setTextColor(R.id.temp_target, rh.gc(info.nightscout.core.ui.R.color.widget_ribbonWarning)) - views.setTextViewText(R.id.temp_target, Profile.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh)) + views.setTextViewText( + R.id.temp_target, + profileUtil.toTargetRangeString(tempTarget.lowTarget, tempTarget.highTarget, GlucoseUnit.MGDL, units) + " " + dateUtil.untilString(tempTarget.end, rh) + ) } else { // If the target is not the same as set in the profile then oref has overridden it profileFunction.getProfile()?.let { profile -> @@ -214,7 +219,7 @@ class Widget : AppWidgetProvider() { if (targetUsed != 0.0 && abs(profile.getTargetMgdl() - targetUsed) > 0.01) { aapsLogger.debug("Adjusted target. Profile: ${profile.getTargetMgdl()} APS: $targetUsed") - views.setTextViewText(R.id.temp_target, Profile.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units)) + views.setTextViewText(R.id.temp_target, profileUtil.toTargetRangeString(targetUsed, targetUsed, GlucoseUnit.MGDL, units)) // this is crashing, use background as text for now //views.setTextColor(R.id.temp_target, rh.gc(R.color.ribbonTextWarning)) //views.setInt(R.id.temp_target, "setBackgroundResource", rh.gc(R.color.tempTargetBackground)) @@ -224,7 +229,7 @@ class Widget : AppWidgetProvider() { //views.setTextColor(R.id.temp_target, rh.gc(R.color.ribbonTextDefault)) //views.setInt(R.id.temp_target, "setBackgroundColor", rh.gc(R.color.ribbonDefault)) views.setTextColor(R.id.temp_target, rh.gc(info.nightscout.core.ui.R.color.widget_ribbonTextDefault)) - views.setTextViewText(R.id.temp_target, Profile.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)) + views.setTextViewText(R.id.temp_target, profileUtil.toTargetRangeString(profile.getTargetLowMgdl(), profile.getTargetHighMgdl(), GlucoseUnit.MGDL, units)) } } } @@ -270,8 +275,8 @@ class Widget : AppWidgetProvider() { R.id.variable_sensitivity, String.format( Locale.getDefault(), "%1$.1f→%2$.1f", - Profile.toUnits(isfMgdl, isfMgdl * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()), - Profile.toUnits(variableSens, variableSens * Constants.MGDL_TO_MMOLL, profileFunction.getUnits()) + profileUtil.fromMgdlToUnits(isfMgdl), + profileUtil.fromMgdlToUnits(variableSens) ) ) views.setViewVisibility(R.id.variable_sensitivity, View.VISIBLE) diff --git a/ui/src/test/java/info/nightscout/ui/defaultProfile/DefaultProfileTest.kt b/ui/src/test/java/info/nightscout/ui/defaultProfile/DefaultProfileTest.kt index a1370c35d5..3d7a4e8de8 100644 --- a/ui/src/test/java/info/nightscout/ui/defaultProfile/DefaultProfileTest.kt +++ b/ui/src/test/java/info/nightscout/ui/defaultProfile/DefaultProfileTest.kt @@ -10,18 +10,18 @@ class DefaultProfileTest : TestBaseWithProfile() { @Test fun profile() { - val dp = DefaultProfile(dateUtil).profile(5, 5.1 / 0.3, 0.0, GlucoseUnit.MMOL) + val dp = DefaultProfile(dateUtil, profileUtil).profile(5, 5.1 / 0.3, 0.0, GlucoseUnit.MMOL) var p = ProfileSealed.Pure(dp!!) Assertions.assertEquals(0.150, p.getBasalTimeFromMidnight(0), 0.001) Assertions.assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) Assertions.assertEquals(11.8, p.getIsfTimeFromMidnight(0), 0.001) - p = ProfileSealed.Pure(DefaultProfile(dateUtil).profile(7, 10.0 / 0.4, 0.0, GlucoseUnit.MMOL)!!) + p = ProfileSealed.Pure(DefaultProfile(dateUtil, profileUtil).profile(7, 10.0 / 0.4, 0.0, GlucoseUnit.MMOL)!!) Assertions.assertEquals(0.350, p.getBasalTimeFromMidnight(0), 0.001) Assertions.assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) Assertions.assertEquals(6.8, p.getIsfTimeFromMidnight(0), 0.001) - p = ProfileSealed.Pure(DefaultProfile(dateUtil).profile(12, 25.0 / 0.5, 0.0, GlucoseUnit.MMOL)!!) + p = ProfileSealed.Pure(DefaultProfile(dateUtil, profileUtil).profile(12, 25.0 / 0.5, 0.0, GlucoseUnit.MMOL)!!) Assertions.assertEquals(0.80, p.getBasalTimeFromMidnight(0), 0.001) Assertions.assertEquals(10.0, p.getIcTimeFromMidnight(0), 0.001) Assertions.assertEquals(2.2, p.getIsfTimeFromMidnight(0), 0.001) diff --git a/workflow/src/main/java/info/nightscout/workflow/PrepareBgDataWorker.kt b/workflow/src/main/java/info/nightscout/workflow/PrepareBgDataWorker.kt index 3255a556d3..4e64a546d4 100644 --- a/workflow/src/main/java/info/nightscout/workflow/PrepareBgDataWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/PrepareBgDataWorker.kt @@ -13,9 +13,8 @@ import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.utils.Round +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import kotlinx.coroutines.Dispatchers import javax.inject.Inject @@ -26,7 +25,7 @@ class PrepareBgDataWorker( ) : LoggingWorker(context, params, Dispatchers.Default) { @Inject lateinit var dataWorkerStorage: DataWorkerStorage - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var repository: AppRepository @@ -49,16 +48,16 @@ class PrepareBgDataWorker( for (bg in data.overviewData.bgReadingsArray) { if (bg.timestamp < fromTime || bg.timestamp > toTime) continue if (bg.value > data.overviewData.maxBgValue) data.overviewData.maxBgValue = bg.value - bgListArray.add(GlucoseValueDataPoint(bg, profileFunction, rh)) + bgListArray.add(GlucoseValueDataPoint(bg, profileUtil, rh)) } bgListArray.sortWith { o1: DataPointWithLabelInterface, o2: DataPointWithLabelInterface -> o1.x.compareTo(o2.x) } data.overviewData.bgReadingGraphSeries = PointsWithLabelGraphSeries(Array(bgListArray.size) { i -> bgListArray[i] }) - data.overviewData.maxBgValue = Profile.fromMgdlToUnits(data.overviewData.maxBgValue, profileFunction.getUnits()) + data.overviewData.maxBgValue = profileUtil.fromMgdlToUnits(data.overviewData.maxBgValue) if (defaultValueHelper.determineHighLine() > data.overviewData.maxBgValue) data.overviewData.maxBgValue = defaultValueHelper.determineHighLine() data.overviewData.maxBgValue = addUpperChartMargin(data.overviewData.maxBgValue) return Result.success() } private fun addUpperChartMargin(maxBgValue: Double) = - if (profileFunction.getUnits() == GlucoseUnit.MGDL) Round.roundTo(maxBgValue, 40.0) + 80 else Round.roundTo(maxBgValue, 2.0) + 4 + if (profileUtil.units == GlucoseUnit.MGDL) Round.roundTo(maxBgValue, 40.0) + 80 else Round.roundTo(maxBgValue, 2.0) + 4 } \ No newline at end of file diff --git a/workflow/src/main/java/info/nightscout/workflow/PrepareIobAutosensGraphDataWorker.kt b/workflow/src/main/java/info/nightscout/workflow/PrepareIobAutosensGraphDataWorker.kt index 679dc2633f..ab2846c92b 100644 --- a/workflow/src/main/java/info/nightscout/workflow/PrepareIobAutosensGraphDataWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/PrepareIobAutosensGraphDataWorker.kt @@ -52,6 +52,7 @@ class PrepareIobAutosensGraphDataWorker( @Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var repository: AppRepository @Inject lateinit var rxBus: RxBus + @Inject lateinit var decimalFormatter: DecimalFormatter private var ctx: Context init { @@ -269,7 +270,7 @@ class PrepareIobAutosensGraphDataWorker( data.overviewData.maxIobValueFound = max(data.overviewData.maxIobValueFound, abs(i.iob)) } data.overviewData.iobPredictions1Series = PointsWithLabelGraphSeries(Array(iobPrediction.size) { i -> iobPrediction[i] }) - aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + DecimalFormatter.to2Decimal(lastAutosensResult.ratio) + ": " + data.iobCobCalculator.iobArrayToString(iobPredictionArray)) + aapsLogger.debug(LTag.AUTOSENS, "IOB prediction for AS=" + decimalFormatter.to2Decimal(lastAutosensResult.ratio) + ": " + data.iobCobCalculator.iobArrayToString(iobPredictionArray)) } else { data.overviewData.iobPredictions1Series = PointsWithLabelGraphSeries() } diff --git a/workflow/src/main/java/info/nightscout/workflow/PreparePredictionsWorker.kt b/workflow/src/main/java/info/nightscout/workflow/PreparePredictionsWorker.kt index 8d9c7bdea7..93fe948e64 100644 --- a/workflow/src/main/java/info/nightscout/workflow/PreparePredictionsWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/PreparePredictionsWorker.kt @@ -15,9 +15,8 @@ import info.nightscout.interfaces.Config import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.nsclient.ProcessedDeviceStatusData import info.nightscout.interfaces.overview.OverviewMenus -import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import kotlinx.coroutines.Dispatchers @@ -41,8 +40,7 @@ class PreparePredictionsWorker( @Inject lateinit var loop: Loop @Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var dataWorkerStorage: DataWorkerStorage - @Inject lateinit var defaultValueHelper: DefaultValueHelper - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var rh: ResourceHelper class PreparePredictionsData( @@ -80,7 +78,7 @@ class PreparePredictionsWorker( val bgListArray: MutableList = ArrayList() val predictions: MutableList? = apsResult?.predictions - ?.map { bg -> GlucoseValueDataPoint(bg, profileFunction, rh) } + ?.map { bg -> GlucoseValueDataPoint(bg, profileUtil, rh) } ?.toMutableList() if (predictions != null) { predictions.sortWith { o1: GlucoseValueDataPoint, o2: GlucoseValueDataPoint -> o1.x.compareTo(o2.x) } diff --git a/workflow/src/main/java/info/nightscout/workflow/PrepareTemporaryTargetDataWorker.kt b/workflow/src/main/java/info/nightscout/workflow/PrepareTemporaryTargetDataWorker.kt index 22b8d1a0ad..f941b2cf29 100644 --- a/workflow/src/main/java/info/nightscout/workflow/PrepareTemporaryTargetDataWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/PrepareTemporaryTargetDataWorker.kt @@ -14,9 +14,9 @@ import info.nightscout.core.workflow.CalculationWorkflow import info.nightscout.database.ValueWrapper import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import kotlinx.coroutines.Dispatchers import javax.inject.Inject @@ -29,6 +29,7 @@ class PrepareTemporaryTargetDataWorker( @Inject lateinit var dataWorkerStorage: DataWorkerStorage @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var rh: ResourceHelper @Inject lateinit var repository: AppRepository @Inject lateinit var loop: Loop @@ -50,7 +51,6 @@ class PrepareTemporaryTargetDataWorker( rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.PREPARE_TEMPORARY_TARGET_DATA, 0, null)) val profile = profileFunction.getProfile() ?: return Result.success(workDataOf("Error" to "missing profile")) - val units = profileFunction.getUnits() var endTime = data.overviewData.endTime val fromTime = data.overviewData.fromTime val targetsSeriesArray: MutableList = ArrayList() @@ -63,9 +63,9 @@ class PrepareTemporaryTargetDataWorker( rxBus.send(EventIobCalculationProgress(CalculationWorkflow.ProgressData.PREPARE_TEMPORARY_TARGET_DATA, progress.toInt(), null)) val tt = repository.getTemporaryTargetActiveAt(time).blockingGet() val value: Double = if (tt is ValueWrapper.Existing) { - Profile.fromMgdlToUnits(tt.value.target(), units) + profileUtil.fromMgdlToUnits(tt.value.target()) } else { - Profile.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2, units) + profileUtil.fromMgdlToUnits((profile.getTargetLowMgdl(time) + profile.getTargetHighMgdl(time)) / 2) } if (lastTarget != value) { if (lastTarget != -1.0) targetsSeriesArray.add(DataPoint(time.toDouble(), lastTarget)) diff --git a/workflow/src/main/java/info/nightscout/workflow/PrepareTreatmentsDataWorker.kt b/workflow/src/main/java/info/nightscout/workflow/PrepareTreatmentsDataWorker.kt index 81e9c5b533..29aae8e9cf 100644 --- a/workflow/src/main/java/info/nightscout/workflow/PrepareTreatmentsDataWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/PrepareTreatmentsDataWorker.kt @@ -3,7 +3,6 @@ package info.nightscout.workflow import android.content.Context import androidx.work.WorkerParameters import androidx.work.workDataOf -import com.jjoe64.graphview.series.LineGraphSeries import info.nightscout.core.events.EventIobCalculationProgress import info.nightscout.core.graph.OverviewData import info.nightscout.core.graph.data.BolusDataPoint @@ -11,7 +10,6 @@ import info.nightscout.core.graph.data.CarbsDataPoint import info.nightscout.core.graph.data.DataPointWithLabelInterface import info.nightscout.core.graph.data.EffectiveProfileSwitchDataPoint import info.nightscout.core.graph.data.ExtendedBolusDataPoint -import info.nightscout.core.graph.data.FixedLineGraphSeries import info.nightscout.core.graph.data.HeartRateDataPoint import info.nightscout.core.graph.data.PointsWithLabelGraphSeries import info.nightscout.core.graph.data.TherapyEventDataPoint @@ -25,10 +23,10 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.Translator import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.DefaultValueHelper -import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.Round import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.T import kotlinx.coroutines.Dispatchers @@ -40,13 +38,14 @@ class PrepareTreatmentsDataWorker( ) : LoggingWorker(context, params, Dispatchers.Default) { @Inject lateinit var dataWorkerStorage: DataWorkerStorage - @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var rh: ResourceHelper @Inject lateinit var rxBus: RxBus @Inject lateinit var translator: Translator @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var repository: AppRepository @Inject lateinit var defaultValueHelper: DefaultValueHelper + @Inject lateinit var decimalFormatter: DecimalFormatter class PrepareTreatmentsData( val overviewData: OverviewData @@ -67,7 +66,7 @@ class PrepareTreatmentsDataWorker( val filteredEps: MutableList = ArrayList() repository.getBolusesDataFromTimeToTime(fromTime, endTime, true).blockingGet() - .map { BolusDataPoint(it, rh, activePlugin, defaultValueHelper) } + .map { BolusDataPoint(it, rh, activePlugin, defaultValueHelper, decimalFormatter) } .filter { it.data.type == Bolus.Type.NORMAL || it.data.type == Bolus.Type.SMB } .forEach { it.y = getNearestBg(data.overviewData, it.x.toLong()) @@ -94,7 +93,7 @@ class PrepareTreatmentsDataWorker( TherapyEventDataPoint( TherapyEvent(timestamp = it.timestamp, duration = it.duration, type = TherapyEvent.Type.APS_OFFLINE, glucoseUnit = TherapyEvent.GlucoseUnit.MMOL), rh, - profileFunction, + profileUtil, translator ) } @@ -103,7 +102,7 @@ class PrepareTreatmentsDataWorker( // Extended bolus if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) { repository.getExtendedBolusDataFromTimeToTime(fromTime, endTime, true).blockingGet() - .map { ExtendedBolusDataPoint(it, rh) } + .map { ExtendedBolusDataPoint(it, rh, decimalFormatter) } .filter { it.duration != 0L } .forEach { it.y = getNearestBg(data.overviewData, it.x.toLong()) @@ -113,7 +112,7 @@ class PrepareTreatmentsDataWorker( // Careportal repository.compatGetTherapyEventDataFromToTime(fromTime - T.hours(6).msecs(), endTime).blockingGet() - .map { TherapyEventDataPoint(it, rh, profileFunction, translator) } + .map { TherapyEventDataPoint(it, rh, profileUtil, translator) } .filterTimeframe(fromTime, endTime) .forEach { if (it.y == 0.0) it.y = getNearestBg(data.overviewData, it.x.toLong()) @@ -142,16 +141,16 @@ class PrepareTreatmentsDataWorker( } private fun addUpperChartMargin(maxBgValue: Double) = - if (profileFunction.getUnits() == GlucoseUnit.MGDL) Round.roundTo(maxBgValue, 40.0) + 80 else Round.roundTo(maxBgValue, 2.0) + 4 + if (profileUtil.units == GlucoseUnit.MGDL) Round.roundTo(maxBgValue, 40.0) + 80 else Round.roundTo(maxBgValue, 2.0) + 4 private fun getNearestBg(overviewData: OverviewData, date: Long): Double { overviewData.bgReadingsArray.let { bgReadingsArray -> for (reading in bgReadingsArray) { if (reading.timestamp > date) continue - return Profile.fromMgdlToUnits(reading.value, profileFunction.getUnits()) + return profileUtil.fromMgdlToUnits(reading.value) } - return if (bgReadingsArray.isNotEmpty()) Profile.fromMgdlToUnits(bgReadingsArray[0].value, profileFunction.getUnits()) - else Profile.fromMgdlToUnits(100.0, profileFunction.getUnits()) + return if (bgReadingsArray.isNotEmpty()) profileUtil.fromMgdlToUnits(bgReadingsArray[0].value) + else profileUtil.fromMgdlToUnits(100.0) } } diff --git a/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOref1Worker.kt b/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOref1Worker.kt index 7a29fe96c3..cfd3ac7c45 100644 --- a/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOref1Worker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOref1Worker.kt @@ -56,6 +56,7 @@ class IobCobOref1Worker( @Inject lateinit var repository: AppRepository @Inject lateinit var dataWorkerStorage: DataWorkerStorage @Inject lateinit var instantiator: Instantiator + @Inject lateinit var decimalFormatter: DecimalFormatter class IobCobOref1WorkerData( val injector: HasAndroidInjector, @@ -193,7 +194,7 @@ class IobCobOref1Worker( autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = activePlugin.activeSensitivity.isMinCarbsAbsorptionDynamic autosensData.activeCarbsList.add(fromCarbs(recentCarbTreatment, isAAPSOrWeighted, profileFunction, aapsLogger, dateUtil, sp)) - autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" + autosensData.pastSensitivity += "[" + decimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" } // if we are absorbing carbs diff --git a/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOrefWorker.kt b/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOrefWorker.kt index c873eb2aca..e1eb101d89 100644 --- a/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOrefWorker.kt +++ b/workflow/src/main/java/info/nightscout/workflow/iob/IobCobOrefWorker.kt @@ -52,6 +52,7 @@ class IobCobOrefWorker @Inject internal constructor( @Inject lateinit var repository: AppRepository @Inject lateinit var dataWorkerStorage: DataWorkerStorage @Inject lateinit var instantiator: Instantiator + @Inject lateinit var decimalFormatter: DecimalFormatter class IobCobOrefWorkerData( val injector: HasAndroidInjector, @@ -186,7 +187,7 @@ class IobCobOrefWorker @Inject internal constructor( autosensData.carbsFromBolus += recentCarbTreatment.amount val isAAPSOrWeighted = activePlugin.activeSensitivity.isMinCarbsAbsorptionDynamic autosensData.activeCarbsList.add(fromCarbs(recentCarbTreatment, isAAPSOrWeighted, profileFunction, aapsLogger, dateUtil, sp)) - autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" + autosensData.pastSensitivity += "[" + decimalFormatter.to0Decimal(recentCarbTreatment.amount) + "g]" } // if we are absorbing carbs